问:
Slim framework Message: Callable Homecontroller does not exist

Project Structure

public/index.php

```<code><?php

require __DIR__ . '/../vendor/autoload.php';

ini_set('display_errors', 'On');

if (PHP_SAPI == 'cli-server') {
    // To help the built-in PHP dev server, check if the request was actually for
    // something which should probably be served as a static file
    $url  = parse_url($_SERVER['REQUEST_URI']);
    $file = __DIR__ . $url['path'];
    if (is_file($file)) {
        return false;
    }
}

session_start();

// Instantiate the app
$settings = require __DIR__ . '/../src/settings.php';

$app = new \Slim\App($settings);

// Set up dependencies
require __DIR__ . '/../src/dependencies.php';

// Register middleware
require __DIR__ . '/../src/middleware.php';

// Register routes
require __DIR__ . '/../src/routes.php';

// Run app
$app->run();
</code>```

Here we have the composer.json

```<code>{

"autoload":{
    "psr-4": {
        "App\\": "src"
    }
},

"require": {
    "php": ">=5.5.0",
    "slim/slim": "^3.1",
    "slim/php-view": "^2.0",
    "monolog/monolog": "^1.17",
    "illuminate/database": "~5.1",
    "slim/twig-view": "^2.3"
},
"require-dev": {
    "phpunit/phpunit": ">=4.8 < 6.0"
},

"autoload-dev": {
    "psr-4": {
        "Tests\\": "tests/"
    }
},
"config": {
    "process-timeout" : 0
},
}
</code>```

Here is my controller, i obtain a error with the namespace and in all the examples that i have seen use this so.. I don't know what to do more

```<code><?php

namespace \App\Controllers;

class Homecontroller
{
    protected $container;

    // constructor receives container instance
    public function __construct(ContainerInterface $container) {
        $this->container = $container;
    }

    public function home($request, $response, $args) {
        echo "locura";
        // your code
        // to access items in the container... $this->container->get('');
        return $response;
    }

    public function contact($request, $response, $args) {
        // your code
        // to access items in the container... $this->container->get('');
        return $response;
    }
}
</code>```

Actual configuration
In my routes.php I have put this:

```<code>$app->get('/new', \Homecontroller::class . ':home');
</code>```

Before configuration

In the above code, I tried to create the controller into the container, and then use

```<code>$app->get('/new', '\HomeController:home');
</code>```

And in the dependencies.php I put this code:

```<code>$container['HomeController'] = function($c) {
$view = $c->get("view"); // retrieve the 'view' from the container
return new HomeController($view);
</code>```

};

but I didn't obtain any result with any configuration

I would like to load the HomeController from router

This is the error that I have when I put api.powertv/new

```<code> Type: RuntimeException
 Message: Callable Homecontroller does not exist
File:       /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/CallableResolver.php
Line: 90
</code>```

i come here, and I put this post like my last resource, if this fails I don't know what I am going to do.

答:
The name inside the container and thoose who you use in the route must match
You've been set the container key to HomeController and used \HomeController in the route, these strings are not equal.

either self create the strings

```<code>$container['HomeController'] = function($c) {
    $view = $c->get("view"); // retrieve the 'view' from the container
    return new HomeController($view);
};
$app->get('/new', 'HomeController:home');
</code>```

or use the ::class syntax for both:

```<code>$container[HomeController::class] = function($c) {
    $view = $c->get("view"); // retrieve the 'view' from the container
    return new HomeController($view);
};
$app->get('/new', [HomeController::class, 'home');
// or $app->get('/new', HomeController::class . ':home');
</code>```

Body:
Project Structure

public/index.php

<?php

require __DIR__ . '/../vendor/autoload.php';

ini_set('display_errors', 'On');

if (PHP_SAPI == 'cli-server') {
    // To help the built-in PHP dev server, check if the request was actually for
    // something which should probably be served as a static file
    $url  = parse_url($_SERVER['REQUEST_URI']);
    $file = __DIR__ . $url['path'];
    if (is_file($file)) {
        return false;
    }
}

session_start();

// Instantiate the app
$settings = require __DIR__ . '/../src/settings.php';

$app = new \Slim\App($settings);

// Set up dependencies
require __DIR__ . '/../src/dependencies.php';

// Register middleware
require __DIR__ . '/../src/middleware.php';

// Register routes
require __DIR__ . '/../src/routes.php';

// Run app
$app->run();

Here we have the composer.json

{

"autoload":{
    "psr-4": {
        "App\\": "src"
    }
},

"require": {
    "php": ">=5.5.0",
    "slim/slim": "^3.1",
    "slim/php-view": "^2.0",
    "monolog/monolog": "^1.17",
    "illuminate/database": "~5.1",
    "slim/twig-view": "^2.3"
},
"require-dev": {
    "phpunit/phpunit": ">=4.8 < 6.0"
},

"autoload-dev": {
    "psr-4": {
        "Tests\\": "tests/"
    }
},
"config": {
    "process-timeout" : 0
},
}

Here is my controller, i obtain a error with the namespace and in all the examples that i have seen use this so.. I don't know what to do more

<?php

namespace \App\Controllers;

class Homecontroller
{
    protected $container;

    // constructor receives container instance
    public function __construct(ContainerInterface $container) {
        $this->container = $container;
    }

    public function home($request, $response, $args) {
        echo "locura";
        // your code
        // to access items in the container... $this->container->get('');
        return $response;
    }

    public function contact($request, $response, $args) {
        // your code
        // to access items in the container... $this->container->get('');
        return $response;
    }
}

Actual configuration
In my routes.php I have put this:

$app->get('/new', \Homecontroller::class . ':home');

Before configuration

In the above code, I tried to create the controller into the container, and then use

$app->get('/new', '\HomeController:home');

And in the dependencies.php I put this code:

$container['HomeController'] = function($c) {
$view = $c->get("view"); // retrieve the 'view' from the container
return new HomeController($view);

};

but I didn't obtain any result with any configuration

I would like to load the HomeController from router

This is the error that I have when I put api.powertv/new

 Type: RuntimeException
 Message: Callable Homecontroller does not exist
File:       /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/CallableResolver.php
Line: 90

i come here, and I put this post like my last resource, if this fails I don't know what I am going to do.

Body:
The name inside the container and thoose who you use in the route must match
You've been set the container key to HomeController and used \HomeController in the route, these strings are not equal.

either self create the strings

$container['HomeController'] = function($c) {
    $view = $c->get("view"); // retrieve the 'view' from the container
    return new HomeController($view);
};
$app->get('/new', 'HomeController:home');

or use the ::class syntax for both:

$container[HomeController::class] = function($c) {
    $view = $c->get("view"); // retrieve the 'view' from the container
    return new HomeController($view);
};
$app->get('/new', [HomeController::class, 'home');
// or $app->get('/new', HomeController::class . ':home');


来源: stackexchange

问:
How to configure htaccess for non www domain?
I want to configure htaccess file. I use domain withoud www, also my domain is indexed in search engines mydomain.com and not www.mydomain.com
when i go to www.mydomain.com it doesn't redirect to mydomain.com
I found that code in htaccess  file. Is it correct? what should i add them?</p>

```<code>RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</code>```

答:
Log into your cPanel
Find the Files category and click on the File Manager icon.
Click Settings at the top right corner.
Choose the document root for the domain you are working with and be sure the checkbox next to Show Hidden Files is checked. Click the Save button.
file-manager-show-hidden
Look for the .htaccess file and right click on it. This brings up a menu. Find and click on the Edit option.
file-manager-htaccess
You are now in the text editor. Place either selection of code in the file and click on the Save Changes button at the top right corner of the screen. Be sure to replace 'example.com' with your actual domain name. NOTE: do not place both selections of code in the file as it will cause an error.

Force www:

```<code>RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ https://example.com/ $1 [L,R=301,NC]
</code>```

Force non-www:

```<code>RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$ https://example.com/ $1 [L,R=301]
</code>```

Now, when you type in your domain name with either www in front or not, it should display as you have set it in the .htaccess file.

ContentLicense: CC BY-SA 3.0

Body:
I want to configure htaccess file. I use domain withoud www, also my domain is indexed in search engines mydomain.com and not www.mydomain.com
when i go to www.mydomain.com it doesn't redirect to mydomain.com
I found that code in htaccess  file. Is it correct? what should i add them?

RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

Body:
Log into your cPanel
Find the Files category and click on the File Manager icon.
Click Settings at the top right corner.
Choose the document root for the domain you are working with and be sure the checkbox next to Show Hidden Files is checked. Click the Save button.
file-manager-show-hidden
Look for the .htaccess file and right click on it. This brings up a menu. Find and click on the Edit option.
file-manager-htaccess
You are now in the text editor. Place either selection of code in the file and click on the Save Changes button at the top right corner of the screen. Be sure to replace 'example.com' with your actual domain name. NOTE: do not place both selections of code in the file as it will cause an error.

Force www:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ https://example.com/ $1 [L,R=301,NC]

Force non-www:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$ https://example.com/ $1 [L,R=301]

Now, when you type in your domain name with either www in front or not, it should display as you have set it in the .htaccess file.


问:
How to add more inputs in a form inside
```

答:
```<code>var Param=//input parametr
var form = $("#signup-form");
var hiddenField = document.createElement("input");
hiddenField.setAttribute("name", "Param");
hiddenField.setAttribute("value", Param);
form.appendChild(hiddenField);
form.submit();
</code>```

Title: How to add more inputs in a form inside <script> tags

Body:
I have a form inside the script tags and I would love to add more input fields before I submit. My submit button does not work and i think it a pblem with how am accessing the submit button when I try this.

below is my form inside the script tags


问:
Creating an instance of a class without defining the __init__ function
I am relativly new to python and I was wondering if you could create an instance of a class without defining the init explicity. Could I call it something else?

First example - with the init method:

```<code>class dog:
def __init__(self,name):
    self.name=name
    print('My name is',name)
Bob = dog('Bob')
</code>```

Second example - without the init method:

```<code>class dog:
def init_instance(self,name):
    self.name = name
    print('My name is',name)

Bob = dog('Bob')
</code>```

In the first example the code works but in the second example I get:

TypeError: object() takes no parameters

So based on this I assume that one has to explicitly call the init method. BUT I have seen code where the init method has not been used, how come?

答:
Every class has an __init__ method. If it doesn't explicitly define one, then it will inherit one from its parent class. In your 2nd example, the class inherits __init__ and a bunch of other methods (and other non-method attributes) from the base object class. We can see that via the dir function:

```<code>class Dog:
    def init_instance(self,name):
        self.name = name
        print('My name is',name)

print(dir(Dog))
</code>```

output

```<code>['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'init_instance']
</code>```

__init__ gets called automatically after the instance is constructed (via the __new__ method), so we might as well use it if we need to initialize our instance. But we can call your init_instance explicitly:

```<code>bob = Dog()
bob.init_instance('Bob')
print(bob.name)
</code>```

output

```<code>My name is Bob
Bob
</code>```

If you give you class an initializer that isn't named __init__ then it won't get called automatically. How should Python know that that method is an initializer? Although it's customary to make __init__ the first method in the class definition, that's by no means mandatory, and some people like to put __init__ last.

You said: "I have seen code where the init method has not been used, how come?" Well, some classes simply don't need their instances to be initialized: their instance attributes are set via various other methods, or by direct assignment in code outside the class definition, eg bob.color = 'brown'. Or they inherit a perfectly usable __init__ from a parent class.

Body:
I am relativly new to python and I was wondering if you could create an instance of a class without defining the init explicity. Could I call it something else?

First example - with the init method:

class dog:
def __init__(self,name):
    self.name=name
    print('My name is',name)
Bob = dog('Bob')

Second example - without the init method:

class dog:
def init_instance(self,name):
    self.name = name
    print('My name is',name)

Bob = dog('Bob')

In the first example the code works but in the second example I get:

TypeError: object() takes no parameters

So based on this I assume that one has to explicitly call the init method. BUT I have seen code where the init method has not been used, how come?

Body:
Every class has an __init__ method. If it doesn't explicitly define one, then it will inherit one from its parent class. In your 2nd example, the class inherits __init__ and a bunch of other methods (and other non-method attributes) from the base object class. We can see that via the dir function:

class Dog:
    def init_instance(self,name):
        self.name = name
        print('My name is',name)

print(dir(Dog))

output

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'init_instance']

__init__ gets called automatically after the instance is constructed (via the __new__ method), so we might as well use it if we need to initialize our instance. But we can call your init_instance explicitly:

bob = Dog()
bob.init_instance('Bob')
print(bob.name)

output

My name is Bob
Bob

If you give you class an initializer that isn't named __init__ then it won't get called automatically. How should Python know that that method is an initializer? Although it's customary to make __init__ the first method in the class definition, that's by no means mandatory, and some people like to put __init__ last.

You said: "I have seen code where the init method has not been used, how come?" Well, some classes simply don't need their instances to be initialized: their instance attributes are set via various other methods, or by direct assignment in code outside the class definition, eg bob.color = 'brown'. Or they inherit a perfectly usable __init__ from a parent class.


问:
Prevent BottomSheetDialogFragment covering navigation bar
I'm using really naive code to show a bottom sheet dialog fragment:

```<code>class LogoutBottomSheetFragment : BottomSheetDialogFragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view = inflater.inflate(R.layout.view_image_source_chooser, container, false)
        return view
    }
}
</code>```

This is how I called this dialog:

```<code>LogoutBottomSheetFragment().show(supportFragmentManager, "logout")
</code>```

But I get this horrible shown in the image below.
How can I keep the navigation bar white (the bottom bar where the back/home software buttons are)?

App Theme I'm using:

```<code> <!-- Base application theme. -->
<style name="BaseAppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
</style

<style name="AppTheme" parent="BaseAppTheme">
    <item name="android:windowNoTitle">true</item>
    <item name="windowActionBar">false</item>

    <!-- Main theme colors -->
    <!--   your app branding color for the app bar -->
    <item name="android:colorPrimary">@color/colorPrimary</item>
    <!--   darker variant for the status bar and contextual app bars -->
    <item name="android:colorPrimaryDark">@android:color/white</item>
    <!--   theme UI controls like checkboxes and text fields -->
    <item name="android:colorAccent">@color/charcoal_grey</item>

    <item name="colorControlNormal">@color/charcoal_grey</item>
    <item name="colorControlActivated">@color/charcoal_grey</item>
    <item name="colorControlHighlight">@color/charcoal_grey</item>

    <item name="android:textColorPrimary">@color/charcoal_grey</item>
    <item name="android:textColor">@color/charcoal_grey</item>

    <item name="android:windowBackground">@color/white</item>
</style>
</code>```

I've also tried to override the setupDialog instead of the onCreateView, but still happens:

```<code>    @SuppressLint("RestrictedApi")
override fun setupDialog(dialog: Dialog, style: Int) {
    super.setupDialog(dialog, style)
    val view = View.inflate(context, R.layout. view_image_source_chooser,null)
    dialog.setContentView(view)
}
</code>```

答:
Don't use BottomSheetDialogFragment.I would prefer use adding bottom sheet by wrapping the layout in the coordinator layout and attaching BottomSheetBehaiviour to that layout

You can follow this as an example

Body:
I'm using really naive code to show a bottom sheet dialog fragment:

class LogoutBottomSheetFragment : BottomSheetDialogFragment() {

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

This is how I called this dialog:

LogoutBottomSheetFragment().show(supportFragmentManager, "logout")

But I get this horrible shown in the image below.
How can I keep the navigation bar white (the bottom bar where the back/home software buttons are)?

App Theme I'm using:

    <item name="android:windowNoTitle">true</item>
    <item name="windowActionBar">false</item>

    <item name="android:colorPrimary">@color/colorPrimary</item>

    <item name="android:colorPrimaryDark">@android:color/white</item>

    <item name="android:colorAccent">@color/charcoal_grey</item>

    <item name="colorControlNormal">@color/charcoal_grey</item>
    <item name="colorControlActivated">@color/charcoal_grey</item>
    <item name="colorControlHighlight">@color/charcoal_grey</item>

    <item name="android:textColorPrimary">@color/charcoal_grey</item>
    <item name="android:textColor">@color/charcoal_grey</item>

    <item name="android:windowBackground">@color/white</item>
</style>

I've also tried to override the setupDialog instead of the onCreateView, but still happens:

    @SuppressLint("RestrictedApi")
override fun setupDialog(dialog: Dialog, style: Int) {
    super.setupDialog(dialog, style)
    val view = View.inflate(context, R.layout. view_image_source_chooser,null)
    dialog.setContentView(view)
}


问:
form does not make the correct query
I want my admin user to be able to approve a jobpost so I defined a method in my jobposts controller like this:

```<code>public function approved(Request $request, JobPost $jobpost)
{
    //save
    $approved = $jobpost->update([
        'approval'=> $request->input('approved')
        ]);

    if($approved)
    {     $user = auth()->user();
        $jobposts = auth()->user()->JobPosts;
        $company = auth()->user()->company;
       return view('/JobPosts/admin/WaitingJobPosts',[
           'jobposts' => $jobposts,
           'company' => $company,
           'user' => $user,
           'approved'=> $approved
       ]);
    } else{
        var_dump($approved);
    }

}
</code>```

Then I defined a rout for it in my web.php:

```<code>Route::patch('jobposts/{job_post}/approved', 'JobPostsController@approved')->name('jobposts.approved');
</code>```

and in my view I have defined a form like this:

```<code> <form method="post" action="{{ route('jobposts.approved', ['job_post' => $jobpost])}}">
                                {{ csrf_field() }}
                                {{ method_field('PATCH') }}
                                <input type="hidden" name="approved" value="1">
                                <div class="form-group">
                                    <button type="submit" class="btn btn-block btn-success">تایید</button>
                                </div>
                            </form>
</code>```

it returns  bool(false). so my query does not work. why?

答: you should change your $jobpost input in your approve method with $job_post because you defined it in your route as {job_post}.

Title: form does not make the correct query

Body:
I want my admin user to be able to approve a jobpost so I defined a method in my jobposts controller like this:

public function approved(Request $request, JobPost $jobpost)
{
    //save
    $approved = $jobpost->update([
        'approval'=> $request->input('approved')
        ]);

    if($approved)
    {     $user = auth()->user();
        $jobposts = auth()->user()->JobPosts;
        $company = auth()->user()->company;
       return view('/JobPosts/admin/WaitingJobPosts',[
           'jobposts' => $jobposts,
           'company' => $company,
           'user' => $user,
           'approved'=> $approved
       ]);
    } else{
        var_dump($approved);
    }

}

Then I defined a rout for it in my web.php:

Route::patch('jobposts/{job_post}/approved', 'JobPostsController@approved')->name('jobposts.approved');

and in my view I have defined a form like this:

 <form method="post" action="{{ route('jobposts.approved', ['job_post' => $jobpost])}}">
                                {{ csrf_field() }}
                                {{ method_field('PATCH') }}
                                <input type="hidden" name="approved" value="1">

                                    <button type="submit" class="btn btn-block btn-success">تایید</button>

                            </form>

it returns  bool(false). so my query does not work. why?


问:
Disabling the title bar in landscape mode
Noob here, having an issue with the action bar in landscape mode (want to keep it in portrait mode).

I post a sample of my manifest xml file having tried the info in other threads.

```<code><?xml version="1.0" encoding="utf-8"?>
</code>```

```<code><application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
</code>```

my styles.xml

```<code><resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light">
    <!-- Primary theme color of the app (sets background color of app bar) -->
    <item name="colorPrimary">#ffcfcf</item>
    <!-- Background color of buttons in the app -->
    <item name="colorButtonNormal">#ff8383</item>
</style>

<style name="AppThemeNoActionBar" parent="AppTheme">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>
</code>```

a snippet from my land\activity_main.xml

```<code><RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:style="@style/AppThemeNoActionBar">

<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/love3"
    android:scaleType="centerCrop"/>
</code>```

...

I have tried changing the parent in styles.xml from AppTheme to Theme.AppCompat.Light to no avail.

portrait layout xml does not have android:style="@style/AppThemeNoActionBar"

Any pointers would be great!

答:
you can do it like this,</p>

```<code>if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
  getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
else {
  getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
</code>```

Body:
Noob here, having an issue with the action bar in landscape mode (want to keep it in portrait mode).

I post a sample of my manifest xml file having tried the info in other threads.

<?xml version="1.0" encoding="utf-8"?>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

my styles.xml

<resources>

a snippet from my land\activity_main.xml

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:style="@style/AppThemeNoActionBar">

<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/love3"
    android:scaleType="centerCrop"/>

...

I have tried changing the parent in styles.xml from AppTheme to Theme.AppCompat.Light to no avail.

portrait layout xml does not have android:style="@style/AppThemeNoActionBar"

Any pointers would be great!

Body:
you can do it like this,

if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
  getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}
else {
  getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
}


问:
Can't hide Bottom Sheet, Android
I'm having problems with my bottom-sheet because when I open the activity it is on, blocking the view

This happens, I think, because of the XML attribute declaring the bottom-sheet with 350dp of height:

```<code><android.support.v4.widget.NestedScrollView
    android:id="@+id/bottom_sheet"
    android:layout_width="match_parent"
    android:layout_height="350dp"
    android:background="?android:attr/windowBackground"
    android:clipToPadding="true"
    app:layout_behavior="android.support.design.widget.BottomSheetBehavior">
</code>```

The thing is, I can't change that value to 0dp because the next time when I try to open the bottom-sheet, there is no bottom-sheet, because the height is 0dp, so it won't show anything.
My question is, is there a way to declare the bottom-sheet off? (I've tried to setState to STATE_COLLAPSED but didn't work).
Bellow is the java code that interacts with the Bottom Sheet.
 JAVA:

```<code>View bottomSheet = findViewById( R.id.bottom_sheet );
        mBottomSheetBehavior = BottomSheetBehavior.from(bottomSheet);
        mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
        mBottomSheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(View bottomSheet, int newState) {
                if (newState == BottomSheetBehavior.STATE_COLLAPSED) {
                    //mBottomSheetBehavior.setPeekHeight(0);
                    //mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                    //mBottomSheetBehavior.isHideable();
                }
            }

            @Override
            public void onSlide(View bottomSheet, float slideOffset) {

            }
        });
</code>```

答:
Inside onCreate add these lines, it can hide the bottombar

```<code>mBottomSheetBehavior = BottomSheetBehavior.from(bottomSheet);
mBottomSheetBehavior.setHideable(true); //Important to add
mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); //Important to add
</code>```

Title: Can't hide Bottom Sheet, Android

Body:
I'm having problems with my bottom-sheet because when I open the activity it is on, blocking the view

This happens, I think, because of the XML attribute declaring the bottom-sheet with 350dp of height:

<android.support.v4.widget.NestedScrollView
    android:id="@+id/bottom_sheet"
    android:layout_width="match_parent"
    android:layout_height="350dp"
    android:background="?android:attr/windowBackground"
    android:clipToPadding="true"
    app:layout_behavior="android.support.design.widget.BottomSheetBehavior">

The thing is, I can't change that value to 0dp because the next time when I try to open the bottom-sheet, there is no bottom-sheet, because the height is 0dp, so it won't show anything.
My question is, is there a way to declare the bottom-sheet off? (I've tried to setState to STATE_COLLAPSED but didn't work).
Bellow is the java code that interacts with the Bottom Sheet.
 JAVA:

View bottomSheet = findViewById( R.id.bottom_sheet );
        mBottomSheetBehavior = BottomSheetBehavior.from(bottomSheet);
        mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
        mBottomSheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(View bottomSheet, int newState) {
                if (newState == BottomSheetBehavior.STATE_COLLAPSED) {
                    //mBottomSheetBehavior.setPeekHeight(0);
                    //mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
                    //mBottomSheetBehavior.isHideable();
                }
            }

            @Override
            public void onSlide(View bottomSheet, float slideOffset) {

            }
        });

Body:
Inside onCreate add these lines, it can hide the bottombar

mBottomSheetBehavior = BottomSheetBehavior.from(bottomSheet);
mBottomSheetBehavior.setHideable(true); //Important to add
mBottomSheetBehavior.setState(BottomSheetBehavior.STATE_HIDDEN); //Important to add

ContentLicense: CC BY-SA 4.0


问:
Have no idea how to get an average from a text file
I am trying to take the average of numbers from a text file and print it. I have gotten as far as getting the numbers to print. I am lost as to how I can assign the values to variables and get the average. The numbers must be formatted like this in the text file:

10 20 30 40 50 60 70 80 90 100 110 120 130 140 150 160 170 180 190 200

```<code>def main():

    numbersFile = open ('numbers.dat', 'r')

    for number in numbersFile:

        print number

main()
</code>```

The expected result is:

```<code>"The average is 105"
</code>```

Any help would be greatly appreciated. I tried to follow posting guidelines but I am new so correct any mistakes I made. Thank you for any help in advance!

答:
You need to parse the numbers, int(number) will do that (if your input file contains one number per line) - then you add the number to a list (define it before the for as allNumbers = [] so you do not reinitialize it all the time to empty list inside the for. append your parsed number to it with allNumbers.append(mynumber).

Outside the for loop you return the numbers in the list:

The avg Function will compute the average (also see: Finding the average of a list )

```<code>def avg(myl):
    return (sum(myl)+0.0) / len(myl)  # + 0.0 needed in 2.x to make it a float

def readNumbersFromFile( filename ):
    '''Function that takes a filepath and parses it. The file is required to
    consist out of integer numbers only - text or floating point numbers
    are not handled and lead to exceptions. The file format allows for
    multiple integer numbers seperated by spaces per line and for multiple
    lines and will parse all numbers into one flat list and return it.'''
    numbersFile = open (filename, 'r') # open file for read
    allNumbers = [] # result list

    for line in numbersFile: # reads one line
        for number in line.split(" "): # splits one line into single numbers
            allNumbers.append(int(number)) # adds each number as integer to list

    return allNumbers # returns the list from this function

nums = readNumbersFromFile(r'numbers.dat')

print("The average is ", avg(nums))
</code>```

My avg-computing uses the build-in sum - you could also compute the avg yourself by adding all elements in the list and dividing by the amount of items in the list

Body:
I am trying to take the average of numbers from a text file and print it. I have gotten as far as getting the numbers to print. I am lost as to how I can assign the values to variables and get the average. The numbers must be formatted like this in the text file:

10 20 30 40 50 60 70 80 90 100 110 120 130 140 150 160 170 180 190 200

def main():

    numbersFile = open ('numbers.dat', 'r')

    for number in numbersFile:

        print number

main()

The expected result is:

"The average is 105"

Any help would be greatly appreciated. I tried to follow posting guidelines but I am new so correct any mistakes I made. Thank you for any help in advance!

Body:
You need to parse the numbers, int(number) will do that (if your input file contains one number per line) - then you add the number to a list (define it before the for as allNumbers = [] so you do not reinitialize it all the time to empty list inside the for. append your parsed number to it with allNumbers.append(mynumber).

Outside the for loop you return the numbers in the list:

The avg Function will compute the average (also see: Finding the average of a list )

def avg(myl):
    return (sum(myl)+0.0) / len(myl)  # + 0.0 needed in 2.x to make it a float

def readNumbersFromFile( filename ):
    '''Function that takes a filepath and parses it. The file is required to
    consist out of integer numbers only - text or floating point numbers
    are not handled and lead to exceptions. The file format allows for
    multiple integer numbers seperated by spaces per line and for multiple
    lines and will parse all numbers into one flat list and return it.'''
    numbersFile = open (filename, 'r') # open file for read
    allNumbers = [] # result list

    for line in numbersFile: # reads one line
        for number in line.split(" "): # splits one line into single numbers
            allNumbers.append(int(number)) # adds each number as integer to list

    return allNumbers # returns the list from this function

nums = readNumbersFromFile(r'numbers.dat')

print("The average is ", avg(nums))

My avg-computing uses the build-in sum - you could also compute the avg yourself by adding all elements in the list and dividing by the amount of items in the list


问:
(basic) Print each letter in Indexing
```<code>a = 'Hello World!'
print(a[0])
</code>```

then I will get 'H'.

But is there any way I can get all the letters inside a seperately without typing print many times?

答:
This code:

```<code>a = 'Hello World!'
print(*a, sep=" ")
</code>```

will print:

```<code>H e l l o   W o r l d !
</code>```

This code:

```<code>a = 'Hello World!'
print(*a, sep="\n")
</code>```

will print:

```<code>H
e
l
l
o

W
o
r
l
d
!
</code>```

Title: (basic) Print each letter in Indexing

Body:
a = 'Hello World!'
print(a[0])

then I will get 'H'.

But is there any way I can get all the letters inside a seperately without typing print many times?

Body:
This code:

a = 'Hello World!'
print(*a, sep=" ")

will print:

H e l l o   W o r l d !

This code:

a = 'Hello World!'
print(*a, sep="\n")

will print:

H
e
l
l
o

W
o
r
l
d
!


问:
Django invite code app recommendation?
I'm looking for a simple Django app that restricts registration to users who have an invite code (for running a private beta). I'm using django-registration, so something that plays nicely with it would be great.

Looks like there are several viable options:

django-inviting

django-privatebeta

django-invite

Given the wealth of options, I'm wondering if people have found a particular app more flexible and/or easier to work with than the others? Are there other apps that I should be aware of?

答:
You miss django-invitation which is really quickly integrated with django-registration.

I just had to hack it a bit to include the name of the inviter in the email message.

ContentLicense: CC BY-SA 2.5

Title: Django invite code app recommendation?


问:
What's Telegram chat memory space limit?
The Telegram has a cloud storage for users self-chat. Limit for uploading files - 1.5GB, yeah, I know about it. But I didn't find something about space limit for a chat. Is it unlimited? I mean, if yes, I can create Telegram-bot for cloud storage? Just, I have more than 20TB files and can I use Telegram for my site files storage and don't be afraid for safety/keeping?</p>

答:
Telegram didn't limit your total storage in each chat.

You can use bots to upload and download files, but it has size limit.


问:
Exclude outliers in python
I have a list of numbers here which needs to be processed before finding the number/numbers which best explains the variance. In this case, it is very obvious that the 1b and -1b should be removed because they skew the data's std dev. After excluding, we see that -998,523 and -2,000,126 should be selected as they can explain 99% of the sum of the remaining figures. edit these 2 numbers are what I'm looking for; they should not be excluded

Question here is what is the best way to exclude outliers? I'm thinking of K-nearest neighbours but it seems like an overkill. Tried IQR, doesn't seem to work well.

Thanks in advance!

```<code> 1,000,000,000
 4                0%
 41               0%
 20               0%
-89               0%
-441              0%
-100,005          3%
-998,523          33%
-2,000,126        66%
 51,651          -2%
 5,176            0%
-1,000,000,000
</code>```

Title: Exclude outliers in python

Body:
I have a list of numbers here which needs to be processed before finding the number/numbers which best explains the variance. In this case, it is very obvious that the 1b and -1b should be removed because they skew the data's std dev. After excluding, we see that -998,523 and -2,000,126 should be selected as they can explain 99% of the sum of the remaining figures. edit these 2 numbers are what I'm looking for; they should not be excluded

Question here is what is the best way to exclude outliers? I'm thinking of K-nearest neighbours but it seems like an overkill. Tried IQR, doesn't seem to work well.

Thanks in advance!

 1,000,000,000
 4                0%
 41               0%
 20               0%
-89               0%
-441              0%
-100,005          3%
-998,523          33%
-2,000,126        66%
 51,651          -2%
 5,176            0%
-1,000,000,000

Body:
You could select the largest outlier as the value the most distant from the average; remove this value, and find the next largest outlier, etc...

def largest_outlier(nums):

    avg = sum(nums) / len(nums)
    delta = [abs(num-avg) for num in nums]
    outlier = max(nums, key=lambda x=delta: abs(x))

    return outlier

nums = [4 ,41, 20, -89, -441, -100005, -998523, -2000126 , 51651, 5176]
numbers = nums[:]

while numbers:
    outlier = largest_outlier(numbers)
    numbers.pop(numbers.index(outlier))
    print(outlier, numbers)

output:

-2000126 [4, 41, 20, -89, -441, -100005, -998523, 51651, 5176]
-998523 [4, 41, 20, -89, -441, -100005, 51651, 5176]
-100005 [4, 41, 20, -89, -441, 51651, 5176]
51651 [4, 41, 20, -89, -441, 5176]
5176 [4, 41, 20, -89, -441]
-441 [4, 41, 20, -89]
-89 [4, 41, 20]
41 [4, 20]
20 [4]
4 []


问:
CONVERT ASP TO ASP.NET
Which is the best way to convert a .asp page to .aspx? Classic asp to asp.net.
I'm trying to avoid rewriting all the pages from scratch.

Thanks

答: It really depends on a lot of things.  Mainly, how complicated the page is, and what it does.  You will need to be a little more specific in your question, but there really isn't any single "one shot" solution.</p>

Title: CONVERT ASP TO ASP.NET


问:
Increment value in the list based on condition
I am preparing code for my personal use which will based on historical lottery numbers give percentage part in each group of numbers. I have divided set of lottery available numbers into three groups:

first_group = [1,2,3,4,5,6,17,18,19,20,21,33,34,35,36,37]
second_group = [7,8,9,10,11,12,22,23,24,25,26,38,39,40,41,42]
third_group = [13,14,15,16,27,28,29,30,31,32,43,44,45,46,47,48,49]

original numbers.txt contain database of all lotteries from the begin

```<code>my_list = []

with open('original numbers.txt') as f:
   lines=f.readlines()
   for line in lines:
       my_array = np.fromstring(line, dtype=int, sep=' ')
       my_list.append(my_array)``
</code>```

Code loop through each line of file and assign 1,2,3 value depends on which group it belongs to.

for line in my_list:
    for num in line:
        if num in first_group:
            new_set.append(1)
        elif num in second_group:
            new_set.append(2)
        elif num in third_group:
            new_set.append(3)

Now the part where I can't go further. I have set conditions if sum of 1,2,3 in each lottery draw is greater than 4 it will increase dash value which is denominator for each group to count percentage value.

```<code>count = Counter(new_set)

'''example
   5    21  28  31  33  41
   1     1   3   3   1   2'''

if count[1] == 4:
    rash_one += 1
    for x,y in line,new_set:
        if y == 1:

elif count[2] == 4:
    rash_two +=1
elif count[3] == 4:
    rash_three +=1``
</code>```

What I want to accomplish is to create list or dict for 1-49 numbers and increment them with count value. So for example if there was lottery draws in which dominated mostly first group I have rash_one = 10 and there were number 2 which was drawn 3 times and 17 which was drawn 4 times. So it gives us 30% for nr 2 and 40% for nr 17.

MY CODE (so far):

```<code> import numpy as np
 from collections import Counter

 my_list = []

 with open('original numbers.txt') as f:
    lines=f.readlines()
    for line in lines:
       my_array = np.fromstring(line, dtype=int, sep=' ')
       my_list.append(my_array)

 first_group = [1,2,3,4,5,6,17,18,19,20,21,33,34,35,36,37]
 second_group = [7,8,9,10,11,12,22,23,24,25,26,38,39,40,41,42]
 third_group = [13,14,15,16,27,28,29,30,31,32,43,44,45,46,47,48,49]
 rash_one = 0
 rash_two = 0
 rash_three = 0
 new_set = []

 for line in my_list:
    for num in line:
        if num in first_group:
            new_set.append(1)
        elif num in second_group:
            new_set.append(2)
        elif num in third_group:
           new_set.append(3)

count = Counter(new_set)

'''example
   5    21  28  31  33  41
   1     1   3   3   1   2'''

if count[1] == 4:
    rash_one += 1
    for x,y in line,new_set:
        if y == 1:
        '''stopped here'''

elif count[2] == 4:
    rash_two +=1
elif count[3] == 4:
    rash_three +=1``
</code>```

答:
SOLVED:</p>

```<code>from collections import defaultdict

first_data_group = defaultdict(int)
second_data_group = defaultdict(int)
third_data_group = defaultdict(int)

if count[1] == 4:
    print(new_set)
    rash_one += 1
    for x,y in zip(line,new_set):
        if y == 1:
            first_data_group[x] += 1

elif count[2] == 4:
    rash_two +=1
    for x,y in zip(line,new_set):
        if y == 2:
            second_data_group[x] += 1

elif count[3] == 4:
    rash_three +=1
    for x,y in zip(line,new_set):
        if y == 3:
            third_data_group[x] += 1
</code>```

Body:
I am preparing code for my personal use which will based on historical lottery numbers give percentage part in each group of numbers. I have divided set of lottery available numbers into three groups:

first_group = [1,2,3,4,5,6,17,18,19,20,21,33,34,35,36,37]
second_group = [7,8,9,10,11,12,22,23,24,25,26,38,39,40,41,42]
third_group = [13,14,15,16,27,28,29,30,31,32,43,44,45,46,47,48,49]

original numbers.txt contain database of all lotteries from the begin

my_list = []

with open('original numbers.txt') as f:
   lines=f.readlines()
   for line in lines:
       my_array = np.fromstring(line, dtype=int, sep=' ')
       my_list.append(my_array)``

Code loop through each line of file and assign 1,2,3 value depends on which group it belongs to.

for line in my_list:
    for num in line:
        if num in first_group:
            new_set.append(1)
        elif num in second_group:
            new_set.append(2)
        elif num in third_group:
            new_set.append(3)

Now the part where I can't go further. I have set conditions if sum of 1,2,3 in each lottery draw is greater than 4 it will increase dash value which is denominator for each group to count percentage value.

count = Counter(new_set)

'''example
   5    21  28  31  33  41
   1     1   3   3   1   2'''

if count[1] == 4:
    rash_one += 1
    for x,y in line,new_set:
        if y == 1:

elif count[2] == 4:
    rash_two +=1
elif count[3] == 4:
    rash_three +=1``

What I want to accomplish is to create list or dict for 1-49 numbers and increment them with count value. So for example if there was lottery draws in which dominated mostly first group I have rash_one = 10 and there were number 2 which was drawn 3 times and 17 which was drawn 4 times. So it gives us 30% for nr 2 and 40% for nr 17.

MY CODE (so far):

 import numpy as np
 from collections import Counter

 my_list = []

 with open('original numbers.txt') as f:
    lines=f.readlines()
    for line in lines:
       my_array = np.fromstring(line, dtype=int, sep=' ')
       my_list.append(my_array)

 first_group = [1,2,3,4,5,6,17,18,19,20,21,33,34,35,36,37]
 second_group = [7,8,9,10,11,12,22,23,24,25,26,38,39,40,41,42]
 third_group = [13,14,15,16,27,28,29,30,31,32,43,44,45,46,47,48,49]
 rash_one = 0
 rash_two = 0
 rash_three = 0
 new_set = []

 for line in my_list:
    for num in line:
        if num in first_group:
            new_set.append(1)
        elif num in second_group:
            new_set.append(2)
        elif num in third_group:
           new_set.append(3)

count = Counter(new_set)

'''example
   5    21  28  31  33  41
   1     1   3   3   1   2'''

if count[1] == 4:
    rash_one += 1
    for x,y in line,new_set:
        if y == 1:
        '''stopped here'''

elif count[2] == 4:
    rash_two +=1
elif count[3] == 4:
    rash_three +=1``

Body:
SOLVED:

from collections import defaultdict

first_data_group = defaultdict(int)
second_data_group = defaultdict(int)
third_data_group = defaultdict(int)

if count[1] == 4:
    print(new_set)
    rash_one += 1
    for x,y in zip(line,new_set):
        if y == 1:
            first_data_group[x] += 1

elif count[2] == 4:
    rash_two +=1
    for x,y in zip(line,new_set):
        if y == 2:
            second_data_group[x] += 1

elif count[3] == 4:
    rash_three +=1
    for x,y in zip(line,new_set):
        if y == 3:
            third_data_group[x] += 1


问:
Return array and show without iterating in laravel
I am sending array through the controller in compact.

```<code>    $medicines = Medicine::all()->pluck('medicine_name')->toArray();
    return view('orders.order',compact('medicines'));
</code>```

I want to display array in the blade without iterating,

output should be like $medicines = ['medicine1','medicine2','medicine3']

how to achieve it?

if I return $medicine variable I am getting the expected output how do I pass into the view?

答:
If i'm understanding you...

you can use json_encode to "convert" the array to string and then print it ... ( use the {!!} to print and not {{}} )

in the tempalte add this:

```<code>$medicines = '{! json_encode($medicines) !}'
</code>```

you can event use implode if you want ...

```<code>@php echo '$medicines = '[\''.imlode("', '", $medicines).'\']' @endphp
</code>```

Body:
I am sending array through the controller in compact.

    $medicines = Medicine::all()->pluck('medicine_name')->toArray();
    return view('orders.order',compact('medicines'));

I want to display array in the blade without iterating,

output should be like $medicines = ['medicine1','medicine2','medicine3']

how to achieve it?

if I return $medicine variable I am getting the expected output how do I pass into the view?

Body:
If i'm understanding you...

you can use json_encode to "convert" the array to string and then print it ... ( use the {!!} to print and not {{}} )

in the tempalte add this:

$medicines = '{! json_encode($medicines) !}'

you can event use implode if you want ...

@php echo '$medicines = '[\''.imlode("', '", $medicines).'\']' @endphp


问:
Why is TensorFlow XLA in experimental status
I'm interested in using XLA for the training with the custom Device (FPGA, ...).

However, I learned that XLA is now in experimental status from developer's tutorial.

https://www.tensorflow.org/performance/xla/

I did not get the reason why XLA is in experimental status.

Is there any big issue about XLA except for the performance improvement?

Thanks

答:
XLA is still very new : it was released on March 2017.

As stated of the Tensorflow XLA page :

Note: XLA is experimental and considered alpha. Most use cases will
  not see improvements in performance (speed or decreased memory usage).
  We have released XLA early so the Open Source Community can contribute
  to its development, as well as create a path for integration with
  hardware accelerators.

If it was released, it is because the development team wants the feedback and the contributions of the Open Source community to the project.

This is backed up by this statement on the Google Developpers Blog :

XLA is still in early stages of development. It is showing very
  promising results for some use cases, and it is clear that TensorFlow
  can benefit even more from this technology in the future. We decided
  to release XLA to TensorFlow Github early to solicit contributions
  from the community and to provide a convenient surface for optimizing
  TensorFlow for various computing devices, as well as retargeting the
  TensorFlow runtime and models to run on new kinds of hardware.

So why is it considered experimental ? Simply because there's a lot of use case and hardware that have not been tested. The benchmarks don't always show the expected improvements.

It's possible that you encounter some bugs while using it, and you are encouraged to signal them via the github issue page of the project.


答: init is nothing else then a method to initially prepare the state of your object. In other languages they have similar concepts as Constructors and it's not necessarily needed.

Title: Creating an instance of a class without defining the __init__ function

Body:
I am relativly new to python and I was wondering if you could create an instance of a class without defining the init explicity. Could I call it something else?

First example - with the init method:

class dog:
def __init__(self,name):
    self.name=name
    print('My name is',name)
Bob = dog('Bob')

Second example - without the init method:

class dog:
def init_instance(self,name):
    self.name = name
    print('My name is',name)

Bob = dog('Bob')

In the first example the code works but in the second example I get:

TypeError: object() takes no parameters

So based on this I assume that one has to explicitly call the init method. BUT I have seen code where the init method has not been used, how come?


问:
How would I go about creating a file compressor similar to ZIP archives in a language like C/C++?
So I was thinking of how a .zip archive is structured and then I thought, how could I create my own archive format.</p>

答:
You would want to know what you want to compress. E.G. zip works great for many things, but not so well for audio files. FLAC works well for audio, but poorly on text files ( provided you could find a way to apply it )

Once you had a compression scheme you would allocate the appropriate metadata so you could later decompress the information, followed by the compressed data.

Perhaps you would research A lossless compression method such as Entropy Encoding. You might decided that Arithmetic coding was more optimal than Huffman coding and decide to implement an Arithmetic codec. You might also look at Dictionary encoding if you are more interested in compressing text.

Edit in response to comment

One would have to include the entropy tables decided upon when encoding the data so it could be later decoded.

Take for example JPEG. JPEG uses a Colorspace transformation to YCrCb, Quantization, A Discrete Cosine Transformation, and then uses Huffman coding on the data. The color space transformation metadata is included in the headers. (how many bits per color and how many samples per channel, along with the size of the image. ) The quantization tables are included and an index of which table match which channel. And the used huffman tables to encode the DC and AC Coefficients. The Discrete Cosine Transformation and ZigZag Coefficient pattern is part of the standard. So after De-quantization you must IDCT the information and dezigzag the coefficients.

Basically for JPEG.

Read the given tables in the header.

Figure out the entropy encoded format with the header info about
size and color.

Use the Huffman table to expand the data segment

Dequantize appropriately

IDCT and de zigzag

You would have to make your own standard, figure out the minimum information needed to recover the information and store it in a way readable without knowing details of whats inside.

I don't know about .zip, but I would imagine it would have a couple dictionary tables and a couple entropy tables. You would de-entropy encode the datasegment (which must be somehow determined by standard or marker ), then use a reverse dictionary substitution.


问:
Adding a number generator to Stack Data Structure using enqueue
I'm new to implementing Queues and need some help here for my practice.

Say, that I'm using enqueue to queue 4 people and I want to add a function to the output to display a random number 'x' from 1 to 10, for 4 times, with the following criteria:

if 'x' is between 1-8, then a name will be added to the queue.
If 'x' is 9 or 10, the program will push 'exit' onto a stack data structure and exit the loop of 4 and display all names on the stack with pop method

Also, with the condition to display the max number of names to be 4 and and minimum to be 0.
Then the results will be displayed for the names that have been added to the queue at the output.

How do I add this in?

```<code>import random  # We will need this to generate the random number

class Queue:
    def __init__(self):
        self.container = []

    def isEmpty(self):
        return self.size() == 0

    def enqueue(self, item):
        self.container.append(item)

    def dequeue(self):
        self.container.pop(0)

    def size(self):
        return len(self.container)

    def peek(self) :
        return self.container[0]

q = Queue()
names = ["Same", "Peter", "James", "Daniel"]  # List of possible names
for i in range(0,4):  # for loop 4 times
    rand = random.randint(1, 10)  # Choose a random number
    print("Number Generated:\n" + str(rand))  # Display selected number
    if rand >= 9:  # number is 9 or 10
        break  # Break out of the loop, you can also add other logic here
    else:  # number is less than 9
        q.enqueue(random.choice(names))  # Enqueue a random name
    print(q.items)
</code>```

I am looking to achieve an output like this

```<code>Number generated:
8
Number generated:
3
Number generated:
2
Number generated:
10

Completed.

Names of people added to queue:
#3 - James
#1 - Sam
#2 – Peter
</code>```

答:
It sounds like you want to generate a random number and, if the random number meets certain criteria, enqueue a value, else break the loop.  Using your definition of Queue class, the following should perform this operation:

```<code>import random  # We will need this to generate the random number

q = Queue()  # Initialize the Queue just like you had it
names = ["Same", "Peter", "James", "Daniel"]  # List of possible names
for i in range(0,4):  # for loop 4 times
    rand = random.randint(1, 10)  # Choose a random number
    print("Number Generated:\n" + str(rand))  # Display selected number
    if rand >= 9:  # number is 9 or 10
        break  # Break out of the loop, you can also add other logic here
    else:  # number is less than 9
        q.enqueue(random.choice(names))  # Enqueue a random name
</code>```

Hope this helps with your problem.

Body:
I'm new to implementing Queues and need some help here for my practice.

Say, that I'm using enqueue to queue 4 people and I want to add a function to the output to display a random number 'x' from 1 to 10, for 4 times, with the following criteria:

if 'x' is between 1-8, then a name will be added to the queue.
If 'x' is 9 or 10, the program will push 'exit' onto a stack data structure and exit the loop of 4 and display all names on the stack with pop method

Also, with the condition to display the max number of names to be 4 and and minimum to be 0.
Then the results will be displayed for the names that have been added to the queue at the output.

How do I add this in?

import random  # We will need this to generate the random number

class Queue:
    def __init__(self):
        self.container = []

    def isEmpty(self):
        return self.size() == 0

    def enqueue(self, item):
        self.container.append(item)

    def dequeue(self):
        self.container.pop(0)

    def size(self):
        return len(self.container)

    def peek(self) :
        return self.container[0]

q = Queue()
names = ["Same", "Peter", "James", "Daniel"]  # List of possible names
for i in range(0,4):  # for loop 4 times
    rand = random.randint(1, 10)  # Choose a random number
    print("Number Generated:\n" + str(rand))  # Display selected number
    if rand >= 9:  # number is 9 or 10
        break  # Break out of the loop, you can also add other logic here
    else:  # number is less than 9
        q.enqueue(random.choice(names))  # Enqueue a random name
    print(q.items)

I am looking to achieve an output like this

Number generated:
8
Number generated:
3
Number generated:
2
Number generated:
10

Completed.

Names of people added to queue:
#3 - James
#1 - Sam
#2 – Peter

Body:
It sounds like you want to generate a random number and, if the random number meets certain criteria, enqueue a value, else break the loop.  Using your definition of Queue class, the following should perform this operation:

import random  # We will need this to generate the random number

q = Queue()  # Initialize the Queue just like you had it
names = ["Same", "Peter", "James", "Daniel"]  # List of possible names
for i in range(0,4):  # for loop 4 times
    rand = random.randint(1, 10)  # Choose a random number
    print("Number Generated:\n" + str(rand))  # Display selected number
    if rand >= 9:  # number is 9 or 10
        break  # Break out of the loop, you can also add other logic here
    else:  # number is less than 9
        q.enqueue(random.choice(names))  # Enqueue a random name

Hope this helps with your problem.


问:
how to solve this error Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation:
I create a shopping cart using OOP PHP.When I return a single product information data from database through HTML form to perform edit operation,
I face this type of error

"Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1' in C:\xampp\htdocs\onlineShop\src\Product.php:100 Stack trace: #0 C:\xampp\htdocs\onlineShop\src\Product.php(100): PDO->query('SELECT * FROM t...') #1 C:\xampp\htdocs\onlineShop\views\Product\editProduct.php(18): App\Product->view() #2 {main} thrown in C:\xampp\htdocs\onlineShop\src\Product.php on line 100"

My editProduct file code below that

```<code><?php
  require_once("../../vendor/autoload.php");
  use App\Product;

  $product  = new Product();
  $product->setData($_GET);
  $allData = $product->view();

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Book Title Create Form</title>
</head>
<body>
<div class="container" align="center" id="body">
    <h3>Add Product Information</h3>
</div>
<div align="center" class="container">

    <form action="store.php" method="post" enctype="multipart/form-data" class="form-horizontal">
        <table class="table table-bordered table-responsive">
            <tr>
                <td><label class="control-label"> Product Name:</label></td>
                <td> <input type="text" class="form-control" name="productName" value=""<?php echo $allData->productName;?>""></td>
            </tr>

            <tr>
                <td><label class="control-label">Category :</label></td>
                <td><select name="categoryID" class="form-control">
                        <?php
                        $category = new App\Category();
                        $oneData= $category->index();
                        foreach($oneData as $singleData){

                            ?>
                            <option
                                <?php if($allData->categoryID==$singleData->categoryID){?>
                                      selected ="selected"
                           <?php } ?>
                                value="<?php echo $singleData->categoryID; ?>"><?php echo $singleData->categoryName;?></option>
                        <?php }?>
                    </select>
                </td>
            </tr>

            <tr>
                <td><label class="control-label">Brand :</label> </td>
                <td>
                    <select name="brandID" class="form-control">
                        <?php
                        $brand = new App\Brand();
                        $allData= $brand->index();
                        foreach($allData as $singleData){
                            ?>
                            <option
                                <?php if($allData->brandID==$singleData->brandID){?>
                                    selected ="selected"
                                <?php } ?> value="<?php echo $singleData->brandID;?>"><?php echo $singleData->brandName;?></option>
                        <?php } ?>
                    </select>
                </td>
            </tr>
            <tr>
                <td><label class="control-label">Description:</label></td>
                <td>
                    <textarea name="description" value="<?php echo $allData->description;?>" class="form-control" ></textarea>
                </td>
            </tr>
            <tr>
                <td><label class="control-label">Price:</label></td>
                <td>
                    <input type="text" value="<?php echo $allData->price;?>" id="price" name="price" class="form-control">
                </td>
            </tr>
            <tr>
                <td><label class="control-label">Upload Image :</label> </td>
                <td>
                    <input class="input-group" type="file"  value="<?php echo $allData->image;?>" id="image" name="image" >
                </td>
            </tr>
            <tr>
                <td><label class="control-label">Product Type :</label></td>
                <td>
                    <select class="form-control" name="productType">
                        <option value="0">Featured</option>
                        <option value="1">General</option>
                    </select>
                </td>

            </tr>

        </table>

</div>
<div class="container">
    <input type="submit" value="EDIT" class="btn btn-success">
</div>

</form>
</body>
</html>
de here
</code>```

My view method below like that which is used for viewing single product information to perform edit operation.

```<code>                public function view()
            {

                $sql = "SELECT * FROM tbl_product WHERE productID=".$this->productID;
                $STH = $this->DBH->query($sql);
                $STH->setFetchMode(PDO::FETCH_OBJ);
                return $STH->fetch();
            }
</code>```

Pls  help me to provide solution this type of error.

答:
if productID is an iteger type

```<code> $sql = "SELECT * FROM `tbl_product` WHERE `produt_id`= ".$this->productID;
</code>```

if productID is an VARCHAR OR TEXT type:-

```<code>$sql = 'SELECT * FROM `tbl_product` WHERE `product_id` ="'.$this->productID.'"';
</code>```

Body:
I create a shopping cart using OOP PHP.When I return a single product information data from database through HTML form to perform edit operation,
I face this type of error

"Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1' in C:\xampp\htdocs\onlineShop\src\Product.php:100 Stack trace: #0 C:\xampp\htdocs\onlineShop\src\Product.php(100): PDO->query('SELECT * FROM t...') #1 C:\xampp\htdocs\onlineShop\views\Product\editProduct.php(18): App\Product->view() #2 {main} thrown in C:\xampp\htdocs\onlineShop\src\Product.php on line 100"

My editProduct file code below that

<?php
  require_once("../../vendor/autoload.php");
  use App\Product;

  $product  = new Product();
  $product->setData($_GET);
  $allData = $product->view();

?>
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Book Title Create Form</title>

Add Product Information

    <form action="store.php" method="post" enctype="multipart/form-data" class="form-horizontal">

                 Product Name:
                 <input type="text" class="form-control" name="productName" value=""<?php echo $allData->productName;?>"">

                Category :
                <select name="categoryID" class="form-control">
                        <?php
                        $category = new App\Category();
                        $oneData= $category->index();
                        foreach($oneData as $singleData){

                            ?>
                            <option
                                <?php if($allData->categoryID==$singleData->categoryID){?>
                                      selected ="selected"
                           <?php } ?>
                                value="<?php echo $singleData->categoryID; ?>"><?php echo $singleData->categoryName;?></option>
                        <?php }?>
                    </select>

                Brand :

                    <select name="brandID" class="form-control">
                        <?php
                        $brand = new App\Brand();
                        $allData= $brand->index();
                        foreach($allData as $singleData){
                            ?>
                            <option
                                <?php if($allData->brandID==$singleData->brandID){?>
                                    selected ="selected"
                                <?php } ?> value="<?php echo $singleData->brandID;?>"><?php echo $singleData->brandName;?></option>
                        <?php } ?>
                    </select>

                Description:

                    <textarea name="description" value="<?php echo $allData->description;?>" class="form-control" ></textarea>

                Price:

                    <input type="text" value="<?php echo $allData->price;?>" id="price" name="price" class="form-control">

                Upload Image :

                    <input class="input-group" type="file"  value="<?php echo $allData->image;?>" id="image" name="image" >

                Product Type :

                    <select class="form-control" name="productType">
                        <option value="0">Featured</option>
                        <option value="1">General</option>
                    </select>

    <input type="submit" value="EDIT" class="btn btn-success">

</form>

de here

My view method below like that which is used for viewing single product information to perform edit operation.

                public function view()
            {

                $sql = "SELECT * FROM tbl_product WHERE productID=".$this->productID;
                $STH = $this->DBH->query($sql);
                $STH->setFetchMode(PDO::FETCH_OBJ);
                return $STH->fetch();
            }

Pls  help me to provide solution this type of error.

Body:
if productID is an iteger type

 $sql = "SELECT * FROM `tbl_product` WHERE `produt_id`= ".$this->productID;

if productID is an VARCHAR OR TEXT type:-

$sql = 'SELECT * FROM `tbl_product` WHERE `product_id` ="'.$this->productID.'"';


问:
Right way of determining internet speed in iOS 8
I am following the below code which I copied and converted from a stack overflow question.

I am getting internet speed however I am not sure, If I am doing right thing.

```<code>import UIKit

class ViewController: UIViewController, NSURLConnectionDataDelegate{
var connection:NSURLConnection!
var length:Int!
var startTime:NSDate!

//let kMinimumMegabytesPerSecond: CGFloat = 1

let kMaximumElapsedTime: CGFloat = 2.0

override func viewDidLoad() {
    super.viewDidLoad()
    self.testDownloadSpeed()
    // Do any additional setup after loading the view, typically from a nib.
}

func testDownloadSpeed() {
    var url: NSURL = NSURL(string: "http://thewallpaperhost.com/wp-content/uploads/2014/12/wallpapers-hd-8000-8331-hd-wallpapers.jpg")!
    var request: NSURLRequest = NSURLRequest(URL: url)
    self.startTime = NSDate()
    self.length = 0
    self.connection = NSURLConnection(request: request, delegate: self)
    self.connection.start()
    let delayInSeconds:Int64 =  1000000000  * 2
    var popTime:dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, (Int64)(delayInSeconds ))
    dispatch_after(popTime, dispatch_get_main_queue(), {() -> Void in
       if let conn = self.connection {
            self.connection.cancel()
            self.connection = nil
            self.useOffline()
        }
    })
}

func determineMegabytesPerSecond() -> CGFloat {
    var elapsed: NSTimeInterval
    if (startTime != nil) {
        elapsed = NSDate().timeIntervalSinceDate(startTime)
        var d =  (Double(length) / elapsed)
        var result = CGFloat( d/1024)
        result = result * 0.0078125
        result = result * 0.0009765625
        return result

    }
    return -1
}

func useOnline() {
     NSLog("Successful")
     NSLog("\(determineMegabytesPerSecond())")

}

func useOffline() {

    NSLog("UnSuccessful")
    NSLog("\(determineMegabytesPerSecond())")
}

func connection(connection: NSURLConnection, didReceiveResponse response: NSURLResponse) {
    NSLog("data came")
    self.startTime = NSDate()
}

func connection(connection: NSURLConnection, didFailWithError error: NSError) {
    if let conn = self.connection {
        self.connection = nil
        useOffline()
    }
}

func connectionDidFinishLoading(connection: NSURLConnection) {
    self.connection = nil

    useOnline()
}

func connection(connection: NSURLConnection, didReceiveData data: NSData) {
    self.length  = self.length +  data.length
    NSLog("\(data.length)")
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}
</code>```

I copied the code from below URL. It was in Objective C so I converted the code!

How to detect Network Signal Strength in iOS Reachability

答:
Here is the updated code in Swift 4.0

```<code>class SpeedTest: UIViewController, URLSessionDelegate, URLSessionDataDelegate {

    typealias speedTestCompletionHandler = (_ megabytesPerSecond: Double? , _ error: Error?) -> Void

    var speedTestCompletionBlock : speedTestCompletionHandler?

    var startTime: CFAbsoluteTime!
    var stopTime: CFAbsoluteTime!
    var bytesReceived: Int!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        checkForSpeedTest()

    }

    func checkForSpeedTest() {

        testDownloadSpeedWithTimout(timeout: 5.0) { (speed, error) in
            print("Download Speed:", speed ?? "NA")
            print("Speed Test Error:", error ?? "NA")
        }

    }

    func testDownloadSpeedWithTimout(timeout: TimeInterval, withCompletionBlock: @escaping speedTestCompletionHandler) {

        guard let url = URL(string: "https://images.apple.com/v/imac-with-retina/a/images/overview/5k_image.jpg") else { return }

        startTime = CFAbsoluteTimeGetCurrent()
        stopTime = startTime
        bytesReceived = 0

        speedTestCompletionBlock = withCompletionBlock

        let configuration = URLSessionConfiguration.ephemeral
        configuration.timeoutIntervalForResource = timeout
        let session = URLSession.init(configuration: configuration, delegate: self, delegateQueue: nil)
        session.dataTask(with: url).resume()

    }

    func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
        bytesReceived! += data.count
        stopTime = CFAbsoluteTimeGetCurrent()
    }

    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {

        let elapsed = stopTime - startTime

        if let aTempError = error as NSError?, aTempError.domain != NSURLErrorDomain && aTempError.code != NSURLErrorTimedOut && elapsed == 0  {
            speedTestCompletionBlock?(nil, error)
            return
        }

        let speed = elapsed != 0 ? Double(bytesReceived) / elapsed / 1024.0 / 1024.0 : -1
        speedTestCompletionBlock?(speed, nil)

    }

}
</code>```

Body:
I am following the below code which I copied and converted from a stack overflow question.

I am getting internet speed however I am not sure, If I am doing right thing.

import UIKit

class ViewController: UIViewController, NSURLConnectionDataDelegate{
var connection:NSURLConnection!
var length:Int!
var startTime:NSDate!

//let kMinimumMegabytesPerSecond: CGFloat = 1

let kMaximumElapsedTime: CGFloat = 2.0

override func viewDidLoad() {
    super.viewDidLoad()
    self.testDownloadSpeed()
    // Do any additional setup after loading the view, typically from a nib.
}

func testDownloadSpeed() {
    var url: NSURL = NSURL(string: "http://thewallpaperhost.com/wp-content/uploads/2014/12/wallpapers-hd-8000-8331-hd-wallpapers.jpg")!
    var request: NSURLRequest = NSURLRequest(URL: url)
    self.startTime = NSDate()
    self.length = 0
    self.connection = NSURLConnection(request: request, delegate: self)
    self.connection.start()
    let delayInSeconds:Int64 =  1000000000  * 2
    var popTime:dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, (Int64)(delayInSeconds ))
    dispatch_after(popTime, dispatch_get_main_queue(), {() -> Void in
       if let conn = self.connection {
            self.connection.cancel()
            self.connection = nil
            self.useOffline()
        }
    })
}

func determineMegabytesPerSecond() -> CGFloat {
    var elapsed: NSTimeInterval
    if (startTime != nil) {
        elapsed = NSDate().timeIntervalSinceDate(startTime)
        var d =  (Double(length) / elapsed)
        var result = CGFloat( d/1024)
        result = result * 0.0078125
        result = result * 0.0009765625
        return result

    }
    return -1
}

func useOnline() {
     NSLog("Successful")
     NSLog("\(determineMegabytesPerSecond())")

}

func useOffline() {

    NSLog("UnSuccessful")
    NSLog("\(determineMegabytesPerSecond())")
}

func connection(connection: NSURLConnection, didReceiveResponse response: NSURLResponse) {
    NSLog("data came")
    self.startTime = NSDate()
}

func connection(connection: NSURLConnection, didFailWithError error: NSError) {
    if let conn = self.connection {
        self.connection = nil
        useOffline()
    }
}

func connectionDidFinishLoading(connection: NSURLConnection) {
    self.connection = nil

    useOnline()
}

func connection(connection: NSURLConnection, didReceiveData data: NSData) {
    self.length  = self.length +  data.length
    NSLog("\(data.length)")
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

I copied the code from below URL. It was in Objective C so I converted the code!

How to detect Network Signal Strength in iOS Reachability

Body:
Here is the updated code in Swift 4.0

class SpeedTest: UIViewController, URLSessionDelegate, URLSessionDataDelegate {

    typealias speedTestCompletionHandler = (_ megabytesPerSecond: Double? , _ error: Error?) -> Void

    var speedTestCompletionBlock : speedTestCompletionHandler?

    var startTime: CFAbsoluteTime!
    var stopTime: CFAbsoluteTime!
    var bytesReceived: Int!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        checkForSpeedTest()

    }

    func checkForSpeedTest() {

        testDownloadSpeedWithTimout(timeout: 5.0) { (speed, error) in
            print("Download Speed:", speed ?? "NA")
            print("Speed Test Error:", error ?? "NA")
        }

    }

    func testDownloadSpeedWithTimout(timeout: TimeInterval, withCompletionBlock: @escaping speedTestCompletionHandler) {

        guard let url = URL(string: "https://images.apple.com/v/imac-with-retina/a/images/overview/5k_image.jpg") else { return }

        startTime = CFAbsoluteTimeGetCurrent()
        stopTime = startTime
        bytesReceived = 0

        speedTestCompletionBlock = withCompletionBlock

        let configuration = URLSessionConfiguration.ephemeral
        configuration.timeoutIntervalForResource = timeout
        let session = URLSession.init(configuration: configuration, delegate: self, delegateQueue: nil)
        session.dataTask(with: url).resume()

    }

    func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
        bytesReceived! += data.count
        stopTime = CFAbsoluteTimeGetCurrent()
    }

    func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {

        let elapsed = stopTime - startTime

        if let aTempError = error as NSError?, aTempError.domain != NSURLErrorDomain && aTempError.code != NSURLErrorTimedOut && elapsed == 0  {
            speedTestCompletionBlock?(nil, error)
            return
        }

        let speed = elapsed != 0 ? Double(bytesReceived) / elapsed / 1024.0 / 1024.0 : -1
        speedTestCompletionBlock?(speed, nil)

    }

}


问:
I want to load ajax response data into dropdown
I want to load ajax resonse data into dropdown list. I have one dropdown list on my page. I just want to load ajax response data which will contain list of options into dropdown list.

This is my dropdown.

```<code><select title="Basic example" id="muliSelect6" class="multipleCheckbox" multiple="multiple" name="example-basic6[]" size="5">

</select>
</code>```

I am using the following ajax script :

```<code>         $.ajax({
                url: "GetPerPersonData.php",
                type: "POST",
                data:           {
             building: $('#muliSelect1').val(),wing:$('#muliSelect3').val()

            },
                success: function(data)
                    {
               $("#muliSelect6").html('');
                       $("#muliSelect6").html(data);
                    }

            });
</code>```

I am getting the response as a list of options as following

```<code><option value="yogesh">Yogesh kale</option>
</code>```

But it does not get loaded in dropdown list. So please help me in getting the output correctly.

答:
As an alternative, you can return your data as JSON payload (this might be better option that returning raw HTML) and directly load JSON data into the dropdown:

```<code>success: function(data) {
    $("multiSelect6").view(data)
}
</code>```

You would need to download this library https://github.com/JocaPC/jquery-view-engine/tree/master/src . Take a look at this https://jocapc.github.io/jquery-view-engine/docs/ajax-dropdown for more details.

Body:
I want to load ajax resonse data into dropdown list. I have one dropdown list on my page. I just want to load ajax response data which will contain list of options into dropdown list.

This is my dropdown.

<select title="Basic example" id="muliSelect6" class="multipleCheckbox" multiple="multiple" name="example-basic6[]" size="5">

</select>

I am using the following ajax script :

         $.ajax({
                url: "GetPerPersonData.php",
                type: "POST",
                data:           {
             building: $('#muliSelect1').val(),wing:$('#muliSelect3').val()

            },
                success: function(data)
                    {
               $("#muliSelect6").html('');
                       $("#muliSelect6").html(data);
                    }

            });

I am getting the response as a list of options as following

<option value="yogesh">Yogesh kale</option>

But it does not get loaded in dropdown list. So please help me in getting the output correctly.

Body:
As an alternative, you can return your data as JSON payload (this might be better option that returning raw HTML) and directly load JSON data into the dropdown:

success: function(data) {
    $("multiSelect6").view(data)
}

You would need to download this library https://github.com/JocaPC/jquery-view-engine/tree/master/src . Take a look at this https://jocapc.github.io/jquery-view-engine/docs/ajax-dropdown for more details.


问:
Trying and failing to cast a PSObject to Int32 in PowerShell
Consider:

```<code>$tabName = "EventsTable"
# Create a table object
$table = New-Object system.Data.DataTable "$tabName"

# Define columns
$col1 = New-Object system.Data.DataColumn EventID,([Int32])

$col2 = New-Object system.Data.DataColumn EventDate,([datetime])
$col3 = New-Object system.Data.DataColumn Instances,([Int32])

# Add the columns
$table.Columns.add($col1)
$table.Columns.add($col2)
$table.Columns.add($col3)

# Enter data in the row
$systemEvents = Get-EventLog `
    -newest 1000 `
    -LogName System `
    -EntryType Information `
    -After (Get-Date).AddDays(-3);

for ($i=0; $i -lt 1; $i++) { #$systemEvents.Count
    # Create a row
    $row = $table.NewRow()
    $row.EventID = $systemEvents.Get($i).EventID
}
</code>```

The penultimate line of code fails due to an "Exception setting

```<code> "EventID":
 "Unable to cast object of type 'System.Management.Automation.PSObject' to
 type 'System.IConvertible'.Couldn't store <2010> in EventID Column.
 Expected type is Int32."
</code>```

However if I change this line to...

$systemEvents.Get($i).EventID.GetType()

The output is Int32.

If EventID is a PSObject, how do I get the Int32 out of it? If EventID is an Int32 then what is PowerShell complaining about?

答:
As iRon said, just add [int] or [int32] in front:</p>
```<code>$row.EventID = [int]$systemEvents.Get($i).EventID
</code>```

Body:
Consider:

$tabName = "EventsTable"
# Create a table object
$table = New-Object system.Data.DataTable "$tabName"

# Define columns
$col1 = New-Object system.Data.DataColumn EventID,([Int32])

$col2 = New-Object system.Data.DataColumn EventDate,([datetime])
$col3 = New-Object system.Data.DataColumn Instances,([Int32])

# Add the columns
$table.Columns.add($col1)
$table.Columns.add($col2)
$table.Columns.add($col3)

# Enter data in the row
$systemEvents = Get-EventLog `
    -newest 1000 `
    -LogName System `
    -EntryType Information `
    -After (Get-Date).AddDays(-3);

for ($i=0; $i -lt 1; $i++) { #$systemEvents.Count
    # Create a row
    $row = $table.NewRow()
    $row.EventID = $systemEvents.Get($i).EventID
}

The penultimate line of code fails due to an "Exception setting

 "EventID":
 "Unable to cast object of type 'System.Management.Automation.PSObject' to
 type 'System.IConvertible'.Couldn't store <2010> in EventID Column.
 Expected type is Int32."

However if I change this line to...

$systemEvents.Get($i).EventID.GetType()

The output is Int32.

If EventID is a PSObject, how do I get the Int32 out of it? If EventID is an Int32 then what is PowerShell complaining about?

Body:
As iRon said, just add [int] or [int32] in front:

$row.EventID = [int]$systemEvents.Get($i).EventID


问:
Remove nodes after filtering
So I am making a Gephi graph and wants to make some subgraphs using filters.

After filtering the nodes using intra edges(based in group) I get some lonely nodes, so I want to remove them: Library->Topology-> Degree range

So theoretically, all those unused nodes should be removed.

But because degree range still stays at 1-32, and no 0 is found, I can't remove the nodes.

I tried different combinations but it just doesn't work somehow. Here is one of the nodes I want to remove because it has 0 in and out degree

答:
Tough one because you need to recompute degrees for the filtered graph. I would recommend the following approach:

Copy your current degree columns to something like [in|out|degree]_global so that they don't get overwritten by step 2

Copy your filtered graph to a new workspace (or save the visible graph only)

Recompute the degrees on the filtered graph

Filter by range as you do now

Title: Remove nodes after filtering


问:
3 Collection Views on One View Controller
I have 3 collection views on 1 view controller.  I've tried a few of the other suggestions I've found on Stack but nothing seems to work.

All 3 Collection Views are in a separate cell of a HomeTableViewController.  I tried to create the outlet connection to the HomeTableViewController but I get the error Outlets cannot be connected to repeating content.

I've read many people being able to hook up their multiple collectionViews so I am a bit confused as to where I'm going wrong...

答:
The UICollectionView instances cannot be hooked up to IBOutlet properties in a separate UITableViewController.

As you describe, the UICollectionViews are actually each children of their own parent UITableViewCell, and as such are not direct descendants of the UITableViewController. This is because the cells will be added to the UITableView at run time.

If you are set on creating the outlets within the HomeTableViewController I would suggest creating them like so:

private weak var collectionViewA: UICollectionView?

and overriding cellForRow like so:

```<code>override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = super.tableView(tableView, cellForRowAt: indexPath)
    // cast cell as collection view parent
    collectionViewA = cell.collectionView
    return cell
}
</code>```

As has been mentioned, the better solution would be to manage the UICollectionView instances from within their own UITableViewCell parents. Example:

```<code>final class CollectionViewAParentTableViewCell: UITableViewCell {
    @IBOutlet private weak var collectionView: UICollectionView!
}
extension CollectionViewAParentTableViewCell: UICollectionViewDataSource {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        …
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        …
    }
}
</code>```

Body:
The UICollectionView instances cannot be hooked up to IBOutlet properties in a separate UITableViewController.

As you describe, the UICollectionViews are actually each children of their own parent UITableViewCell, and as such are not direct descendants of the UITableViewController. This is because the cells will be added to the UITableView at run time.

If you are set on creating the outlets within the HomeTableViewController I would suggest creating them like so:

private weak var collectionViewA: UICollectionView?

and overriding cellForRow like so:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = super.tableView(tableView, cellForRowAt: indexPath)
    // cast cell as collection view parent
    collectionViewA = cell.collectionView
    return cell
}

As has been mentioned, the better solution would be to manage the UICollectionView instances from within their own UITableViewCell parents. Example:

final class CollectionViewAParentTableViewCell: UITableViewCell {
    @IBOutlet private weak var collectionView: UICollectionView!
}
extension CollectionViewAParentTableViewCell: UICollectionViewDataSource {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        …
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        …
    }
}


问:
Improve performance - perhaps parallel implementation
We have a Visual Studio 2017 extension, which creates a solution in VS, loads files from the database into the created project and then compiles it.

This takes a couple of minutes, and I want to do it faster.
I know there are tools out there, I just don't know what to google for exactly.
So I don't expect someone to re-write my code (although a quick example would be great!) but some guidance as to what I could use would be very helpful.

So here we have the method that creates the solution and takes care of loading the files from the database into it:

```<code>public void LoadFilesIntoVS()
    {
        CreateSolution();
        LoadCalcFiles();
        LoadTemplateFiles();
        LoadAdvancedCalcFiles();
        LoadOtherFilesIntoSolution();
    }
</code>```

The four LoadXYZ methods are similar, so I will just continue with an example of LoadCalcFiles().

```<code>public void LoadCalcFiles()
    {
        CalcFilesList = new ObservableCollection<CalcFile>(BuilderService.GetAllCalcFiles());

        foreach (CalcFile file in CalcFilesList)
        {
            LoadCalcFileIntoSolution(file);
        }
    }
</code>```

LoadCalcFileIntoSolution:

```<code>private void LoadCalcFileIntoSolution(CalcFile file)
    {
        try
        {
        string sourcePath = BuilderService.GetCalcFileSourcePath(file.ID);
        string fullName = sourcePath.Substring(sourcePath.LastIndexOf("\\") + 1);
        if (!calcObjects.ContainsKey(fullName))
        {

            if (!File.Exists(sourcePath))
            {
                BuilderService.GenerateCalcFileMethod(file.ID);
            }

            ProjectItem calcFile = LoadAsProjectItem(sourcePath);
            calcObjects.Add(fullName, file);
        }
      }
        catch (Exception e)
        {
            SetErrorStatus("Problem loading CalcFile into Solution. " + e.Message);
        }
    }
</code>```

So yes, I've heard of a parallel foreach. Would it be beneficial to use that in LoadCalcFiles?
Also, could I somehow run the four LoadXYZ methods at the same time after creating the solution?

答:
The easiest change to LoadFilesIntoVS() could be:

```<code>    Parallel.Invoke(
        () => CreateSolution(),
        () => LoadCalcFiles(),
        () => LoadTemplateFiles(),
        () => LoadAdvancedCalcFiles(),
        () => LoadOtherFilesIntoSolution()
    );
</code>```

this way you keep int synchronous.

But are all files used up front? Else you should consider Lazy<CalcFile> in your CalcFilesList, so files are first loaded when used first time. It is threadsafe, and you bootstrap time will be close to zero.

Body:
We have a Visual Studio 2017 extension, which creates a solution in VS, loads files from the database into the created project and then compiles it.

This takes a couple of minutes, and I want to do it faster.
I know there are tools out there, I just don't know what to google for exactly.
So I don't expect someone to re-write my code (although a quick example would be great!) but some guidance as to what I could use would be very helpful.

So here we have the method that creates the solution and takes care of loading the files from the database into it:

public void LoadFilesIntoVS()
    {
        CreateSolution();
        LoadCalcFiles();
        LoadTemplateFiles();
        LoadAdvancedCalcFiles();
        LoadOtherFilesIntoSolution();
    }

The four LoadXYZ methods are similar, so I will just continue with an example of LoadCalcFiles().

public void LoadCalcFiles()
    {
        CalcFilesList = new ObservableCollection<CalcFile>(BuilderService.GetAllCalcFiles());

        foreach (CalcFile file in CalcFilesList)
        {
            LoadCalcFileIntoSolution(file);
        }
    }

LoadCalcFileIntoSolution:

private void LoadCalcFileIntoSolution(CalcFile file)
    {
        try
        {
        string sourcePath = BuilderService.GetCalcFileSourcePath(file.ID);
        string fullName = sourcePath.Substring(sourcePath.LastIndexOf("\\") + 1);
        if (!calcObjects.ContainsKey(fullName))
        {

            if (!File.Exists(sourcePath))
            {
                BuilderService.GenerateCalcFileMethod(file.ID);
            }

            ProjectItem calcFile = LoadAsProjectItem(sourcePath);
            calcObjects.Add(fullName, file);
        }
      }
        catch (Exception e)
        {
            SetErrorStatus("Problem loading CalcFile into Solution. " + e.Message);
        }
    }

So yes, I've heard of a parallel foreach. Would it be beneficial to use that in LoadCalcFiles?
Also, could I somehow run the four LoadXYZ methods at the same time after creating the solution?

Body:
The easiest change to LoadFilesIntoVS() could be:

    Parallel.Invoke(
        () => CreateSolution(),
        () => LoadCalcFiles(),
        () => LoadTemplateFiles(),
        () => LoadAdvancedCalcFiles(),
        () => LoadOtherFilesIntoSolution()
    );

this way you keep int synchronous.

But are all files used up front? Else you should consider Lazy<CalcFile> in your CalcFilesList, so files are first loaded when used first time. It is threadsafe, and you bootstrap time will be close to zero.