问:
Are there any potential issues with // in a img src file path?
Simple question, hope fully someone can help.
One of my img tags has https://s0.2mdn.net/creatives/assets//6870555/image.jpg.

Even with the double //, it works as expected and doesn't seem to present any issues in chrome, firefox and IE10+.

To be clear the double // is referencing the slashes after 'assets' not the https://.

Can anyone confirm that this filepath structure isn't an issue?

Thanks All,
Moe

答: If it is a link to a web page, then yes that is not an issue at all.</p>


来源: stackexchange

问:
Objective-C crash with EXC_BAD_ACCESS after reading a file
A EXC_BAD_ACCESS is causing my app to crash. This issue normally occurs when you try to access unitialized or deallocated memory but I can't find where. I've tried to check with Zombie in Xcode without success. The app crash and instrument doesn't notice a zombie. I am using ARC.

The bad access occurs at the end of a method, on the closing curly bracket. (See screenshot). The issue only occurs in release mode (with optimizations) and only for a few devices.

To test, I've made a dummy project where the method is called right after didFinishLaunching.

Call Stack

didFinishLaunchingWithOptions

Alloc and init my custom object

Call readFile on the newly created object

Execute the code in readFile

About to exit readFile, but app crash

Here's a simplified version of the code

```<code>- (void)readFromFile:(NSString *)fileName {
   if (!fileName) {
      return;
   }

   NSString* filePath = [[NSBundle mainBundle] pathForResource:fileName ofType:nil];
   if (!filePath) {
      return;
   }

   FILE* file = fopen([filePath UTF8String], "r");
   if (file == NULL) {
       return;
   }

   size_t length;
   char *cLine = fgetln(file, &length);

   // I don't think it matters, but the file has about 400 000 lines
   while (length > 0) {
      char str[length - 1]; // All lines length are > 2
      strncpy(str, cLine, length);
      str[length - 1] = '\0'; // The crash would still occurs without this line, but less often

      // Custom code with str

      cLine = fgetln(file, &length);
   }
   fclose(file);
}
</code>```

In case it could help you, here is the code of my reader object

```<code>@protocol MyReaderProtocol <NSObject>
 - (void)readFromFile:(NSString *)fileName;
@end

@interface MyReader : NSObject <MyReaderProtocol>
@end

// How I initialize the objet in the app delegate
MyReader myReader = [[MyReader alloc] init];
[myReader readFromFile:@"myFile.txt"];
</code>```

答:
Based on reading your code only

The function call to fgetln() returns in length the number of characters in the line.

A C-array of characters with n elements is declared as char a[n] and the elements are addressed as a[0] to a[n-1].

You need to store length characters plus 1 for the EOS, you allocate an array of capacity length - 1 which is 2 too short.

Your strncpy() then writes past the end of the array.

Finally you write the EOS at index length - 1 when then maximum index is length - 2.

You are only overwriting by 1 byte (you write the EOS over the last character of the line), but that is enough to clobber whatever is next to the array on the stack (which might be cLine...)

HTH

ContentLicense: CC BY-SA 3.0

Body:
A EXC_BAD_ACCESS is causing my app to crash. This issue normally occurs when you try to access unitialized or deallocated memory but I can't find where. I've tried to check with Zombie in Xcode without success. The app crash and instrument doesn't notice a zombie. I am using ARC.

The bad access occurs at the end of a method, on the closing curly bracket. (See screenshot). The issue only occurs in release mode (with optimizations) and only for a few devices.

To test, I've made a dummy project where the method is called right after didFinishLaunching.

Call Stack

didFinishLaunchingWithOptions

Alloc and init my custom object

Call readFile on the newly created object

Execute the code in readFile

About to exit readFile, but app crash

Here's a simplified version of the code

- (void)readFromFile:(NSString *)fileName {
   if (!fileName) {
      return;
   }

   NSString* filePath = [[NSBundle mainBundle] pathForResource:fileName ofType:nil];
   if (!filePath) {
      return;
   }

   FILE* file = fopen([filePath UTF8String], "r");
   if (file == NULL) {
       return;
   }

   size_t length;
   char *cLine = fgetln(file, &length);

   // I don't think it matters, but the file has about 400 000 lines
   while (length > 0) {
      char str[length - 1]; // All lines length are > 2
      strncpy(str, cLine, length);
      str[length - 1] = '\0'; // The crash would still occurs without this line, but less often

      // Custom code with str

      cLine = fgetln(file, &length);
   }
   fclose(file);
}

In case it could help you, here is the code of my reader object

@protocol MyReaderProtocol <NSObject>
 - (void)readFromFile:(NSString *)fileName;
@end

@interface MyReader : NSObject <MyReaderProtocol>
@end

// How I initialize the objet in the app delegate
MyReader myReader = [[MyReader alloc] init];
[myReader readFromFile:@"myFile.txt"];


问:
Are there any libraries that support Android images to add watermarks?
I tried for a long time and couldn't get any better,On different mobile phones:

1. I would like to add pictures and words to the sourceBitmap.

2. want to be able to adjust bitmap and word positions.

答:
Without using library simply we can watermark image using canvas and paint concept

```<code> Point point=new Point();
 point.set(180, 1000);
 Bitmap b=waterMark(BitmapFactory.decodeResource(getResources(), R.drawable.image),"your Text",point,Color.WHITE,90,30,true);
 imageView.setImageBitmap(b);
</code>```

the method code

```<code>public  Bitmap waterMark(Bitmap src, String watermark, Point location, int color, int alpha, int size, boolean underline) {
 //get source image width and height
 int w = src.getWidth();
 int h = src.getHeight();

 Bitmap result = Bitmap.createBitmap(w, h, src.getConfig());
 //create canvas object
 Canvas canvas = new Canvas(result);
 //draw bitmap on canvas
 canvas.drawBitmap(src, 0, 0, null);
 //create paint object
 Paint paint = new Paint();
 //apply color
 paint.setColor(color);
 //set transparency
 paint.setAlpha(alpha);
 //set text size
 paint.setTextSize(size);
 paint.setAntiAlias(true);
 //set should be underlined or not
 paint.setUnderlineText(underline);
 //draw text on given location
  canvas.drawText(watermark, location.x, location.y, paint);
 return result;
}
</code>```

Body:
Without using library simply we can watermark image using canvas and paint concept

 Point point=new Point();
 point.set(180, 1000);
 Bitmap b=waterMark(BitmapFactory.decodeResource(getResources(), R.drawable.image),"your Text",point,Color.WHITE,90,30,true);
 imageView.setImageBitmap(b);

the method code

public  Bitmap waterMark(Bitmap src, String watermark, Point location, int color, int alpha, int size, boolean underline) {
 //get source image width and height
 int w = src.getWidth();
 int h = src.getHeight();

 Bitmap result = Bitmap.createBitmap(w, h, src.getConfig());
 //create canvas object
 Canvas canvas = new Canvas(result);
 //draw bitmap on canvas
 canvas.drawBitmap(src, 0, 0, null);
 //create paint object
 Paint paint = new Paint();
 //apply color
 paint.setColor(color);
 //set transparency
 paint.setAlpha(alpha);
 //set text size
 paint.setTextSize(size);
 paint.setAntiAlias(true);
 //set should be underlined or not
 paint.setUnderlineText(underline);
 //draw text on given location
  canvas.drawText(watermark, location.x, location.y, paint);
 return result;
}


问:
undefined method error after change column name in rails
i've just changed one column 'bedNumber' to 'bed_number' in my beds model, and i've ald changed the permit in controller and input field but still, i get error "
undefined method `bedNumber' for # Did you mean? bed_number bed_number? bed_number=". can somebody help me debug this please? The index file is working fine with the new column name, the only problem is the adding and editing.

Here's my beds controller:

```<code>class BedsController < ApplicationController
  before_action :set_bed, only: [:show, :edit, :update, :destroy]

  # GET /beds
  def index
    @beds = Bed.all
  end

  # GET /beds/1
  def show
  end

  # GET /beds/new
  def new
    @bed = Bed.new
  end

  # GET /beds/1/edit
  def edit
  end

  # POST /beds
  def create
    @bed = Bed.new(bed_params)

    if @bed.save
      redirect_to @bed, notice: 'Bed was successfully created.'
    else
      render :new
    end
  end

  # PATCH/PUT /beds/1
  def update
    if @bed.update(bed_params)
      redirect_to @bed, notice: 'Bed was successfully updated.'
    else
      render :edit
    end
  end

  # DELETE /beds/1
  def destroy
    @bed.destroy
    redirect_to beds_url, notice: 'Bed was successfully destroyed.'
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_bed
      @bed = Bed.find(params[:id])
    end

    # Only allow a trusted parameter "white list" through.
    def bed_params
      params.require(:bed).permit(:bed_number, :description, :room_id)
    end
end
</code>```

here's my schema file:

```<code>create_table "beds", force: :cascade do |t|
    t.string   "bed_number"
    t.string   "description"
    t.integer  "room_id"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
    t.index ["room_id"], name: "index_beds_on_room_id", using: :btree
  end
</code>```

and here's my input view:

```<code>= simple_form_for(@bed) do |f|
  = f.error_notification

  .form-inputs
    = f.input :bed_number, placeholder: 'e.g., Bed-10, Bed-12...etc'
    = f.input :description, placeholder: 'e.g., 1m*2m...etc'
    - if Room.any?
      = f.association :room, default: Room.first.name
    - else
      = f.association :room, prompt: 'Please create a room', disabled: true
      = "No room available yet! Please create one by "
      = link_to 'CLICKING HERE', new_room_path

  .form-actions
    = f.button :submit, class: "btn btn-success"
</code>```

答: Lol...turned out i forgot to change the column name in validation in model file.</p>

Body:
i've just changed one column 'bedNumber' to 'bed_number' in my beds model, and i've ald changed the permit in controller and input field but still, i get error "
undefined method `bedNumber' for # Did you mean? bed_number bed_number? bed_number=". can somebody help me debug this please? The index file is working fine with the new column name, the only problem is the adding and editing.

Here's my beds controller:

class BedsController < ApplicationController
  before_action :set_bed, only: [:show, :edit, :update, :destroy]

  # GET /beds
  def index
    @beds = Bed.all
  end

  # GET /beds/1
  def show
  end

  # GET /beds/new
  def new
    @bed = Bed.new
  end

  # GET /beds/1/edit
  def edit
  end

  # POST /beds
  def create
    @bed = Bed.new(bed_params)

    if @bed.save
      redirect_to @bed, notice: 'Bed was successfully created.'
    else
      render :new
    end
  end

  # PATCH/PUT /beds/1
  def update
    if @bed.update(bed_params)
      redirect_to @bed, notice: 'Bed was successfully updated.'
    else
      render :edit
    end
  end

  # DELETE /beds/1
  def destroy
    @bed.destroy
    redirect_to beds_url, notice: 'Bed was successfully destroyed.'
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_bed
      @bed = Bed.find(params[:id])
    end

    # Only allow a trusted parameter "white list" through.
    def bed_params
      params.require(:bed).permit(:bed_number, :description, :room_id)
    end
end

here's my schema file:

create_table "beds", force: :cascade do |t|
    t.string   "bed_number"
    t.string   "description"
    t.integer  "room_id"
    t.datetime "created_at",  null: false
    t.datetime "updated_at",  null: false
    t.index ["room_id"], name: "index_beds_on_room_id", using: :btree
  end

and here's my input view:

= simple_form_for(@bed) do |f|
  = f.error_notification

  .form-inputs
    = f.input :bed_number, placeholder: 'e.g., Bed-10, Bed-12...etc'
    = f.input :description, placeholder: 'e.g., 1m*2m...etc'
    - if Room.any?
      = f.association :room, default: Room.first.name
    - else
      = f.association :room, prompt: 'Please create a room', disabled: true
      = "No room available yet! Please create one by "
      = link_to 'CLICKING HERE', new_room_path

  .form-actions
    = f.button :submit, class: "btn btn-success"


问:
Working on a https wordpress site on local enviroment but unable to connect
Working on a https wordpress site on local enviroment but unable to connect when trying to load pages.  I'm on ubuntu with apache essentially running lamp. I've set up local hosts before but this isn't working. I heard it has something to do with ssl certificates or something but should it be necessary since its local and if so how would I enable it</p>

答:
SSl is A Little bit tough to setup if you want to develop wordpress on local environment just disable ssl and after making it live enable it back to ssl
if some media or posts cant be encrypted and if ssl doesn't works just use wp-force ssl plugin from here https://wordpress.org/plugins/wp-force-ssl/ or if you cant setup ssl in live environment use plugin really simple ssl and all you need is a certificate thats it all will be taken care by plugin
if you encounter any problem with that i can help you because i too even got the problem and this process helped me to get rid of this problem...</p>


问:
A problem connecting to a MySQL DB using JDBC
Here's how I'm trying to connect:

```<code>try {
   Class.forName("com.mysql.jdbc.Driver").newInstance();
   } catch (Exception e) {
      throw new DbConnectionException();
   }
   try {
      connection = DriverManager.getConnection(url,username,password);
   } catch (SQLException e) {
      e.printStackTrace();
      throw new DbConnectionException();
   }
</code>```

I'm 100% sure that the url, username, password strings are correct. I've already connected successfully using an external tool (MySQL query browser).
This is the error I receive:

com.mysql.jdbc.CommunicationsException:
  Communications link failure due to
  underlying exception:

** BEGIN NESTED EXCEPTION **

java.net.SocketException MESSAGE:
  java.net.ConnectException: Connection
  refused

...

答: Double check the format of your url.  It should start with "jdbc:mysql:".  Make sure you are using a current version for the driver as well.</p>

ContentLicense: CC BY-SA 2.5

Body:
Here's how I'm trying to connect:

try {
   Class.forName("com.mysql.jdbc.Driver").newInstance();
   } catch (Exception e) {
      throw new DbConnectionException();
   }
   try {
      connection = DriverManager.getConnection(url,username,password);
   } catch (SQLException e) {
      e.printStackTrace();
      throw new DbConnectionException();
   }

I'm 100% sure that the url, username, password strings are correct. I've already connected successfully using an external tool (MySQL query browser).
This is the error I receive:

com.mysql.jdbc.CommunicationsException:
  Communications link failure due to
  underlying exception:

** BEGIN NESTED EXCEPTION **

java.net.SocketException MESSAGE:
  java.net.ConnectException: Connection
  refused

...


问:
Elegantly Toggling Many Functions
Let's say I have a handful of functions that do things:

```<code>function doStuff()  { console.log('doing stuff'); }
function doThings() { console.log('doing things'); }
function doIt()     { console.log('doing it'); }
function doThis()   { console.log('doing this'); }
function doThat()   { console.log('doing that'); }
</code>```

And then just as many that disable their behaviors:

```<code>function stopStuff()  { console.log('stopping stuff'); }
function stopThings() { console.log('stopping things'); }
function stopIt()     { console.log('stopping it'); }
function stopThis()   { console.log('stopping this'); }
function stopThat()   { console.log('stopping that'); }
</code>```

Then I put all the 'do' functions in an object so I can dynamically access them by setting what:

```<code>var what = 'things';

var doing = {
    stuff:  function() { doStuff(); },
    things: function() { doThings(); },
    it:     function() { doIt(); },
    this:   function() { doThis(); },
    that:   function() { doThat(); }
};

doing[what](); //console logs 'doing things'
</code>```

Is there a way to go about enabling one do function while iterating through all the non-matching stop functions?

For example, if I do var what = 'this'; doing[what]();, I want it to not only doThis(); but also stopStuff(); stopThings(); stopIt(); stopThat();

I'm having trouble coming up with an elegant method that doesn't involve lengthy if statements or case/switch.

答:
If all your do/stop functions are global - this works

function doStuff()  { console.log('doing stuff'); }
function doThings() { console.log('doing things'); }
function doIt()     { console.log('doing it'); }
function doThis()   { console.log('doing this'); }
function doThat()   { console.log('doing that'); }

function stopStuff()  { console.log('stopping stuff'); };
function stopThings() { console.log('stopping things'); };
function stopIt()     { console.log('stopping it'); };
function stopThis()   { console.log('stopping this'); };
function stopThat()   { console.log('stopping that'); };

var run = function(root) {
    var fnNames = ['stuff', 'things', 'it', 'this', 'that'];
    return function(what) {
        fnNames.forEach(function (fn) {
            var fnName = fn[0].toUpperCase() + fn.slice(1);
            root[(what == fn ? 'do' : 'stop') + fnName]();
        });
    };
}(window);
// usage
console.log('things');
run('things');
console.log('this');
run('this');```
</div>
</div>
</p>

<p>However, if they are not global, it's a little messier, but not by much</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function doStuff()  { console.log('doing stuff'); }
function doThings() { console.log('doing things'); }
function doIt()     { console.log('doing it'); }
function doThis()   { console.log('doing this'); }
function doThat()   { console.log('doing that'); }

function stopStuff()  { console.log('stopping stuff'); }
function stopThings() { console.log('stopping things'); }
function stopIt()     { console.log('stopping it'); }
function stopThis()   { console.log('stopping this'); }
function stopThat()   { console.log('stopping that'); }

var run = (() => {
    var fns = {
        stuff:  { run: doStuff,  stop: stopStuff  },
        things: { run: doThings, stop: stopThings },
        it:     { run: doIt,     stop: stopIt     },
        "this": { run: doThis,   stop: stopThis   },
        that:   { run: doThat,   stop: stopThat   }
    };
    return what => Object.keys(fns)
        // include the sort only if you need to stop all first before start
        // change a == what to b == what to start selected and then stop the rest
        .sort((a,b) => a == what)
        .forEach(key => fns[key][what == key ? 'run' : 'stop']());
})();

console.log('things');
run('things');
console.log('this');
run('this');</code>```

Title: Elegantly Toggling Many Functions

Body:
Let's say I have a handful of functions that do things:

function doStuff()  { console.log('doing stuff'); }
function doThings() { console.log('doing things'); }
function doIt()     { console.log('doing it'); }
function doThis()   { console.log('doing this'); }
function doThat()   { console.log('doing that'); }

And then just as many that disable their behaviors:

function stopStuff()  { console.log('stopping stuff'); }
function stopThings() { console.log('stopping things'); }
function stopIt()     { console.log('stopping it'); }
function stopThis()   { console.log('stopping this'); }
function stopThat()   { console.log('stopping that'); }

Then I put all the 'do' functions in an object so I can dynamically access them by setting what:

var what = 'things';

var doing = {
    stuff:  function() { doStuff(); },
    things: function() { doThings(); },
    it:     function() { doIt(); },
    this:   function() { doThis(); },
    that:   function() { doThat(); }
};

doing[what](); //console logs 'doing things'

Is there a way to go about enabling one do function while iterating through all the non-matching stop functions?

For example, if I do var what = 'this'; doing[what]();, I want it to not only doThis(); but also stopStuff(); stopThings(); stopIt(); stopThat();

I'm having trouble coming up with an elegant method that doesn't involve lengthy if statements or case/switch.

Body:
If all your do/stop functions are global - this works

function doStuff()  { console.log('doing stuff'); }
function doThings() { console.log('doing things'); }
function doIt()     { console.log('doing it'); }
function doThis()   { console.log('doing this'); }
function doThat()   { console.log('doing that'); }

function stopStuff()  { console.log('stopping stuff'); };
function stopThings() { console.log('stopping things'); };
function stopIt()     { console.log('stopping it'); };
function stopThis()   { console.log('stopping this'); };
function stopThat()   { console.log('stopping that'); };

var run = function(root) {
    var fnNames = ['stuff', 'things', 'it', 'this', 'that'];
    return function(what) {
        fnNames.forEach(function (fn) {
            var fnName = fn[0].toUpperCase() + fn.slice(1);
            root[(what == fn ? 'do' : 'stop') + fnName]();
        });
    };
}(window);
// usage
console.log('things');
run('things');
console.log('this');
run('this');

However, if they are not global, it's a little messier, but not by much

function doStuff()  { console.log('doing stuff'); }
function doThings() { console.log('doing things'); }
function doIt()     { console.log('doing it'); }
function doThis()   { console.log('doing this'); }
function doThat()   { console.log('doing that'); }

function stopStuff()  { console.log('stopping stuff'); }
function stopThings() { console.log('stopping things'); }
function stopIt()     { console.log('stopping it'); }
function stopThis()   { console.log('stopping this'); }
function stopThat()   { console.log('stopping that'); }

var run = (() => {
    var fns = {
        stuff:  { run: doStuff,  stop: stopStuff  },
        things: { run: doThings, stop: stopThings },
        it:     { run: doIt,     stop: stopIt     },
        "this": { run: doThis,   stop: stopThis   },
        that:   { run: doThat,   stop: stopThat   }
    };
    return what => Object.keys(fns)
        // include the sort only if you need to stop all first before start
        // change a == what to b == what to start selected and then stop the rest
        .sort((a,b) => a == what)
        .forEach(key => fns[key][what == key ? 'run' : 'stop']());
})();

console.log('things');
run('things');
console.log('this');
run('this');


问:
Swift: How to refresh tableview without lag (UIRefreshControl)
Filling my table view with objects from a MYSQL database using PHP and JSON to Swift 3. I have a pull down to refresh function but when I'm pulling down to refresh it lags mid way for a second and then continues (like the wheel won't spin for a second).

How can I update my tableview smoother because I'm guessing as I add more content to the database in the future the bigger the lag. I currently have 12 objects in my database so imagine with 100+ objects.

In viewDidLoad

```<code>// Pull to Refresh
    let refreshControl = UIRefreshControl()
    refreshControl.addTarget(self, action: #selector(handleRefresh), for: .valueChanged)
    if #available(iOS 10.0, *) {
        myTableView.refreshControl = refreshControl
        print("iOS 10")
    } else {
        myTableView.addSubview(refreshControl)
        print("iOS 9 or iOS 8")
    }
</code>```

Then pull to refresh function

```<code>// Pull to Refresh
func handleRefresh(refreshControl: UIRefreshControl) {

    // Fetching Data for TableView
    retrieveDataFromServer()

    // Stop Refreshing
    refreshControl.endRefreshing()
}

// Retrieving Data from Server
func retrieveDataFromServer() {

    // Loading Data from File Manager
    loadData()

    let getDataURL = "http://example.com/receiving.php"
    let url: NSURL = NSURL(string: getDataURL)!

    do {
        let data: Data = try Data(contentsOf: url as URL)
        let jsonArray = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! NSMutableArray

        // Clear the arrays
        self.followedArray = [Blog]()
        self.mainArray = [Blog]()

        // Looping through jsonArray
        for jsonObject in jsonArray {

            if let blog = Blog(jsonObject:jsonObject as! [String : Any]) {

                // Check if Identifiers Match
                if followedIdentifiers.contains(blog.blogID) {
                    self.followedArray.append(blog)
                } else {
                    self.mainArray.append(blog)
                }
            }
        }
    } catch {
        print("Error: (Retrieving Data)")
    }
    myTableView.reloadData()
}
</code>```

答:
I imagine the lag you're experiencing is due to the network request being executed synchronously on the main thread:

```<code>let data: Data = try Data(contentsOf: url as URL)
</code>```

Network requests are slow and should almost certainly be done off the main thread. The solution here is to move the networking call to a background thread so the main (UI) thread doesn't get blocked (lag).

So how do you do that? Well that is a large question with many different answers.

I highly recommend you spend some time learning about multi-threaded programming (also known as concurrency) in Swift. Going through this Ray Wenderlich tutorial should give you a good foundation.

Then it's probably a good idea to learn about URLSession which is used for performing asynchronous network requests in iOS apps. Again Ray Wenderlich has a great starter tutorial.

Finally... here is a quick and dirty solution for you. It's "hacky" and you probably shouldn't use it, but it will probably fix your lag issue:

```<code>func retrieveDataFromServer() {

    // Loading Data from File Manager
    loadData()

    let getDataURL = "http://example.com/receiving.php"
    let url: NSURL = NSURL(string: getDataURL)!

    // Move to a background queue to fetch and process data from network.
    DispatchQueue.global().async {

        // Don't touch anything related to the UI here.
        do {
            let data: Data = try Data(contentsOf: url as URL)
            let jsonArray = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! NSMutableArray

            // Create new temp arrays to process json
            var tempFollowedArray = [Blog]()
            var tempMainArray = [Blog]()

            // Looping through jsonArray
            for jsonObject in jsonArray {

                if let blog = Blog(jsonObject:jsonObject as! [String : Any]) {

                    // Check if Identifiers Match
                    if self.followedIdentifiers.contains(blog.blogID) {
                        tempFollowedArray.append(blog)
                    } else {
                        tempMainArray.append(blog)
                    }
                }
            }

            // Jump back to main (UI) thread to update results
            DispatchQueue.main.async {
                print("success")
                self.followedArray = tempFollowedArray
                self.mainArray = tempMainArray

                self.myTableView.reloadData()
            }
        } catch {
            DispatchQueue.main.async {
                print("Error: (Retrieving Data)")
                // This reload is probably not necessary, but it was
                // in your original code so I included it.
                self.myTableView.reloadData()
            }
        }
    }
}
</code>```

Body:
Filling my table view with objects from a MYSQL database using PHP and JSON to Swift 3. I have a pull down to refresh function but when I'm pulling down to refresh it lags mid way for a second and then continues (like the wheel won't spin for a second).

How can I update my tableview smoother because I'm guessing as I add more content to the database in the future the bigger the lag. I currently have 12 objects in my database so imagine with 100+ objects.

In viewDidLoad

// Pull to Refresh
    let refreshControl = UIRefreshControl()
    refreshControl.addTarget(self, action: #selector(handleRefresh), for: .valueChanged)
    if #available(iOS 10.0, *) {
        myTableView.refreshControl = refreshControl
        print("iOS 10")
    } else {
        myTableView.addSubview(refreshControl)
        print("iOS 9 or iOS 8")
    }

Then pull to refresh function

// Pull to Refresh
func handleRefresh(refreshControl: UIRefreshControl) {

    // Fetching Data for TableView
    retrieveDataFromServer()

    // Stop Refreshing
    refreshControl.endRefreshing()
}

// Retrieving Data from Server
func retrieveDataFromServer() {

    // Loading Data from File Manager
    loadData()

    let getDataURL = "http://example.com/receiving.php"
    let url: NSURL = NSURL(string: getDataURL)!

    do {
        let data: Data = try Data(contentsOf: url as URL)
        let jsonArray = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! NSMutableArray

        // Clear the arrays
        self.followedArray = [Blog]()
        self.mainArray = [Blog]()

        // Looping through jsonArray
        for jsonObject in jsonArray {

            if let blog = Blog(jsonObject:jsonObject as! [String : Any]) {

                // Check if Identifiers Match
                if followedIdentifiers.contains(blog.blogID) {
                    self.followedArray.append(blog)
                } else {
                    self.mainArray.append(blog)
                }
            }
        }
    } catch {
        print("Error: (Retrieving Data)")
    }
    myTableView.reloadData()
}

Body:
I imagine the lag you're experiencing is due to the network request being executed synchronously on the main thread:

let data: Data = try Data(contentsOf: url as URL)

Network requests are slow and should almost certainly be done off the main thread. The solution here is to move the networking call to a background thread so the main (UI) thread doesn't get blocked (lag).

So how do you do that? Well that is a large question with many different answers.

I highly recommend you spend some time learning about multi-threaded programming (also known as concurrency) in Swift. Going through this Ray Wenderlich tutorial should give you a good foundation.

Then it's probably a good idea to learn about URLSession which is used for performing asynchronous network requests in iOS apps. Again Ray Wenderlich has a great starter tutorial.

Finally... here is a quick and dirty solution for you. It's "hacky" and you probably shouldn't use it, but it will probably fix your lag issue:

func retrieveDataFromServer() {

    // Loading Data from File Manager
    loadData()

    let getDataURL = "http://example.com/receiving.php"
    let url: NSURL = NSURL(string: getDataURL)!

    // Move to a background queue to fetch and process data from network.
    DispatchQueue.global().async {

        // Don't touch anything related to the UI here.
        do {
            let data: Data = try Data(contentsOf: url as URL)
            let jsonArray = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! NSMutableArray

            // Create new temp arrays to process json
            var tempFollowedArray = [Blog]()
            var tempMainArray = [Blog]()

            // Looping through jsonArray
            for jsonObject in jsonArray {

                if let blog = Blog(jsonObject:jsonObject as! [String : Any]) {

                    // Check if Identifiers Match
                    if self.followedIdentifiers.contains(blog.blogID) {
                        tempFollowedArray.append(blog)
                    } else {
                        tempMainArray.append(blog)
                    }
                }
            }

            // Jump back to main (UI) thread to update results
            DispatchQueue.main.async {
                print("success")
                self.followedArray = tempFollowedArray
                self.mainArray = tempMainArray

                self.myTableView.reloadData()
            }
        } catch {
            DispatchQueue.main.async {
                print("Error: (Retrieving Data)")
                // This reload is probably not necessary, but it was
                // in your original code so I included it.
                self.myTableView.reloadData()
            }
        }
    }
}


问:
Adding legend based on existing color series
I plotted some data using scatter plot and specified it as such:

```<code>plt.scatter(rna.data['x'], rna.data['y'], s=size,
                    c=rna.data['colors'], edgecolors='none')
</code>```

and the rna.data object is a pandas dataframe that is organized such that each row represents a data point ('x' and 'y' represents the coordinate and 'colors' is an integer between 0-5 representing the color of the point). I grouped the data points into six distinct clusters numbered 0-5, and put the cluster number at each cluster's mean coordinates.

This outputs the following graph:

I was wondering how I can add a legend to this plot specifying the color and its corresponding cluster number. plt.legend() requires the style code to be in the format such as red_patch but it does not seem to take numeric values (or the numeric strings). How can I add this legend using matplotlib then? Is there a way to translate my numeric value color codes to the format that plt.legend() takes? Thanks a lot!

答:
Altair can be a great choice here.

Continuous classes

```<code>import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

df = pd.DataFrame(40*np.random.randn(10, 3), columns=['A', 'B','C'])

from altair import *
Chart(df).mark_circle().encode(x='A',y='B', color='C').configure_cell(width=200, height=150)
</code>```

Discrete classes

```<code>df = pd.DataFrame(10*np.random.randn(40, 2), columns=['A', 'B'])
df['C'] = np.random.choice(['alpha','beta','gamma','delta'], size=40)

from altair import *
Chart(df).mark_circle().encode(x='A',y='B', color='C').configure_cell(width=200, height=150)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I plotted some data using scatter plot and specified it as such:

plt.scatter(rna.data['x'], rna.data['y'], s=size,
                    c=rna.data['colors'], edgecolors='none')

and the rna.data object is a pandas dataframe that is organized such that each row represents a data point ('x' and 'y' represents the coordinate and 'colors' is an integer between 0-5 representing the color of the point). I grouped the data points into six distinct clusters numbered 0-5, and put the cluster number at each cluster's mean coordinates.

This outputs the following graph:

I was wondering how I can add a legend to this plot specifying the color and its corresponding cluster number. plt.legend() requires the style code to be in the format such as red_patch but it does not seem to take numeric values (or the numeric strings). How can I add this legend using matplotlib then? Is there a way to translate my numeric value color codes to the format that plt.legend() takes? Thanks a lot!

Body:
Altair can be a great choice here.

Continuous classes

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

df = pd.DataFrame(40*np.random.randn(10, 3), columns=['A', 'B','C'])

from altair import *
Chart(df).mark_circle().encode(x='A',y='B', color='C').configure_cell(width=200, height=150)

Discrete classes

df = pd.DataFrame(10*np.random.randn(40, 2), columns=['A', 'B'])
df['C'] = np.random.choice(['alpha','beta','gamma','delta'], size=40)

from altair import *
Chart(df).mark_circle().encode(x='A',y='B', color='C').configure_cell(width=200, height=150)


问:
Rails Render View If File Exists
I'm in the process of creating a modular Rails template based on the Device template. I have the main application layout:

application.html.erb

```<code><!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><%= content_for?(:title) ? yield(:title) : "Rails Devise" %></title>
    <meta name="description" content="<%= content_for?(:description) ? yield(:description) : "Rails Devise" %>">
    <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
    <%= csrf_meta_tags %>
  </head>
  <body>
    <header>
      <%= render 'layouts/navigation' %>
    </header>
    <main role="main">
       <%= render 'layouts/messages' %>
       <%= yield %>
    </main>
    <footer>
       <% if File.exist?('layouts/footer') %>
          <%= render 'layouts/footer' %>
       <% end %>
    </footer>
  </body>
</html>
</code>```

I have a footer template that I'd like to include if the file is present (which it may not be):

_footer.html.erb

```<code><p class="text-muted">
  © <%= Time.now.year.to_s %> All rights reserved
</p>
</code>```

File.exist? isn't rendering the footer when it's there. How can I include the footer only if the template file exists?

答:
Try use rescue nil at the end of render.

render nil will show nothing.

<%= render 'layouts/footer' rescue nil %>

Hope it helps, cheers!

Title: Rails Render View If File Exists

Body:
I'm in the process of creating a modular Rails template based on the Device template. I have the main application layout:

application.html.erb

<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><%= content_for?(:title) ? yield(:title) : "Rails Devise" %></title>
    <meta name="description" content="<%= content_for?(:description) ? yield(:description) : "Rails Devise" %>">
    <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
    <%= csrf_meta_tags %>

      <%= render 'layouts/navigation' %>

       <%= render 'layouts/messages' %>
       <%= yield %>

       <% if File.exist?('layouts/footer') %>
          <%= render 'layouts/footer' %>
       <% end %>

I have a footer template that I'd like to include if the file is present (which it may not be):

_footer.html.erb

  © <%= Time.now.year.to_s %> All rights reserved

File.exist? isn't rendering the footer when it's there. How can I include the footer only if the template file exists?


问:
Adding submodules to a repository
I added another repository as a submodule on my repository (/path/myrepo) on git.I am using git extensions on Windows. After adding the repository the only file that I committed is

```<code>[submodule "comms"]
    path = comms
    url = http://xxx-eng1/stash/scm/ta/sub.git
</code>```

The repository is there in my /path/myrepo. Should I commit and push this submodule into my master?

答:
Yes, you should. The .gitmodules file is version-controlled with the other files, like the .gitignore file. It’s also pushed and pulled with the rest of the project.

you can do $ git diff --cached --submodule to be more clear

when you commit these changes you will see message like
create mode 160000 comms

The 160000 mode is a special mode in Git which means you’re recording a commit as a directory entry rather than a subdirectory or a file

Title: Adding submodules to a repository

Body:
I added another repository as a submodule on my repository (/path/myrepo) on git.I am using git extensions on Windows. After adding the repository the only file that I committed is

[submodule "comms"]
    path = comms
    url = http://xxx-eng1/stash/scm/ta/sub.git

The repository is there in my /path/myrepo. Should I commit and push this submodule into my master?


问:
how strip commas from string in Elixir?
I wonder how to remove commas from given string. My try was:

```<code>st = "1,2,3"
String.strip(st, ?,)
#=> "1,2,3"
</code>```

What am I doing wrong?

答:
You could also do something like this: </p>

```<code>st |> String.split(",") |> Enum.join
</code>```

<p>Of course it's best to use the standard tool, but then this is an alternative. </p>

Title: how strip commas from string in Elixir?

Body:
I wonder how to remove commas from given string. My try was:

st = "1,2,3"
String.strip(st, ?,)
#=> "1,2,3"

What am I doing wrong?

Body:
You could also do something like this:

st |> String.split(",") |> Enum.join

Of course it's best to use the standard tool, but then this is an alternative.


问:
getValue() for SelectField
All I simply want to do is to get the name of the Company and save it to the database

I was trying with do with text, and was trying to fetch using the below code

sport: this.refs.company.getValue(), and it was working perfect.

Then I decided to use the SelectField from Material UI for Company

And it's not fetching the data.

```<code>constructor(props) {
super(props);
this.state = {
  value: 1,
};
}

submitResume(event) {
    event.preventDefault();
    console.log(this.state.company.getValue({value}));

CreatePost.insert({
        company: this.refs.company.getValue(),

        employee: this.refs.employee.getValue(),

    });
    console.log("Employee Profile Submitted!");
}

handleNameChange = (event, index, value) => this.setState({value});

    <form onSubmit={this.submitResume.bind(this)}>

          <SelectField
                    floatingLabelText="Company Name"
                    className="validate"
                    ref="company"
                    id="company"
                    floatingLabelStyle={{fontSize:20}}
                    fullWidth={true}
                    value={this.state.value}
                    onChange={this.handleNameChange}
                  >
                    <MenuItem value={1} primaryText="Google" />
                    <MenuItem value={2} primaryText="Facebook" />
                    <MenuItem value={3} primaryText="Amazon" />
                    <MenuItem value={4} primaryText="Nest" />
                    <MenuItem value={5} primaryText="Microsoft" />
            </SelectField>

            <TextField
                className="validate"
                type="text"
                ref="employee"
                id="employee"
                hintText="Enter Full Name"
                floatingLabelStyle={{fontSize:20}}
                floatingLabelText="Employee Name"
                multiLine={true}
                rows={1}
                fullWidth={true}
            />
</code>```

It's working fine for TextField, but not for SelectField.

答:
Now see this updated one
you will get your value in one of the parameter value, index or event

```<code>constructor(props) {
super(props);
this.state = {
  value: 1,
};
}

submitResume(event) {
    event.preventDefault();
    console.log(this.state.company.getValue({value}));

CreatePost.insert({
        company: this.refs.company.getValue(),

        employee: this.refs.employee.getValue(),

    });
    console.log("Employee Profile Submitted!");
}

handleNameChange(event, index, value) {
  console.log(event);
  console.log(index);
  console.log(value);
  this.setState({value});
}

    <form onSubmit={this.submitResume.bind(this)}>

          <SelectField
                    floatingLabelText="Company Name"
                    className="validate"
                    ref="company"
                    id="company"
                    floatingLabelStyle={{fontSize:20}}
                    fullWidth={true}
                    value={this.state.value}
                    onChange={this.handleNameChange}
                  >
                    <MenuItem value={"Google"} primaryText="Google" />
                    <MenuItem value={"Facebook"} primaryText="Facebook" />
                    <MenuItem value={"Amazon"} primaryText="Amazon" />
                    <MenuItem value={"Nest"} primaryText="Nest" />
                    <MenuItem value={"Microsoft"} primaryText="Microsoft" />
            </SelectField>

            <TextField
                className="validate"
                type="text"
                ref="employee"
                id="employee"
                hintText="Enter Full Name"
                floatingLabelStyle={{fontSize:20}}
                floatingLabelText="Employee Name"
                multiLine={true}
                rows={1}
                fullWidth={true}
            />
</code>```

Title: getValue() for SelectField

Body:
All I simply want to do is to get the name of the Company and save it to the database

I was trying with do with text, and was trying to fetch using the below code

sport: this.refs.company.getValue(), and it was working perfect.

Then I decided to use the SelectField from Material UI for Company

And it's not fetching the data.

constructor(props) {
super(props);
this.state = {
  value: 1,
};
}

submitResume(event) {
    event.preventDefault();
    console.log(this.state.company.getValue({value}));

CreatePost.insert({
        company: this.refs.company.getValue(),

        employee: this.refs.employee.getValue(),

    });
    console.log("Employee Profile Submitted!");
}

handleNameChange = (event, index, value) => this.setState({value});

    <form onSubmit={this.submitResume.bind(this)}>

          <SelectField
                    floatingLabelText="Company Name"
                    className="validate"
                    ref="company"
                    id="company"
                    floatingLabelStyle={{fontSize:20}}
                    fullWidth={true}
                    value={this.state.value}
                    onChange={this.handleNameChange}
                  >
                    <MenuItem value={1} primaryText="Google" />
                    <MenuItem value={2} primaryText="Facebook" />
                    <MenuItem value={3} primaryText="Amazon" />
                    <MenuItem value={4} primaryText="Nest" />
                    <MenuItem value={5} primaryText="Microsoft" />
            </SelectField>

            <TextField
                className="validate"
                type="text"
                ref="employee"
                id="employee"
                hintText="Enter Full Name"
                floatingLabelStyle={{fontSize:20}}
                floatingLabelText="Employee Name"
                multiLine={true}
                rows={1}
                fullWidth={true}
            />

It's working fine for TextField, but not for SelectField.

Body:
Now see this updated one
you will get your value in one of the parameter value, index or event

constructor(props) {
super(props);
this.state = {
  value: 1,
};
}

submitResume(event) {
    event.preventDefault();
    console.log(this.state.company.getValue({value}));

CreatePost.insert({
        company: this.refs.company.getValue(),

        employee: this.refs.employee.getValue(),

    });
    console.log("Employee Profile Submitted!");
}

handleNameChange(event, index, value) {
  console.log(event);
  console.log(index);
  console.log(value);
  this.setState({value});
}

    <form onSubmit={this.submitResume.bind(this)}>

          <SelectField
                    floatingLabelText="Company Name"
                    className="validate"
                    ref="company"
                    id="company"
                    floatingLabelStyle={{fontSize:20}}
                    fullWidth={true}
                    value={this.state.value}
                    onChange={this.handleNameChange}
                  >
                    <MenuItem value={"Google"} primaryText="Google" />
                    <MenuItem value={"Facebook"} primaryText="Facebook" />
                    <MenuItem value={"Amazon"} primaryText="Amazon" />
                    <MenuItem value={"Nest"} primaryText="Nest" />
                    <MenuItem value={"Microsoft"} primaryText="Microsoft" />
            </SelectField>

            <TextField
                className="validate"
                type="text"
                ref="employee"
                id="employee"
                hintText="Enter Full Name"
                floatingLabelStyle={{fontSize:20}}
                floatingLabelText="Employee Name"
                multiLine={true}
                rows={1}
                fullWidth={true}
            />


问:
ListBox throwing ArgumentOutOfRangeException when adding to DataSource
I'm trying use a BindingList as a DataSource for a ListBox in C# WinForms, but whenever I try to add items to the BindingList, I get an ArgumentOutOfRangeException thrown.  The following code demonstrates the problem (assume a form with ListBox listBox1):

```<code>BindingList<string> dataSource = new BindingList<string>();
listBox1.DataSource = dataSource;
dataSource.Add("Test1"); // Exception, here.
</code>```

Note that if dataSource already has items in it, I do not get the exception:

```<code>BindingList<string> dataSource = new BindingList<string>();
dataSource.Add("Test1");
listBox1.DataSource = dataSource;
dataSource.Add("Test2"); // Appears to work correctly.
</code>```

I can work around the problem by setting the DataSource property to null before adding an item, and re-setting the DataSource afterward, but this feels like a hack, and I'd like to be able to avoid doing so.

Is there a (non-hack) way to use an empty DataSource on a ListBox, such that adding items to it doesn't throw exceptions?

Edit: Stack Trace:

System.Windows.Forms.dll!System.Windows.Forms.ListBox.SelectedIndex.set(int
  value) + 0x1ec bytes

    System.Windows.Forms.dll!System.Windows.Forms.ListControl.DataManager_PositionChanged(object
  sender, System.EventArgs e) + 0x2e
  bytes

    System.Windows.Forms.dll!System.Windows.Forms.CurrencyManager.OnPositionChanged(System.EventArgs
  e) + 0x39 bytes

    System.Windows.Forms.dll!System.Windows.Forms.CurrencyManager.ChangeRecordState(int
  newPosition, bool validating, bool
  endCurrentEdit, bool
  firePositionChange, bool pullData) +
  0x14f bytes

    System.Windows.Forms.dll!System.Windows.Forms.CurrencyManager.List_ListChanged(object
  sender,
  System.ComponentModel.ListChangedEventArgs
  e) + 0x2e4 bytes

    System.dll!System.ComponentModel.BindingList.OnListChanged(System.ComponentModel.ListChangedEventArgs
  e) + 0x17 bytes

    System.dll!System.ComponentModel.BindingList.FireListChanged(System.ComponentModel.ListChangedType
  type, int index) + 0x35 bytes

    System.dll!System.ComponentModel.BindingList.InsertItem(int
  index, System._Canon item) + 0x3f
  bytes

    mscorlib.dll!System.Collections.ObjectModel.Collection.Add(System._Canon
  item) + 0x76 bytes

答: It turns out I had everything checked in the "Exceptions" dialog (Debug->Exceptions).  So, the exception exists, but is (silently) handled by the .Net framework.  Continuing program execution displays the expected results.</p>

Body:
I'm trying use a BindingList as a DataSource for a ListBox in C# WinForms, but whenever I try to add items to the BindingList, I get an ArgumentOutOfRangeException thrown.  The following code demonstrates the problem (assume a form with ListBox listBox1):

BindingList<string> dataSource = new BindingList<string>();
listBox1.DataSource = dataSource;
dataSource.Add("Test1"); // Exception, here.

Note that if dataSource already has items in it, I do not get the exception:

BindingList<string> dataSource = new BindingList<string>();
dataSource.Add("Test1");
listBox1.DataSource = dataSource;
dataSource.Add("Test2"); // Appears to work correctly.

I can work around the problem by setting the DataSource property to null before adding an item, and re-setting the DataSource afterward, but this feels like a hack, and I'd like to be able to avoid doing so.

Is there a (non-hack) way to use an empty DataSource on a ListBox, such that adding items to it doesn't throw exceptions?

Edit: Stack Trace:

System.Windows.Forms.dll!System.Windows.Forms.ListBox.SelectedIndex.set(int
  value) + 0x1ec bytes

    System.Windows.Forms.dll!System.Windows.Forms.ListControl.DataManager_PositionChanged(object
  sender, System.EventArgs e) + 0x2e
  bytes

    System.Windows.Forms.dll!System.Windows.Forms.CurrencyManager.OnPositionChanged(System.EventArgs
  e) + 0x39 bytes

    System.Windows.Forms.dll!System.Windows.Forms.CurrencyManager.ChangeRecordState(int
  newPosition, bool validating, bool
  endCurrentEdit, bool
  firePositionChange, bool pullData) +
  0x14f bytes

    System.Windows.Forms.dll!System.Windows.Forms.CurrencyManager.List_ListChanged(object
  sender,
  System.ComponentModel.ListChangedEventArgs
  e) + 0x2e4 bytes

    System.dll!System.ComponentModel.BindingList.OnListChanged(System.ComponentModel.ListChangedEventArgs
  e) + 0x17 bytes

    System.dll!System.ComponentModel.BindingList.FireListChanged(System.ComponentModel.ListChangedType
  type, int index) + 0x35 bytes

    System.dll!System.ComponentModel.BindingList.InsertItem(int
  index, System._Canon item) + 0x3f
  bytes

    mscorlib.dll!System.Collections.ObjectModel.Collection.Add(System._Canon
  item) + 0x76 bytes


问:
Firebase Email Authentication iOS: "The email is badly formatted"
Attempting to create a Firebase login/signup but no matter what I enter into the email textfield it prints the error "The email address is badly formatted", even if its a valid email. Also I'm a beginner so...sorry about the format. This is the code:</p>

```<code>import UIKit
import Firebase
import FirebaseAuth

class SecondViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

      //  FirebaseApp.configure()
        }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    @IBOutlet weak var username_input: UITextField!
    @IBOutlet weak var password_input: UITextField!
    @IBOutlet weak var signupButton: UIButton!
    @IBOutlet weak var segmentControl: UISegmentedControl!
    @IBAction func doSignUp(_ sender: Any) {
    let email = self.username_input.text
    let password = self.password_input.text

      if email != "" && password != ""
        {
            if segmentControl.selectedSegmentIndex == 1 //signup

            {

                Auth.auth().createUser(withEmail: email!, password: password!, completion: { (user, error) in
                    if error == nil {
                        print("You have successfully signed up")
                        // Goes to main page
                        let vc = self.storyboard?.instantiateViewController(withIdentifier: "Home")
                        self.present(vc!, animated: true, completion: nil)
                        self.performSegue(withIdentifier: "segue", sender: self)
                        let request = Auth.auth().currentUser?.createProfileChangeRequest()
                        request?.displayName = email

                    }
                    else {
                        if (error?.localizedDescription) != nil
                        {

                            //   let alertController = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert)
                            //  let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
                            //   alertController.addAction(defaultAction)
                            // self.present(alertController, animated: true, completion: nil)
                            print(error?.localizedDescription as Any)
                            let myError1 = error?.localizedDescription
                            print(myError1!)

                        }
                    }
                })
            }
        }

    if segmentControl.selectedSegmentIndex == 0 {
    //login

    Auth.auth().signIn(withEmail: self.username_input.text!, password: self.password_input.text!, completion: { (user, error) in
    if user != nil
    {
    self.performSegue(withIdentifier: "segue", sender: self)
    //sign in user
    }
    else
    {
    if (error?.localizedDescription) != nil
    {
    _ = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert)

    let myError = error?.localizedDescription
    print(myError!)

            }
    else {
        Auth.auth().signIn(withEmail: self.username_input.text!, password: self.password_input.text!, completion: { (user, error) in
            if user != nil
            {
                self.performSegue(withIdentifier: "segue", sender: self)
                //sign in user
            }
            else
            {
                if (error?.localizedDescription) != nil
                {
                    _ = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert)

                    let myError = error?.localizedDescription
                    print(myError!)
        }

    }
}
)}
}
}
)
}
}
</code>```

答:
My code For Reference have a look     </p>

```<code>//Outlets
        @IBOutlet weak var emailTextField: UITextField!
        @IBOutlet weak var passwordTextField: UITextField!

    //Sign Up Action for email
    @IBAction func createAccountAction(_ sender: AnyObject) {

        let email = emailTextField.text
        let pass = passwordTextField.text
        if emailTextField.text == "" {
            let alertController = UIAlertController(title: "Error", message: "Please enter your email and password", preferredStyle: .alert)

            let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
            alertController.addAction(defaultAction)

            present(alertController, animated: true, completion: nil)

        } else {
            Auth.auth().createUser(withEmail: email!, password: pass!) { (user, error) in

                if error == nil {
                    print("You have successfully signed up")
                    //Goes to the Setup page which lets the user take a photo for their profile picture and also chose a username

                    let vc = self.storyboard?.instantiateViewController(withIdentifier: "Home")
                    self.present(vc!, animated: true, completion: nil)

                } else {
                    let alertController = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert)

                    let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
                    alertController.addAction(defaultAction)

                    self.present(alertController, animated: true, completion: nil)
                }
            }

        }
    }
</code>```

Body:
Attempting to create a Firebase login/signup but no matter what I enter into the email textfield it prints the error "The email address is badly formatted", even if its a valid email. Also I'm a beginner so...sorry about the format. This is the code:

import UIKit
import Firebase
import FirebaseAuth

class SecondViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

      //  FirebaseApp.configure()
        }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    @IBOutlet weak var username_input: UITextField!
    @IBOutlet weak var password_input: UITextField!
    @IBOutlet weak var signupButton: UIButton!
    @IBOutlet weak var segmentControl: UISegmentedControl!
    @IBAction func doSignUp(_ sender: Any) {
    let email = self.username_input.text
    let password = self.password_input.text

      if email != "" && password != ""
        {
            if segmentControl.selectedSegmentIndex == 1 //signup

            {

                Auth.auth().createUser(withEmail: email!, password: password!, completion: { (user, error) in
                    if error == nil {
                        print("You have successfully signed up")
                        // Goes to main page
                        let vc = self.storyboard?.instantiateViewController(withIdentifier: "Home")
                        self.present(vc!, animated: true, completion: nil)
                        self.performSegue(withIdentifier: "segue", sender: self)
                        let request = Auth.auth().currentUser?.createProfileChangeRequest()
                        request?.displayName = email

                    }
                    else {
                        if (error?.localizedDescription) != nil
                        {

                            //   let alertController = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert)
                            //  let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
                            //   alertController.addAction(defaultAction)
                            // self.present(alertController, animated: true, completion: nil)
                            print(error?.localizedDescription as Any)
                            let myError1 = error?.localizedDescription
                            print(myError1!)

                        }
                    }
                })
            }
        }

    if segmentControl.selectedSegmentIndex == 0 {
    //login

    Auth.auth().signIn(withEmail: self.username_input.text!, password: self.password_input.text!, completion: { (user, error) in
    if user != nil
    {
    self.performSegue(withIdentifier: "segue", sender: self)
    //sign in user
    }
    else
    {
    if (error?.localizedDescription) != nil
    {
    _ = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert)

    let myError = error?.localizedDescription
    print(myError!)

            }
    else {
        Auth.auth().signIn(withEmail: self.username_input.text!, password: self.password_input.text!, completion: { (user, error) in
            if user != nil
            {
                self.performSegue(withIdentifier: "segue", sender: self)
                //sign in user
            }
            else
            {
                if (error?.localizedDescription) != nil
                {
                    _ = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert)

                    let myError = error?.localizedDescription
                    print(myError!)
        }

    }
}
)}
}
}
)
}
}

Body:
My code For Reference have a look

//Outlets
        @IBOutlet weak var emailTextField: UITextField!
        @IBOutlet weak var passwordTextField: UITextField!

    //Sign Up Action for email
    @IBAction func createAccountAction(_ sender: AnyObject) {

        let email = emailTextField.text
        let pass = passwordTextField.text
        if emailTextField.text == "" {
            let alertController = UIAlertController(title: "Error", message: "Please enter your email and password", preferredStyle: .alert)

            let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
            alertController.addAction(defaultAction)

            present(alertController, animated: true, completion: nil)

        } else {
            Auth.auth().createUser(withEmail: email!, password: pass!) { (user, error) in

                if error == nil {
                    print("You have successfully signed up")
                    //Goes to the Setup page which lets the user take a photo for their profile picture and also chose a username

                    let vc = self.storyboard?.instantiateViewController(withIdentifier: "Home")
                    self.present(vc!, animated: true, completion: nil)

                } else {
                    let alertController = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert)

                    let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
                    alertController.addAction(defaultAction)

                    self.present(alertController, animated: true, completion: nil)
                }
            }

        }
    }


问:
Freemarker Template: "Sort_by" one or other
I have a Freemarker template and There are two times involved
"LocalTime" and "ServerTime". If I can determine user's LocalTime from the data, i need to use "LocalTime" & sort_by it, else i need to sort_by ServerTime. The whole data exists within a list (from a record)

Originally it was alright to do using ServerTime and the function was like:

```<code><#list x.data.record?sort_by("ServerTime") as s>
</code>```

But if I want to check if there is "LocalTime" , how to do this?

I am expecting something in line..

```<code><#list x.data.record?sort_by("ServerTime||LocalTime") as s>
</code>```

(Please note, this is different from sorting two columns)

答:
I am still a newbie with freemarker, but I believe I solved this just now for myself. Its ugly, but it works. I'm not dealing with thousands or even hundreds of rows most of the time, so efficiency is not a huge concern with this case. NetSuite is the system feeding into Freemarker, and its a bit of a pain.

Essentially, I run through the list once and store one value or the other (server/local time for you) into a single variable (invoiceDate, in my case). I then put that variable, along with the other display variables I need, into a hash. That hash is then one line in a list.

To display: I run through the list, which is sorted by my invoiceDate variable and for each line (hash), I print out the info I need from that key/value pair.

I know this was 4 years ago but I needed an answer tonight and couldn't find  one until I thought about it this way...hope this helps the next guy!

```<code><#assign y=[]>
  <#list record.lines as tmpLine>

    <#assign invoiceDate = tmpLine.datecol>
    <#if (tmpLine.someIdentifyingMarker != "")>
        <#assign invoiceDate = tmpLine.custbody_p_ending_date>
    </#if>

    <#assign dataLine = {"displayDate":invoiceDate, "Description":tmpLine.description, "CheckNum":tmpLine.custbody_checknumprint, "InvoiceAmount":tmpLine.charge,"Credit":tmpLine.payment,"Remaining":tmpLine.amountremaining,"Balance":tmpLine.balance}>
    <#assign y = y+[dataLine]>

    </#list>

<#list y?sort_by('displayDate') as line><tr>

    <td colspan="4">${line.displayDate}</td>
    <td colspan="10">${line.Description}</td>
    <td colspan="4"><span style="background-color: rgb(255, 255, 255);">${line.CheckNum}</span></td>
    <td align="right" colspan="5">${line.InvoiceAmount}</td>
    <td align="right" colspan="4">${line.Credit}</td>
    <td align="right" colspan="4"><span style="text-align: -webkit-right; background-color: rgb(255, 255, 255);">${line.Remaining}</span></td>
    <td align="right" colspan="5">${line.Balance}</td>
    </tr>
    </#list></table>
</code>```

Body:
I have a Freemarker template and There are two times involved
"LocalTime" and "ServerTime". If I can determine user's LocalTime from the data, i need to use "LocalTime" & sort_by it, else i need to sort_by ServerTime. The whole data exists within a list (from a record)

Originally it was alright to do using ServerTime and the function was like:

<#list x.data.record?sort_by("ServerTime") as s>

But if I want to check if there is "LocalTime" , how to do this?

I am expecting something in line..

<#list x.data.record?sort_by("ServerTime||LocalTime") as s>

(Please note, this is different from sorting two columns)

Body:
I am still a newbie with freemarker, but I believe I solved this just now for myself. Its ugly, but it works. I'm not dealing with thousands or even hundreds of rows most of the time, so efficiency is not a huge concern with this case. NetSuite is the system feeding into Freemarker, and its a bit of a pain.

Essentially, I run through the list once and store one value or the other (server/local time for you) into a single variable (invoiceDate, in my case). I then put that variable, along with the other display variables I need, into a hash. That hash is then one line in a list.

To display: I run through the list, which is sorted by my invoiceDate variable and for each line (hash), I print out the info I need from that key/value pair.

I know this was 4 years ago but I needed an answer tonight and couldn't find  one until I thought about it this way...hope this helps the next guy!

<#assign y=[]>
  <#list record.lines as tmpLine>

    <#assign invoiceDate = tmpLine.datecol>
    <#if (tmpLine.someIdentifyingMarker != "")>
        <#assign invoiceDate = tmpLine.custbody_p_ending_date>
    </#if>

    <#assign dataLine = {"displayDate":invoiceDate, "Description":tmpLine.description, "CheckNum":tmpLine.custbody_checknumprint, "InvoiceAmount":tmpLine.charge,"Credit":tmpLine.payment,"Remaining":tmpLine.amountremaining,"Balance":tmpLine.balance}>
    <#assign y = y+[dataLine]>

    </#list>

<#list y?sort_by('displayDate') as line><tr>

    <td colspan="4">${line.displayDate}</td>
    <td colspan="10">${line.Description}</td>
    <td colspan="4"><span style="background-color: rgb(255, 255, 255);">${line.CheckNum}</span></td>
    <td align="right" colspan="5">${line.InvoiceAmount}</td>
    <td align="right" colspan="4">${line.Credit}</td>
    <td align="right" colspan="4"><span style="text-align: -webkit-right; background-color: rgb(255, 255, 255);">${line.Remaining}</span></td>
    <td align="right" colspan="5">${line.Balance}</td>
    </tr>
    </#list></table>


问:
Combine two overlapping tables of date ranges
I'm trying to combine two tables with date ranges, in Excel.

I have properties that have certain seasonal pricing, and I have packages that have OTHER seasonal margins, and I need to combine the date brackets for the two.

I can figure out all the margin/pricing stuff in VBA. It's included here because otherwise the data looks identical in certain cases, even when it's not. But I'm having no luck even getting started on combining the dates.

This is the primary table; any date created by joining the two tables/ranges should be included in these dates:

I need to merge this type of regional data with specific property data:

And when I combine, them, it needs to look something like this:

I can do this easily dumping data into SQL, but I need something replicable by anyone in the company, from Excel spreadsheets.

I've tried various formula schemes - do this, then that, then this other thing. I've tried doing a cross-join with power query, and then trying to eliminate the dates that I don't want. None of that works.

I knew from the gitgo that it wanted to be done in VBA, and everything else I tried was kinda stalling tactics. The problem is, I can't seem to even wrap my head around the logic required. And I have more than one use-case for this logic.

All property dates need to exist (within a range) in the primary table.
Properties may have dates that don't exist in the primary ranges at all.

答:
I'm sure there are more efficient ways but here is how I would do it using named tables for the data and a range for the output. You should be able to modify it to suit. The logic was a bit more complicated that I thought. Under the code is a screen grab of my test output which matches your table.

```<code>Option Explicit
Sub TableMerge()
    Dim i As Integer
    Dim j As Integer
    Dim insert_row As Integer
    Dim prev_FINISH As Date
    Dim Table_1 As ListObject
    Dim Table_2 As ListObject

    insert_row = 2
    prev_FINISH = CDate("01/01/1900")

    Set Table_1 = ActiveSheet.ListObjects("Table1")
    Set Table_2 = ActiveSheet.ListObjects("Table2")

    For i = 1 To Table_2.ListRows.Count
        For j = 1 To Table_1.ListRows.Count

        ' assumes the headers are in place, using range L:R for Table3
            If (Table_2.DataBodyRange.Cells(i, Table_2.ListColumns("REG").Index) = Table_1.DataBodyRange.Cells(j, Table_1.ListColumns("REG").Index)) And (Table_2.DataBodyRange.Cells(i, Table_2.ListColumns("Finish").Index) > Table_1.DataBodyRange.Cells(j, Table_1.ListColumns("Start").Index)) And (Table_2.DataBodyRange.Cells(i, Table_2.ListColumns("sTART").Index) < Table_1.DataBodyRange.Cells(j, Table_1.ListColumns("Finish").Index)) Then
                If (prev_FINISH = CDate("01/01/1900") And (Table_2.DataBodyRange.Cells(i, Table_2.ListColumns("Start").Index) <= Table_1.DataBodyRange.Cells(j, Table_1.ListColumns("Finish").Index))) Or (prev_FINISH >= Table_1.DataBodyRange.Cells(j, Table_1.ListColumns("Start").Index)) Or (Table_2.DataBodyRange.Cells(i, Table_2.ListColumns("Finish").Index) >= Table_1.DataBodyRange.Cells(j, Table_1.ListColumns("Start").Index)) Then

                'If (prev_FINISH = CDate("01/01/1900") And (Table_2.DataBodyRange.Cells(i, Table_2.ListColumns("Start").Index) <= Table_1.DataBodyRange.Cells(j, Table_1.ListColumns("Finish").Index)) 'Or (Table_2.DataBodyRange.Cells(i, Table_2.ListColumns("Finish").Index) >= Table_1.DataBodyRange.Cells(j, Table_1.ListColumns("Finish").Index))) Then
                ' add new entry
                    ActiveSheet.Range("L" & insert_row).Value = Table_2.DataBodyRange.Cells(i, Table_2.ListColumns("REG").Index)
                    ActiveSheet.Range("M" & insert_row).Value = Table_2.DataBodyRange.Cells(i, Table_2.ListColumns("Name").Index)
                    ActiveSheet.Range("N" & insert_row).Value = maxoftwo(maxoftwo(Table_1.DataBodyRange.Cells(j, Table_1.ListColumns("Start").Index), Table_2.DataBodyRange.Cells(i, Table_2.ListColumns("Start").Index)), prev_FINISH)
                    ActiveSheet.Range("O" & insert_row).Value = minoftwo(Table_1.DataBodyRange.Cells(j, Table_1.ListColumns("Finish").Index), Table_2.DataBodyRange.Cells(i, Table_2.ListColumns("Finish").Index))
                    ActiveSheet.Range("P" & insert_row).Value = Table_1.DataBodyRange.Cells(j, Table_1.ListColumns("MARG").Index)
                    ActiveSheet.Range("Q" & insert_row).Value = Table_2.DataBodyRange.Cells(i, Table_2.ListColumns("COST").Index)
                    ActiveSheet.Range("R" & insert_row).Formula = "=Q:Q/(1-P:P)"
                    If ActiveSheet.Range("O" & insert_row).Value <> Table_2.DataBodyRange.Cells(i, Table_2.ListColumns("Finish").Index) Then
                        prev_FINISH = ActiveSheet.Range("O" & insert_row).Value
                    Else
                        prev_FINISH = CDate("01/01/1900")
                        j = 1
                        insert_row = insert_row + 1
                        GoTo Next_i
                    End If
                    insert_row = insert_row + 1
                End If
            End If
        Next j
        prev_FINISH = CDate("01/01/1900")
    Next_i:
    Next i
End Sub

Function maxoftwo(date1 As Date, date2 As Date) As Date
    maxoftwo = date1
    If date2 > date1 Then maxoftwo = date2
End Function

Function minoftwo(date1 As Date, date2 As Date) As Date
    minoftwo = date1
    If date2 < date1 Then minoftwo = date2
End Function
</code>```

Body:
I'm sure there are more efficient ways but here is how I would do it using named tables for the data and a range for the output. You should be able to modify it to suit. The logic was a bit more complicated that I thought. Under the code is a screen grab of my test output which matches your table.

Option Explicit
Sub TableMerge()
    Dim i As Integer
    Dim j As Integer
    Dim insert_row As Integer
    Dim prev_FINISH As Date
    Dim Table_1 As ListObject
    Dim Table_2 As ListObject

    insert_row = 2
    prev_FINISH = CDate("01/01/1900")

    Set Table_1 = ActiveSheet.ListObjects("Table1")
    Set Table_2 = ActiveSheet.ListObjects("Table2")

    For i = 1 To Table_2.ListRows.Count
        For j = 1 To Table_1.ListRows.Count

        ' assumes the headers are in place, using range L:R for Table3
            If (Table_2.DataBodyRange.Cells(i, Table_2.ListColumns("REG").Index) = Table_1.DataBodyRange.Cells(j, Table_1.ListColumns("REG").Index)) And (Table_2.DataBodyRange.Cells(i, Table_2.ListColumns("Finish").Index) > Table_1.DataBodyRange.Cells(j, Table_1.ListColumns("Start").Index)) And (Table_2.DataBodyRange.Cells(i, Table_2.ListColumns("sTART").Index) < Table_1.DataBodyRange.Cells(j, Table_1.ListColumns("Finish").Index)) Then
                If (prev_FINISH = CDate("01/01/1900") And (Table_2.DataBodyRange.Cells(i, Table_2.ListColumns("Start").Index) <= Table_1.DataBodyRange.Cells(j, Table_1.ListColumns("Finish").Index))) Or (prev_FINISH >= Table_1.DataBodyRange.Cells(j, Table_1.ListColumns("Start").Index)) Or (Table_2.DataBodyRange.Cells(i, Table_2.ListColumns("Finish").Index) >= Table_1.DataBodyRange.Cells(j, Table_1.ListColumns("Start").Index)) Then

                'If (prev_FINISH = CDate("01/01/1900") And (Table_2.DataBodyRange.Cells(i, Table_2.ListColumns("Start").Index) <= Table_1.DataBodyRange.Cells(j, Table_1.ListColumns("Finish").Index)) 'Or (Table_2.DataBodyRange.Cells(i, Table_2.ListColumns("Finish").Index) >= Table_1.DataBodyRange.Cells(j, Table_1.ListColumns("Finish").Index))) Then
                ' add new entry
                    ActiveSheet.Range("L" & insert_row).Value = Table_2.DataBodyRange.Cells(i, Table_2.ListColumns("REG").Index)
                    ActiveSheet.Range("M" & insert_row).Value = Table_2.DataBodyRange.Cells(i, Table_2.ListColumns("Name").Index)
                    ActiveSheet.Range("N" & insert_row).Value = maxoftwo(maxoftwo(Table_1.DataBodyRange.Cells(j, Table_1.ListColumns("Start").Index), Table_2.DataBodyRange.Cells(i, Table_2.ListColumns("Start").Index)), prev_FINISH)
                    ActiveSheet.Range("O" & insert_row).Value = minoftwo(Table_1.DataBodyRange.Cells(j, Table_1.ListColumns("Finish").Index), Table_2.DataBodyRange.Cells(i, Table_2.ListColumns("Finish").Index))
                    ActiveSheet.Range("P" & insert_row).Value = Table_1.DataBodyRange.Cells(j, Table_1.ListColumns("MARG").Index)
                    ActiveSheet.Range("Q" & insert_row).Value = Table_2.DataBodyRange.Cells(i, Table_2.ListColumns("COST").Index)
                    ActiveSheet.Range("R" & insert_row).Formula = "=Q:Q/(1-P:P)"
                    If ActiveSheet.Range("O" & insert_row).Value <> Table_2.DataBodyRange.Cells(i, Table_2.ListColumns("Finish").Index) Then
                        prev_FINISH = ActiveSheet.Range("O" & insert_row).Value
                    Else
                        prev_FINISH = CDate("01/01/1900")
                        j = 1
                        insert_row = insert_row + 1
                        GoTo Next_i
                    End If
                    insert_row = insert_row + 1
                End If
            End If
        Next j
        prev_FINISH = CDate("01/01/1900")
    Next_i:
    Next i
End Sub

Function maxoftwo(date1 As Date, date2 As Date) As Date
    maxoftwo = date1
    If date2 > date1 Then maxoftwo = date2
End Function

Function minoftwo(date1 As Date, date2 As Date) As Date
    minoftwo = date1
    If date2 < date1 Then minoftwo = date2
End Function


答:
Let the functions take a parameter, and iterate through an array of functions that call each of them except the parameter. Example: </p>

```<code>var doing = [
  stuff:  function(func) {
    stopping.forEach(element => {
      if (element !== func) {
        element()
      }
    }
    doStuff()
  },
  ...
];

var stopping = [
  stopStuff:  function() { stoppingStuff() },
  ...
];
</code>```

Title: Elegantly Toggling Many Functions

Body:
Let's say I have a handful of functions that do things:

function doStuff()  { console.log('doing stuff'); }
function doThings() { console.log('doing things'); }
function doIt()     { console.log('doing it'); }
function doThis()   { console.log('doing this'); }
function doThat()   { console.log('doing that'); }

And then just as many that disable their behaviors:

function stopStuff()  { console.log('stopping stuff'); }
function stopThings() { console.log('stopping things'); }
function stopIt()     { console.log('stopping it'); }
function stopThis()   { console.log('stopping this'); }
function stopThat()   { console.log('stopping that'); }

Then I put all the 'do' functions in an object so I can dynamically access them by setting what:

var what = 'things';

var doing = {
    stuff:  function() { doStuff(); },
    things: function() { doThings(); },
    it:     function() { doIt(); },
    this:   function() { doThis(); },
    that:   function() { doThat(); }
};

doing[what](); //console logs 'doing things'

Is there a way to go about enabling one do function while iterating through all the non-matching stop functions?

For example, if I do var what = 'this'; doing[what]();, I want it to not only doThis(); but also stopStuff(); stopThings(); stopIt(); stopThat();

I'm having trouble coming up with an elegant method that doesn't involve lengthy if statements or case/switch.

Body:
Let the functions take a parameter, and iterate through an array of functions that call each of them except the parameter. Example:

var doing = [
  stuff:  function(func) {
    stopping.forEach(element => {
      if (element !== func) {
        element()
      }
    }
    doStuff()
  },
  ...
];

var stopping = [
  stopStuff:  function() { stoppingStuff() },
  ...
];


问:
How to Find All TRUE Conditions and Concatenate Corresponding Variables into New Variable?
```<code>a = 4
b = 5
c = 7

if (a >= 4){
    text1 = “a is high”;
}
if (b >= 8){
    text2 = “b is high”;
}
if (c >= 6){
    text3 = “c is high”;
}
</code>```

In C or C++, how would I find which of these statements are true (a & c) and create a new variable that concatenates their accompanying variables containing text to produce a result like “a is high and c is high”? The next time the code executes it may find that only a is high, or whatever the case may be.  How would I go about doing this?

答:
Use a single variable and keep on appending as you get the required information.</p>

```<code>string text1;
if (a >= 4)
   text1.append("a is high");
if (b >= 8)
{
    if(text1.length()!=0)
         text1.append(" and ");
    text1.append("b is high");
}
if (c <= 6)
{
   if(text1.length()!=0)
        text1.append(" and ");
   text1.append("c is high");
 }
</code>```

Body:
a = 4
b = 5
c = 7

if (a >= 4){
    text1 = “a is high”;
}
if (b >= 8){
    text2 = “b is high”;
}
if (c >= 6){
    text3 = “c is high”;
}

In C or C++, how would I find which of these statements are true (a & c) and create a new variable that concatenates their accompanying variables containing text to produce a result like “a is high and c is high”? The next time the code executes it may find that only a is high, or whatever the case may be.  How would I go about doing this?

Body:
Use a single variable and keep on appending as you get the required information.

string text1;
if (a >= 4)
   text1.append("a is high");
if (b >= 8)
{
    if(text1.length()!=0)
         text1.append(" and ");
    text1.append("b is high");
}
if (c <= 6)
{
   if(text1.length()!=0)
        text1.append(" and ");
   text1.append("c is high");
 }


问:
Set system property inside TestNG XML suite
I have a test suite like this:

```<code><suite name="MySuite">
    <parameter name="key" value="val"/>
    <test name="testing">
        <packages>
            <package name="mypack.testpackage.*"/>
        </packages>
    </test>
</suite>
</code>```

but I need to use key as a system property instead of a parameter (because I use it later in some Spring ELs where I can't use @Parameters to take its value).

So I'd like to use something like:

```<code>    <system-property name="key" value="val"/>
</code>```

or

```<code>    <parameter name="key" value="val" system-property="true"/>
</code>```

instead of the parameter

```<code>    <parameter name="key" value="val"/>
</code>```

Does TestNG support this?

答: Doesn't support out of the box - you will need to write code for it to override if values are available as system properties.</p>

Body:
I have a test suite like this:

<suite name="MySuite">
    <parameter name="key" value="val"/>
    <test name="testing">
        <packages>
            <package name="mypack.testpackage.*"/>
        </packages>
    </test>
</suite>

but I need to use key as a system property instead of a parameter (because I use it later in some Spring ELs where I can't use @Parameters to take its value).

So I'd like to use something like:

    <system-property name="key" value="val"/>

or

    <parameter name="key" value="val" system-property="true"/>

instead of the parameter

    <parameter name="key" value="val"/>

Does TestNG support this?


问:
What is the conditional code to affect IE8 browser?
I don't mean conditional comments embedded into the html. I am refering to the conditional code that can be put directly into the css file. Like:

```<code>*+html .myClass {} is for IE7
* html .myClass {} is for IE 6
</code>```

what is the one for IE 8?

答:
Conditional comment for the HTML tag, which will allow you to target .ie8 in your CSS:

```<code><!--[if lt IE 7 ]> <html class="ie6"> <![endif]-->
<!--[if IE 7 ]>    <html class="ie7"> <![endif]-->
<!--[if IE 8 ]>    <html class="ie8"> <![endif]-->
<!--[if IE 9 ]>    <html class="ie9"> <![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--> <html class=""> <!--<![endif]--></code>```

That is what's currently being used in html5boilerplate.

Also, be weary of the last few paragraphs in Paul's blog post. I agree that you should try to make it work without targeting specific browsers, it at all possible.

Body:
I don't mean conditional comments embedded into the html. I am refering to the conditional code that can be put directly into the css file. Like:

*+html .myClass {} is for IE7
* html .myClass {} is for IE 6

what is the one for IE 8?

Body:
Conditional comment for the HTML tag, which will allow you to target .ie8 in your CSS:

<!--[if lt IE 7 ]> <html class="ie6"> <![endif]-->
<!--[if IE 7 ]>    <html class="ie7"> <![endif]-->
<!--[if IE 8 ]>    <html class="ie8"> <![endif]-->
<!--[if IE 9 ]>    <html class="ie9"> <![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--> <html class=""> <!--<![endif]-->

That is what's currently being used in html5boilerplate.

Also, be weary of the last few paragraphs in Paul's blog post. I agree that you should try to make it work without targeting specific browsers, it at all possible.


问:
DropDown to select data from MS SQL server
I'm trying to make a PHP web application display the data from specific Countries from a dropdown but I can't figure it out how to use the WHERE [Column] = [Value1, Value2, Value3] on a PHP dropdown.

I'm using the "Adventure Works 2014 Full Database Backup" for test purpose.

```<code><html>
</body>
<!-- form for tower selection -->
<form action="test20.php" method="POST">
Please select the tower you are about to work on. </br></br>
<select name="TowerSelect"><option> Choose </option>
<?php
$serverName = 'SERVERNAME';
$uid = 'USERNAME';
$pwd = 'PASSWORD';
$databaseName = 'AdWorks';

$connectionInfo = array( 'UID'=>$uid,
                        'PWD'=>$pwd,
                        'Database'=>$databaseName);

$conn = sqlsrv_connect($serverName,$connectionInfo);
if($conn){
    echo '';
}else{
    echo 'Connection failure<br />';
die(print_r(sqlsrv_errors(),TRUE));
}
$sql = "SELECT BusinessEntityID, FirstName FROM dbo.vKelvin WHERE CountryRegionName = 'United States'";
$result = sqlsrv_query($conn,$sql) or die("Couldn't execut query");
while ($data=sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)){

    echo "<option value=";
    echo $data['BusinessEntityID'];
    echo ">";
    echo $data['BusinessEntityID'];
    echo "</option>";
}
?>
<input type="submit" value="Select Tower">
</select></br></br>
</form>
</body></html>
<?php
if(empty($_POST['TowerSelect'])){
    $_SESSION['tower'] = '';
} else {
    $_SESSION['tower'] = $_POST['TowerSelect'];
    echo "<tr>";
    echo $_SESSION['tower'];
    echo "  selected. </p>";
    echo('<td>'.$row['BusinessEntityID'].'</td><td>'.$row['FirstName'].'</td></tr>');
}
</code>```

答:
Ok, I got the solution, my select was wrong</p>

```<code>$sql = "SELECT DISTINCT CountryRegionName FROM dbo.vKelvin ORDER BY CountryRegionName";
$result = sqlsrv_query($conn,$sql) or die("Couldn't execut query");
while ($data=sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)){
echo '<option value="'.$data['CountryRegionName'].'">';
echo $data['CountryRegionName'];
echo "</option>";
</code>```

Body:
I'm trying to make a PHP web application display the data from specific Countries from a dropdown but I can't figure it out how to use the WHERE [Column] = [Value1, Value2, Value3] on a PHP dropdown.

I'm using the "Adventure Works 2014 Full Database Backup" for test purpose.

<form action="test20.php" method="POST">
Please select the tower you are about to work on.

<select name="TowerSelect"><option> Choose </option>
<?php
$serverName = 'SERVERNAME';
$uid = 'USERNAME';
$pwd = 'PASSWORD';
$databaseName = 'AdWorks';

$connectionInfo = array( 'UID'=>$uid,
                        'PWD'=>$pwd,
                        'Database'=>$databaseName);

$conn = sqlsrv_connect($serverName,$connectionInfo);
if($conn){
    echo '';
}else{
    echo 'Connection failure
';
die(print_r(sqlsrv_errors(),TRUE));
}
$sql = "SELECT BusinessEntityID, FirstName FROM dbo.vKelvin WHERE CountryRegionName = 'United States'";
$result = sqlsrv_query($conn,$sql) or die("Couldn't execut query");
while ($data=sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)){

    echo "<option value=";
    echo $data['BusinessEntityID'];
    echo ">";
    echo $data['BusinessEntityID'];
    echo "</option>";
}
?>
<input type="submit" value="Select Tower">
</select>

</form>

<?php
if(empty($_POST['TowerSelect'])){
    $_SESSION['tower'] = '';
} else {
    $_SESSION['tower'] = $_POST['TowerSelect'];
    echo "
";
    echo $_SESSION['tower'];
    echo "  selected.
";
    echo(''.$row['BusinessEntityID'].'	'.$row['FirstName'].'
');
}

Body:
Ok, I got the solution, my select was wrong

$sql = "SELECT DISTINCT CountryRegionName FROM dbo.vKelvin ORDER BY CountryRegionName";
$result = sqlsrv_query($conn,$sql) or die("Couldn't execut query");
while ($data=sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC)){
echo '<option value="'.$data['CountryRegionName'].'">';
echo $data['CountryRegionName'];
echo "</option>";


问:
How many concurrent requests can dockerd handle?
We have 1 swarm cluster with 3 managers and 10 workers for performance test. When 100 concurrent requests(create service) sent to one swarm manager, dockerd may accept all the requests to dispatch to workers. But if we increase the num of concurrent requests, the dockerd error log says:

```<code>Error creating service serviceXXX: rpc error: code = 4 desc = context
deadline exceeded"
</code>```

Is there a default value of max concurrent requests that dockerd can handle in code? How could we increase the concurrent requests that dockerd can process successfully?

The daemon is version 17.03.

答:
As commented in issue 29987, this error message is not very explicit:

I think whenever we encounter a context deadline exceeded error, we should rewrite it to a coherent explanation of what timed out, and perhaps list possible reasons that could cause the timeout (loss of quorum, etc).

When working on docker/docker-e2e, I had problems where things were timing out causing context deadline exceed errors, but the root cause of the timeout was some other error that was getting ignored, superseded, or otherwise buried.

As detailed in issue 33631:

This error can have various causes (See this search for existing issues mentioning this error).

The error itself is quite generic, and could mean that the manager was not able to communicate with other managers in the cluster.

From just the error, it's not easy to discover why it fails to communicate (it can be either a bad network connection, other managers did not properly re-join the cluster, therefore you lost quorum, or it could be if (e.g.) managers did not have a static IP-address, and the IP-address changed - which is currently not supported).

You can see a similar case here but this happens also with less queries.

Body:
We have 1 swarm cluster with 3 managers and 10 workers for performance test. When 100 concurrent requests(create service) sent to one swarm manager, dockerd may accept all the requests to dispatch to workers. But if we increase the num of concurrent requests, the dockerd error log says:

Error creating service serviceXXX: rpc error: code = 4 desc = context
deadline exceeded"

Is there a default value of max concurrent requests that dockerd can handle in code? How could we increase the concurrent requests that dockerd can process successfully?

The daemon is version 17.03.


问:
How to set color of the Back icon of Form's Toolbar?
I'm trying to change color of all elements of form's toolbar:

```<code>public class LoginForm extends Form{

    private Form formSplash;

    public LoginForm(Resources theme) {
        super("Login", new BorderLayout());
        setUIID("rush-login");
        getToolbar().getTitleComponent().setUIID("rush-login-title");
        getToolbar().getAllStyles().setBgTransparency(0);
        getToolbar().setBackCommand("Back", e -> {
                    if(formSplash != null) {
                        formSplash.showBack();
                    }
        });
        setScrollable(false);
    }

    public void setFormSplash(Form formSplash) {
        this.formSplash = formSplash;
    }
}
</code>```

I do see the title's color changed, but the back icon still has the original color:

Is any way to have the same color for each element of the toolbar?

答:
I'm not sure if this will work for setBackCommand but you can use findCommandComponent on the toolbar and set the UIID to whatever you want:

```<code>Button b = toolbar.findCommandComponent(cmd);
</code>```

setBackCommand returns a Command object you should be able to use for that although you might need to use the add command to left side methods instead for this use case.

Body:
I'm trying to change color of all elements of form's toolbar:

public class LoginForm extends Form{

    private Form formSplash;

    public LoginForm(Resources theme) {
        super("Login", new BorderLayout());
        setUIID("rush-login");
        getToolbar().getTitleComponent().setUIID("rush-login-title");
        getToolbar().getAllStyles().setBgTransparency(0);
        getToolbar().setBackCommand("Back", e -> {
                    if(formSplash != null) {
                        formSplash.showBack();
                    }
        });
        setScrollable(false);
    }

    public void setFormSplash(Form formSplash) {
        this.formSplash = formSplash;
    }
}

I do see the title's color changed, but the back icon still has the original color:

Is any way to have the same color for each element of the toolbar?

Body:
I'm not sure if this will work for setBackCommand but you can use findCommandComponent on the toolbar and set the UIID to whatever you want:

Button b = toolbar.findCommandComponent(cmd);

setBackCommand returns a Command object you should be able to use for that although you might need to use the add command to left side methods instead for this use case.


问:
cannot write(2) file larger than 2GB (up to 2TB)
I have a program written by C. It computes something and writes the output into a file. My problem is that it does not write more than 2GB. Let me put a simplified code.

```<code>#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <malloc.h>
#include <errno.h>
int main() {
    size_t size = 3221225472LL;
    char *map = malloc(size);
    size_t allocated = malloc_usable_size(map);
    int fd = open("myfile", O_RDWR|O_CREAT|O_TRUNC, (mode_t)0644);
    ssize_t written = write(fd, map, size);
    return 0;
}
</code>```

Although the output file "myfile" is being created, the size is always 2GB (2147479552 Bytes) for whatever size greater than 2GB I requested.The malloc() successfully allocated memory of the requested size (in this case, "allocated" is 3GB). The errno after write() is 0.

The environment is the following

OS:  Ubuntu 16.04.1 x86_64

Physical memory size: 32GB

File system: ext4

Compilation:

```<code>gcc code.c -D_FILE_OFFSET_BITS=64 -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -D_LARGEFILE64_SOURCE
</code>```

What could be the reason for this?

Addition:
After getting two responses, I added retry code as following:

```<code>int main() {
    size_t size = 3221225472LL;
    char *map = malloc(size);
    size_t allocated = malloc_usable_size(map);
    int fd = open("myfile", O_RDWR|O_CREAT|O_TRUNC, (mode_t)0644);
    ssize_t written = write(fd, map, size);
    while (written < size) {
        written += write(fd, &map[written], size-written);
    }
    return 0;
}
</code>```

答:
According to the man page (emphasis mine)

On Linux, write() (and similar system calls) will transfer at most 0x7ffff000 (2,147,479,552) bytes, returning the number of bytes actually transferred.  (This is true on both 32-bit and 64-bit systems.)

Body:
I have a program written by C. It computes something and writes the output into a file. My problem is that it does not write more than 2GB. Let me put a simplified code.

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <malloc.h>
#include <errno.h>
int main() {
    size_t size = 3221225472LL;
    char *map = malloc(size);
    size_t allocated = malloc_usable_size(map);
    int fd = open("myfile", O_RDWR|O_CREAT|O_TRUNC, (mode_t)0644);
    ssize_t written = write(fd, map, size);
    return 0;
}

Although the output file "myfile" is being created, the size is always 2GB (2147479552 Bytes) for whatever size greater than 2GB I requested.The malloc() successfully allocated memory of the requested size (in this case, "allocated" is 3GB). The errno after write() is 0.

The environment is the following

OS:  Ubuntu 16.04.1 x86_64

Physical memory size: 32GB

File system: ext4

Compilation:

gcc code.c -D_FILE_OFFSET_BITS=64 -D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE -D_LARGEFILE64_SOURCE

What could be the reason for this?

Addition:
After getting two responses, I added retry code as following:

int main() {
    size_t size = 3221225472LL;
    char *map = malloc(size);
    size_t allocated = malloc_usable_size(map);
    int fd = open("myfile", O_RDWR|O_CREAT|O_TRUNC, (mode_t)0644);
    ssize_t written = write(fd, map, size);
    while (written < size) {
        written += write(fd, &map[written], size-written);
    }
    return 0;
}


问:
Winform Checklistbox Headers/Columns
Is there a way to implement a new column with a header in a checklistbox in vb.net?  I've done a bit of searching, but didn't find much on the topic.  Should I just abandon the quest and use a listview or some other control?

Thanks for any/all help!
JFV

答: Another alternative is a DataGridView with a checkbox column. </p>

OwnerDisplayName: JFV

Title: Winform Checklistbox Headers/Columns

OwnerDisplayName: novatrust