问:
Use of promises in NODE.js // console log prints the result several times
I'm making a program that takes an array of links and returns how many are broken and how many are working. Right now, I'm testing it with an array that has four working links and two broken links. Here's my code:

```<code>function getBrokenLinks(linksArr){
    let links = linksArr
    let brokenLinks = 0
    links.forEach(link => {
        fetch(link.href)
            .then( res => {
                if ( res.status != 200 ){
                    brokenLinks++
                }
            }).then( () => {console.log(brokenLinks)})
    })
    return brokenLinks
}
</code>```

and this is the output i receive:

output

I want the console to print the total of broken links only once, and after it has completed fetching all the links.

答:
You can use Promise.all to wait for all promises to be resvoled:

```<code>/*
Promise.all([promise1, promise2,..])
.then(function() {
    // all promises have been resolved
})
*/

function getBrokenLinks(linksArr) {
    let links = linksArr
    let brokenLinks = 0
    let promises = []

    links.forEach(link => {
        // save promise to push onto array
        let promise = fetch(link.href)
        .then(res => {
            if (res.status != 200) {
                brokenLinks++
            }
        })
        promises.push(promise)
    })

    return Promise.all(promises)
    .then(() => {
        return brokenLinks
    })
}

// Calling code:
/*
getBrokenLinks([])
.then(console.log)
*/
</code>```

Body:
I'm making a program that takes an array of links and returns how many are broken and how many are working. Right now, I'm testing it with an array that has four working links and two broken links. Here's my code:

function getBrokenLinks(linksArr){
    let links = linksArr
    let brokenLinks = 0
    links.forEach(link => {
        fetch(link.href)
            .then( res => {
                if ( res.status != 200 ){
                    brokenLinks++
                }
            }).then( () => {console.log(brokenLinks)})
    })
    return brokenLinks
}

and this is the output i receive:

output

I want the console to print the total of broken links only once, and after it has completed fetching all the links.

Body:
You can use Promise.all to wait for all promises to be resvoled:

/*
Promise.all([promise1, promise2,..])
.then(function() {
    // all promises have been resolved
})
*/

function getBrokenLinks(linksArr) {
    let links = linksArr
    let brokenLinks = 0
    let promises = []

    links.forEach(link => {
        // save promise to push onto array
        let promise = fetch(link.href)
        .then(res => {
            if (res.status != 200) {
                brokenLinks++
            }
        })
        promises.push(promise)
    })

    return Promise.all(promises)
    .then(() => {
        return brokenLinks
    })
}

// Calling code:
/*
getBrokenLinks([])
.then(console.log)
*/


来源: stackexchange

问:
Problem with the data
I have the problem with the data in my database.
I tried to put some data and show it on my spinner. But I have the empty spinner.
I really don't understand where I was wrong.
Here is my code

```<code>public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE "+TABLE_NAME+" ("+colCountryID+ " INTEGER PRIMARY KEY , "+
            colCountryName+ " TEXT)");
    InsertCountry(db);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME);
    onCreate(db);
}
public Cursor getAllDepts() {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cur = db.rawQuery("SELECT " + colCountryID + " as _id, " + colCountryName + " from " + TABLE_NAME, new String[] {});
    return cur;
}

public void InsertCountry(SQLiteDatabase db) {
    ContentValues cv = new ContentValues();
    cv.put(colCountryID, 1);
    cv.put(colCountryName, "GB");
    db.insert(TABLE_NAME, null, cv);
    Log.w(TABLE_NAME, "insert");

}
</code>```

And

```<code>database = new DBTestHelper(this);

Cursor c=database.getAllDepts();
startManagingCursor(c);

SimpleCursorAdapter ca=new SimpleCursorAdapter(this,R.layout.dvdfg, c, new String [] {DBTestHelper.colCountryName,"_id"}, new int []{R.id.text});
//ca.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
counry.setAdapter(ca);
</code>```

答:
```<code>Cursor cur = db.rawQuery("SELECT " + colCountryID + " as _id, " + colCountryName + " from " + TABLE_NAME, new String[] {});
</code>```

seems strange to me try to pass a null array as last argument

```<code>Cursor cur = db.rawQuery("SELECT " + colCountryID + " as _id, " + colCountryName + " from " + TABLE_NAME, null);
</code>```

ContentLicense: CC BY-SA 3.0

Title: Problem with the data

Body:
I have the problem with the data in my database.
I tried to put some data and show it on my spinner. But I have the empty spinner.
I really don't understand where I was wrong.
Here is my code

public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE "+TABLE_NAME+" ("+colCountryID+ " INTEGER PRIMARY KEY , "+
            colCountryName+ " TEXT)");
    InsertCountry(db);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME);
    onCreate(db);
}
public Cursor getAllDepts() {
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor cur = db.rawQuery("SELECT " + colCountryID + " as _id, " + colCountryName + " from " + TABLE_NAME, new String[] {});
    return cur;
}

public void InsertCountry(SQLiteDatabase db) {
    ContentValues cv = new ContentValues();
    cv.put(colCountryID, 1);
    cv.put(colCountryName, "GB");
    db.insert(TABLE_NAME, null, cv);
    Log.w(TABLE_NAME, "insert");

}

And

database = new DBTestHelper(this);

Cursor c=database.getAllDepts();
startManagingCursor(c);

SimpleCursorAdapter ca=new SimpleCursorAdapter(this,R.layout.dvdfg, c, new String [] {DBTestHelper.colCountryName,"_id"}, new int []{R.id.text});
//ca.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
counry.setAdapter(ca);

Body:
Cursor cur = db.rawQuery("SELECT " + colCountryID + " as _id, " + colCountryName + " from " + TABLE_NAME, new String[] {});

seems strange to me try to pass a null array as last argument

Cursor cur = db.rawQuery("SELECT " + colCountryID + " as _id, " + colCountryName + " from " + TABLE_NAME, null);


问:
How to undo php artisan storage:link command that deleting all storage folder content
I uploaded an image file using this code.

```<code>// Get filename with the extension
$filenameWithExt = $request->file('cover_image')->getClientOriginalName();
// Get just filename
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
// Get just ext
$extension = $request->file('cover_image')->getClientOriginalExtension();
// Filename to store
$fileNameToStore= $filename.'_'.time().'.'.$extension;
// Upload Image
$path = $request->file('cover_image')->storeAs('public/cover_images', $fileNameToStore);
</code>```

Then tried to make a symlink to the storage folder so it can be accessible from the public folder. I typed this command php artisan storage:link in the cmd, But then it destroyed all the contents in the storage folder and deleted it then displayed this error.

```<code>The system cannot find the path specified.
The [public/storage] directory has been linked.
</code>```

Now when I run the server PHP artisan serve I get this error.

I am new to laravel and now am stuck, how can I solve this? The storage folder was recreated with nothing but log files in it.

答:
I was actually able to solve this error. The good thing is that I had a copy of the same project in another directory, so I delete the current storage folder showing log files only and the copy and pasted the storage folder from the other project I had backedup and re-uploaded the image. After that, I used the same command php artisan storage:link but this time I had the public folder path selected

C:\xampp\htdocs\mwalimu_shaaban\public

C:\xampp\htdocs\mwalimu_shaaban>php artisan storage:link
The [public/storage] directory has been linked.

I Think the problem arouse since I had not selected the symbolic link destination path in the beginning.

ContentLicense: CC BY-SA 4.0

Body:
I uploaded an image file using this code.

// Get filename with the extension
$filenameWithExt = $request->file('cover_image')->getClientOriginalName();
// Get just filename
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
// Get just ext
$extension = $request->file('cover_image')->getClientOriginalExtension();
// Filename to store
$fileNameToStore= $filename.'_'.time().'.'.$extension;
// Upload Image
$path = $request->file('cover_image')->storeAs('public/cover_images', $fileNameToStore);

Then tried to make a symlink to the storage folder so it can be accessible from the public folder. I typed this command php artisan storage:link in the cmd, But then it destroyed all the contents in the storage folder and deleted it then displayed this error.

The system cannot find the path specified.
The [public/storage] directory has been linked.

Now when I run the server PHP artisan serve I get this error.

I am new to laravel and now am stuck, how can I solve this? The storage folder was recreated with nothing but log files in it.


问:
Why can't receive messages using gateway in MQTT Google IoT Core?
I am using the Cloud IoT Core module to send messages from a device to the cloud using MQTT.
The device uses a gateway to send these messages and the gateway is configured with the Association only method.
For this, the MQTT Client is configured with the gatewayID so the gateway is the only one authenticated.

The problem is that, if the gateway publishes telemetry data using the device's MQTT topic like this  "/devices/{device-id}/events", the telemetry data is not received in the cloud (I have checked this with a Cloud pub/sub subscription). It doesn't show any error on the gateway, and even the Message Delivered callback is called.

However, if the gateway publishes data to its topic, which is "/devices/{gateway-id}/events", the telemetry data is received correctly in the cloud.

I have checked Google's GitHub documentation (I am using JAVA for this with mqtt paho) and the topic it uses to publish telemetry data on behalf the device (also with the association only method) is the "/devices/{device-id}/events".

Is this because the Authorization only method only allows publishing the telemetry data through the gateway's MQTT topic??

答:
For gateways to work properly you need to have the devices set up correctly and that the gateway is binded to the device then you can attach the device topic,commands,and configuration.

Association only refers to when you're attaching the device to the gateway and you should be able to send telemetry data from the devices event topic.

I think that either your devices aren't setup properly or you didn't bind the devices to the gateway.


问:
Java for( x : y) execution
I have the following for loop:

```<code>for(String s : someString.split("\\s+")){
   //do something
}
</code>```

Does java execute the split() method each time the loop iterates, or does it do it only once and keep a temp array to iterate on?

答: No the split is executed once on the string and after that the loop iterate over the result </p>

Title: Java for( x : y) execution

Body:
I have the following for loop:

for(String s : someString.split("\\s+")){
   //do something
}

Does java execute the split() method each time the loop iterates, or does it do it only once and keep a temp array to iterate on?


问:
Can a GitHub organization owner remove another owner?
Say I make an organization, and set someone else to owner. Will they be able to remove me from that organization? Or are there special elevated perms for the "original" owner?

I'm not sure if StackOverflow is even the right place for this question, but I haven't been able to find anything about this online.

答:
Depends what you want to do. If you want them to be able to add/remove other members without giving over full organisation access you try to add a team, add the repositories you want to that team with write access, then make the user a "maintainer" of the team which should allow them to add/remove users and therefore manage write access to particular repositories.

https://help.github.com/en/github/setting-up-and-managing-organizations-and-teams/permission-levels-for-an-organization


问:
Combining multiple callbacks in javascript
In my call back response of chrome.runtime.onMessage.addListener gets undefined or True. When chrome.runtime.onMessage.addListener receives a message it communicates to a native application and retrieves a response. I want to return that response to the chrome.runtime.onMessage.addListener response. I tried learning about combing two callbacks, but didn't have any luck over there.

```<code>async processMsg(response, param2) {}

async function A1(msg, sender) {
      await chrome.runtime.sendNativeMessage(hostName, mesg,async function(response) {
            var resp = await processMsg(response, param2);
            return resp;
        });

  return true;
}

chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
   A1(msg, sender).then(sendResponse);
    return true;
});
</code>```

答:
You should to return the promise in A1 function, like this:

async processMsg(response, param2) {
    return "not null"
}

async function A1(msg, sender) {
    return await chrome.runtime.sendNativeMessage(hostName, mesg,async function(response) {
        return processMsg(response, param2);
    });
}

chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
    A1(msg, sender).then(sendResponse);
    return true; //I don't think you need to return anything here
});
```

Body:
In my call back response of chrome.runtime.onMessage.addListener gets undefined or True. When chrome.runtime.onMessage.addListener receives a message it communicates to a native application and retrieves a response. I want to return that response to the chrome.runtime.onMessage.addListener response. I tried learning about combing two callbacks, but didn't have any luck over there.

async processMsg(response, param2) {}

async function A1(msg, sender) {
      await chrome.runtime.sendNativeMessage(hostName, mesg,async function(response) {
            var resp = await processMsg(response, param2);
            return resp;
        });

  return true;
}

chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
   A1(msg, sender).then(sendResponse);
    return true;
});


问:
How do you manage image versions with Packer and Terraform?
I'm currently using a Kubernetes cluster running on bare metal nodes provisioned with Ansible. There are plans to move to the cloud and I'm reading about Terraform and Packer, in preparation for this. Leaving the data migration aside, it seems like there is a pretty straight forward migration path for us:

Build image with Packer using our existing Ansible scripts

Deploy built image to the cloud with Terraform

Deploy our Kubernetes resources with our current tooling

That's all great. We now have immutable infrastructure, using state of the art tooling.

What I am struggling to find is how images built with Packer are versioned. Somewhere down the line, we will have to upgrade some software in those images. Sometimes the Ansible scripts will change, but sometimes it's just a matter of having the latest security updates in the image. Either way, Packer will have to build a new image for us and we will have to deploy it with Terraform. If the new image ends up causing trouble, we will have to revert to the old one.

I can imagine how this could be done manually by editing the template before running it and then editing the terraform configuration to pick up the new version, but that's not going to work for a CI/CD pipeline. Another issue is that we may move between different regions and vendors. So a version of the image may be present in one region, but not the other, and ideally, the pipeline should create the image if it doesn't exist and use the existing one if it is already there. This may cause images in different regions or clouds to be different, especially since they might be built on different days and have different security updates applied.

All of this is built in to the Docker workflow, but with Packer, it's far from obvious what to do. I haven't found any documentation or tutorials that cover this topic. Is there any built-in versioning functionality in Packer and Terraform? Is Terraform able to invoke Packer if an image is missing? Is there any accepted best practice?

I can imagine automating this by using the API from the cloud provider to check for the existence of the required images and invoke Packer for any missing images, before executing Terraform. This would work, but I wouldn't want to write custom integration for each cloud provider and it sounds like something that should already be provided by Terraform. I haven't used Terraform before, so maybe I just don't know where to look, and maybe it's not that difficult to implement in Terraform, but then why aren't there any tutorials showing me how?

答:
So for what it’s worth, the image versioning is useful because you can save some defaults for things like kubernetes host nodes (pre-downloaded docker images, etc) so by the time it passes the AWS checks, it is already joining the cluster.

I have don’t this for numerous apps and found it is typically best to do something like below

```<code>vendor-app-appversion-epoch
</code>```

This approach allows you to version your Ami along with your apps, and then you can treat your instances like cattle (to be slaughtered) versus pets (to be cared for throughout their life).

```<code>data "aws_ami" "amazon_linux2" {
  most_recent = true
  filter {
    name = "name"
    values = ["amzn2-ami-*-x86_64-gp2"]
  }

  filter {
    name = "virtualization-type"
    values = ["hvm"]
  }

  owners = ["amazon"]
}
</code>```

This will pull the latest image for linux2 when you apply terraform.

Body:
So for what it’s worth, the image versioning is useful because you can save some defaults for things like kubernetes host nodes (pre-downloaded docker images, etc) so by the time it passes the AWS checks, it is already joining the cluster.

I have don’t this for numerous apps and found it is typically best to do something like below

vendor-app-appversion-epoch

This approach allows you to version your Ami along with your apps, and then you can treat your instances like cattle (to be slaughtered) versus pets (to be cared for throughout their life).

data "aws_ami" "amazon_linux2" {
  most_recent = true
  filter {
    name = "name"
    values = ["amzn2-ami-*-x86_64-gp2"]
  }

  filter {
    name = "virtualization-type"
    values = ["hvm"]
  }

  owners = ["amazon"]
}

This will pull the latest image for linux2 when you apply terraform.


问:
CSS Media Query using multiple using the and logical operator not working as expected
I have added the following media query to my code:

```<code>@media screen and (min-width: 700px) and (max-width: 800px){
    body {
        margin: 50px;
    }

    body, p {
        font-size: 1.6rem;
        font-size: 16px;
    }

    #title {
        font-size: 4rem;
        font-size: 40px;
    }
}
</code>```

However, when displaying the page in a macBook 13, which has a screen bigger than the max-width of 800px, the styling is still following the media query above instead of the code outside of the media query.

Here's the link to the GitHub repo with the full HTML and CSS code:
MVP survey-form repo

It's a single page project.

Thanks.

答:
Ok. I found the issue:

Besides the media query that I posted on the question, I also had this one right before it:

```<code>@media screen and (min-width: 300px){
    body {
        background-color: #605853;
        margin: 0px;
        font-size: 100%;
    }

    p, p.definition {
        font-size: 1em;
    }

    #title {
        font-size: 1.250em !important;
    }

    .form-control{
        height: 3rem;
    }

}
</code>```

Now I know I should have included both. My bad.

When the page is bigger than 800px, instead of the page following the general CSS code, it was defaulting to the first media query because I have only specified min-width. A way to correct the problem is to add a max-width to that first media query. This took care of the problem:

```<code>@media screen and (min-width: 300px) and (max-width: 699px)
</code>```

I'll read more on media queries, cause I'm not sure if this is the best way to handle small screens. It feels too broad.

Thank you for everyone who replied.

Body:
I have added the following media query to my code:

@media screen and (min-width: 700px) and (max-width: 800px){
    body {
        margin: 50px;
    }

    body, p {
        font-size: 1.6rem;
        font-size: 16px;
    }

    #title {
        font-size: 4rem;
        font-size: 40px;
    }
}

However, when displaying the page in a macBook 13, which has a screen bigger than the max-width of 800px, the styling is still following the media query above instead of the code outside of the media query.

Here's the link to the GitHub repo with the full HTML and CSS code:
MVP survey-form repo

It's a single page project.

Thanks.

Body:
Ok. I found the issue:

Besides the media query that I posted on the question, I also had this one right before it:

@media screen and (min-width: 300px){
    body {
        background-color: #605853;
        margin: 0px;
        font-size: 100%;
    }

    p, p.definition {
        font-size: 1em;
    }

    #title {
        font-size: 1.250em !important;
    }

    .form-control{
        height: 3rem;
    }

}

Now I know I should have included both. My bad.

When the page is bigger than 800px, instead of the page following the general CSS code, it was defaulting to the first media query because I have only specified min-width. A way to correct the problem is to add a max-width to that first media query. This took care of the problem:

@media screen and (min-width: 300px) and (max-width: 699px)

I'll read more on media queries, cause I'm not sure if this is the best way to handle small screens. It feels too broad.

Thank you for everyone who replied.


问:
Unable to store instance in JavaScript variable
I'm currently working on implementing a Stack in JavaScript using a LinkedList. However, I have an issue when instantiating a Node class. When I try to have a variable let newNode = new Node(x) I get undefined.

I'm not sure why that is but I would like to understand. If in the repl I run new Node(x) I get { val: -2, next: null } a node. But when I store it in a variable I get undefined let newNode = new Node(x) it returns undefined if I console newNode.

```<code>/**
 * initialize your data structure here.
 */
var MinStack = function() {
  this.size = 0;
  this.min = null;
  this.first = null;
};

var Node = function(val) {
  this.val = val;
  this.next = null;
}
/**
 * @param {number} x
 * @return {void}
 */
MinStack.prototype.push = function(x) {
  if(this.first == null) {
    this.first = new Node(x);
    this.min = this.first;
    this.size++;
    return
  }

  let newNode = new Node(x);
  if(newNode.val < this.min.val) {
    this.min = newNode.val;
  }
  let oldFirst = this.first;
  newNode.next = oldFirst;
  this.first = newNode;
  this.size++;
};
/**
 * @return {void}
 */
MinStack.prototype.pop = function() {
  if(this.first === null) {
    return;
  }
  if(this.min === this.first) {
    let current = this.first.next;
    this.min = current;
    while(current != null) {
      if(current.val < this.min.val || this.size === 2) {
        this.min = current;
      }
      current = current.next;
    }
  }
  this.first = this.first.next;
  this.size--;
  return
};
/**
 * @return {number}
 */
MinStack.prototype.top = function() {
  return this.first.val;
};
/**
 * @return {number}
 */
MinStack.prototype.getMin = function() {
    return this.min.val;
};
// ["MinStack","push","push","push","getMin","pop","top","getMin"]
// [[],[-2],[0],[-3],[],[],[],[]]

var obj = new MinStack()
obj.push(-2)
obj.push(0)
obj.push(-3)
console.log(obj.getMin())
obj.pop();
obj.top();
obj.getMin();
</code>```

This is what I get when I get to the debugger breakpoint

```<code>> let newNode = new Node(x)
undefined
> newNode
undefined
> new Node(x)
{ val: 0, next: null }
</code>```

What am I missing?

答:
missing semicolon after closing bracket of Node class/function definition

```<code>var Node = function(val) {
  this.val = val;
  this.next = null;
}
</code>```

should be

```<code>var Node = function(val) {
  this.val = val;
  this.next = null;
};
</code>```

Body:
I'm currently working on implementing a Stack in JavaScript using a LinkedList. However, I have an issue when instantiating a Node class. When I try to have a variable let newNode = new Node(x) I get undefined.

I'm not sure why that is but I would like to understand. If in the repl I run new Node(x) I get { val: -2, next: null } a node. But when I store it in a variable I get undefined let newNode = new Node(x) it returns undefined if I console newNode.

/**
 * initialize your data structure here.
 */
var MinStack = function() {
  this.size = 0;
  this.min = null;
  this.first = null;
};

var Node = function(val) {
  this.val = val;
  this.next = null;
}
/**
 * @param {number} x
 * @return {void}
 */
MinStack.prototype.push = function(x) {
  if(this.first == null) {
    this.first = new Node(x);
    this.min = this.first;
    this.size++;
    return
  }

  let newNode = new Node(x);
  if(newNode.val < this.min.val) {
    this.min = newNode.val;
  }
  let oldFirst = this.first;
  newNode.next = oldFirst;
  this.first = newNode;
  this.size++;
};
/**
 * @return {void}
 */
MinStack.prototype.pop = function() {
  if(this.first === null) {
    return;
  }
  if(this.min === this.first) {
    let current = this.first.next;
    this.min = current;
    while(current != null) {
      if(current.val < this.min.val || this.size === 2) {
        this.min = current;
      }
      current = current.next;
    }
  }
  this.first = this.first.next;
  this.size--;
  return
};
/**
 * @return {number}
 */
MinStack.prototype.top = function() {
  return this.first.val;
};
/**
 * @return {number}
 */
MinStack.prototype.getMin = function() {
    return this.min.val;
};
// ["MinStack","push","push","push","getMin","pop","top","getMin"]
// [[],[-2],[0],[-3],[],[],[],[]]

var obj = new MinStack()
obj.push(-2)
obj.push(0)
obj.push(-3)
console.log(obj.getMin())
obj.pop();
obj.top();
obj.getMin();

This is what I get when I get to the debugger breakpoint

> let newNode = new Node(x)
undefined
> newNode
undefined
> new Node(x)
{ val: 0, next: null }

What am I missing?

Body:
missing semicolon after closing bracket of Node class/function definition

var Node = function(val) {
  this.val = val;
  this.next = null;
}

should be

var Node = function(val) {
  this.val = val;
  this.next = null;
};


问:
Resizing iFrame with jQuery UI
I have this code and it works fine:

Head

```<code>    <script>
    $(document).ready(function()
    {
        $("#test").resizable({minHeight: 50, minWidth: 50});
    });
</script>
</code>```

Body

```<code><div id="test" style="border: .1em solid black;">
</div>
</code>```

However when I change my "div" into "iframe" I can't resize it anymore.

Body

```<code><iframe id="test" style="border: .1em solid black;">
</iframe>
</code>```

答:
Found redsquare's demo a bit wonky when moving the mouse more than a few pixels at a time.  I've applied a couple modifications that help make resizing a lot smoother:

```<code><html>
<head>
  <style type="text/css">
    #resizable { width: 150px; height: 150px; padding: 0.5em; }
    #resizable h3 { text-align: center; margin: 0; }
    .ui-resizable-helper { border: 75px solid #EFEFEF; margin: -75px; }
  </style>
  <script type="text/javascript">
    $(function() {
      $("#resizable").resizable({
        helper: "ui-resizable-helper"
      });
    });
  </script>
</head>
<body>
  <div class="demo">
    <div id="resizable" class="ui-widget-content">
      <iframe src="http://pastebin.me/f9ed9b9d36d17a7987e9cb670e01f0e2" class="ui-widget-content" frameborder="no" id="test" width="100%" height="100%" />
    </div>
  <div>
</body>
</html>
</code>```

The weirdness of resizing seems to happen because mousemove events don't bubble up from within the iframe.  Using a resize handler and a large border in the handler CSS minimizes the effect caused by the iframe as long as the browser can keep up with the mousemove events.

OwnerDisplayName: Questionable

ContentLicense: CC BY-SA 2.5

Title: Resizing iFrame with jQuery UI

Body:
I have this code and it works fine:

Head

Body

However when I change my "div" into "iframe" I can't resize it anymore.

Body

Body:
Found redsquare's demo a bit wonky when moving the mouse more than a few pixels at a time.  I've applied a couple modifications that help make resizing a lot smoother:

<html>
<head>
  <style type="text/css">
    #resizable { width: 150px; height: 150px; padding: 0.5em; }
    #resizable h3 { text-align: center; margin: 0; }
    .ui-resizable-helper { border: 75px solid #EFEFEF; margin: -75px; }
  </style>
  <script type="text/javascript">
    $(function() {
      $("#resizable").resizable({
        helper: "ui-resizable-helper"
      });
    });
  </script>
</head>
<body>
  <div class="demo">
    <div id="resizable" class="ui-widget-content">
      <iframe src="http://pastebin.me/f9ed9b9d36d17a7987e9cb670e01f0e2" class="ui-widget-content" frameborder="no" id="test" width="100%" height="100%" />
    </div>
  <div>
</body>
</html>

The weirdness of resizing seems to happen because mousemove events don't bubble up from within the iframe.  Using a resize handler and a large border in the handler CSS minimizes the effect caused by the iframe as long as the browser can keep up with the mousemove events.


问:
Uppercase specific words in EditText
Inside EditText I want to know how to capitalize on specific words. The code is below.

```<code> editText.addTextChangedListener(new TextWatcher() {

        private static final String KEYWORD = "rain";
        private static final String KEYWORD1 = "music";

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            onSaveNote();
        }

        @Override
        public void afterTextChanged(Editable s) {
            onSaveNote();

            try {

                for (StyleSpan span : s.getSpans(0, s.length(), StyleSpan.class)) {
                    s.removeSpan(span);
                }

                // Add new spans for every occurrence of the keyword.
                int i = 0;
                while (i != -1) {
                    i = editText.getText().toString().indexOf(KEYWORD, i);
                    if (i != -1) {
                        s.setSpan(new InputFilter[]{new InputFilter.AllCaps()}, i, i + KEYWORD.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

                    }

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

I tried searching for this but not found any. InputFilter doesn't work. How to do this?

答:
If you know value of your text and start and end index of your text.

```<code>editText.getText().toString().substring(startIndex, endIndex).toUpperCase();
</code>```

You can find start index in text like this:

```<code>editText.getText().toString().indexOf(KEYWORD)
</code>```

and end index like this:

```<code>editText.getText().toString().indexOf(KEYWORD) + KEYWORD.length()
</code>```

Title: Uppercase specific words in EditText

Body:
Inside EditText I want to know how to capitalize on specific words. The code is below.

 editText.addTextChangedListener(new TextWatcher() {

        private static final String KEYWORD = "rain";
        private static final String KEYWORD1 = "music";

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            onSaveNote();
        }

        @Override
        public void afterTextChanged(Editable s) {
            onSaveNote();

            try {

                for (StyleSpan span : s.getSpans(0, s.length(), StyleSpan.class)) {
                    s.removeSpan(span);
                }

                // Add new spans for every occurrence of the keyword.
                int i = 0;
                while (i != -1) {
                    i = editText.getText().toString().indexOf(KEYWORD, i);
                    if (i != -1) {
                        s.setSpan(new InputFilter[]{new InputFilter.AllCaps()}, i, i + KEYWORD.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

                    }

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

I tried searching for this but not found any. InputFilter doesn't work. How to do this?

Body:
If you know value of your text and start and end index of your text.

editText.getText().toString().substring(startIndex, endIndex).toUpperCase();

You can find start index in text like this:

editText.getText().toString().indexOf(KEYWORD)

and end index like this:

editText.getText().toString().indexOf(KEYWORD) + KEYWORD.length()


问:
Is there a way to make a map object repeat?
Say if I have a map object: map(lambda x: int(x), "123"), but I want 6 items, I would expect 1,2,3,1,2,3 (Note I don't want it in list format, I would use next to get each item), but instead I just get a StopIteration error once I pull out 3 items. I do have a workaround but it's not as clean as I would like:

```<code>def MakeMap(): return map(lambda x:int(x), "123")
mapped=MakeMap()
for i in range(6):
     try:
         print(next(mapped))
     except StopIteration:
         mapped=MakeMap()
         print(next(mapped))
</code>```

While this works, as stated above I would like it to be just as easy as:

```<code>mapped=map(lambda x:int(x), "123")
for i in range(6):
    print(next(mapped))
</code>```

Is there anyway to do this?

答:
itertools.cycle is the general way to (indefinitely) repeat any iterator's sequence.

```<code>>>> from itertools import cycle
>>> mapped = cycle(map(int, "123"))
>>> for i in range(6):
...    print(next(mapped))
1
2
3
1
2
3
</code>```

Do note the other change:  lambda x: int(x) works, but is an expensive and obscure way to spell plain old int.

Body:
Say if I have a map object: map(lambda x: int(x), "123"), but I want 6 items, I would expect 1,2,3,1,2,3 (Note I don't want it in list format, I would use next to get each item), but instead I just get a StopIteration error once I pull out 3 items. I do have a workaround but it's not as clean as I would like:

def MakeMap(): return map(lambda x:int(x), "123")
mapped=MakeMap()
for i in range(6):
     try:
         print(next(mapped))
     except StopIteration:
         mapped=MakeMap()
         print(next(mapped))

While this works, as stated above I would like it to be just as easy as:

mapped=map(lambda x:int(x), "123")
for i in range(6):
    print(next(mapped))

Is there anyway to do this?

Body:
itertools.cycle is the general way to (indefinitely) repeat any iterator's sequence.

>>> from itertools import cycle
>>> mapped = cycle(map(int, "123"))
>>> for i in range(6):
...    print(next(mapped))
1
2
3
1
2
3

Do note the other change:  lambda x: int(x) works, but is an expensive and obscure way to spell plain old int.


问:
iOS Background service limitations
I would like to know if there are limitations regarding how often I can execute something in the background. I found this library : background fetch and it says that on the iOS part I cannot execute it more often than 15 minutes.

Are there workarounds for this?

My purpose is to check in the background the available Bluetooth devices detected and to send them to a database.

I only have experience in android and I'm not sure how to convert it to iOS or if it is possible.

答:
Yes, there are limitations imposed by iOS.  It will decide when your app is given time to execute background tasks such as a fetch of web data.  It can be more frequent than 15 minutes but on average it may be every 20 minutes at best.  It might be two hours or more.  We are not privy to the algorithm and cannot predict the result.

Known factors are power state, how well your app conforms to the rules and gets its work done in the time allotted, and some measure of how (and when) the user uses your app.  Low battery?  Fewer background tasks allowed.  User never uses the app before 8AM?  Few fetches called overnight.  It's all beyond developer control.

A developer can use a timer to trigger a routine task but it's only relevant if the app stays active in the foreground.

Title: iOS Background service limitations


问:
Python - How to Save 2 values outputf.write
I am trying to save user:password if  got 200 response status code to a textfile.

but it only saves one value "User" I dunno why. I've tried to add multi values with failed attempts.

```<code>outputFilepath = "validaccounts.txt"

def OutPut(text):
    with open(outputFilepath, "a") as outputf:
        outputf.write("{}\n".format(text))
        #headers removed#
        #Payload removed#
        response = requests.post(url, data=payload, headers=headers, proxies=proxies, timeout=10)
    #print(response.text)
        if response.status_code == 200:
            OutPut(user, password)
    except:
        pass
</code>```

How to make it save User:password format in textfile what needed to be edited in outputf.write?

Note: I've removed the payload + headers, I just need to fix the output save user:password part.

Thank you,
regards.

答:
Fixed by doing the following:</p>

```<code>def OutPut(text, text1):
    with open(outputFilepath, "a") as outputf:
        outputf.write("{}:{}\n".format(text, text1))

output(user, password)
</code>```

Body:
I am trying to save user:password if  got 200 response status code to a textfile.

but it only saves one value "User" I dunno why. I've tried to add multi values with failed attempts.

outputFilepath = "validaccounts.txt"

def OutPut(text):
    with open(outputFilepath, "a") as outputf:
        outputf.write("{}\n".format(text))
        #headers removed#
        #Payload removed#
        response = requests.post(url, data=payload, headers=headers, proxies=proxies, timeout=10)
    #print(response.text)
        if response.status_code == 200:
            OutPut(user, password)
    except:
        pass

How to make it save User:password format in textfile what needed to be edited in outputf.write?

Note: I've removed the payload + headers, I just need to fix the output save user:password part.

Thank you,
regards.

Body:
Fixed by doing the following:

def OutPut(text, text1):
    with open(outputFilepath, "a") as outputf:
        outputf.write("{}:{}\n".format(text, text1))

output(user, password)


问:
Click on HTML button URL string?
First off all total n00b here.
Is it possible to skip clicking on HTML button with simple URL string?

example:
Im visiting page www.somesite.com/page1
on page1 there is a html button (type=submit, value=ADD)
when I press that button it sending me to www.somesite.com/page2

question:
Is there a way to put pressing button command in URL that gonna bring me directly to page 2 (something like www.somesite.com/page1&press button value=ADD) ???

Thanks

答:
Try with jquery</p>

```<code><!DOCTYPE html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!-->
<html class="no-js">
<!--<![endif]-->

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.js"></script>
</head>

<body>

    <form>
        <input id="data" value="132">
        <button class="goToPage">Save</button>
    </form>

    <script>
        $(document).ready(function () {
            $('.goToPage').click(function () {
                var data = $('#data').val();
                window.location = "yourUrl?data=" + data;
            });
        });
    </script>
    <!--[if lt IE 7]>
            <p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="#">upgrade your browser</a> to improve your experience.</p>
        <![endif]-->

    <script src="" async defer></script>

</body>

</html>
</code>```

Title: Click on HTML button URL string?

Body:
Try with jquery

<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]><!-->
<html class="no-js">
<!--<![endif]-->

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.js"></script>
</head>

<body>

    <form>
        <input id="data" value="132">
        <button class="goToPage">Save</button>
    </form>

    <script>
        $(document).ready(function () {
            $('.goToPage').click(function () {
                var data = $('#data').val();
                window.location = "yourUrl?data=" + data;
            });
        });
    </script>
    <!--[if lt IE 7]>
            <p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="#">upgrade your browser</a> to improve your experience.</p>
        <![endif]-->

    <script src="" async defer></script>

</body>

</html>


问:
Complex For & If loop confusion, returning and accessing classes. Objective-C
I have a view which has a number of subviews. I need to find a particular UIImageView with a particular UIImage.

Here is the code I'm using to loop through:

```<code>BOOL fileExistsAtLocation;
for (id subview in drawGallery.subviews){
    if ([[subview class] isSubclassOfClass: [UIImageView class]]){
        // I need to detect the subview's image property to see if it matches.
    }
}
</code>```

I've tried

```<code>if(subview.image == [UIImage imageNamed:image]){

}
</code>```

But I'm getting told that image isn't part of the structure, which is understandable as all the subviews are essentially of UIView type. How do I target only the UIImageViews and then check their image property?

Regarding the 'tag' answer, the code I tried was:

```<code>BOOL fileIsAtLocation;
for (id subview in drawGallery.subviews){
    if ([subview isKindOfClass:[UIImageView class]]){
        if ((UIView *)subview.tag){
            NSLog(@"FOUND");
        }
    }
}
</code>```

答:
Did you try to use type conversion?

```<code>if(((UIImageView *)subview).image == [UIImage imageNamed:image]){

}
</code>```

UPDATE:

You can also try to change iteration logic:

for (UIView *subview in drawGallery.subviews) {

If you have to find a single view with tag, try

UIImageView *imageViewISearchFor = [drawGallery viewWithTag:uniqueIDAssignedToImage];

Body:
I have a view which has a number of subviews. I need to find a particular UIImageView with a particular UIImage.

Here is the code I'm using to loop through:

BOOL fileExistsAtLocation;
for (id subview in drawGallery.subviews){
    if ([[subview class] isSubclassOfClass: [UIImageView class]]){
        // I need to detect the subview's image property to see if it matches.
    }
}

I've tried

if(subview.image == [UIImage imageNamed:image]){

}

But I'm getting told that image isn't part of the structure, which is understandable as all the subviews are essentially of UIView type. How do I target only the UIImageViews and then check their image property?

Regarding the 'tag' answer, the code I tried was:

BOOL fileIsAtLocation;
for (id subview in drawGallery.subviews){
    if ([subview isKindOfClass:[UIImageView class]]){
        if ((UIView *)subview.tag){
            NSLog(@"FOUND");
        }
    }
}

Body:
Did you try to use type conversion?

if(((UIImageView *)subview).image == [UIImage imageNamed:image]){

}

UPDATE:

You can also try to change iteration logic:

for (UIView *subview in drawGallery.subviews) {

If you have to find a single view with tag, try

UIImageView *imageViewISearchFor = [drawGallery viewWithTag:uniqueIDAssignedToImage];


问:
React Native: Creating a Switch Navigator using React Navigation v5
I had my authentication workflow working using a Switch Navigator and then I would use "props.navigation.navigate()" to switch to a different screen or navigator.

I'm using the Switch navigator because I don't want the user to be able to click back between these places:

```<code>MainNavigator(Switch Navigator)
    - Splash (Screen)

    - Auth (Stack Navigator)
        -Login (Screen)
        -Register (Screen)

    - Tutorial (Stack Navigator)
        -Tutorial Page 1 (Screen)
        -Tutorial Page 2 (Screen)
        -Tutorial Page 3 (Screen)

    - App (Drawer Navigator)
        -All screens for app

1-First Splash screen loads everything and check if there is an auth token inside the local storage.
2-If token found then "navigate('App')" if token not found then "navigate('Auth')"
3-If user register successfully then "navigate('Tutorial')"
4-At the end of the tutorial "navigate('App')"
</code>```

The problem comes when I try to do the same thing using React Navigation v5. It seems that they have removed the Switch navigator and in their documentation, they only show one example of using a
"isLoggedIn" state to switch between 2 different navigators.

Any ideas or suggestions?
Thanks

答:
React Navigation v5 supports a compatibility layer which exposes a Switch Navigator.

npm install @react-navigation/compat

```<code>import { createSwitchNavigator } from "@react-navigation/compat";

const AppNavigator = createSwitchNavigator({
    "splash": { screen: SplashScreen, },
    "home": HomeNavigator,
    "login": AuthNavigator,
},
{
    initialRouteName: "splash",
});

function App() {
    return (
        <NavigationContainer>
            <AppNavigator />
        </NavigationContainer>
    );
}

export default App;
</code>```

https://reactnavigation.org/docs/compatibility/

Body:
I had my authentication workflow working using a Switch Navigator and then I would use "props.navigation.navigate()" to switch to a different screen or navigator.

I'm using the Switch navigator because I don't want the user to be able to click back between these places:

MainNavigator(Switch Navigator)
    - Splash (Screen)

    - Auth (Stack Navigator)
        -Login (Screen)
        -Register (Screen)

    - Tutorial (Stack Navigator)
        -Tutorial Page 1 (Screen)
        -Tutorial Page 2 (Screen)
        -Tutorial Page 3 (Screen)

    - App (Drawer Navigator)
        -All screens for app

1-First Splash screen loads everything and check if there is an auth token inside the local storage.
2-If token found then "navigate('App')" if token not found then "navigate('Auth')"
3-If user register successfully then "navigate('Tutorial')"
4-At the end of the tutorial "navigate('App')"

The problem comes when I try to do the same thing using React Navigation v5. It seems that they have removed the Switch navigator and in their documentation, they only show one example of using a
"isLoggedIn" state to switch between 2 different navigators.

Any ideas or suggestions?
Thanks

Body:
React Navigation v5 supports a compatibility layer which exposes a Switch Navigator.

npm install @react-navigation/compat

import { createSwitchNavigator } from "@react-navigation/compat";

const AppNavigator = createSwitchNavigator({
    "splash": { screen: SplashScreen, },
    "home": HomeNavigator,
    "login": AuthNavigator,
},
{
    initialRouteName: "splash",
});

function App() {
    return (
        <NavigationContainer>
            <AppNavigator />
        </NavigationContainer>
    );
}

export default App;

https://reactnavigation.org/docs/compatibility/


问:
Trying to integrate Agora IO with Unity WebGL. Error when building demo scene
Problem description

When building the demo scene in Unity for webgl, and then loading it, the scene loads, but when I click join, I get an error saying 'abort(To use dlopen, you need to use Emscripten's linking support...). Screenshot of the error.

Background information

I've done some googling. Here is someone having the same problem: https://dev.to/joelthomas362/create-an-agora-group-video-chat-using-unity-33ce (scroll down to the comments).

I think it has something to do with the way the agora DLL's are linked (see this thread for example: https://forum.unity.com/threads/to-use-dlopen-you-need-to-use-emscriptens-linking-support.521968/) where a unity Dev posts: Dynamic linking, i.e. @DllImport statements, are not supported by WebAssembly (in a form that would be useful to Unity WebGL plugin builds at least). When compiling plugins, the plugins should be authored to link statically to the project instead. However, I can't find how to statically link Agora IO.

Question

Is it possible to get Agora IO to work with Unity WebGL, and if so, how?

How to reproduce

Download Agora video SDK for unity (2.9.2)

Import SDK into unity

Enter AppID in GameController object from the demo.

Go to 'build settings'. Add SceneHome and ScenHelloVideo from the demo to 'Scenes in build'. Click 'WebGl'. Click 'Switch platform', then build (might take a while).

Upload the output files to a server (WebGl builds in Unity don't open locally in Chrome).

Open the index.html file on the server.

The scene loads. Click 'join'. Now you get an error.

答: Currently Agora Video SDK for Unity does NOT support WebGL.  It is on the future development roadmap however.  Please stay tuned for the updates.</p>


问:
Paste Excel range as picture into email body
My aim is to paste a range as an image into an Outlook email. I turned on the references in the VBA editor for MS Excel, Word and Outlook 15.0 as my latest version on my network.

I've spent hours looking through previously answered similar questions.

I cannot save the image as a temporary file/use html to reference the attachment as a solution due to other users not having access to specific drives where it would be temporarily saved if they ran the code on their own machines.

If I remove the email body section the image pastes fine however if I have both pieces of code in together, the email body writes over the image. I do however need the image to be pasted within the email body text.

```<code>Sub CreateEmail()

Dim OlApp As Object
Dim OlMail As Object
Dim ToRecipient As Variant
Dim CcRecipient As Variant
Dim PictureRange As Range
Dim OApp As Object, OMail As Object, signature As String

Set OlApp = CreateObject("Outlook.Application")
Set OlMail = OlApp.createitem(olmailitem)

ExtractName = ActiveWorkbook.Sheets("macros").Range("C11").Value

ToRecipient = ActiveWorkbook.Sheets("macros").Range("K11")
OlMail.Recipients.Add ToRecipient

CC_Check = ActiveWorkbook.Sheets("macros").Range("k10")
If CC_Check = "" Then GoTo Skip_CC

CcRecipient = ActiveWorkbook.Sheets("macros").Range("K10")

OlMail.Recipients.Add CcRecipient

OlMail.Subject = ExtractName
signature = OlMailbody
With OlMail
Set PictureRange = ActiveWorkbook.Sheets("DCTVV").Range("A2:D13")
PictureRange.Copy
OlMail.Display

'This section pastes the image

Dim wordDoc As Word.Document
Set wordDoc = OlMail.GetInspector.WordEditor
wordDoc.Range.PasteAndFormat wdChartPicture

'This section is the email body it needs inserting into

OlMail.body = "Text here," & vbNewLine & vbNewLine & _
        "Today's report is attached." & vbNewLine & _
        "IMAGE NEEDS TO BE PASTED HERE" _
      & vbNewLine & vbNewLine & "More text here" _
      & vbNewLine & vbNewLine & "Kind regards,"
.signature

End With
Set OMail = Nothing
Set OApp = Nothing
OlMail.Attachments.Add ("filepath &attachment1")
OlMail.Attachments.Add ("filepath &attachment2")
'OlMail.Attachments.Add ("filepath &attachment3")

OlMail.Display

End Sub
</code>```

答:
If your code suddenly stopped working after migrating to Office 365 or for any other reasons, please refer to the code below. Comments have been added for easy understanding and implementation.

If you have administrative rights then try the registry changes given at below link:
https://support.microsoft.com/en-au/help/926512/information-for-administrators-about-e-mail-security-settings-in-outlo

However, as developer, I recommend a code that's rather compatible with all versions of Excel instead of making system changes because system changes will be required on each end user's machine as well.

As the VBA code below use 'Late Binding', it's also compatible with all previous and current versions of MS Office viz. Excel 2003, Excel 2007, Excel 2010, Excel 2013, Excel 2016, Office 365

```<code>Option Explicit

Sub Create_Email(ByVal strTo As String, ByVal strSubject As String)

    Dim rngToPicture As Range
    Dim outlookApp As Object
    Dim Outmail As Object
    Dim strTempFilePath As String
    Dim strTempFileName As String

    'Name it anything, doesn't matter
    strTempFileName = "RangeAsPNG"

    'rngToPicture is defined as NAMED RANGE in the workbook, do modify this name before use
    Set rngToPicture = Range("rngToPicture")
    Set outlookApp = CreateObject("Outlook.Application")
    Set Outmail = outlookApp.CreateItem(olMailItem)

    'Create an email
    With Outmail
        .To = strTo
        .Subject = strSubject

        'Create the range as a PNG file and store it in temp folder
        Call createPNG(rngToPicture, strTempFileName)

        'Embed the image in Outlook
        strTempFilePath = Environ$("temp") & "\" & strTempFileName & ".png"
        .Attachments.Add strTempFilePath, olByValue, 0

        'Change the HTML below to add Header (Dear John) or signature (Kind Regards) using newline tag (<br />)
        .HTMLBody = "<img src='cid:" & strTempFileName & ".png' style='border:0'>"

        .Display

    End With

    Set Outmail = Nothing
    Set outlookApp = Nothing
    Set rngToPicture = Nothing

End Sub

Sub createPNG(ByRef rngToPicture As Range, nameFile As String)

    Dim wksName As String

    wksName = rngToPicture.Parent.Name

    'Delete the existing PNG file of same name, if exists
    On Error Resume Next
        Kill Environ$("temp") & "\" & nameFile & ".png"
    On Error GoTo 0

    'Copy the range as picture
    rngToPicture.CopyPicture

    'Paste the picture in Chart area of same dimensions
    With ThisWorkbook.Worksheets(wksName).ChartObjects.Add(rngToPicture.Left, rngToPicture.Top, rngToPicture.Width, rngToPicture.Height)
        .Activate
        .Chart.Paste
        'Export the chart as PNG File to Temp folder
        .Chart.Export Environ$("temp") & "\" & nameFile & ".png", "PNG"
    End With
    Worksheets(wksName).ChartObjects(Worksheets(wksName).ChartObjects.Count).Delete

End Sub
</code>```

Body:
My aim is to paste a range as an image into an Outlook email. I turned on the references in the VBA editor for MS Excel, Word and Outlook 15.0 as my latest version on my network.

I've spent hours looking through previously answered similar questions.

I cannot save the image as a temporary file/use html to reference the attachment as a solution due to other users not having access to specific drives where it would be temporarily saved if they ran the code on their own machines.

If I remove the email body section the image pastes fine however if I have both pieces of code in together, the email body writes over the image. I do however need the image to be pasted within the email body text.

Sub CreateEmail()

Dim OlApp As Object
Dim OlMail As Object
Dim ToRecipient As Variant
Dim CcRecipient As Variant
Dim PictureRange As Range
Dim OApp As Object, OMail As Object, signature As String

Set OlApp = CreateObject("Outlook.Application")
Set OlMail = OlApp.createitem(olmailitem)

ExtractName = ActiveWorkbook.Sheets("macros").Range("C11").Value

ToRecipient = ActiveWorkbook.Sheets("macros").Range("K11")
OlMail.Recipients.Add ToRecipient

CC_Check = ActiveWorkbook.Sheets("macros").Range("k10")
If CC_Check = "" Then GoTo Skip_CC

CcRecipient = ActiveWorkbook.Sheets("macros").Range("K10")

OlMail.Recipients.Add CcRecipient

OlMail.Subject = ExtractName
signature = OlMailbody
With OlMail
Set PictureRange = ActiveWorkbook.Sheets("DCTVV").Range("A2:D13")
PictureRange.Copy
OlMail.Display

'This section pastes the image

Dim wordDoc As Word.Document
Set wordDoc = OlMail.GetInspector.WordEditor
wordDoc.Range.PasteAndFormat wdChartPicture

'This section is the email body it needs inserting into

OlMail.body = "Text here," & vbNewLine & vbNewLine & _
        "Today's report is attached." & vbNewLine & _
        "IMAGE NEEDS TO BE PASTED HERE" _
      & vbNewLine & vbNewLine & "More text here" _
      & vbNewLine & vbNewLine & "Kind regards,"
.signature

End With
Set OMail = Nothing
Set OApp = Nothing
OlMail.Attachments.Add ("filepath &attachment1")
OlMail.Attachments.Add ("filepath &attachment2")
'OlMail.Attachments.Add ("filepath &attachment3")

OlMail.Display

End Sub

Body:
If your code suddenly stopped working after migrating to Office 365 or for any other reasons, please refer to the code below. Comments have been added for easy understanding and implementation.

If you have administrative rights then try the registry changes given at below link:
https://support.microsoft.com/en-au/help/926512/information-for-administrators-about-e-mail-security-settings-in-outlo

However, as developer, I recommend a code that's rather compatible with all versions of Excel instead of making system changes because system changes will be required on each end user's machine as well.

As the VBA code below use 'Late Binding', it's also compatible with all previous and current versions of MS Office viz. Excel 2003, Excel 2007, Excel 2010, Excel 2013, Excel 2016, Office 365

Option Explicit

Sub Create_Email(ByVal strTo As String, ByVal strSubject As String)

    Dim rngToPicture As Range
    Dim outlookApp As Object
    Dim Outmail As Object
    Dim strTempFilePath As String
    Dim strTempFileName As String

    'Name it anything, doesn't matter
    strTempFileName = "RangeAsPNG"

    'rngToPicture is defined as NAMED RANGE in the workbook, do modify this name before use
    Set rngToPicture = Range("rngToPicture")
    Set outlookApp = CreateObject("Outlook.Application")
    Set Outmail = outlookApp.CreateItem(olMailItem)

    'Create an email
    With Outmail
        .To = strTo
        .Subject = strSubject

        'Create the range as a PNG file and store it in temp folder
        Call createPNG(rngToPicture, strTempFileName)

        'Embed the image in Outlook
        strTempFilePath = Environ$("temp") & "\" & strTempFileName & ".png"
        .Attachments.Add strTempFilePath, olByValue, 0

        'Change the HTML below to add Header (Dear John) or signature (Kind Regards) using newline tag (<br />)
        .HTMLBody = "<img src='cid:" & strTempFileName & ".png' style='border:0'>"

        .Display

    End With

    Set Outmail = Nothing
    Set outlookApp = Nothing
    Set rngToPicture = Nothing

End Sub

Sub createPNG(ByRef rngToPicture As Range, nameFile As String)

    Dim wksName As String

    wksName = rngToPicture.Parent.Name

    'Delete the existing PNG file of same name, if exists
    On Error Resume Next
        Kill Environ$("temp") & "\" & nameFile & ".png"
    On Error GoTo 0

    'Copy the range as picture
    rngToPicture.CopyPicture

    'Paste the picture in Chart area of same dimensions
    With ThisWorkbook.Worksheets(wksName).ChartObjects.Add(rngToPicture.Left, rngToPicture.Top, rngToPicture.Width, rngToPicture.Height)
        .Activate
        .Chart.Paste
        'Export the chart as PNG File to Temp folder
        .Chart.Export Environ$("temp") & "\" & nameFile & ".png", "PNG"
    End With
    Worksheets(wksName).ChartObjects(Worksheets(wksName).ChartObjects.Count).Delete

End Sub


问:
Add multiple legends to ggplot geom_tile
I'm using ggplot to create a heat-map style plot, and would like to add a second legend with the data scaled a different way. I'm wondering if there is a simple way to do this.

I do not believe that this is a duplicate of other "multiple legends" questions e.g. Multiple legends for a ggplot in R as crucially I want to add extra legends for the same aesthetic - i.e. one aesthetic mapping, two legends.

Example code

```<code># Create a dataframe with some dummy data

x <- c()
y <- c()

for(i in 1:100){
  for(j in 1:100){

    x <- c(x, i)
    y <- c(y, j)
  }
}

example_data <- data.frame(x, y)
example_data$z <- example_data$x*example_data$y
example_data$z_rescale <- example_data$z*0.5
</code>```

Now we've got some data that I'd like to plot as a heatmap with "z" as a colour gradient.

```<code>ggplot(example_data, aes(x = x, y = y, fill = z)) +
  geom_tile() +
  scale_fill_gradient(low = "blue", high = "red") +
  scale_x_continuous(expand = c(0, 0)) +
  scale_y_continuous(expand = c(0, 0))
</code>```

Doing the same with the rescaled z gives an identical plot, but with the rescaled legend:

```<code>ggplot(example_data, aes(x = x, y = y, fill = z_rescale)) +
  geom_tile() +
  scale_fill_gradient(low = "blue", high = "red") +
  scale_x_continuous(expand = c(0, 0)) +
  scale_y_continuous(expand = c(0, 0))
</code>```

What I'd like to do however is have a single plot showing the two different legends, which would look something like this mock-up:

Now, I imagine this would be possible by creating two plots, finding the grob that represents the legend in one of the plots and cunningly adding it to the second plot... however, is there a much simpler way that I'm overlooking?

Many thanks!

答:
Please add the code

```<code>aes(color = z_rescale) +
scale_color_gradient(low = "blue", high = "red") +
</code>```

after geom_tile() line and you will get the desired

Body:
I'm using ggplot to create a heat-map style plot, and would like to add a second legend with the data scaled a different way. I'm wondering if there is a simple way to do this.

I do not believe that this is a duplicate of other "multiple legends" questions e.g. Multiple legends for a ggplot in R as crucially I want to add extra legends for the same aesthetic - i.e. one aesthetic mapping, two legends.

Example code

# Create a dataframe with some dummy data

x <- c()
y <- c()

for(i in 1:100){
  for(j in 1:100){

    x <- c(x, i)
    y <- c(y, j)
  }
}

example_data <- data.frame(x, y)
example_data$z <- example_data$x*example_data$y
example_data$z_rescale <- example_data$z*0.5

Now we've got some data that I'd like to plot as a heatmap with "z" as a colour gradient.

ggplot(example_data, aes(x = x, y = y, fill = z)) +
  geom_tile() +
  scale_fill_gradient(low = "blue", high = "red") +
  scale_x_continuous(expand = c(0, 0)) +
  scale_y_continuous(expand = c(0, 0))

Doing the same with the rescaled z gives an identical plot, but with the rescaled legend:

ggplot(example_data, aes(x = x, y = y, fill = z_rescale)) +
  geom_tile() +
  scale_fill_gradient(low = "blue", high = "red") +
  scale_x_continuous(expand = c(0, 0)) +
  scale_y_continuous(expand = c(0, 0))

What I'd like to do however is have a single plot showing the two different legends, which would look something like this mock-up:

Now, I imagine this would be possible by creating two plots, finding the grob that represents the legend in one of the plots and cunningly adding it to the second plot... however, is there a much simpler way that I'm overlooking?

Many thanks!

Body:
Please add the code

aes(color = z_rescale) +
scale_color_gradient(low = "blue", high = "red") +

after geom_tile() line and you will get the desired


问:
Can't insert string to Delta Table using Update in Pyspark
I have encountered an issue were it will not allow me to insert a string using update and returns. I'm running 6.5 (includes Apache Spark 2.4.5, Scala 2.11), but it is not working on 6.4 runtime as well.

I have a delta table with the following columns, partitioned by the created date

```<code>ID string
 , addressLineOne string
 , addressLineTwo string
 , addressLineThree string
 , addressLineFour string
 , matchName string
 , createdDate
</code>```

And I'm running a process that hits an API and updates the matchName column.

Using Pyspark if it do this, just to test writing

```<code> deltaTable.update(col("ID") == "ABC123", {"matchName ": "example text"})
</code>```

I get the following error:

```<code>Py4JJavaError: An error occurred while calling o1285.update.
: org.apache.spark.sql.catalyst.analysis.UnresolvedException: Invalid call to dataType on unresolved object, tree: 'example
</code>```

If I try this, change the string to 123, it updates without an issue

```<code>deltaTable.update(col("ID") == "ABC123", {"matchName ": "123"})
</code>```

Yet if I use sql and do

```<code>UPDATE myTable SET matchName = "Some text" WHERE ID = "ABC123"
</code>```

It inserts fine. I've searched and can't see a similar issue, Any suggestions? Have I missed something obvious?

答: Looks like you have an extra space after matchName in your python code

Body:
I have encountered an issue were it will not allow me to insert a string using update and returns. I'm running 6.5 (includes Apache Spark 2.4.5, Scala 2.11), but it is not working on 6.4 runtime as well.

I have a delta table with the following columns, partitioned by the created date

ID string
 , addressLineOne string
 , addressLineTwo string
 , addressLineThree string
 , addressLineFour string
 , matchName string
 , createdDate

And I'm running a process that hits an API and updates the matchName column.

Using Pyspark if it do this, just to test writing

 deltaTable.update(col("ID") == "ABC123", {"matchName ": "example text"})

I get the following error:

Py4JJavaError: An error occurred while calling o1285.update.
: org.apache.spark.sql.catalyst.analysis.UnresolvedException: Invalid call to dataType on unresolved object, tree: 'example

If I try this, change the string to 123, it updates without an issue

deltaTable.update(col("ID") == "ABC123", {"matchName ": "123"})

Yet if I use sql and do

UPDATE myTable SET matchName = "Some text" WHERE ID = "ABC123"

It inserts fine. I've searched and can't see a similar issue, Any suggestions? Have I missed something obvious?


问:
Am i disposing my ODBCConnection
I'm using a helper method like this:

```<code>    private OdbcCommand GetCommand(string sql)
    {
        string conString = "blah";
        var con = new OdbcConnection(conString);
        var cmd = new OdbcCommand(sql, con);
        return cmd;
    }
</code>```

Then i use it like this:

```<code>using (var cmd = GetCommand("select * from myTable")
{
    cmd.connection.open();
    using(var reader = cmd.ExecuteReader())
    {
    }
}
</code>```

Here is a second example:

```<code>    public static OdbcDataReader GetReader(string conString,string sql)
    {
        var cmd = GetCommand(conString, sql);
        cmd.Connection.Open();
        return cmd.ExecuteReader();
    }
</code>```

used like this:

```<code>     using(var reader = GetReader("blah","select * from blah")
    {
    }
</code>```

In these two cases, am i disposing of the connection and cmd objects? I think connection is not being disposed in the first, and neither connection nor cmd in the second, is that right?

Do i need to do i the long way to ensure correct disposal, or is there a shorter approach?

```<code>using (var con ...)
    using (var cmd)
        using (var reader)
</code>```

答:
For both examples where you wrap your Reader in a using block, you will close the connection with the existing code IF you use the override that accepts a CommandBehavior and set it to 'CloseConnection'

```<code>using(var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection)){}
</code>```

see http://msdn.microsoft.com/en-us/library/s9bz2k02.aspx

Microsoft knows that the connection must remain open while the reader is consumed, and therefore created the option to close the connection when the Reader is closed.

You are correct that the command is not being Disposed in the second example.

Title: Am i disposing my ODBCConnection

Body:
I'm using a helper method like this:

    private OdbcCommand GetCommand(string sql)
    {
        string conString = "blah";
        var con = new OdbcConnection(conString);
        var cmd = new OdbcCommand(sql, con);
        return cmd;
    }

Then i use it like this:

using (var cmd = GetCommand("select * from myTable")
{
    cmd.connection.open();
    using(var reader = cmd.ExecuteReader())
    {
    }
}

Here is a second example:

    public static OdbcDataReader GetReader(string conString,string sql)
    {
        var cmd = GetCommand(conString, sql);
        cmd.Connection.Open();
        return cmd.ExecuteReader();
    }

used like this:

     using(var reader = GetReader("blah","select * from blah")
    {
    }

In these two cases, am i disposing of the connection and cmd objects? I think connection is not being disposed in the first, and neither connection nor cmd in the second, is that right?

Do i need to do i the long way to ensure correct disposal, or is there a shorter approach?

using (var con ...)
    using (var cmd)
        using (var reader)

Body:
For both examples where you wrap your Reader in a using block, you will close the connection with the existing code IF you use the override that accepts a CommandBehavior and set it to 'CloseConnection'

using(var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection)){}

see http://msdn.microsoft.com/en-us/library/s9bz2k02.aspx

Microsoft knows that the connection must remain open while the reader is consumed, and therefore created the option to close the connection when the Reader is closed.

You are correct that the command is not being Disposed in the second example.


问:
Can I redistribute the result of Google Text-To-Speech?
My question concerns the Google Text-to-Speech engine and in particular the following scenario.

The user writes a text in an Android application

The Text-to-Speech saves it as a .wav file

Am I allowed to upload this file to a web server and use it as part of a web application or are there licensing issues?

Any help will be appreciated

答:
Per the Google Text to Speech API Quotas and Limits page:

You can use the audio data files you create using Text-to-Speech in your applications or media in compliance with the Google Cloud Platform Terms of Service including compliance with all applicable law.

As far as I could interpret (I am not an attorney) from the aforementioned Google Cloud Platform Terms of Service page there are no limits on audio file usage or distribution. Note that this is not explicitly stated; it is just not stated at all.


问:
Unity reading the left key as the right key when pressing up
EDIT: The problem only occurs with the arrow keys, wasd keys work just fine, so I'm guessing the problem is my keyboard, but not completely sure.

I'm new to coding and to unity, so I'm trying to make a basic top down shooter game, but I'm having a problem with the movement, when I press up and right, if I press left and release the right key, the player keeps going right, as if I was pressing the right button. It doesn't happens the other way around, I don't know if the problem is in my movement code, in unity or in my keyboard. My movement script is as follows

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

public class playerMovement : MonoBehaviour
{
    public float moveSpeed = 10f;
    private float horizontalMove = 0f;
    private float verticalMove = 0f;
    public Rigidbody2D rb;

    void Start()
    {

    }

    void Update()
    {
        horizontalMove = Input.GetAxisRaw("Horizontal") * moveSpeed;
        verticalMove = Input.GetAxisRaw("Vertical") * moveSpeed;
    }

    void FixedUpdate()
    {
        Vector2 moveDirection = new Vector2(horizontalMove, verticalMove);
        rb.AddForce(moveDirection);
    }
}
</code>```

答:
It's because you are using rb.AddForce(moveDirection); to move. Every fixed update if the key was pressed that line will add a force to the rigidbody; so it will repeatedly increase the force.

I assume that if you press the key and release it, the player still moves in that direction.

I suggest you to use another way to move the player. Like rb.velocity, it's easier to use, instead of AddForce, try:

```<code>rb.velocity = moveDirection;
</code>```

Also, read the documentation of rb.AddForce.

Edit

Ok, so the problem may be the keyboard.
We now need to test if that it's true. Input.GetAxis methods are configured in Edit > Project Settings > Input, if the arrow keys are the problem, we should try with other keys. In the input menu find the Horizontal and Vertical Axes, and change the Positive Button and Negative Button for another key, and try again now with those keys.

You can read more about Axes Settings in the Input Manager documentation.

Body:
EDIT: The problem only occurs with the arrow keys, wasd keys work just fine, so I'm guessing the problem is my keyboard, but not completely sure.

I'm new to coding and to unity, so I'm trying to make a basic top down shooter game, but I'm having a problem with the movement, when I press up and right, if I press left and release the right key, the player keeps going right, as if I was pressing the right button. It doesn't happens the other way around, I don't know if the problem is in my movement code, in unity or in my keyboard. My movement script is as follows

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

public class playerMovement : MonoBehaviour
{
    public float moveSpeed = 10f;
    private float horizontalMove = 0f;
    private float verticalMove = 0f;
    public Rigidbody2D rb;

    void Start()
    {

    }

    void Update()
    {
        horizontalMove = Input.GetAxisRaw("Horizontal") * moveSpeed;
        verticalMove = Input.GetAxisRaw("Vertical") * moveSpeed;
    }

    void FixedUpdate()
    {
        Vector2 moveDirection = new Vector2(horizontalMove, verticalMove);
        rb.AddForce(moveDirection);
    }
}

Body:
It's because you are using rb.AddForce(moveDirection); to move. Every fixed update if the key was pressed that line will add a force to the rigidbody; so it will repeatedly increase the force.

I assume that if you press the key and release it, the player still moves in that direction.

I suggest you to use another way to move the player. Like rb.velocity, it's easier to use, instead of AddForce, try:

rb.velocity = moveDirection;

Also, read the documentation of rb.AddForce.

Edit

Ok, so the problem may be the keyboard.
We now need to test if that it's true. Input.GetAxis methods are configured in Edit > Project Settings > Input, if the arrow keys are the problem, we should try with other keys. In the input menu find the Horizontal and Vertical Axes, and change the Positive Button and Negative Button for another key, and try again now with those keys.

You can read more about Axes Settings in the Input Manager documentation.


问:
How to add new html items with Flask
I am making a flask app that creates an "Order of Services" for a church. This basically just allows you to input a list of items that can be seen by all the staff in real-time. Is there any way to append an html item? To clarify, here is my python:

from flask import Flask, jsonify, request, url_for, redirect, session, render_template, g
import sqlite3

app = Flask(__name__)

app.config['SECRET_KEY'] = 'Thisisasecret!'

def connect_db():
    connect = sqlite3.connect('Path to my DataBase')
    connect.row_factory = sqlite3.Row
    return connect

def get_db():
    if not hasattr(g, 'sqlite3'):
        g.sqlite_db = connect_db()
    return g.sqlite_db

@app.teardown_appcontext
def close_db(error):
    if hasattr(g, 'sqlite_db'):
        g.sqlite_db.close()

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/add', methods=['POST'])
def add():
    if request.method == 'GET':
        return render_template('index.html')
    else:
        serviceitem = request.form['serviceitem']

        db = get_db()
        db.execute('insert into oos (serviceitem) values (?)', [serviceitem])
        db.commit()

    return render_template('index.html', serviceitem=serviceitem)

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

<p>My <code>index.html</code> is as follows:</p>

<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
    <head>
        <title>SFBC Order of Services</title>
        <!-- <link rel="stylesheet" href="style.css"> -->
        <link rel="stylesheet"
                href="https://fonts.googleapis.com/css?family=Raleway">
        <style>
            body {
                font-family: Raleway;
            }

            div {
                margin-left: 500px;
            }

            span {
                margin-left: 520px;
            }

            h1, h2, h3, h4 {
                text-align: center;
            }
        </style>
    </head>

    <body>

        {% block content %}
        <h1>Santa Fe Baptist Church Order of Services</h1>
        <h3>Please select an item or create a new one below.</h3>
        <br><br><br>

        <div>Add a new Service item:
            <form action="/add" method="POST">
                <input type="text" name="serviceitem">
                <input type="submit">
            </form>
        </div><br>

        <h1>You appended {{ serviceitem }} to the Database.</h1>

        {% endblock %}

    </body>
</html>
</code>```

So what I want to do is to add a new list item once a new item is added, and maybe remove a placeholder once there is a value. I know that I can do this with javascript, so if there is any way to trigger some javascript that would be great, too!
Thanks for any help!

EDIT:

I tried @the_gañañufla 's answer, but it did not quite work. When I append a number to the database, it returns this:

If I edit it to include the serviceitem instead of item, then it just puts in "letters" or whatever I put in, iterating it the amount of times that there are letters. (7 letters in letters, so it shows seven letters).

Sorry if that is convoluted and unreadable for my bad word choice :)

答:
In the route('/') you need to add a query.all(), to get all the information of your db, and send this data in the render template.

```<code> @app.route('/')
 def index():
     db = get_db()
     serviceitem = db.query.all()
     return render_template('index.html', serviceitem=serviceitem)
</code>```

In other case, in unnecesary to send info with the render in the /add action

```<code> @app.route('/add', methods=['POST'])
    def add():
        if request.method == 'GET':
            return render_template('index.html')
        else:
            serviceitem = request.form['serviceitem']

            db = get_db()
            db.execute('insert into oos (serviceitem) values (?)'[serviceitem])
            db.commit()

        return render_template('index.html')
</code>```

Title: How to add new html items with Flask

Body:
I am making a flask app that creates an "Order of Services" for a church. This basically just allows you to input a list of items that can be seen by all the staff in real-time. Is there any way to append an html item? To clarify, here is my python:

from flask import Flask, jsonify, request, url_for, redirect, session, render_template, g
import sqlite3

app = Flask(__name__)

app.config['SECRET_KEY'] = 'Thisisasecret!'

def connect_db():
    connect = sqlite3.connect('Path to my DataBase')
    connect.row_factory = sqlite3.Row
    return connect

def get_db():
    if not hasattr(g, 'sqlite3'):
        g.sqlite_db = connect_db()
    return g.sqlite_db

@app.teardown_appcontext
def close_db(error):
    if hasattr(g, 'sqlite_db'):
        g.sqlite_db.close()

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/add', methods=['POST'])
def add():
    if request.method == 'GET':
        return render_template('index.html')
    else:
        serviceitem = request.form['serviceitem']

        db = get_db()
        db.execute('insert into oos (serviceitem) values (?)', [serviceitem])
        db.commit()

    return render_template('index.html', serviceitem=serviceitem)

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

My index.html is as follows:

<!DOCTYPE html>

        <title>SFBC Order of Services</title>

        <link rel="stylesheet"
                href="https://fonts.googleapis.com/css?family=Raleway">

        {% block content %}

Santa Fe Baptist Church Order of Services

Please select an item or create a new one below.

Add a new Service item:
            <form action="/add" method="POST">
                <input type="text" name="serviceitem">
                <input type="submit">
            </form>

You appended {{ serviceitem }} to the Database.

        {% endblock %}

So what I want to do is to add a new list item once a new item is added, and maybe remove a placeholder once there is a value. I know that I can do this with javascript, so if there is any way to trigger some javascript that would be great, too!
Thanks for any help!

EDIT:

I tried @the_gañañufla 's answer, but it did not quite work. When I append a number to the database, it returns this:

If I edit it to include the serviceitem instead of item, then it just puts in "letters" or whatever I put in, iterating it the amount of times that there are letters. (7 letters in letters, so it shows seven letters).

Sorry if that is convoluted and unreadable for my bad word choice :)

Body:
In the route('/') you need to add a query.all(), to get all the information of your db, and send this data in the render template.

 @app.route('/')
 def index():
     db = get_db()
     serviceitem = db.query.all()
     return render_template('index.html', serviceitem=serviceitem)

In other case, in unnecesary to send info with the render in the /add action

 @app.route('/add', methods=['POST'])
    def add():
        if request.method == 'GET':
            return render_template('index.html')
        else:
            serviceitem = request.form['serviceitem']

            db = get_db()
            db.execute('insert into oos (serviceitem) values (?)'[serviceitem])
            db.commit()

        return render_template('index.html')


问:
How to read a file and use getc in C?
I am a senior Comp Sci major about to enter my last semester where I will be taking just one class involving only the language C. I was attempting to practice my skills by making a rather simple program that I conceived of. I simply want to read a single file, put its entire contents into an array, and then traverse this array looking for a sequence of characters that spells out "Waldo".  In other words, a sort of Where's Waldo? program.

I have not gotten into coding the "Waldo" search with the array yet, but instead, I simply just wanted to test my use of the getc() function and output the input file's contents, but with the source code I have so far, I only receiving incorrect outputs of seemingly gibberish (probably having to do with the way I am incorrectly utilizing the getc() return value).

Maybe I should not be using getc() and instead be using a scanf() type function?  Also, I very much am trying to master the by-reference pointer-notation when inserting into and printing out the array here, so I would like to avoid referring to array elements using bracket notations (by-value).  Admittedly so, I may not have the most complete understanding of pointers.

```<code>#include <stdio.h>
#include <stdlib.h>

void main( int argc, char *argv[] )
{

    FILE *filePointer;
    int filechar, i;
    char input_file_array[512];
    char *arrayPointer = input_file_array;
    filePointer = fopen( argv[1], "r" );

    if ( argc > 2 || ( filePointer = fopen( argv[1], "r" ) ) == NULL )
    {
        printf( "\nIncorrect usage, please say...\nRunWaldo *filename*\n\n" );
        exit( 1 );
    }

    if ( filePointer != NULL )
    {
        while ( !feof( filePointer ) )
        {
            *arrayPointer = getc( filePointer );
            arrayPointer++;
        }

    for ( i = 0; i < 512; i++ )
    {
        printf( "%c", *(arrayPointer + i) );
    }

    printf("\n");

}
</code>```

答:
The major issue in your code is actually how you printed out the input_file_array. Imagine you are reading 10 characters from file. arrayPointer is now offsetted by 10 from the original position of input_file_array. Afterwards, you are not resetting arrayPointer back to input_file_array[0].

So it starts printing from input_file_array[10] and onwards. And an even larger problem happens when you output input_file_array[512+10] because you have officially gone out of bounds and some funky things will happen. What you should do is this:

```<code>#include <stdio.h>
#include <stdlib.h>

void main( int argc, char *argv[] )
{

    FILE *filePointer;
    int filechar, i;
    char input_file_array[512];
    char *arrayPointer = input_file_array;
    filePointer = fopen( argv[1], "r" );

    if ( argc > 2 || ( filePointer = fopen( argv[1], "r" ) ) == NULL )
    {
        printf( "\nIncorrect usage, please say...\nRunWaldo *filename*\n\n" );
        exit( 1 );
    }

    if ( filePointer != NULL )
    {
        while ( !feof( filePointer ) )
        {
            *arrayPointer = getc( filePointer );
            arrayPointer++;
        }
    }

    arrayPointer = input_file_array; // or you can just output input_file_array[i] instead
    for ( i = 0; i < 512; i++ )
    {
        printf( "%c", *(arrayPointer + i) );
    }

    printf("\n");

}
</code>```

Title: How to read a file and use getc in C?

Body:
I am a senior Comp Sci major about to enter my last semester where I will be taking just one class involving only the language C. I was attempting to practice my skills by making a rather simple program that I conceived of. I simply want to read a single file, put its entire contents into an array, and then traverse this array looking for a sequence of characters that spells out "Waldo".  In other words, a sort of Where's Waldo? program.

I have not gotten into coding the "Waldo" search with the array yet, but instead, I simply just wanted to test my use of the getc() function and output the input file's contents, but with the source code I have so far, I only receiving incorrect outputs of seemingly gibberish (probably having to do with the way I am incorrectly utilizing the getc() return value).

Maybe I should not be using getc() and instead be using a scanf() type function?  Also, I very much am trying to master the by-reference pointer-notation when inserting into and printing out the array here, so I would like to avoid referring to array elements using bracket notations (by-value).  Admittedly so, I may not have the most complete understanding of pointers.

#include <stdio.h>
#include <stdlib.h>

void main( int argc, char *argv[] )
{

    FILE *filePointer;
    int filechar, i;
    char input_file_array[512];
    char *arrayPointer = input_file_array;
    filePointer = fopen( argv[1], "r" );

    if ( argc > 2 || ( filePointer = fopen( argv[1], "r" ) ) == NULL )
    {
        printf( "\nIncorrect usage, please say...\nRunWaldo *filename*\n\n" );
        exit( 1 );
    }

    if ( filePointer != NULL )
    {
        while ( !feof( filePointer ) )
        {
            *arrayPointer = getc( filePointer );
            arrayPointer++;
        }

    for ( i = 0; i < 512; i++ )
    {
        printf( "%c", *(arrayPointer + i) );
    }

    printf("\n");

}

Body:
The major issue in your code is actually how you printed out the input_file_array. Imagine you are reading 10 characters from file. arrayPointer is now offsetted by 10 from the original position of input_file_array. Afterwards, you are not resetting arrayPointer back to input_file_array[0].

So it starts printing from input_file_array[10] and onwards. And an even larger problem happens when you output input_file_array[512+10] because you have officially gone out of bounds and some funky things will happen. What you should do is this:

#include <stdio.h>
#include <stdlib.h>

void main( int argc, char *argv[] )
{

    FILE *filePointer;
    int filechar, i;
    char input_file_array[512];
    char *arrayPointer = input_file_array;
    filePointer = fopen( argv[1], "r" );

    if ( argc > 2 || ( filePointer = fopen( argv[1], "r" ) ) == NULL )
    {
        printf( "\nIncorrect usage, please say...\nRunWaldo *filename*\n\n" );
        exit( 1 );
    }

    if ( filePointer != NULL )
    {
        while ( !feof( filePointer ) )
        {
            *arrayPointer = getc( filePointer );
            arrayPointer++;
        }
    }

    arrayPointer = input_file_array; // or you can just output input_file_array[i] instead
    for ( i = 0; i < 512; i++ )
    {
        printf( "%c", *(arrayPointer + i) );
    }

    printf("\n");

}


问:
bit data type returns -1
I am working on a web application in Visual Studio 2010. I am writing and reading to a database table using SQL Server 2008.

I have a database table, myTable with a column myColumn of datatype bit. I write to this column on the web app like so:

```<code>UPDATE myTable
SET myColumn = 1
</code>```

This works fine, and using SQL Server Management Studio I can see the column gets updated to TRUE as I would expect.

In another part of my web app I query the table like so:

```<code>sqlCmd.CommandText = "SELECT myColumn FROM myTable"

sqlRdr = sqlCmd.ExecuteReader()

While sqlRdr.Read
      myColumn = sqlRdr(0)
End While
</code>```

When I run this query, myColumn gets set to -1. How does this happen? According to Microsoft Documentation a bit is

An integer data type that can take a value of 1, 0, or NULL.

and

The string values TRUE and FALSE can be converted to bit values: TRUE is converted to 1 and FALSE is converted to 0.

I do not understand how I am getting myColumn = -1 from this query.

答:
The SQL Bit type is mapped to the .Net System Boolean type (True/False).

Your code,

```<code>myColumn = sqlRdr(0)
</code>```

is using VB's rules for implicit type conversions. Presumably myColumn is an integer type and the Object variable type returned by sqlRdr(0) is a Boolean.  VB maps true to a value of -1 and false to a value of 0.

If you were to use System.Convert.ToInt32 for Boolean to integer conversion, you would receive a value of one (1) when converting a boolean true value.

```<code>myColumn = System.Convert.ToInt32(sqlRdr(0))
</code>```

Note that if you use VB's preferred CInt function, or Ctype function, you would also receive a -1 value.

Title: bit data type returns -1

Body:
I am working on a web application in Visual Studio 2010. I am writing and reading to a database table using SQL Server 2008.

I have a database table, myTable with a column myColumn of datatype bit. I write to this column on the web app like so:

UPDATE myTable
SET myColumn = 1

This works fine, and using SQL Server Management Studio I can see the column gets updated to TRUE as I would expect.

In another part of my web app I query the table like so:

sqlCmd.CommandText = "SELECT myColumn FROM myTable"

sqlRdr = sqlCmd.ExecuteReader()

While sqlRdr.Read
      myColumn = sqlRdr(0)
End While

When I run this query, myColumn gets set to -1. How does this happen? According to Microsoft Documentation a bit is

An integer data type that can take a value of 1, 0, or NULL.

and

The string values TRUE and FALSE can be converted to bit values: TRUE is converted to 1 and FALSE is converted to 0.

I do not understand how I am getting myColumn = -1 from this query.

Body:
The SQL Bit type is mapped to the .Net System Boolean type (True/False).

Your code,

myColumn = sqlRdr(0)

is using VB's rules for implicit type conversions. Presumably myColumn is an integer type and the Object variable type returned by sqlRdr(0) is a Boolean.  VB maps true to a value of -1 and false to a value of 0.

If you were to use System.Convert.ToInt32 for Boolean to integer conversion, you would receive a value of one (1) when converting a boolean true value.

myColumn = System.Convert.ToInt32(sqlRdr(0))

Note that if you use VB's preferred CInt function, or Ctype function, you would also receive a -1 value.


问:
Subscribe to events in VBA?
Did I understood correctly that you can't subscribe to an event other than using the VBA Editor's control name + event name comboboxes? There is no combobox.change+=eventhandler syntax available as in other languages like C#, is there?</p>

答:
Correct. Event handling is done via naming convention in VB6/VBA.

The name can be the name of the control itlsef, or it can be a variable declared WithEvents. By assigning this variable a different reference, you start receiving events from that new object. This can be seen as dynamical subscribing.

However, certain environments can provide additional means. For example, in Excel some placeable objects have hidden properties, such as Button.OnAction. You can assign a name of a macro to this property (as a string), and it will be called on button press.

Title: Subscribe to events in VBA?