问:
Messages are not delivered with kafka python
I'm trying to set up a simple Kafka application with kafka-python. I've been trying to get some of the examples I found online to work but can't seem to make it. I have a kafka instance running in a docker container. I tested the shell tools and the instance is definitely working. I am able to send and receive messages. I suspect that the producer messages time out. Here are two versions of the code with basically the same behaviour:

```<code>import time
from kafka import SimpleProducer, KafkaClient
#  connect to Kafka
kafka = KafkaClient('localhost:9092')
producer = SimpleProducer(kafka)
# Assign a topic
topic = 'test'
producer.send_messages(topic, b'this is a message')
</code>```

And the second version:

```<code>from kafka import KafkaProducer
from kafka.errors import KafkaError

producer = KafkaProducer(bootstrap_servers=['0.0.0.0:9092'], api_version=(0,10))
topic = "test"

producer.send(topic, b'test message')
</code>```

答:
It depends on how you ran docker but I believe your issue is with the host name you're trying to connect to. You need to point to the host set in the ADVERTISED_HOST environment variable. For example when I run kafka-docker as docker run --hostname kafka-1 -p 2181:2181 -p 9092:9092 --env ADVERTISED_HOST='kafka-1' --env ADVERTISED_PORT=9092 spotify/kafka I produce to kafka like such

```<code>from kafka import SimpleProducer, KafkaClient

kafka = KafkaClient('kafka-1:9092')
producer = SimpleProducer(kafka)
topic = 'test'
for i in range(100):
    producer.send_messages(topic, 'hullo-' + str(i))
</code>```

additionally I needed to add 127.0.0.1 kafka-1 to my /etc/hosts file. After doing this I was able to consume the messages produced by the python client with bin/kafka-console-consumer.sh --bootstrap-server kafka-1:9092 --topic test --from-beginning

Body:
I'm trying to set up a simple Kafka application with kafka-python. I've been trying to get some of the examples I found online to work but can't seem to make it. I have a kafka instance running in a docker container. I tested the shell tools and the instance is definitely working. I am able to send and receive messages. I suspect that the producer messages time out. Here are two versions of the code with basically the same behaviour:

import time
from kafka import SimpleProducer, KafkaClient
#  connect to Kafka
kafka = KafkaClient('localhost:9092')
producer = SimpleProducer(kafka)
# Assign a topic
topic = 'test'
producer.send_messages(topic, b'this is a message')

And the second version:

from kafka import KafkaProducer
from kafka.errors import KafkaError

producer = KafkaProducer(bootstrap_servers=['0.0.0.0:9092'], api_version=(0,10))
topic = "test"

producer.send(topic, b'test message')

Body:
It depends on how you ran docker but I believe your issue is with the host name you're trying to connect to. You need to point to the host set in the ADVERTISED_HOST environment variable. For example when I run kafka-docker as docker run --hostname kafka-1 -p 2181:2181 -p 9092:9092 --env ADVERTISED_HOST='kafka-1' --env ADVERTISED_PORT=9092 spotify/kafka I produce to kafka like such

from kafka import SimpleProducer, KafkaClient

kafka = KafkaClient('kafka-1:9092')
producer = SimpleProducer(kafka)
topic = 'test'
for i in range(100):
    producer.send_messages(topic, 'hullo-' + str(i))

additionally I needed to add 127.0.0.1 kafka-1 to my /etc/hosts file. After doing this I was able to consume the messages produced by the python client with bin/kafka-console-consumer.sh --bootstrap-server kafka-1:9092 --topic test --from-beginning


来源: stackexchange

问:
Changing Placeholder Text Color with Swift
I have a design that implements a dark blue UITextField, as the placeholder text is by default a dark grey colour I can barely make out what the place holder text says.

I've googled the problem of course but I have yet to come up with a solution while using the Swift language and not Obj-c.

Is there a way to change the placeholder text colour in a UITextField using Swift?

答:
For Swift

```<code>func setPlaceholderColor(textField: UITextField, placeholderText: String) {
    textField.attributedPlaceholder = NSAttributedString(string: placeholderText, attributes: [NSForegroundColorAttributeName: UIColor.pelorBlack])
}
</code>```

You can use this;

```<code>self.setPlaceholderColor(textField: self.emailTextField, placeholderText: "E-Mail/Username")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
For Swift

func setPlaceholderColor(textField: UITextField, placeholderText: String) {
    textField.attributedPlaceholder = NSAttributedString(string: placeholderText, attributes: [NSForegroundColorAttributeName: UIColor.pelorBlack])
}

You can use this;

self.setPlaceholderColor(textField: self.emailTextField, placeholderText: "E-Mail/Username")

ContentLicense: CC BY-SA 3.0


问:
kendo proggressbar required script files
as mentioned in kendo references

http://docs.telerik.com/kendo-ui/intro/installation/what-you-need#individual-scripts

we can add specific script files for a component . so i want to do this because kendo.all.min.js is a big file and i don't need other stuff . and they don't mentioned progress bar files.

i tried adding:

```<code>/kendo/kendo.progressbar.min.js
</code>```

but seems like it is not enough.

anyone knows about its required script files?

答:
You also need jquery and kendo.core:

```<code><script src="https://kendo.cdn.telerik.com/2017.2.621/js/jquery.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2017.2.621/js/kendo.core.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2017.2.621/js/kendo.progressbar.min.js"></script>
</code>```

http://docs.telerik.com/kendo-ui/intro/supporting/scripts-interactivity

Body:
as mentioned in kendo references

http://docs.telerik.com/kendo-ui/intro/installation/what-you-need#individual-scripts

we can add specific script files for a component . so i want to do this because kendo.all.min.js is a big file and i don't need other stuff . and they don't mentioned progress bar files.

i tried adding:

/kendo/kendo.progressbar.min.js

but seems like it is not enough.

anyone knows about its required script files?

Body:
You also need jquery and kendo.core:

<script src="https://kendo.cdn.telerik.com/2017.2.621/js/jquery.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2017.2.621/js/kendo.core.min.js"></script>
<script src="https://kendo.cdn.telerik.com/2017.2.621/js/kendo.progressbar.min.js"></script>

http://docs.telerik.com/kendo-ui/intro/supporting/scripts-interactivity


问:
iPad Kiosk application // Guided Access and empty Battery
We want to use iPads with iOS7 for an POS/Kiosk application. We use the guided access mode to restrict the customers to one app. The store will shut down the power during weekends, so the iPads will run out of battery. This raises several questions:

Is there a way to send an ipad to sleep mode and awake them programmatically? So that the iPad battery might last a complete weekend without power?

What will happen when the power resumes, if the ipad blacked out?

Will the last run app be resumed in guided access mode?

Any help is appreciated! Thanks for your help!

Chris

答:
Alright, after quite some time I can give an update on this. The way we used in the end was a MDM solution (mobile device management). We had less then 100 devices to manage, so we use the free version of meraki (https://meraki.cisco.com/). Which is an awesome tool. With Meraki you are able to remotely to install certificates, that lock the iPad completely.

In a way, that if you don't have Wifi / Internet on the iPads, you cannot remove the lock, without resetting the iPad completely.

Coming back to the original question, the iPads run on battery until they die in the morning. And they are charged throughout the day. So it's a complete load / discharge cycle everyday. Since there is no way of changing this, we stopped to deploy iPads for POS in-store projects and switched to Android devices like without battery.

Hope this helps someone!


问:
Saving nested relation in laravel elequent?
I have 2 tables and three relationship,

first, award table,

Award criteria,

Here criteria table self joined,

When saving the award in database,

Now I am saving as follows,

```<code>$award->save();
foreach ($request->criterias as $key => $row) {
            $criteria = new AwardCriteria();
            $criteria->title = $row['title'];
            $criteria->mark = $row['mark'];
            $criteria->save();
            foreach ($row['sub_criterias'] as $row2) {
                $subCrt = new AwardCriteria();
                $subCriteria->award_id = $award->id;
                $subCriteria->award_criteria_id = $criteria->id;
                $subCrt->title = $row2['title'];
                $subCrt->mark = $row2['mark'];
                $subCrt->save();
            }
        }
</code>```

I can do it this way also,

```<code>  $award->save();
  $award->criteria()->saveMany($criteria);
</code>```

But here How can save sub critirea's? Can you please anyone suggest good method?

答: You can actually listen for saving events on a model and trigger an action. This post has some good examples around that.</p>

Body:
I have 2 tables and three relationship,

first, award table,

Award criteria,

Here criteria table self joined,

When saving the award in database,

Now I am saving as follows,

$award->save();
foreach ($request->criterias as $key => $row) {
            $criteria = new AwardCriteria();
            $criteria->title = $row['title'];
            $criteria->mark = $row['mark'];
            $criteria->save();
            foreach ($row['sub_criterias'] as $row2) {
                $subCrt = new AwardCriteria();
                $subCriteria->award_id = $award->id;
                $subCriteria->award_criteria_id = $criteria->id;
                $subCrt->title = $row2['title'];
                $subCrt->mark = $row2['mark'];
                $subCrt->save();
            }
        }

I can do it this way also,

  $award->save();
  $award->criteria()->saveMany($criteria);

But here How can save sub critirea's? Can you please anyone suggest good method?


问:
C# - StreamReader ReadToEnd - WebException: The request was aborted: The request was canceled
My app produces the following error randomly. I havent been able to re-produce it on my machine, but on users who have installed it, it happens to them.

```<code>System.Net.WebException: The request was aborted: The request was canceled.
   at System.Net.ConnectStream.Read(Byte[] buffer, Int32 offset, Int32 size)
   at System.IO.StreamReader.ReadBuffer()
   at System.IO.StreamReader.ReadToEnd()
</code>```

Whats odd is, ReadToEnd() cant product a WebException error (Found out by hovering over it and seeing what type of exceptions it can cause), yet from this Crash Dump it is?, To make sure I even put a WebException try catch and it still happens.

I read online a tiny bit and see it might be caused by ServicePointManager.DefaultConnectionLimit so I added that in with 1000 int value, and now im not sure if it fixed it - I havent seen any reports, but that doesnt mean its not happening.

```<code>using (HttpWebResponse resp = (HttpWebResponse)r.GetResponse())
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
    string s = "";
    try { s = sr.ReadToEnd(); }
    catch (IOException) { return "2"; }
    catch (WebException) { return "2"; }
}
</code>```

This is the code im using, if needed, I can provide r's values. Just know that I use quite a lot.

EDIT: I can confirm on the client's side that even with the ServicePointManager.DefaultConnectionLimit set to 1000 it still occurs.

答:
Found out what managed to fix it, no idea WHY, but this works:

```<code>try
{
    using (HttpWebResponse resp = httpparse.response(r))
    {
        if(resp != null)
        {
            using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
            {
                string s = "";
                try { s = sr.ReadToEnd(); }
                catch (IOException) { return "2"; }
            }
        } else
        {
            return "2";
        }
    }
}
catch (WebException)
{
    return "2";
}
</code>```

Makes no sense, the error occurs at sr.ReadToEnd(), yet putting the Try Catch over the response() makes it fixed?

Body:
My app produces the following error randomly. I havent been able to re-produce it on my machine, but on users who have installed it, it happens to them.

System.Net.WebException: The request was aborted: The request was canceled.
   at System.Net.ConnectStream.Read(Byte[] buffer, Int32 offset, Int32 size)
   at System.IO.StreamReader.ReadBuffer()
   at System.IO.StreamReader.ReadToEnd()

Whats odd is, ReadToEnd() cant product a WebException error (Found out by hovering over it and seeing what type of exceptions it can cause), yet from this Crash Dump it is?, To make sure I even put a WebException try catch and it still happens.

I read online a tiny bit and see it might be caused by ServicePointManager.DefaultConnectionLimit so I added that in with 1000 int value, and now im not sure if it fixed it - I havent seen any reports, but that doesnt mean its not happening.

using (HttpWebResponse resp = (HttpWebResponse)r.GetResponse())
using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
{
    string s = "";
    try { s = sr.ReadToEnd(); }
    catch (IOException) { return "2"; }
    catch (WebException) { return "2"; }
}

This is the code im using, if needed, I can provide r's values. Just know that I use quite a lot.

EDIT: I can confirm on the client's side that even with the ServicePointManager.DefaultConnectionLimit set to 1000 it still occurs.

Body:
Found out what managed to fix it, no idea WHY, but this works:

try
{
    using (HttpWebResponse resp = httpparse.response(r))
    {
        if(resp != null)
        {
            using (StreamReader sr = new StreamReader(resp.GetResponseStream()))
            {
                string s = "";
                try { s = sr.ReadToEnd(); }
                catch (IOException) { return "2"; }
            }
        } else
        {
            return "2";
        }
    }
}
catch (WebException)
{
    return "2";
}

Makes no sense, the error occurs at sr.ReadToEnd(), yet putting the Try Catch over the response() makes it fixed?


问:
Get the count of nested ng-repeat in the outermost ng-repeat and update in dynamically according to ng-model value
I have three nested ng-repeat to display the drives their corresponding folders and their corresponding files. A sample data is shown below

```<code>Drives=[
   {
      name:'C Drive',
      folders:[
         {
            name:'personal',
            files:[
               {
                  name:'a.txt'
               },
               {
                  name:'b.txt'
               }
            ]
         }
      ]
   }
]
</code>```

So I have three nested ng-repeat to display the drive name, its folders and the files in the folders.
How to get the total number of files in a drive and display it along the drive name.

Sample code

```<code><div ng-repeat="drive in drives">
{{drive.name}} <I want the total count of files in a drive here>
    <div ng-repeat="folder in drive.folders">
    {{folder.name}} {{filteredfiles.length}}
        <div ng-repeat="file in filteredfiles=(folder.files | filter
        {name:search})">
        {{file.name}}
        </div>
    </div>
</div>
<input type="text" ng-model="search"/>
</code>```

Note that I have a search filter so the number of files in a drive should get updated dynamically according to the filter value applied to denote the number of files with the same name as the search value in a particular drive.

How to incrementally count the number of files in a drive and apply two way binding such that the count gets updated according to the search value ?

For Angular version 1.6

答:
There's two ways to handle this. If using components and the components are appropriately nested, as they should be, you can simply hand down a variable in your child component definition as such:

```<code>.component('ComponentName', {
    bindings: {
          myVariable: '=' //Look up the appropriate sigil for the binding behavior you want
        },
`//....rest of component def here

    })
</code>```

Then you would simply hand it down through your directive that you've made in your router (or when you instantiate the component)

```<code><my-directive my-variable="$ctrl.myVariable"></my-directive>
</code>```

Example: https://toddmotto.com/one-way-data-binding-in-angular-1-5/

Alternatively, you would just make a service and have it be a dependency in both controllers and set the value there through getters/setters, since services are singleton and can maintain the value between controllers.

Body:
I have three nested ng-repeat to display the drives their corresponding folders and their corresponding files. A sample data is shown below

Drives=[
   {
      name:'C Drive',
      folders:[
         {
            name:'personal',
            files:[
               {
                  name:'a.txt'
               },
               {
                  name:'b.txt'
               }
            ]
         }
      ]
   }
]

So I have three nested ng-repeat to display the drive name, its folders and the files in the folders.
How to get the total number of files in a drive and display it along the drive name.

Sample code

{{drive.name}}

    {{folder.name}} {{filteredfiles.length}}

        {{file.name}}

<input type="text" ng-model="search"/>

Note that I have a search filter so the number of files in a drive should get updated dynamically according to the filter value applied to denote the number of files with the same name as the search value in a particular drive.

How to incrementally count the number of files in a drive and apply two way binding such that the count gets updated according to the search value ?

For Angular version 1.6

Body:
There's two ways to handle this. If using components and the components are appropriately nested, as they should be, you can simply hand down a variable in your child component definition as such:

.component('ComponentName', {
    bindings: {
          myVariable: '=' //Look up the appropriate sigil for the binding behavior you want
        },
`//....rest of component def here

    })

Then you would simply hand it down through your directive that you've made in your router (or when you instantiate the component)

<my-directive my-variable="$ctrl.myVariable"></my-directive>

Example: https://toddmotto.com/one-way-data-binding-in-angular-1-5/

Alternatively, you would just make a service and have it be a dependency in both controllers and set the value there through getters/setters, since services are singleton and can maintain the value between controllers.


问:
Reliable timer in a console application
I am aware that in .NET there are three timer types (see Comparing the Timer Classes in the .NET Framework Class Library). I have chosen a threaded timer as the other types can drift if the main thread is busy, and I need this to be reliable.

The way this timer works in the control of the timer is put on another thread so it can always tick along with the work begin completed on the parent thread when it is not busy.

The issue with this timer in a console application is that while the timer is ticking along on another thread the main thread is not doing anything to the application closes.

I tried adding a while true loop, but then the main thread is too busy when the timer does go off.

答: You can use something like Console.ReadLine() to block the main thread, so other background threads (like timer threads) will still work. You may also use an AutoResetEvent to block the execution, then (when you need to) you can call Set() method on that AutoResetEvent object to release the main thread. Also ensure that your reference to Timer object doesn't go out of scope and garbage collected.

Title: Reliable timer in a console application

LastEditorDisplayName: Jim Anderson

LastEditorDisplayName: huseyint


问:
Can a piece of code, if reusable and applicable to different contexts be classified a pattern?
What constitutes a pattern ? If i have a template/code that is reusable and can be applied to other similar situations, can it be called a pattern ?

The following is what i have created. It is a binary approach to handling conditional constructs. I have a field in a table that is composite i.e. it comprises of 3 or more other sub-fields each of which have a true or false value.

Now, i have the sub-fields representing true/false values as 0 and 1. These fields are presented as drop downs to the user in the web based application. These fields are combined to form a byte value comprising 8 bits with the first 3 bits have values of 0 or 1 which the user chooses as false or true. If the user chooses all fields as true the main field would have a value 7 and if he chooses all fields as false, the main field would have a value 0 and like wise.

The main field represents one of the columns in an existing table. The advantage of this code is that, as new sub-fields are required, there is no need to add new columns in the table. The user interface would have an additional drop down for each new sub-field.

This code is reusable and can be applied to different contexts. Could this be classified as a pattern ?

答:
Not really. A pattern is a solution, a way to approach a common programming problem, and not a piece of code.

What you're describing is better named a module or a library (or even a function/subroutine) that does something.

OwnerDisplayName: Subramanian

LastEditorDisplayName: Binary Worrier

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: MaxVT


问:
bison: How does one solve the Varname&Varname reduce/reduce problem?
Lets say you are writing a C++ like language and you allow references

```<code>int& i
</code>```

You also allow bitwise ands

```<code>7&5
</code>```

How do you solve reduce/reduce conflicts? I dont mean use the glr-parser but have no conflicts at all. Example syntax problem is

```<code>var&var //could be type& var or logical val & val
</code>```

答:
You could tell flex to return a different token for the literal & depending on what has been "lexed" before. So you end up with two rules:

```<code><type> T_AMPERSAND <identifier>
</code>```

and

```<code><expression> T_LOGIC_AND <expression>
</code>```

If your new language supports user defined types, the lexer will not know whether or not it had just found a <type> or an <identifier>, though. In that case you might want to make sure that <type> '&' <identifier> is regarded a valid standalone statement whereas <expression> '&' <expression> can only appear as an rvalue (at right right side of an assignment).

Body:
Lets say you are writing a C++ like language and you allow references

int& i

You also allow bitwise ands

7&5

How do you solve reduce/reduce conflicts? I dont mean use the glr-parser but have no conflicts at all. Example syntax problem is

var&var //could be type& var or logical val & val

Body:
You could tell flex to return a different token for the literal & depending on what has been "lexed" before. So you end up with two rules:

<type> T_AMPERSAND <identifier>

and

<expression> T_LOGIC_AND <expression>

If your new language supports user defined types, the lexer will not know whether or not it had just found a <type> or an <identifier>, though. In that case you might want to make sure that <type> '&' <identifier> is regarded a valid standalone statement whereas <expression> '&' <expression> can only appear as an rvalue (at right right side of an assignment).


问:
Android - Send data to the server in every 5 minutes
I have some data in my SQLite database table. When my app starts, I want to send that data to the server every 5 minutes.

When the app is closed, it should stop.

What is the best approach for this?

Should I use Service or IntentService?

Should I use AlarmManager, Handler or any other thing?

I'm aware of my application speed. I don't want to make it slow. What is the effective approach?

答:
Alarm manager is not precise, an alarm schedule for 5 minutes may be that when the device is sleeping it will be fired at twice or triple the time.

If you want accuracy the device does not have to fall in sleep. ( I know that will shorten battery duration)

If you want to prevent the device to go to sleep you need to launch a foreground Service with a non dismissable Notification. That's the Service has to call startForeground()

While the device is awake both Alarmamanager and Handler + Runnable will be accurate ... I prefer the Handler.


问:
Python/Flask Rest API not passing preflight w/CORS
I am trying to get the simplest rest api up that I can in python and I am having trouble. I'm not sure what I am doing wrong, but I think it has something to do with CORS. This is frustrating, as I have used the flask_cors package in order to fix this and it does not appear to work.

In my main.py file i have the following

```<code>from flask import Flask
from flask_cors import CORS, cross_origin

app = Flask(__name__)
CORS(app)

import routes.login

if __name__ == '__main__':
    app.run(debug=True)
</code>```

For my project I have this as my folder structure:

```<code>main.py
__init__.py
routes
  __init__.py
  login.py
</code>```

And i have the following code in login.py

```<code>from flask import Flask
from flask_cors import CORS, cross_origin

from main import app
CORS(app)

@app.route('/login', methods=['POST', 'GET'])
@cross_origin()
def login(name, password):
    if request.method == 'POST':
        print('inside login POST')
    if request.method == 'GET':
        print('inside login GET')
</code>```

I'm currently getting this error:

```<code>xhr.js:178 OPTIONS http://localhost:5000/login 404 (NOT FOUND)
dispatchXhrRequest @ xhr.js:178
xhrAdapter @ xhr.js:12
dispatchRequest @ dispatchRequest.js:52
:3000/pictureswapper:1 XMLHttpRequest cannot load http://localhost:5000/login.
 Response for preflight has invalid HTTP status code 404
</code>```

There is some sort of CORS error, but I really don't know what's going wrong. Any ideas?

EDIT: The only place in the documentation that has anything to say about preflight is here (https://flask-cors.readthedocs.io/en/v1.3.1/index.html?highlight=preflight). If I add

```<code>@cross_origin(headers=['Content-Type']) # Send Access-Control-Allow-Headers
</code>```

It doesn't break the application, but neither does it fix the error.

答: Add OPTIONS to the methods keyword of your route decorator, or remove that keyword altogether. </p>

Body:
I am trying to get the simplest rest api up that I can in python and I am having trouble. I'm not sure what I am doing wrong, but I think it has something to do with CORS. This is frustrating, as I have used the flask_cors package in order to fix this and it does not appear to work.

In my main.py file i have the following

from flask import Flask
from flask_cors import CORS, cross_origin

app = Flask(__name__)
CORS(app)

import routes.login

if __name__ == '__main__':
    app.run(debug=True)

For my project I have this as my folder structure:

main.py
__init__.py
routes
  __init__.py
  login.py

And i have the following code in login.py

from flask import Flask
from flask_cors import CORS, cross_origin

from main import app
CORS(app)

@app.route('/login', methods=['POST', 'GET'])
@cross_origin()
def login(name, password):
    if request.method == 'POST':
        print('inside login POST')
    if request.method == 'GET':
        print('inside login GET')

I'm currently getting this error:

xhr.js:178 OPTIONS http://localhost:5000/login 404 (NOT FOUND)
dispatchXhrRequest @ xhr.js:178
xhrAdapter @ xhr.js:12
dispatchRequest @ dispatchRequest.js:52
:3000/pictureswapper:1 XMLHttpRequest cannot load http://localhost:5000/login.
 Response for preflight has invalid HTTP status code 404

There is some sort of CORS error, but I really don't know what's going wrong. Any ideas?

EDIT: The only place in the documentation that has anything to say about preflight is here (https://flask-cors.readthedocs.io/en/v1.3.1/index.html?highlight=preflight). If I add

@cross_origin(headers=['Content-Type']) # Send Access-Control-Allow-Headers

It doesn't break the application, but neither does it fix the error.


问:
Connecting to Access database through HTML on PC
So I'm trying to figure out how to connect to an access database that is on my  desktop through html. Everything I've found so far involves the DB being server side and people mentioning ASP.net or just using SQL or mySQL instead. I just need to know how to get the connection up and running. Any help would be appreciated.</p>

答:
You're just going to get the same answers here. If you want to stay with Access, ASP.Net is the way to go. Access isn't webbased, most other databases are, so it's a bad fit.

If you want a professional solution, you could get yourself a Sharepoint server and put an Access WebApp on there. But note that this is intended for larger businesses, and priced accordingly, and your database will be limited in features (no VBA for example).


问:
Multiple Composer Installs with (Independent) Modular Projects
I am trying to find the best way to use composer for a modular structure.

Let's say I have this framework tree:

/cms

/site/addons

Let's say that addons are available for developers to add their projects with their composer.json installs.
Like /site/addons/MyNewFeature/composer.json

So the next question is the /vendor location. Should each addon have a /vendor directory and should I autoload them all within the main framework, which I think the performance of that would be too much and multiple composer installs would probably install a lot of the same dependencies. And I can't have them all install within the same /vendor directory like /site/addons/vendor because composer will automatically remove all projects not included in the current install and use its own lock file.

How could you do multiple composer installs for modular project based system; while each project requires its own composer vendor, but for performance it would be best to include only 1 vendor install. I have yet to find a solution to this and wondering if any of you guys have an idea or lead me into the right direction.

This is almost like you need a main composer.json install that automatically goes to each one of the addons and installs them as well...

The other solution is just use composer for all the addon (installs/updates) which gives me less control and poses issues with everything being located in the /vendor directory.

答:
After some research and testing, I've come across this concept.

This allows the framework to install/update addons manually the way it was designed, and within the main composer.json file using repositories wildcard path.

```<code>"repositories": [
        {
            "type": "path",
            "url": "../site/addons/*",
            "options": {
                "symlink": false
            }
        }
    ]
</code>```

Now it will check all the addon directories for composer.json files and install all of their dependencies into a universal /vendor directory like I originally wanted.

I am not sure the issues that may arise later by doing this, but so far this gives the control I want.

The framework would just need to make sure the require in the main json has all the addons that are enabled.

https://getcomposer.org/doc/05-repositories.md#path

Body:
After some research and testing, I've come across this concept.

This allows the framework to install/update addons manually the way it was designed, and within the main composer.json file using repositories wildcard path.

"repositories": [
        {
            "type": "path",
            "url": "../site/addons/*",
            "options": {
                "symlink": false
            }
        }
    ]

Now it will check all the addon directories for composer.json files and install all of their dependencies into a universal /vendor directory like I originally wanted.

I am not sure the issues that may arise later by doing this, but so far this gives the control I want.

The framework would just need to make sure the require in the main json has all the addons that are enabled.

https://getcomposer.org/doc/05-repositories.md#path


问:
Load a javascript file when i select an option in popup.html
im making a chrome extension and i have a problem loading a file...
I want to load a file when i select an option in the popup.html file
for example, if i select option1 i want eventPage1.js, to be loaded, and if i select option2 i want eventPage2.js to be loaded, but not the two at the same time, just one.

This its my popup.html file

<!DOCTYPE html>

<form>
Paises en el menu contextual:

    <input type="radio" id="opcion1" name="opcion" value="opcion1" onclick=
    Todos los paises

    <input type="radio" id="opcion2" name="opcion" value="opcion2" onclick=
    Solo Mexico

</form>

```
</div>
</div>
</p>

<p>each eventpage file, its a context menu... </p>

<p>this its how my manifest file looks like</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>{
"manifest_version": 2,
"name": "help me",
"author": "me man",
"version": "1.1.4",
"description": "test test",
"browser_action":
 {
  "default_icon": "icon-large.png",
  "default_popup": "popup.html"
 },

  "background": {
    "scripts": ["menuSelection.js"]
 },
  "permissions": [
 "storage",
 "contextMenus"
  ],
  "icons": {
          "16": "icon-bitty.png",
          "48": "icon-small.png",
          "128": "icon-large.png"
 }
}</code>```

another problem that i have, its that when i select an option... save that option in storage so everytime i use the extension its automatically loaded that option

答:
I think you would probably want to do something like this when you click on the selected option:

```<code><script type="text/javascript">

    function LoadJavascriptFile(fileToLoad){
        var script = document.createElement("script");
        script.id = "customScript";
        script.type = "text/javascript";
        script.src = "fileToLoad";
        document.getElementsByTagName("head")[0].appendChild(script);
    }

</script>
</code>```

On you option select you'd call

```<code>LoadJavascriptFile("PathToMyFile.js")
</code>```

You'd then check if the Script ID exists in the header.  If it does, update the SRC otherwise create the SRC

Body:
im making a chrome extension and i have a problem loading a file...
I want to load a file when i select an option in the popup.html file
for example, if i select option1 i want eventPage1.js, to be loaded, and if i select option2 i want eventPage2.js to be loaded, but not the two at the same time, just one.

This its my popup.html file

<!DOCTYPE html>

<form>
Paises en el menu contextual:

    <input type="radio" id="opcion1" name="opcion" value="opcion1" onclick=
    Todos los paises

    <input type="radio" id="opcion2" name="opcion" value="opcion2" onclick=
    Solo Mexico

</form>

each eventpage file, its a context menu...

this its how my manifest file looks like

{
"manifest_version": 2,
"name": "help me",
"author": "me man",
"version": "1.1.4",
"description": "test test",
"browser_action":
 {
  "default_icon": "icon-large.png",
  "default_popup": "popup.html"
 },

  "background": {
    "scripts": ["menuSelection.js"]
 },
  "permissions": [
 "storage",
 "contextMenus"
  ],
  "icons": {
          "16": "icon-bitty.png",
          "48": "icon-small.png",
          "128": "icon-large.png"
 }
}

another problem that i have, its that when i select an option... save that option in storage so everytime i use the extension its automatically loaded that option

Body:
I think you would probably want to do something like this when you click on the selected option:

<script type="text/javascript">

    function LoadJavascriptFile(fileToLoad){
        var script = document.createElement("script");
        script.id = "customScript";
        script.type = "text/javascript";
        script.src = "fileToLoad";
        document.getElementsByTagName("head")[0].appendChild(script);
    }

</script>

On you option select you'd call

LoadJavascriptFile("PathToMyFile.js")

You'd then check if the Script ID exists in the header.  If it does, update the SRC otherwise create the SRC


问:
calculating the outliers in R
I have a data frame like this:

x

```<code>Team 01/01/2012  01/02/2012  01/03/2012  01/01/2012 01/04/2012 SD Mean
A     100         50           40        NA         30       60  80
</code>```

I like to perform calculation on each cell to the mean and sd to calculate the outliers. For example,

```<code>abs(x-Mean) > 3*SD
</code>```

x$count<-c(1) (increment this value if the above condition is met).

I am doing this to check the anomaly in my data set. If I know the column names, it would be easier to do the calculations, but number of columns will vary. Some cells may have NA in them.

I like to subtrack mean from each cell, and I tried this

```<code>x$diff<-sweep(x, 1, x$Mean, FUN='-')
</code>```

does not seem to be working, any ideas?

答:
The following formulas could be used to determine which values are outliers:

upper.outlier.calc <- function(x.var, df){
  with(df, quantile(x.var, 0.75) + (1.5 * (quantile(x.var, 0.75) - quantile(x.var, 0.25))))
}

lower.outlier.calc <- function(x.var, df){
  with(df, quantile(x.var, 0.25) - (1.5 * (quantile(x.var, 0.75) - quantile(x.var, 0.25))))
}
```

Title: calculating the outliers in R

Body:
I have a data frame like this:

x

Team 01/01/2012  01/02/2012  01/03/2012  01/01/2012 01/04/2012 SD Mean
A     100         50           40        NA         30       60  80

I like to perform calculation on each cell to the mean and sd to calculate the outliers. For example,

abs(x-Mean) > 3*SD

x$count<-c(1) (increment this value if the above condition is met).

I am doing this to check the anomaly in my data set. If I know the column names, it would be easier to do the calculations, but number of columns will vary. Some cells may have NA in them.

I like to subtrack mean from each cell, and I tried this

x$diff<-sweep(x, 1, x$Mean, FUN='-')

does not seem to be working, any ideas?


问:
Symfony select form with conditon
I want to create a form for a planning subscription. 1 The user can participate in 1 planning and can subscribe at 1 day. So if 1 user subscribes at the planningid: 1 and choose the Friday, it will be written in the DB like that:
User: planning_id:1 and planningday: 5.
So now we have a second user, who want's to subscribe at the same planning 1.
But now he can't choose the Friday because the first user already takes that day.
I want to display a form who show only the remainings days.

For nom i have created a simple form like that:

```<code>$form = $this->get('form.factory')->createBuilder(FormType::class, $user)
            ->add('planningday', ChoiceType::class, array(
                    'label' => 'Sélectionnez un jour',
                    'choices' => array(
                        'Lundi' => 1,
                        'Mardi' => 2,
                        'Mercredi' => 3,
                        'Jeudi' => 4,
                        'Vendredi' => 5
                    )
                ))
            ->add('planningcontent', TextType::class, array( 'label' => 'Description'))
            ->add('S\'inscrire au planning', SubmitType::class)
</code>```

I want to improve this form but I have no idea on what I can do in this way.

Thanks for your help.

答:
You have to set up many to many in doctrine data-mapping:

http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/association-mapping.html#many-to-many-unidirectional

Title: Symfony select form with conditon

Body:
I want to create a form for a planning subscription. 1 The user can participate in 1 planning and can subscribe at 1 day. So if 1 user subscribes at the planningid: 1 and choose the Friday, it will be written in the DB like that:
User: planning_id:1 and planningday: 5.
So now we have a second user, who want's to subscribe at the same planning 1.
But now he can't choose the Friday because the first user already takes that day.
I want to display a form who show only the remainings days.

For nom i have created a simple form like that:

$form = $this->get('form.factory')->createBuilder(FormType::class, $user)
            ->add('planningday', ChoiceType::class, array(
                    'label' => 'Sélectionnez un jour',
                    'choices' => array(
                        'Lundi' => 1,
                        'Mardi' => 2,
                        'Mercredi' => 3,
                        'Jeudi' => 4,
                        'Vendredi' => 5
                    )
                ))
            ->add('planningcontent', TextType::class, array( 'label' => 'Description'))
            ->add('S\'inscrire au planning', SubmitType::class)

I want to improve this form but I have no idea on what I can do in this way.

Thanks for your help.


问:
How to use the main window scroll bar to scroll a modal?
The problem is that if you have a long modal, then you need to add an option to scroll it down.

However, adding a scroll bar to the modal itself would be bad for UX, cause people are intuitively used to scrolling with the scroll bar at the right end of the screen.

Several websites have this figured out, like Twitter and Product Hunt:

I can't still understand how to implement it. I have been searching for some materials online, but unfortunately couldn't find any.

If you have an idea on how it's done, please let me know.

Update:

Here are the styles for my current modal:

```<code>.modal {
    box-shadow:0 12px 30px rgba(0,0,0,0.3);
    z-index:103;
    border-radius:5px;
    text-align:center;
    left: 50%;
    -webkit-transform: translateX(-50%);
    transform: translateX(-50%);
    top: 60px;
    position:fixed;
    overflow-y: auto;
    overflow-x: hidden;
    max-height: calc(100vh - 100px);
 }
</code>```

答:
The scrollbar on twitter isn't the main window scrollbar - it's just a scrollbar in their modal dialog with is full screen, then they position the content of the modal dialog in the center. So when you scroll the modal, the scrollbar is on the far right, like the main window scrollbar.

To do that, I would just make your .modal a full screen modal with overflow: auto, then absolutely position the content of the modal inside of it. So you're scrolling the main .modal window, and the scrollbar is positioned to the far right like the main window scrollbar.

.modal {
  z-index: 103;

  text-align: center;
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  overflow: auto;
}

.modalContent {
  position: absolute;
  top: 60px;
  left: 50%;
  box-shadow: 0 12px 30px rgba(0, 0, 0, 0.3);
  -webkit-transform: translateX(-50%);
  transform: translateX(-50%);
  border-radius: 5px;
  margin-bottom: 60px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="modal">
  <div class="modalContent">
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
  </div>
</div></code>```

Body:
The problem is that if you have a long modal, then you need to add an option to scroll it down.

However, adding a scroll bar to the modal itself would be bad for UX, cause people are intuitively used to scrolling with the scroll bar at the right end of the screen.

Several websites have this figured out, like Twitter and Product Hunt:

I can't still understand how to implement it. I have been searching for some materials online, but unfortunately couldn't find any.

If you have an idea on how it's done, please let me know.

Update:

Here are the styles for my current modal:

.modal {
    box-shadow:0 12px 30px rgba(0,0,0,0.3);
    z-index:103;
    border-radius:5px;
    text-align:center;
    left: 50%;
    -webkit-transform: translateX(-50%);
    transform: translateX(-50%);
    top: 60px;
    position:fixed;
    overflow-y: auto;
    overflow-x: hidden;
    max-height: calc(100vh - 100px);
 }

Body:
The scrollbar on twitter isn't the main window scrollbar - it's just a scrollbar in their modal dialog with is full screen, then they position the content of the modal dialog in the center. So when you scroll the modal, the scrollbar is on the far right, like the main window scrollbar.

To do that, I would just make your .modal a full screen modal with overflow: auto, then absolutely position the content of the modal inside of it. So you're scrolling the main .modal window, and the scrollbar is positioned to the far right like the main window scrollbar.

.modal {
  z-index: 103;

  text-align: center;
  position: fixed;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  overflow: auto;
}

.modalContent {
  position: absolute;
  top: 60px;
  left: 50%;
  box-shadow: 0 12px 30px rgba(0, 0, 0, 0.3);
  -webkit-transform: translateX(-50%);
  transform: translateX(-50%);
  border-radius: 5px;
  margin-bottom: 60px;
}

<div class="modal">
  <div class="modalContent">
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
    <p>blah</p>
  </div>
</div>


问:
many-to-many, poco, ef4
I have 3 entities:

```<code>Goods [GID(PK), GoodName]
Persons [PID(PK), PersonName]
Roles [RID(PK), RoleName]
</code>```

But now I need to associate these object with each other.
In other words, each Good can have MANY Persons in MANY Roles.
I have a table in DB with 3 fields (GID, PID, RID)

For example:

```<code>Book (GID#1), can have 3 associated persons:

1. Jack (PID#1) in role Author (RID#1)
2. Jack (PID#1) in role Editor (RID#2)
3. Bill (PID#2) in role Painter (RID#3)
</code>```

How can I map this in POCO format in Entity Framework 4?

答:
I believe you have to create another PersonRoles header where you store the Person-Role relation, then you access the person+role via this one:

PersonRoles [PRID(PK), PersonName, RoleName] (note: you could also do this withnow entitykey, just relationships, EF will eliminate this entity and give a direct Person.Roles entity, which you can do access it via Book.Persons.Select((p) p.Roles)).

```<code>PersonRole#1: Jack#1/Author#1
PersonRole#2: Jack#1/Editor#2
PersonRole#3: Bill#2/Painter#3

Book.PersonRole = context.PersonRoles.
  SingleOrDefault((pr) => pr.Person.PersonId == 1 && pr.RoleId == 1);
</code>```

Note: my main lang is VB.NET so I apologize for the pseudu code above, but I hope you get the idea.

Update

It should be like:

```<code><DataContract(IsReference:=True)>
<KnownType(GetType(Good))>
<KnownType(GetType(Person))>
<KnownType(GetType(Role))>
Partial Public Class GoodPersonRole
    Implements IObjectWithChangeTracker
    Implements INotifyPropertyChanged

<DataMember()>
Public Property GoodId() As Integer
    Get
        Return _goodId
    End Get
    Set(ByVal value As Integer)
        If Not Equals(_goodId, value) Then
            If ChangeTracker.ChangeTrackingEnabled AndAlso ChangeTracker.State <> ObjectState.Added Then
                Throw New InvalidOperationException("The property 'GoodId' is part of the object's key and cannot be changed. Changes to key properties can only be made when the object is not being tracked or is in the Added state.")
            End If
            If Not IsDeserializing Then
                If Good IsNot Nothing AndAlso Not Equals(Good.GoodId, value) Then
                    Good = Nothing
                End If
            End If
            _goodId = value
            OnPropertyChanged("GoodId")
        End If
    End Set
End Property

Private _goodId As Integer

<DataMember()>
Public Property Good() As Good
    Get
        Return _good
    End Get
    Set(ByVal value As Good)
        If _good IsNot value Then
            If ChangeTracker.ChangeTrackingEnabled AndAlso ChangeTracker.State <> ObjectState.Added AndAlso value IsNot Nothing Then
                ' This the dependent end of an identifying relationship, so the principal end cannot be changed if it is already set,
                ' otherwise it can only be set to an entity with a primary key that is the same value as the dependent's foreign key.
                If Not Equals(GoodId, value.GoodId) Then
                    Throw New InvalidOperationException("The principal end of an identifying relationship can only be changed when the dependent end is in the Added state.")
                End If
            End If
            Dim previousValue As Good = _good
            _good = value
            FixupGood(previousValue)
            OnNavigationPropertyChanged("Good")
        End If
    End Set
End Property
Private _good As Good
End Class
</code>```

(part from the generated entity by ADO.NET VB POCO Entity Generator)

I just copied the 'Good' Id and nav. property but it should be the three of them.

Title: many-to-many, poco, ef4

Body:
I have 3 entities:

Goods [GID(PK), GoodName]
Persons [PID(PK), PersonName]
Roles [RID(PK), RoleName]

But now I need to associate these object with each other.
In other words, each Good can have MANY Persons in MANY Roles.
I have a table in DB with 3 fields (GID, PID, RID)

For example:

Book (GID#1), can have 3 associated persons:

1. Jack (PID#1) in role Author (RID#1)
2. Jack (PID#1) in role Editor (RID#2)
3. Bill (PID#2) in role Painter (RID#3)

How can I map this in POCO format in Entity Framework 4?

Body:
I believe you have to create another PersonRoles header where you store the Person-Role relation, then you access the person+role via this one:

PersonRoles [PRID(PK), PersonName, RoleName] (note: you could also do this withnow entitykey, just relationships, EF will eliminate this entity and give a direct Person.Roles entity, which you can do access it via Book.Persons.Select((p) p.Roles)).

PersonRole#1: Jack#1/Author#1
PersonRole#2: Jack#1/Editor#2
PersonRole#3: Bill#2/Painter#3

Book.PersonRole = context.PersonRoles.
  SingleOrDefault((pr) => pr.Person.PersonId == 1 && pr.RoleId == 1);

Note: my main lang is VB.NET so I apologize for the pseudu code above, but I hope you get the idea.

Update

It should be like:

<DataContract(IsReference:=True)>
<KnownType(GetType(Good))>
<KnownType(GetType(Person))>
<KnownType(GetType(Role))>
Partial Public Class GoodPersonRole
    Implements IObjectWithChangeTracker
    Implements INotifyPropertyChanged

<DataMember()>
Public Property GoodId() As Integer
    Get
        Return _goodId
    End Get
    Set(ByVal value As Integer)
        If Not Equals(_goodId, value) Then
            If ChangeTracker.ChangeTrackingEnabled AndAlso ChangeTracker.State <> ObjectState.Added Then
                Throw New InvalidOperationException("The property 'GoodId' is part of the object's key and cannot be changed. Changes to key properties can only be made when the object is not being tracked or is in the Added state.")
            End If
            If Not IsDeserializing Then
                If Good IsNot Nothing AndAlso Not Equals(Good.GoodId, value) Then
                    Good = Nothing
                End If
            End If
            _goodId = value
            OnPropertyChanged("GoodId")
        End If
    End Set
End Property

Private _goodId As Integer

<DataMember()>
Public Property Good() As Good
    Get
        Return _good
    End Get
    Set(ByVal value As Good)
        If _good IsNot value Then
            If ChangeTracker.ChangeTrackingEnabled AndAlso ChangeTracker.State <> ObjectState.Added AndAlso value IsNot Nothing Then
                ' This the dependent end of an identifying relationship, so the principal end cannot be changed if it is already set,
                ' otherwise it can only be set to an entity with a primary key that is the same value as the dependent's foreign key.
                If Not Equals(GoodId, value.GoodId) Then
                    Throw New InvalidOperationException("The principal end of an identifying relationship can only be changed when the dependent end is in the Added state.")
                End If
            End If
            Dim previousValue As Good = _good
            _good = value
            FixupGood(previousValue)
            OnNavigationPropertyChanged("Good")
        End If
    End Set
End Property
Private _good As Good
End Class

(part from the generated entity by ADO.NET VB POCO Entity Generator)

I just copied the 'Good' Id and nav. property but it should be the three of them.


问:
How to print JSON values in javascript fetched using AJAX
I have made a js file in which data is being fetched from js file and the values are stored in a request object. Example of JSON file

```<code>{
    "name": "ABC",
    "age": 20
}
</code>```

I want to display the value of name using variable name. I want something like this.

```<code>var x = "name";
var req = JSON.parse(request.responseText);
console.log(req.x);
</code>```

But the above statement displays undefined. Any solutions?

答:
Use brackets instead of dot:

var x = "name";
var req = {
  "name": "ABC",
  "age": 20
};

console.log(req[x]);```

You need to use brackets here because the name of the property is dynamic, with the value coming from a variable (dot should be used only when the name of the property is static)

Body:
I have made a js file in which data is being fetched from js file and the values are stored in a request object. Example of JSON file

{
    "name": "ABC",
    "age": 20
}

I want to display the value of name using variable name. I want something like this.

var x = "name";
var req = JSON.parse(request.responseText);
console.log(req.x);

But the above statement displays undefined. Any solutions?

Body:
Use brackets instead of dot:

var x = "name";
var req = {
  "name": "ABC",
  "age": 20
};

console.log(req[x]);

You need to use brackets here because the name of the property is dynamic, with the value coming from a variable (dot should be used only when the name of the property is static)


问:
Why is this printing a key in two different ways?
Why is it that the print key yields a list of the names of the fruits but print prices[key] yields the numbers after each fruit? Should key print the same thing (the fruit names)?

Here's the code

```<code>    prices = {
    "banana" : 4,
    "apple"  : 2,
    "orange" : 1.5,
    "pear"   : 3,
}
stock = {
    "banana" : 6,
    "apple"  : 0,
    "orange" : 32,
    "pear"   : 15,
}

for key in prices:
    print key
    print "price: %s" % prices[key]
    print "stock: %s" % stock[key]
</code>```

Here is the result

orange
price: 1.5
stock: 32
pear
price: 3
stock: 15
banana
price: 4
stock: 6
apple
price: 2
stock: 0

答:
NVM what I previously wrote (misread question). Like the other post states you are printing the key of the dictionary with the statement print key and then you are printing the value that is associated w/ the key when you do print price[key] so to print all in one like you can do the following

```<code>for key in prices:
    print "item: ", key, " price: ", prices[key], " stock: " stock[key]
</code>```

The above will throw a key error if it does not exist in the stock dictionary FYI.

Here is a solid answer to a similar question https://stackoverflow.com/a/5905166/3990806

Body:
Why is it that the print key yields a list of the names of the fruits but print prices[key] yields the numbers after each fruit? Should key print the same thing (the fruit names)?

Here's the code

    prices = {
    "banana" : 4,
    "apple"  : 2,
    "orange" : 1.5,
    "pear"   : 3,
}
stock = {
    "banana" : 6,
    "apple"  : 0,
    "orange" : 32,
    "pear"   : 15,
}

for key in prices:
    print key
    print "price: %s" % prices[key]
    print "stock: %s" % stock[key]

Here is the result

orange
price: 1.5
stock: 32
pear
price: 3
stock: 15
banana
price: 4
stock: 6
apple
price: 2
stock: 0

Body:
NVM what I previously wrote (misread question). Like the other post states you are printing the key of the dictionary with the statement print key and then you are printing the value that is associated w/ the key when you do print price[key] so to print all in one like you can do the following

for key in prices:
    print "item: ", key, " price: ", prices[key], " stock: " stock[key]

The above will throw a key error if it does not exist in the stock dictionary FYI.

Here is a solid answer to a similar question https://stackoverflow.com/a/5905166/3990806


问:
How to make custom buttons in corona, Lua
I'm trying to make a mobile application with a screen that looks like this:

I'm making this using Corona, it's written in the Lua language

It's a scrollable list of buttons, I somewhat understand the scroll aspect. What I'm having problems now is making a button that can have more than one line of text and also an image. I've literally been searching for hour but haven't found anything (I'm probably bad at finding things). I think I'd have to create a custom button but I have no idea how to do this. I would appreciate some help with this be it a link or just some lines of text explaining it, thank you so much!

答: Found a solution, widget.newTable does this perfectly</p>


问:
using editText Globally
I'm new in android developing. in my simple project I'm using an editText very often to get the value in my java file and I wanted to declare and find my edit text just one time and after that i Use it in my entire java file. I code like this:

```<code>    EditText editText = (EditText) findViewById(R.id.editText);

public void onClick1(View v){
    Editable input = editText.getText();
    this.editText.setText(input+"1");

}
public void onClick2(View v){
    Editable input = editText.getText();
    this.editText.setText(input+"2");

}
</code>```

but this code close my application unexpectedly when I try to run it.
Please let me know your idea about declaring that edit text and using in my functions.

答:
DefineEditText editText; right after your class declaration (private is suggested), so, it should look like:

```<code>public class MainActivity extends Activity{
     private EditText editText;
     ...
}
</code>```

and initialize in your onCreate() method

```<code>editText = (EditText) findViewById(R.id.editText);
</code>```

So you can reach that throughtout your class

Title: using editText Globally

Body:
I'm new in android developing. in my simple project I'm using an editText very often to get the value in my java file and I wanted to declare and find my edit text just one time and after that i Use it in my entire java file. I code like this:

    EditText editText = (EditText) findViewById(R.id.editText);

public void onClick1(View v){
    Editable input = editText.getText();
    this.editText.setText(input+"1");

}
public void onClick2(View v){
    Editable input = editText.getText();
    this.editText.setText(input+"2");

}

but this code close my application unexpectedly when I try to run it.
Please let me know your idea about declaring that edit text and using in my functions.

Body:
DefineEditText editText; right after your class declaration (private is suggested), so, it should look like:

public class MainActivity extends Activity{
     private EditText editText;
     ...
}

and initialize in your onCreate() method

editText = (EditText) findViewById(R.id.editText);

So you can reach that throughtout your class


答: The statement for key in prices gives you the keys of the dictionary.  The statement print prices[key] gives you the value associated with key.

Title: Why is this printing a key in two different ways?


问:
How to use function to call button instead of pressing it (swift3)
I want to be able to call function start within function use without hitting the action button for start. I know simple thing to do is just put print("a") in use. But I am using this as a simple example because I have a more complex problem in mind. </p>

```<code>   @IBAction func start(_ sender: Any) {
print("a")}

fun use() {
}

viewdidload() {
use()
}
</code>```

答:
Create an IBOutlet for your button:

```<code>@IBOutlet weak var button: UIButton!
</code>```

Then simply, use this code to trigger its action:

```<code>button.sendActions(for: .touchUpInside)
</code>```

Body:
I want to be able to call function start within function use without hitting the action button for start. I know simple thing to do is just put print("a") in use. But I am using this as a simple example because I have a more complex problem in mind.

   @IBAction func start(_ sender: Any) {
print("a")}

fun use() {
}

viewdidload() {
use()
}

Body:
Create an IBOutlet for your button:

@IBOutlet weak var button: UIButton!

Then simply, use this code to trigger its action:

button.sendActions(for: .touchUpInside)


问:
How to add Certificate Authority file in CentOS 7
I am trying to add certificate Authority (CA) file name - ca.crt to /etc/ssl/certs, for that I followed this article.

I copied my ca.crt file  to /etc/pki/ca-trust/source/anchors/ and run the command below;

```<code>update-ca-trust extract
</code>```

After that I checked /etc/pki/ca-trust/extracted/openssl/ca-bundle.trust.crt file, but I didn't find my CA.

I am not able to figure out what may be the problem.

What am I doing wrong and how can I fix it?

答:
copy your certificates inside

```<code>/etc/pki/ca-trust/source/anchors/
</code>```

then run the following command

```<code>update-ca-trust
</code>```

Body:
I am trying to add certificate Authority (CA) file name - ca.crt to /etc/ssl/certs, for that I followed this article.

I copied my ca.crt file  to /etc/pki/ca-trust/source/anchors/ and run the command below;

update-ca-trust extract

After that I checked /etc/pki/ca-trust/extracted/openssl/ca-bundle.trust.crt file, but I didn't find my CA.

I am not able to figure out what may be the problem.

What am I doing wrong and how can I fix it?

Body:
copy your certificates inside

/etc/pki/ca-trust/source/anchors/

then run the following command

update-ca-trust


问:
Using File System as source of videos for playing offline
I am trying to add offline functionality to my HTML5 video player. I am attempting to write the files into the chrome file system as a blob and then read them from there. I believe that I am running into an issue where the files are not actually being written, just the file name. As my below code is currently constituted, it works, though still only if it is permanently connected to the internet. My goal is to have the files download to a persistent directory in the filesystem and then continue to play if the internet is disconnected.</p>

```<code>$(document).ready(function() {

    var dir = "http://www.kevmoe.com/networks/gsplayer/";
    var fileextension = ".mp4";
    var srcfiles = $.ajax({
        //This will retrieve the contents of the folder if the folder is configured as 'browsable'
        url: dir,
        success: function(data) {
            //List all .mp4 file names in the page
            $(data).find("a:contains(" + fileextension + ")").each(function() {
                var filename = $(this).attr("href").replace(window.location.host, "").replace("http://", "");

                $("#container").append("<div id='div1' class='video'><video id='video1' class='vidarray' preload='none' poster='bkg.png'><source src='" + filename + "' type='video/mp4'></video></div>");
                async: false;

                window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;

                window.requestFileSystem(window.PERSISTANT, 200000 * 1024 * 1024, initFS, errorHandler);

                function initFS(fs) {
                    console.log('filesystem engaged'); // Just to check if everything is OK :)
                    // place the functions you will learn bellow here
                    function errorHandler(err) {
                        var msg = 'An error occured: ';
                    };

                    function createDir(rootDir, folders) {
                        rootDir.getDirectory(folders[0], {
                            create: true
                        }, function(dirEntry) {
                            if (folders.length) {
                                createDir(dirEntry, folders.slice(1));
                            }
                        }, errorHandler);
                    };

                    createDir(fs.root, 'files/video/'.split('/'));

                    fs.root.getDirectory('video', {}, function(dirEntry) {
                        var dirReader = dirEntry.createReader();
                        dirReader.readEntries(function(entries) {
                            for (var i = 0; i < entries.length; i++) {
                                var entry = entries[i];
                                if (entry.isDirectory) {
                                    console.log('Directory: ' + entry.fullPath);
                                } else if (entry.isFile) {
                                    console.log('File: ' + entry.fullPath);
                                }
                            }

                        }, errorHandler);
                    }, errorHandler);

                    fs.root.getFile(filename, {
                        create: true,
                        exclusive: true
                    }, function(fileEntry) {
                        fileEntry.createWriter(function(fileWriter) {
                            var blob = new Blob([data], {
                                type: 'video/mp4'
                            });
                            fileWriter.write(blob);
                        }, errorHandler);

                        console.log('file downloaded');
                    }, errorHandler);

                    //Try to add an event listener for when all files are finished loading into file system. Then use another function to source the videos locally.
                    var dirReader = fs.root.createReader();
                    var entries = [];

                    // Call the reader.readEntries() until no more results are returned.

                    dirReader.readEntries(function(results) {

                        //List all .mp4 file names in the page
                        $(results).find("a:contains(" + fileextension + ")").each(function() {
                            var filename = $(this).attr("href").replace(window.location.host, "").replace("http://", "");

                            $("#container").append("<div id='div1' class='video'><video id='video1' class='vidarray' preload='none' poster='bkg.png'><source src='" + filename + "' type='video/mp4'></video></div>");
                            async: false;

                        }, errorHandler);
                    });
                };

                function errorHandler() {
                    console.log('An error occured');
                };
            });

            var videos = $('.video');
            //handle ending of video
            videos.find('video').on('ended', function() {
                playNextVideo(videos);
            });

            // start with the first one
            playNextVideo(videos);

            function playNextVideo(videoList) {
                var activeVideo = videoList.filter('.active').removeClass('active'), // identify active video and remove active class
                    activeIndex = videoList.index(activeVideo), // get the active video index in the group
                    nextVideo = videoList.eq(activeIndex + 1), // get the next video in line
                    actualVideo;

                // if there is no next video start from first
                if (nextVideo.length == 0) nextVideo = videoList.first();

                // pause all videos
                videoList.find('video').each(function() {
                    this.pause();
                })

                // get reference to next video element
                actualVideo = nextVideo.find('video').get(0);

                // add active class to next video
                nextVideo.addClass('active');

                // load and play
                actualVideo.volume = 0.04;
                actualVideo.load();
                actualVideo.play();
            }
        }
    });
});
</code>```

答:
Your user must grant your app permission to store data locally before your app can use persistent storage.
That's why you have to request quota first. The amount of bytes you ask for is 200000 * 1024 * 1024 bytes.

```<code>window.storageInfo.requestQuota(PERSISTENT, 200000 * 1024 * 1024,
    function(grantedBytes) {
        window.requestFileSystem(window.PERSISTENT, grantedBytes, onInitFs, errorHandler);
    },
    errorHandler
);
</code>```

MDN documentation

I noticed you are writing this for Chrome, here's how you manage the quota in Chrome

Body:
I am trying to add offline functionality to my HTML5 video player. I am attempting to write the files into the chrome file system as a blob and then read them from there. I believe that I am running into an issue where the files are not actually being written, just the file name. As my below code is currently constituted, it works, though still only if it is permanently connected to the internet. My goal is to have the files download to a persistent directory in the filesystem and then continue to play if the internet is disconnected.

$(document).ready(function() {

    var dir = "http://www.kevmoe.com/networks/gsplayer/";
    var fileextension = ".mp4";
    var srcfiles = $.ajax({
        //This will retrieve the contents of the folder if the folder is configured as 'browsable'
        url: dir,
        success: function(data) {
            //List all .mp4 file names in the page
            $(data).find("a:contains(" + fileextension + ")").each(function() {
                var filename = $(this).attr("href").replace(window.location.host, "").replace("http://", "");

                $("#container").append("
<video id='video1' class='vidarray' preload='none' poster='bkg.png'><source src='" + filename + "' type='video/mp4'></video>
");
                async: false;

                window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;

                window.requestFileSystem(window.PERSISTANT, 200000 * 1024 * 1024, initFS, errorHandler);

                function initFS(fs) {
                    console.log('filesystem engaged'); // Just to check if everything is OK :)
                    // place the functions you will learn bellow here
                    function errorHandler(err) {
                        var msg = 'An error occured: ';
                    };

                    function createDir(rootDir, folders) {
                        rootDir.getDirectory(folders[0], {
                            create: true
                        }, function(dirEntry) {
                            if (folders.length) {
                                createDir(dirEntry, folders.slice(1));
                            }
                        }, errorHandler);
                    };

                    createDir(fs.root, 'files/video/'.split('/'));

                    fs.root.getDirectory('video', {}, function(dirEntry) {
                        var dirReader = dirEntry.createReader();
                        dirReader.readEntries(function(entries) {
                            for (var i = 0; i < entries.length; i++) {
                                var entry = entries[i];
                                if (entry.isDirectory) {
                                    console.log('Directory: ' + entry.fullPath);
                                } else if (entry.isFile) {
                                    console.log('File: ' + entry.fullPath);
                                }
                            }

                        }, errorHandler);
                    }, errorHandler);

                    fs.root.getFile(filename, {
                        create: true,
                        exclusive: true
                    }, function(fileEntry) {
                        fileEntry.createWriter(function(fileWriter) {
                            var blob = new Blob([data], {
                                type: 'video/mp4'
                            });
                            fileWriter.write(blob);
                        }, errorHandler);

                        console.log('file downloaded');
                    }, errorHandler);

                    //Try to add an event listener for when all files are finished loading into file system. Then use another function to source the videos locally.
                    var dirReader = fs.root.createReader();
                    var entries = [];

                    // Call the reader.readEntries() until no more results are returned.

                    dirReader.readEntries(function(results) {

                        //List all .mp4 file names in the page
                        $(results).find("a:contains(" + fileextension + ")").each(function() {
                            var filename = $(this).attr("href").replace(window.location.host, "").replace("http://", "");

                            $("#container").append("
<video id='video1' class='vidarray' preload='none' poster='bkg.png'><source src='" + filename + "' type='video/mp4'></video>
");
                            async: false;

                        }, errorHandler);
                    });
                };

                function errorHandler() {
                    console.log('An error occured');
                };
            });

            var videos = $('.video');
            //handle ending of video
            videos.find('video').on('ended', function() {
                playNextVideo(videos);
            });

            // start with the first one
            playNextVideo(videos);

            function playNextVideo(videoList) {
                var activeVideo = videoList.filter('.active').removeClass('active'), // identify active video and remove active class
                    activeIndex = videoList.index(activeVideo), // get the active video index in the group
                    nextVideo = videoList.eq(activeIndex + 1), // get the next video in line
                    actualVideo;

                // if there is no next video start from first
                if (nextVideo.length == 0) nextVideo = videoList.first();

                // pause all videos
                videoList.find('video').each(function() {
                    this.pause();
                })

                // get reference to next video element
                actualVideo = nextVideo.find('video').get(0);

                // add active class to next video
                nextVideo.addClass('active');

                // load and play
                actualVideo.volume = 0.04;
                actualVideo.load();
                actualVideo.play();
            }
        }
    });
});

Body:
Your user must grant your app permission to store data locally before your app can use persistent storage.
That's why you have to request quota first. The amount of bytes you ask for is 200000 * 1024 * 1024 bytes.

window.storageInfo.requestQuota(PERSISTENT, 200000 * 1024 * 1024,
    function(grantedBytes) {
        window.requestFileSystem(window.PERSISTENT, grantedBytes, onInitFs, errorHandler);
    },
    errorHandler
);

MDN documentation

I noticed you are writing this for Chrome, here's how you manage the quota in Chrome


问:
Google app engine error ImportError: No module named bccache
When trying to run my Google App Engine app, I get the following error:</p>

```<code> (/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py:263)
Traceback (most recent call last):
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 240, in Handle
    handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler
    handler, path, err = LoadObject(self._handler)
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 96, in LoadObject
    __import__(cumulative_path)
  File "/base/data/home/apps/p~mygoolgeappproject/3.402458165629390060/village/main.py", line 4, in <module>
    import flask
  File "/base/data/home/apps/p~mygoolgeappproject/3.402458165629390060/libs/flask/__init__.py", line 19, in <module>
    from jinja2 import Markup, escape
  File "/base/data/home/apps/p~mygoolgeappproject/3.402458165629390060/libs/jinja2/__init__.py", line 41, in <module>
    from jinja2.bccache import BytecodeCache, FileSystemBytecodeCache, \
ImportError: No module named bccache
</code>```

答:
It is not quite clear whether you're using App Engine Standard or App Engine Flexible environment. I'm taking a guess that it is App Engine Standard and posting this answer.

App Engine Standard has only a limited set of libraries available in the runtime environment. If you need to add any third-party libraries, you will need to add them manually by following this guide.

You can also look at these answers for more info.

How to include third party Python libraries in Google App Engine?

Python 2.7 : How to use BeautifulSoup in Google App Engine? [duplicate]

Body:
When trying to run my Google App Engine app, I get the following error:

 (/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py:263)
Traceback (most recent call last):
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 240, in Handle
    handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 299, in _LoadHandler
    handler, path, err = LoadObject(self._handler)
  File "/base/data/home/runtimes/python27/python27_lib/versions/1/google/appengine/runtime/wsgi.py", line 96, in LoadObject
    __import__(cumulative_path)
  File "/base/data/home/apps/p~mygoolgeappproject/3.402458165629390060/village/main.py", line 4, in <module>
    import flask
  File "/base/data/home/apps/p~mygoolgeappproject/3.402458165629390060/libs/flask/__init__.py", line 19, in <module>
    from jinja2 import Markup, escape
  File "/base/data/home/apps/p~mygoolgeappproject/3.402458165629390060/libs/jinja2/__init__.py", line 41, in <module>
    from jinja2.bccache import BytecodeCache, FileSystemBytecodeCache, \
ImportError: No module named bccache


答:
It should be console.log(req[x]);

OR

```<code>console.log(req.name);
</code>```

Title: How to print JSON values in javascript fetched using AJAX

Body:
It should be console.log(req[x]);

OR

console.log(req.name);


问:
Xcode 8.3.2 Clang Error
I am trying to update one of my project, when I opened it I performed validated settings, but when I try to build it I just face with this error :

Apple Mach-O Linker Error Group : clang: error: linker command failed
  with exit code 1 (use -v to see invocation)

with no more infos and I am not using cocoapods or any external frameworks. I just searched everywhere and did any possible solution such as :

Clean and run

Searched for duplicate files

Check imported header files

Delete xxxTest

Checked Build Active architecture

Validated Settings

Checked missing frameworks

Restart mac

Changed iOS deployment target

Disabled bitcode

and etc...

Is there anything to solve this issue ?!

答: Right-click the error in the the Issue Navigator. Choose "Reveal in Log" or "Reveal in Project Navigator "and see the actual error message.</p>

Title: Xcode 8.3.2 Clang Error


问:
How to use regex expression for letters numbers and alphanumeric characters
Can anyone help me with my regex expression. Im trying to validate the date string as follows 27 August 1979 - 05:25 am can anyone help me to fix my code by using uppercase lowercase hyphen, colon text and numbers.

Code

```<code>regula.custom({
    name:'AlphaSpecial',
    defaultMessage: "The text field can only contain letters,numbers and alphanumeric characters!",
    validator:function(){
        return /^[a-zA-Z0-9_.:-]*$/.test(this.value)
    }
})
</code>```

答:
You could try matching ^\w+\s\d{4}\s-\s\d{2}:\d{2}\s\w{2}$

To learn more about regex I would recommend using https://developer.mozilla.org/nl/docs/Web/JavaScript/Guide/Regular_Expressions

And to test your regex this site is great: https://regex101.com/

Body:
Can anyone help me with my regex expression. Im trying to validate the date string as follows 27 August 1979 - 05:25 am can anyone help me to fix my code by using uppercase lowercase hyphen, colon text and numbers.

Code

regula.custom({
    name:'AlphaSpecial',
    defaultMessage: "The text field can only contain letters,numbers and alphanumeric characters!",
    validator:function(){
        return /^[a-zA-Z0-9_.:-]*$/.test(this.value)
    }
})


答:
Use obj[key]</p>

```<code>console.log(req[x]);
</code>```

Body:
Use obj[key]

console.log(req[x]);


问:
Android Bluetooth permission not displayed, still descirbed as turned on
I have a problem with bluetooth permission. I've declared in the manifest following lines:

```<code><permission android:name="android.permission.BLUETOOTH" android:label="BLUETOOTH" />
<permission android:name="android.permission.BLUETOOTH_ADMIN" />
</code>```

What is weird that in app settings instead of bluetooth I've got a right to add permission for Location and Storage. But ok, lets say android doesn't provide specific perms for bluetooth and these are the same as BT. Weird thing is that even when I don't give any permission to the app (not for memory, not for localization), by using following code:

```<code>  int permissionCheck = ContextCompat.checkSelfPermission(this,
                Manifest.permission.BLUETOOTH_ADMIN);

        if(permissionCheck ==  PackageManager.PERMISSION_GRANTED){
            Toast.makeText(this, "granted", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(this, "not granted :(", Toast.LENGTH_SHORT).show();
        }
</code>```

I still get message that permission are granted. What the heck? Should I check specifically for a EXTERNAL_STORAGE and Location permissions? And why bluetooth isn't displayed in app permision configurations?

答:
There are two types of permissions in Android:

Dangerous permissions: These permissions are required to ask on run time if targetSdkVersion is 23 or above.

Normal Permissions: If you define these permissions in Manifest that is enough.

For more details check this link given below:

https://developer.android.com/guide/topics/permissions/requesting.html#normal-dangerous

Body:
I have a problem with bluetooth permission. I've declared in the manifest following lines:

<permission android:name="android.permission.BLUETOOTH" android:label="BLUETOOTH" />
<permission android:name="android.permission.BLUETOOTH_ADMIN" />

What is weird that in app settings instead of bluetooth I've got a right to add permission for Location and Storage. But ok, lets say android doesn't provide specific perms for bluetooth and these are the same as BT. Weird thing is that even when I don't give any permission to the app (not for memory, not for localization), by using following code:

  int permissionCheck = ContextCompat.checkSelfPermission(this,
                Manifest.permission.BLUETOOTH_ADMIN);

        if(permissionCheck ==  PackageManager.PERMISSION_GRANTED){
            Toast.makeText(this, "granted", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(this, "not granted :(", Toast.LENGTH_SHORT).show();
        }

I still get message that permission are granted. What the heck? Should I check specifically for a EXTERNAL_STORAGE and Location permissions? And why bluetooth isn't displayed in app permision configurations?


问:
C++ RIFF WAVE reader is painfully slow
So I've never really worked with binary files before and I'm new to C++. I wanted to read a wav file and output its data section into a txt (seperating the value of each sample with a comma). I also managed to read in the header section, but this code is not important here so I'll not include it.

My wav file stores data in the IEEE 754 standard (floating point numbers) at 32bps. I first read the entire wav file into a char vector and try to work with that afterwards. The output of the program is what I expect it to be, I can play the sound back in Python by reading in the txt without issues. The program is just horribly slow (it takes several minutes for a wav file that is a couple seconds long).

This is wavReader.cpp:

```<code>#include "stdafx.h"
#include "wavFile.h"
#include <fstream>
#include <iostream>
#include <vector>

int main()
{
    std::ifstream file("file.wav", std::ios::binary);
    std::vector<char> buffer((
        std::istreambuf_iterator<char>(file)),
        (std::istreambuf_iterator<char>()));
    std::cout << "Loading complete!\n";

    WavFile wavFile = setWavFile(buffer);

    return 0;
}
</code>```

This is wavFile.h:

```<code>#pragma once
#include <iostream>
#include <vector>

struct WavFile
{
    uint32_t dataSize;
};

WavFile setWavFile(std::vector<char> buffer);
uint32_t getUint32(std::vector<char> buffer, std::vector<char>::iterator it);
</code>```

This is wavFile.cpp:

```<code>#include "stdafx.h"
#include "WavFile.h"
#include <fstream>

WavFile setWavFile(std::vector<char> buffer) {

    WavFile wavFile;
    std::vector<char>::iterator it = buffer.begin();

    // Beginning of data chunk is marked with "data"
    it += 4;
    while (*(it - 4) != 'd' ||
        *(it - 3) != 'a' ||
        *(it - 2) != 't' ||
        *(it - 1) != 'a')
        it++;

    wavFile.dataSize = getUint32(buffer, it), it += 4;
    std::ofstream output("data.txt");

    while (it != buffer.end())
    {
        char outputChar[4];
        for (int i = 0; i < 4; (i++, it++))
            outputChar[i] = *it;
        char* outputStr = outputChar;
        char** outputStrPtr = &outputStr;
        float** outputPtr = reinterpret_cast<float**>(outputStrPtr);
        output << **outputPtr << ", ";
        std::cout << static_cast<double>(std::distance(buffer.begin(), it)) * 100 / wavFile.dataSize << "\%\n";
    }

    return wavFile;
}

uint32_t getUint32(std::vector<char> buffer, std::vector<char>::iterator it)
{
    char outputChar[4];
    for (int i = 0; i < 4; (i++, it++))
        outputChar[i] = *it;
    char* outputStr = outputChar;
    char** outputStrPtr = &outputStr;
    uint32_t** outputPtr = reinterpret_cast<uint32_t**>(outputStrPtr);
    return **outputPtr;
}
</code>```

I made the program print the progress to the console. Note that this only works with wav files that have one channel and store the samples in IEEE 754 standard. You can find the file I used here. I'm just a hobby programmer, so forgive me that I have no clue what makes my program this slow... Is it the vector iteration? Or is it the kinda messy variable declarations with reinterpret_cast?

答:
You are reading it completely wrong way. Wave files have RIFF format. Each file consists of RIFF file header and a sequence of chunks.

```<code>#include <Windows.h> // for DWORD
#include <MMReg.h> // for PCMWAVEFORMATPCMWAVEFORMAT and FORCC

struct t_RiffFileHeader
{
    ::FOURCC m_riff;      // must be 'R', 'I', 'F', 'F'
    ::DWORD  m_file_size; // should be less than or equal to the total file zize
    ::FOURCC m_formtype;  // must be 'W', 'A', 'V', 'E'
};
static_assert(12 == sizeof(t_RiffFileHeader), "");
</code>```

So you first read 12 bytes of this riff header and verify that it is correct.

```<code>size_t remaining_bytes_count(buffer.size());
const char * p_cursor(buffer.data());
if(remaining_bytes_count <= sizeof(t_RiffFileHeader))
{
    exit(1);
}
const t_RiffFileHeader & riff_header(*reinterpret_cast< const t_RiffFileHeader * >(reinterpret_cast< uintptr_t >(p_cursor)));
if(static_cast< size_t >(riff_header.m_file_size) < sizeof(t_RiffChunkHeader))
{
    exit(1);
}
p_cursor += sizeof(t_RiffFileHeader);
remaining_bytes_count -= sizeof(t_RiffFileHeader);
</code>```

Then you proceed to read chunks.

```<code>struct t_RiffChunkHeader
{
    ::FOURCC m_id;
    ::DWORD  m_chunk_content_size;
};
static_assert(8 == sizeof(t_RiffFileHeader), "");
</code>```

You read chunk header and then read m_chunk_content_size bytes of data based on chunk id:

'f', 'm', 't', ' ' chunk is typically first and should contain  PCMWAVEFORMAT structure describing wav data;

'd', 'a', 't', 'a' chunk contains audio data;

other chunks can be skipped.

If you are done with reading of the last chunk but file end is not reached yet then most likely there is another RIFF file attached. Because of 32-bit length limitation large files are constructed by concatenating several smaller RIFF files.

Title: C++ RIFF WAVE reader is painfully slow

Body:
So I've never really worked with binary files before and I'm new to C++. I wanted to read a wav file and output its data section into a txt (seperating the value of each sample with a comma). I also managed to read in the header section, but this code is not important here so I'll not include it.

My wav file stores data in the IEEE 754 standard (floating point numbers) at 32bps. I first read the entire wav file into a char vector and try to work with that afterwards. The output of the program is what I expect it to be, I can play the sound back in Python by reading in the txt without issues. The program is just horribly slow (it takes several minutes for a wav file that is a couple seconds long).

This is wavReader.cpp:

#include "stdafx.h"
#include "wavFile.h"
#include <fstream>
#include <iostream>
#include <vector>

int main()
{
    std::ifstream file("file.wav", std::ios::binary);
    std::vector<char> buffer((
        std::istreambuf_iterator<char>(file)),
        (std::istreambuf_iterator<char>()));
    std::cout << "Loading complete!\n";

    WavFile wavFile = setWavFile(buffer);

    return 0;
}

This is wavFile.h:

#pragma once
#include <iostream>
#include <vector>

struct WavFile
{
    uint32_t dataSize;
};

WavFile setWavFile(std::vector<char> buffer);
uint32_t getUint32(std::vector<char> buffer, std::vector<char>::iterator it);

This is wavFile.cpp:

#include "stdafx.h"
#include "WavFile.h"
#include <fstream>

WavFile setWavFile(std::vector<char> buffer) {

    WavFile wavFile;
    std::vector<char>::iterator it = buffer.begin();

    // Beginning of data chunk is marked with "data"
    it += 4;
    while (*(it - 4) != 'd' ||
        *(it - 3) != 'a' ||
        *(it - 2) != 't' ||
        *(it - 1) != 'a')
        it++;

    wavFile.dataSize = getUint32(buffer, it), it += 4;
    std::ofstream output("data.txt");

    while (it != buffer.end())
    {
        char outputChar[4];
        for (int i = 0; i < 4; (i++, it++))
            outputChar[i] = *it;
        char* outputStr = outputChar;
        char** outputStrPtr = &outputStr;
        float** outputPtr = reinterpret_cast<float**>(outputStrPtr);
        output << **outputPtr << ", ";
        std::cout << static_cast<double>(std::distance(buffer.begin(), it)) * 100 / wavFile.dataSize << "\%\n";
    }

    return wavFile;
}

uint32_t getUint32(std::vector<char> buffer, std::vector<char>::iterator it)
{
    char outputChar[4];
    for (int i = 0; i < 4; (i++, it++))
        outputChar[i] = *it;
    char* outputStr = outputChar;
    char** outputStrPtr = &outputStr;
    uint32_t** outputPtr = reinterpret_cast<uint32_t**>(outputStrPtr);
    return **outputPtr;
}

I made the program print the progress to the console. Note that this only works with wav files that have one channel and store the samples in IEEE 754 standard. You can find the file I used here. I'm just a hobby programmer, so forgive me that I have no clue what makes my program this slow... Is it the vector iteration? Or is it the kinda messy variable declarations with reinterpret_cast?

Body:
You are reading it completely wrong way. Wave files have RIFF format. Each file consists of RIFF file header and a sequence of chunks.

#include <Windows.h> // for DWORD
#include <MMReg.h> // for PCMWAVEFORMATPCMWAVEFORMAT and FORCC

struct t_RiffFileHeader
{
    ::FOURCC m_riff;      // must be 'R', 'I', 'F', 'F'
    ::DWORD  m_file_size; // should be less than or equal to the total file zize
    ::FOURCC m_formtype;  // must be 'W', 'A', 'V', 'E'
};
static_assert(12 == sizeof(t_RiffFileHeader), "");

So you first read 12 bytes of this riff header and verify that it is correct.

size_t remaining_bytes_count(buffer.size());
const char * p_cursor(buffer.data());
if(remaining_bytes_count <= sizeof(t_RiffFileHeader))
{
    exit(1);
}
const t_RiffFileHeader & riff_header(*reinterpret_cast< const t_RiffFileHeader * >(reinterpret_cast< uintptr_t >(p_cursor)));
if(static_cast< size_t >(riff_header.m_file_size) < sizeof(t_RiffChunkHeader))
{
    exit(1);
}
p_cursor += sizeof(t_RiffFileHeader);
remaining_bytes_count -= sizeof(t_RiffFileHeader);

Then you proceed to read chunks.

struct t_RiffChunkHeader
{
    ::FOURCC m_id;
    ::DWORD  m_chunk_content_size;
};
static_assert(8 == sizeof(t_RiffFileHeader), "");

You read chunk header and then read m_chunk_content_size bytes of data based on chunk id:

'f', 'm', 't', ' ' chunk is typically first and should contain  PCMWAVEFORMAT structure describing wav data;

'd', 'a', 't', 'a' chunk contains audio data;

other chunks can be skipped.

If you are done with reading of the last chunk but file end is not reached yet then most likely there is another RIFF file attached. Because of 32-bit length limitation large files are constructed by concatenating several smaller RIFF files.


问:
Github pages picking readme but not index.html
I am using github pages to host a single page application which I have been working on. This is my first time using github pages. The project is based on angular js and the structure of project is like

project:

src

index.html

...

...

It is a public repo you can see that at https://github.com/ChanikyaMohan/Angular-play

The problem is the github pages is picking up readme file but not index.html.
Any suggestions on how to fix it?

Thanks.

答:
your index.html is in the src folder ..
place it in the top of the gh-pages</p>


答: You can also use console.log(req.name)

Body:
I have made a js file in which data is being fetched from js file and the values are stored in a request object. Example of JSON file

{
    "name": "ABC",
    "age": 20
}

I want to display the value of name using variable name. I want something like this.

var x = "name";
var req = JSON.parse(request.responseText);
console.log(req.x);

But the above statement displays undefined. Any solutions?

Body: You can also use console.log(req.name)


问:
Use of undeclared type Xcode with Cocoapods
I am trying to refer to the app delegate in a UIButton Action that is in a Pods class in my workspace, however, I keep getting the error "Use of undeclared type". I believe this is due to the App Delegate being in the other workspace project. I would like to know how to fix it? Thank you.

Button Code

```<code>@IBAction func buttonAction(sender: AnyObject) {
    let paymentViewController = storyboard.instantiateViewControllerWithIdentifier("paymentViewController") as! AddCardViewController

    let paymentPageNav = UINavigationController(rootViewController: paymentViewController)

    let appDelegate:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

   appDelegate.drawerContainer!.centerViewController = paymentPageNav
   appDelegate.drawerContainer!.toggleDrawerSide(MMDrawerSide.Left, animated: true, completion: nil)
}
</code>```

I get use of undeclared type for AddCardViewController, AppDelegate and MMDrawerSide.

答:
Had this problem with casting to custom controls from pods on my project, what solved it for me is to add import statement in the head of the file for my custom controller.

So if for example I am in MainViewController.swift and want to use a custom control/view/lib called MyCustomController imported with CocoaPods I add import MyCustomController after the import UIKit

Body:
I am trying to refer to the app delegate in a UIButton Action that is in a Pods class in my workspace, however, I keep getting the error "Use of undeclared type". I believe this is due to the App Delegate being in the other workspace project. I would like to know how to fix it? Thank you.

Button Code

@IBAction func buttonAction(sender: AnyObject) {
    let paymentViewController = storyboard.instantiateViewControllerWithIdentifier("paymentViewController") as! AddCardViewController

    let paymentPageNav = UINavigationController(rootViewController: paymentViewController)

    let appDelegate:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

   appDelegate.drawerContainer!.centerViewController = paymentPageNav
   appDelegate.drawerContainer!.toggleDrawerSide(MMDrawerSide.Left, animated: true, completion: nil)
}

I get use of undeclared type for AddCardViewController, AppDelegate and MMDrawerSide.