问:
How to block and inform threads
I have a List object in my class and two methods which are used to add and remove items from the list.

There are multiple threads trying to access the list.

I want to ensure that only one thread is updating the list at an instance.

If a list is empty and a thread wants to remove an item then I want to make the thread wait till there is an item in the list.

When an item is inserted in the list
then I want to inform other threads
which are waiting to access the list
that the list is not empty anymore
and they can remove the items (using events).

What is the best mechanism to achieve this goal?

答: This is a multithreaded producer/consumer pattern. Take a look at this question.</p>

Title: How to block and inform threads


来源: stackexchange

问:
Django and api widget
I am relatively new in web development and I needed your help with the following.

I am creating a basic website using Django where a user can manage his portfolio.
Now I was using this widget from Tradingview.com in this manner.

Now what I wanted to know was if I could somehow store what the user was adding in the watchlist in the database itself and load it when the widget loads next time

答:
Tradingview.com's widget is implemented using an iframe tag on your website, so you want to execute javascript inside the iframe so everytime a user adds to his wishlist you sent an ajax request to your django backend.

but thats not possibles if the widget is from another domain than tradingview.com

Calling a parent JS function from iframe is possible, but only when
  both the parent and the page loaded in the iframe are from same
  domain i.e. abc.com, and both are using same protocol i.e. both are
  either on http:// or https://.

The call will fail in below mentioned cases:

Parent page and the iframe page are from different domain.

They are using different protocols, one is on http:// and other is on https://.

Any workaround to this restriction would be extremely insecure.

For instance, imagine I registered the domain superwinningcontest.com
  and sent out links to people's emails. When they loaded up the main
  page, I could hide a few iframes in there and read their Facebook
  feed, check recent Amazon or PayPal transactions, or--if they used a
  service that did not implement sufficient security--transfer money out
  of their accounts. That's why JavaScript is limited to same-domain and
  same-protocol.

SOURCE: https://stackoverflow.com/a/2663118/4885802

ContentLicense: CC BY-SA 3.0

Title: Django and api widget


问:
While Loop Issue
Hoping that someone can offer some assistance, I am currently working on a piece of code which seems to be having issues.  Unfortunately I cant post the underlying data but will try and explain.

The code currently cycles through a selection of kpi's and calculates if something needs to be run or not based on the current time and whether the individual kpi's need to be run.  At the moment if I hard code a number of kpi's the code works fine but if I let it cycle through all the kpi's, ones that should not run are being told to run, also in the select that defines things like @Period, when I let it run through all KPI's its setting the @Period incorrectly when it shouldn't run but when its meant to run it set it fine.

Overall I have 2 issues which I think are related KPI's run when they are not meant to and when they are running when they are not meant to they pick up the wrong Period either way which is odd.  I think what is happening is when I let it run all the way through the KPI's are getting mixed up but I cant see how this is happening, any help would be great before I go mad.

As you can see from my code there are 2 @current_timestamps, when its set to 23.45.18.873 it should not run some of the kpi's but it runs them all anyway and the 21.45.18.873 means that they can run.

```<code>declare @job_current_time_minute float,
        @job_current_date_time_minute as datetime,
        @current_timestamp as datetime

SET @job_current_time_minute = 52--cast(datepart(minute, getdate()) as float)
SET @job_current_date_time_minute =  getdate()
--SET @current_timestamp = cast('2017-04-02 23:45:18.873' as datetime)
SET @current_timestamp = cast('2017-04-02 21:45:18.873' as datetime)
--Run: 88 6 0 52 5 5 5
--Run: 88 1 10 52 5 5 5

declare
    @kpi_id int,
    @kpi_parent_id int,
    @sql nvarchar(max),
    @kpi_last_result nvarchar(100),
    @kpi_last_runtime datetime,
    @kpi_params nvarchar(max),
    @kpi_current_time_minute float,
    @schedulue_minute float,
    @reoccurrence float,
    @result float,
    @kpi2 int,

    -- Email Variables
    @kpi_name nvarchar(150),
    @kpi_desc nvarchar(150),
    @kpi_report_link nvarchar(150),
    @kpi_email_subject nvarchar(150),
    @kpi_email_body nvarchar(300),
    @kpi_email_query nvarchar(max),
    @kpi_sms_msg nvarchar(300);

SET @kpi_params = N'@retvalOUT varchar(max) OUTPUT';

select @kpi_id = min(kpi_id) from KPI where KPI_Active = 1; --and kpi_id in (86, 88)

    while @kpi_id is not null

        begin

            select
            @kpi_parent_id = kpi_parent_id,
            @sql = kpi_Script,
            @schedulue_minute = datepart(minute,s.Schedule_Start),
            @reoccurrence = s.Reoccurrence,
            @result = cast((@job_current_time_minute - datepart(minute,s.Schedule_Start)) / s.Reoccurrence as decimal(18,2)),
            @kpi_name = kpi_name,
            @kpi_desc = kpi_desc,
            @kpi_report_link = kpi_report_link,
            @kpi_email_subject = kpi_email_subject,
            @kpi_email_body = kpi_email_body,
            @kpi_email_query = kpi_email_query,
            @kpi_sms_msg = kpi_sms_msg,
            @kpi_current_time_minute = 60*DATEPART(HOUR, GETDATE())+DATEPART(MINUTE,GETDATE()),
            @kpi2 = KPI_ID
            from EWI..KPI
            inner join EWI..Schedule s on KPI.Schedule_ID = s.Schedule_ID where kpi_id = @kpi_id--order by kpi_id asc

            --set @sql = 'select @retvalOUT= (' + @sql + ')'

if floor(@result) <> ceiling(@result)

        begin

            PRINT 'Not Time to Run: ' + ' ' + cast(@kpi_id as varchar(11)) + ' ' + cast(@result as varchar(11))

        end

else

        begin

                    declare
                    @ThresholdID int,
                    @PeriodID int,
                    @Threshold_value int,
                    @Threshold_PosNeg nvarchar(5)

            select @ThresholdID = Threshold_ID, @PeriodID = Period_ID, @Threshold_value = Threshold_value, @Threshold_PosNeg = Threshold_PosNeg from (
            --  select * from (
                select * from (
                        select KPI_ID, t.Threshold_ID, p.Period_ID, t.Threshold_Value, t.Threshold_PosNeg, p.DayStartTime, p.DayEndTime, Period_desc, [Day]
                        from EWI..Threshold t join
                                    EWI..Period p on t.Period_ID = p.Period_ID where KPI_ID = @kpi_id
                ) x where (case when [Day] = datename(dw,getdate()) then Period_id
                    when [Day] = choose(datepart(dw, getdate()), 'WEEKEND','Weekday','Weekday','Weekday','Weekday','Weekday','WEEKEND') then Period_ID
                    when [Day] = 'All' then Period_ID end) is not null
            ) y where case when datediff(second,DayStartTime,DayEndTime) > 0 then
            case when convert(time(0), @current_timestamp) >= DayStartTime and convert(time(0), @current_timestamp) < DayEndTime then 1 else 0 end
            else case when convert(time(0), @current_timestamp) >= DayStartTime or convert(time(0), @current_timestamp) < DayEndTime then 1 else 0 end
            end = 1

select 'Run: ' + cast(@kpi_id as varchar(11)) + ' ' + cast(@PeriodID as varchar(11)) + ' ' +
cast(@Threshold_value as varchar(11)) + ' ' + cast(@job_current_time_minute as varchar(11))  + ' ' +
cast(@result as varchar(11))  + ' ' +
cast(ceiling(@result) as varchar(11))+ ' ' +cast(floor(@result) as varchar(11))

    end

    select @kpi_id = min(kpi_id) from KPI where KPI_Active = 1 and kpi_id > @kpi_id;

end
</code>```

答:
Take a look at this rextester demo. Do you agree that this model reproduces the problem? It seems that comparing ceiling(@result) to floor(@result) will indeed give everywhere true.

After our discussion it seems to me that the test should be:
if (@result - datepart(minute, Schedule_Start)) % @reoccurrence = 0
or something like that. But this assumes @reoccurence to be an integer.

Title: While Loop Issue

Body:
Hoping that someone can offer some assistance, I am currently working on a piece of code which seems to be having issues.  Unfortunately I cant post the underlying data but will try and explain.

The code currently cycles through a selection of kpi's and calculates if something needs to be run or not based on the current time and whether the individual kpi's need to be run.  At the moment if I hard code a number of kpi's the code works fine but if I let it cycle through all the kpi's, ones that should not run are being told to run, also in the select that defines things like @Period, when I let it run through all KPI's its setting the @Period incorrectly when it shouldn't run but when its meant to run it set it fine.

Overall I have 2 issues which I think are related KPI's run when they are not meant to and when they are running when they are not meant to they pick up the wrong Period either way which is odd.  I think what is happening is when I let it run all the way through the KPI's are getting mixed up but I cant see how this is happening, any help would be great before I go mad.

As you can see from my code there are 2 @current_timestamps, when its set to 23.45.18.873 it should not run some of the kpi's but it runs them all anyway and the 21.45.18.873 means that they can run.

declare @job_current_time_minute float,
        @job_current_date_time_minute as datetime,
        @current_timestamp as datetime

SET @job_current_time_minute = 52--cast(datepart(minute, getdate()) as float)
SET @job_current_date_time_minute =  getdate()
--SET @current_timestamp = cast('2017-04-02 23:45:18.873' as datetime)
SET @current_timestamp = cast('2017-04-02 21:45:18.873' as datetime)
--Run: 88 6 0 52 5 5 5
--Run: 88 1 10 52 5 5 5

declare
    @kpi_id int,
    @kpi_parent_id int,
    @sql nvarchar(max),
    @kpi_last_result nvarchar(100),
    @kpi_last_runtime datetime,
    @kpi_params nvarchar(max),
    @kpi_current_time_minute float,
    @schedulue_minute float,
    @reoccurrence float,
    @result float,
    @kpi2 int,

    -- Email Variables
    @kpi_name nvarchar(150),
    @kpi_desc nvarchar(150),
    @kpi_report_link nvarchar(150),
    @kpi_email_subject nvarchar(150),
    @kpi_email_body nvarchar(300),
    @kpi_email_query nvarchar(max),
    @kpi_sms_msg nvarchar(300);

SET @kpi_params = N'@retvalOUT varchar(max) OUTPUT';

select @kpi_id = min(kpi_id) from KPI where KPI_Active = 1; --and kpi_id in (86, 88)

    while @kpi_id is not null

        begin

            select
            @kpi_parent_id = kpi_parent_id,
            @sql = kpi_Script,
            @schedulue_minute = datepart(minute,s.Schedule_Start),
            @reoccurrence = s.Reoccurrence,
            @result = cast((@job_current_time_minute - datepart(minute,s.Schedule_Start)) / s.Reoccurrence as decimal(18,2)),
            @kpi_name = kpi_name,
            @kpi_desc = kpi_desc,
            @kpi_report_link = kpi_report_link,
            @kpi_email_subject = kpi_email_subject,
            @kpi_email_body = kpi_email_body,
            @kpi_email_query = kpi_email_query,
            @kpi_sms_msg = kpi_sms_msg,
            @kpi_current_time_minute = 60*DATEPART(HOUR, GETDATE())+DATEPART(MINUTE,GETDATE()),
            @kpi2 = KPI_ID
            from EWI..KPI
            inner join EWI..Schedule s on KPI.Schedule_ID = s.Schedule_ID where kpi_id = @kpi_id--order by kpi_id asc

            --set @sql = 'select @retvalOUT= (' + @sql + ')'

if floor(@result) <> ceiling(@result)

        begin

            PRINT 'Not Time to Run: ' + ' ' + cast(@kpi_id as varchar(11)) + ' ' + cast(@result as varchar(11))

        end

else

        begin

                    declare
                    @ThresholdID int,
                    @PeriodID int,
                    @Threshold_value int,
                    @Threshold_PosNeg nvarchar(5)

            select @ThresholdID = Threshold_ID, @PeriodID = Period_ID, @Threshold_value = Threshold_value, @Threshold_PosNeg = Threshold_PosNeg from (
            --  select * from (
                select * from (
                        select KPI_ID, t.Threshold_ID, p.Period_ID, t.Threshold_Value, t.Threshold_PosNeg, p.DayStartTime, p.DayEndTime, Period_desc, [Day]
                        from EWI..Threshold t join
                                    EWI..Period p on t.Period_ID = p.Period_ID where KPI_ID = @kpi_id
                ) x where (case when [Day] = datename(dw,getdate()) then Period_id
                    when [Day] = choose(datepart(dw, getdate()), 'WEEKEND','Weekday','Weekday','Weekday','Weekday','Weekday','WEEKEND') then Period_ID
                    when [Day] = 'All' then Period_ID end) is not null
            ) y where case when datediff(second,DayStartTime,DayEndTime) > 0 then
            case when convert(time(0), @current_timestamp) >= DayStartTime and convert(time(0), @current_timestamp) < DayEndTime then 1 else 0 end
            else case when convert(time(0), @current_timestamp) >= DayStartTime or convert(time(0), @current_timestamp) < DayEndTime then 1 else 0 end
            end = 1

select 'Run: ' + cast(@kpi_id as varchar(11)) + ' ' + cast(@PeriodID as varchar(11)) + ' ' +
cast(@Threshold_value as varchar(11)) + ' ' + cast(@job_current_time_minute as varchar(11))  + ' ' +
cast(@result as varchar(11))  + ' ' +
cast(ceiling(@result) as varchar(11))+ ' ' +cast(floor(@result) as varchar(11))

    end

    select @kpi_id = min(kpi_id) from KPI where KPI_Active = 1 and kpi_id > @kpi_id;

end


问:
How to use the initialized Webdriver instance from Base class to child class java
```<code>public class Base
{
    public WebDriver driver;

    @BeforeMethod
    public void setUp()
    {
        driver = new FirefoxDriver();
    }

}

public class useFunction extends Base
{

    public useFunction(WebDriver driver)
    {
        this.driver = driver;
    }

    public void func1()
    {
        driver.findElement().click();  //driver is null
        --------
        ---------
    }
}

Public class Test extends Base
{
    useFunction funObj = new useFunction(driver);
    @Test
    public void testMethod1()
   {
       funObj.func1();
       ----
       ------

  }
}
</code>```

How can i use the initialized value of WebDriver instance in UseFunction class without declaring the Webdriver instance as static. When i pass the driver in constructor of UseFunction class while creating its object inside Test class, getting Null Pointer Exception

答:
Initialize web driver in base class constructor and extend Base class in Test class then assign driver to Base.driver.

Try below code

Base Class:

```<code>import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class Base
{
public WebDriver driver;

public Base(){
    driver = new ChromeDriver();
}
}
</code>```

UseFunction class:

```<code>import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;

public class useFunction
 {
     WebDriver driver;

  public useFunction(WebDriver driver)
  {
    this.driver = driver;
  }

  public void func1()
  {
    driver.findElement(By.id("id of the element")).click();
  }
  }
</code>```

Test1 class:

```<code>import org.testng.annotations.Test;

public class Test1{

@Test
public void testMethod1()
{
    Base base = new Base();
    useFunction funObj = new useFunction(base.driver);
    funObj.func1();

}
}
</code>```

Try it and let me know if it works for you

Body:
public class Base
{
    public WebDriver driver;

    @BeforeMethod
    public void setUp()
    {
        driver = new FirefoxDriver();
    }

}

public class useFunction extends Base
{

    public useFunction(WebDriver driver)
    {
        this.driver = driver;
    }

    public void func1()
    {
        driver.findElement().click();  //driver is null
        --------
        ---------
    }
}

Public class Test extends Base
{
    useFunction funObj = new useFunction(driver);
    @Test
    public void testMethod1()
   {
       funObj.func1();
       ----
       ------

  }
}

How can i use the initialized value of WebDriver instance in UseFunction class without declaring the Webdriver instance as static. When i pass the driver in constructor of UseFunction class while creating its object inside Test class, getting Null Pointer Exception

Body:
Initialize web driver in base class constructor and extend Base class in Test class then assign driver to Base.driver.

Try below code

Base Class:

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class Base
{
public WebDriver driver;

public Base(){
    driver = new ChromeDriver();
}
}

UseFunction class:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;

public class useFunction
 {
     WebDriver driver;

  public useFunction(WebDriver driver)
  {
    this.driver = driver;
  }

  public void func1()
  {
    driver.findElement(By.id("id of the element")).click();
  }
  }

Test1 class:

import org.testng.annotations.Test;

public class Test1{

@Test
public void testMethod1()
{
    Base base = new Base();
    useFunction funObj = new useFunction(base.driver);
    funObj.func1();

}
}

Try it and let me know if it works for you


问:
How to find the second lowest and second highest number in a user-inputted list using loops and no arrays
For my program, I need to find the highest pair and lowest pair from 8 user-inputted ints, I am required to use a loop and no arrays.
Ex. 6, 7, 8, 9, 10, 11, 12, 13 should return: (13, 12) , (6, 7)

How should I go about finding the second highest and second lowest number using a loop?

答:
I'd look for the highest and the lowest values and keep track of the previous highest and lowest value, something like this:</p>

```<code>import java.io.*;
import java.util.Scanner;

    public static void findMaxMinPairs() {
    Scanner scanner = new Scanner(System.in);

    int min1=Integer.MAX_VALUE;int min2=Integer.MAX_VALUE; int max1=Integer.MIN_VALUE; int max2=Integer.MIN_VALUE;
    while (scanner.hasNext()) {
    int curr = scanner.nextInt();
        if(curr < min1){
            min2 = min1;
            min1 = curr;

        }else if(curr < min2) {
               min2 = curr;
        }
        if(curr > max1){
          max2 = max1;
          max1 = curr;
        }else if(curr >max2) {
          max2 = curr;
        }
   }
   System.out.println("("+min1+","+min2+") ,("+max1+","+max2+")");
   scanner.close();

  }
</code>```

Body:
I'd look for the highest and the lowest values and keep track of the previous highest and lowest value, something like this:

import java.io.*;
import java.util.Scanner;

    public static void findMaxMinPairs() {
    Scanner scanner = new Scanner(System.in);

    int min1=Integer.MAX_VALUE;int min2=Integer.MAX_VALUE; int max1=Integer.MIN_VALUE; int max2=Integer.MIN_VALUE;
    while (scanner.hasNext()) {
    int curr = scanner.nextInt();
        if(curr < min1){
            min2 = min1;
            min1 = curr;

        }else if(curr < min2) {
               min2 = curr;
        }
        if(curr > max1){
          max2 = max1;
          max1 = curr;
        }else if(curr >max2) {
          max2 = curr;
        }
   }
   System.out.println("("+min1+","+min2+") ,("+max1+","+max2+")");
   scanner.close();

  }


问:
C++ - Class not updating member properly
I've been programming an adventure game and have everything working up until the movement throughout a two-dimensional array dungeon. The Maps are their own struct, while the Character is a class. One of the member variables of the Character class is a Map, curMap, which represents the map the player is currently on. However, in testing in Main.cpp, the works but the map doesn't update properly. Here's the code, after which I'll explain what I've already done.

Maps.h

```<code>#include <string>
#include <vector>

using namespace std;

struct Map {
    vector<string> layout;
    vector<int> exits; //indices in allMaps array
    string name;
    int level;
    Map();
    Map(vector<string> l, vector<int> e, string n, int lvl);

};

extern Map noMap;
extern Map highashPlainsA, highashPlainsB, highashPlainsC; //Highash Plains
extern Map alnwick, alnwickForge, alnwickMarket, alnwickInn; //Alnwick
extern vector<Map> allMaps;

extern vector<string> blankLayout;
extern vector<string> plainsLayoutA, plainsLayoutB, plainsLayoutC; //Highash Plains
extern vector<string> alnwickLayout; //Major Towns
extern vector<string> forgeLayout, marketLayout, innLayout; //Town Buildings
</code>```

Maps.cpp

```<code>#include "Maps.h"

Map::Map() :
    layout(blankLayout),
    exits({0, 0, 0, 0}),
    name("_NO_MAP_"),
    level(0){}

Map::Map(vector<string> l, vector<int> e, string n, int lvl) :
    layout(l),
    exits(e),
    name(n),
    level(lvl){}

Map noMap = Map();
Map highashPlainsA = Map(plainsLayoutA, {4, 3, 2}, "Highash Plains A", 1);
vector<Map> allMaps = {noMap, highashPlainsA};

vector<string> blankLayout =
{"##############################",
 "#                            #",
 "#                            #",
 "#                            #",
 "#                            #",
 "#                            #",
 "#                            #",
 "#                            #",
 "#                            #",
 "##############################"};

vector<string> plainsLayoutA =
{"##########################33##",
 "# G #####   ####### E ####   2",
 "# # # D # #  G      #        2",
 "# # #  ## ####################",
 "# # ##E#   #   G            G#",
 "#E# G#  G                   G#",
 "# #    ##########E############",
 "# #### #DE  G              ED#",
 "# ###D #DE         G       ED#",
 "################111###########"};
</code>```

Character.h (I cut out a lot of unimportant code here)

```<code>#include "Maps.h"
#include <iostream>

class Character {

Map curMap;

public:
    Character();
    ~Character();
    void SetMap(Map map);
    Map GetMap();
};

extern Character player;
</code>```

Character.cpp (Left out said unimportant code here as well)

```<code>#include "Character.h"

Character::Character() : curMap(highashPlainsA){}

Character::~Character(){}

void Character::SetMap(Map map){
    cout << "OLD MAP NAME: " << curMap.name << "\n";
    curMap = map;
    curMap.layout = map.layout;
    curMap.exits = map.exits;
    curMap.name = map.name;
    curMap.level = map.level;
    cout << "NEW MAP NAME: " << curMap.name << "\n";
}

Map Character::GetMap(){
    return curMap;
}

Character player = Character();
</code>```

Main.cpp

```<code>#include "Character.h"

int main(){
    player.SetMap(highashPlainsA);
    cout << "\nSIZE OF CURRENT LAYOUT: " << player.GetMap().layout.size() << "\n";
    cout << "SIZE OF PLAINS A: " << plainsLayoutA.size() << "\n";
    cout << "Name of map: " << player.GetMap().name << "\n";
//  cout << "Layout of map: \n" << player.GetMap().layout[0] << "\n" << player.GetMap().layout[1] << "\n" << player.GetMap().layout[2] << "\n"<< player.GetMap().layout[3] << "\n"; // Crashes because for whatever reason the layout size is 0
    return 0;
}
</code>```

What has been tested:
In Character::SetMap() I even tried changing each individual variable, but shouldn't setting the Map as a whole change all of those values? Additionally, in Map::Map(vector<string> l, vector<int> e, string n, int lvl), I tried it without an initializer list but it still didn't work. I didn't really expect it to, but it was worth a shot I guess.

The issues:

Console Output:

```<code>OLD MAP NAME: Highash Plains A
NEW MAP NAME: Highash Plains A

SIZE OF CURRENT LAYOUT: 0
SIZE OF PLAINS A: 10
Name of map: Highash Plains A
</code>```

The character class does initialize the curMap member, and calls the default constructor to do so. This is intended functionality, because it doesn't matter what map the player is on during setup. However, upon trying to set the map to another precreated Map instance (using SetMap(), everything goes downhill from there. According to the console logging, curMap's name was set to the correct name (OLD MAP NAME) and it maintained this when set to the new map. But, the layout returns a null vector whereas a log of the direct size of the target vector gives the proper value. What is going on, and how can I fix it?

答:
solved: Your problem was that the constructor for HighplainsA was being called before your constructor for plainsLayout. That's because all the constructors are in the global scope, so the order they're run is down to pure luck. It's an example of why having static variables in the global scope is just a terrible idea in general.

When I put debug statements into the constructor for Map, the layout data was empty. This is because the layout data's own constructor had not been executed yet, it was an empty vector. Once you hit main, however, all the constructors have been run, so it appeared that the layout was correct. It just wasn't correct when the Maps were created.

Note that this is an insidious error you can come across if you try and do the right thing and change a raw const char*[] table of strings, into a vector variable. A raw char* table doesn't have a constructor, it's some memory addresses that are determined at compile time, whereas vectors have to call a constructor before they're valid. One way to resolve that issue would have been to store a reference to the layout vector in the Map instead of copying it. That way by the time you actually accessed it in main, all the data would have been constructed, and the global values would merely be connecting the dots.

However, don't rely on globals at all, because any time you gave a class type that has a constructor then it must be called at the start of your program. This is especially bad if you use another object that has a constructor, such as your vector for layout, and you use that in the constructor for another object that's also in the global scope. It's anyone's guess which one will run first.

Basically, you want to create initialization functions for all data that relies on other data. Then you're able to manually control the order in which the data is initialized.

~~~

Some other advice is to minimize the number of copies of the map you're creating when you access the map:

```<code>Map &Character::GetMap(){
    return curMap;
}
</code>```

^ this returns a reference to the actual map. You were making another copy every time this was called before, then the copy gets deleted when it was finished being used.

As for storing the map. Currently, Character also has a copy of the map. This is not the same thing as your map object that's not in the Character. I don't know if that's by design but you probably didn't intend it to be. The map needs to be used by many classes, e.g. enemies, as well as the character. So each character should not have an entire copy of the map.

References can be stored in the class, but only when the object is created, so if you used a reference to store the map, you  couldn't change it after creating your character. Pointers however are like references, but can be changed while it's running. e.g. you could do this:

```<code>class Character
{
    Map *currMap; // * here specifies that it is a pointer

    void setMap(Map &newMap) // & here specifies that it is a reference
    {
        currMap = &newMap; // & here, turns a reference into a pointer
    }

    Map &Character::GetMap() // & here, is returning a reference
    {
        return *curMap; // * here, turns a pointer into a reference
    }
}
</code>```

The pointer *currmap holds the address of a map. A references &newMap is being passed in, then the memory address (&newMap) is being saved in currMap. don't get too confused about the * and &, they're used in slightly different contexts here, so you just need to memorize which one for which occasion. To access a subvalue from a pointer you can do it one of these ways:

```<code>currMap->name; // get a subvalue from a pointer

(*currMap).name; // * on the left here turns a pointer into a reference
</code>```

Body:
I've been programming an adventure game and have everything working up until the movement throughout a two-dimensional array dungeon. The Maps are their own struct, while the Character is a class. One of the member variables of the Character class is a Map, curMap, which represents the map the player is currently on. However, in testing in Main.cpp, the works but the map doesn't update properly. Here's the code, after which I'll explain what I've already done.

Maps.h

#include <string>
#include <vector>

using namespace std;

struct Map {
    vector<string> layout;
    vector<int> exits; //indices in allMaps array
    string name;
    int level;
    Map();
    Map(vector<string> l, vector<int> e, string n, int lvl);

};

extern Map noMap;
extern Map highashPlainsA, highashPlainsB, highashPlainsC; //Highash Plains
extern Map alnwick, alnwickForge, alnwickMarket, alnwickInn; //Alnwick
extern vector<Map> allMaps;

extern vector<string> blankLayout;
extern vector<string> plainsLayoutA, plainsLayoutB, plainsLayoutC; //Highash Plains
extern vector<string> alnwickLayout; //Major Towns
extern vector<string> forgeLayout, marketLayout, innLayout; //Town Buildings

Maps.cpp

#include "Maps.h"

Map::Map() :
    layout(blankLayout),
    exits({0, 0, 0, 0}),
    name("_NO_MAP_"),
    level(0){}

Map::Map(vector<string> l, vector<int> e, string n, int lvl) :
    layout(l),
    exits(e),
    name(n),
    level(lvl){}

Map noMap = Map();
Map highashPlainsA = Map(plainsLayoutA, {4, 3, 2}, "Highash Plains A", 1);
vector<Map> allMaps = {noMap, highashPlainsA};

vector<string> blankLayout =
{"##############################",
 "#                            #",
 "#                            #",
 "#                            #",
 "#                            #",
 "#                            #",
 "#                            #",
 "#                            #",
 "#                            #",
 "##############################"};

vector<string> plainsLayoutA =
{"##########################33##",
 "# G #####   ####### E ####   2",
 "# # # D # #  G      #        2",
 "# # #  ## ####################",
 "# # ##E#   #   G            G#",
 "#E# G#  G                   G#",
 "# #    ##########E############",
 "# #### #DE  G              ED#",
 "# ###D #DE         G       ED#",
 "################111###########"};

Character.h (I cut out a lot of unimportant code here)

#include "Maps.h"
#include <iostream>

class Character {

Map curMap;

public:
    Character();
    ~Character();
    void SetMap(Map map);
    Map GetMap();
};

extern Character player;

Character.cpp (Left out said unimportant code here as well)

#include "Character.h"

Character::Character() : curMap(highashPlainsA){}

Character::~Character(){}

void Character::SetMap(Map map){
    cout << "OLD MAP NAME: " << curMap.name << "\n";
    curMap = map;
    curMap.layout = map.layout;
    curMap.exits = map.exits;
    curMap.name = map.name;
    curMap.level = map.level;
    cout << "NEW MAP NAME: " << curMap.name << "\n";
}

Map Character::GetMap(){
    return curMap;
}

Character player = Character();

Main.cpp

#include "Character.h"

int main(){
    player.SetMap(highashPlainsA);
    cout << "\nSIZE OF CURRENT LAYOUT: " << player.GetMap().layout.size() << "\n";
    cout << "SIZE OF PLAINS A: " << plainsLayoutA.size() << "\n";
    cout << "Name of map: " << player.GetMap().name << "\n";
//  cout << "Layout of map: \n" << player.GetMap().layout[0] << "\n" << player.GetMap().layout[1] << "\n" << player.GetMap().layout[2] << "\n"<< player.GetMap().layout[3] << "\n"; // Crashes because for whatever reason the layout size is 0
    return 0;
}

What has been tested:
In Character::SetMap() I even tried changing each individual variable, but shouldn't setting the Map as a whole change all of those values? Additionally, in Map::Map(vector<string> l, vector<int> e, string n, int lvl), I tried it without an initializer list but it still didn't work. I didn't really expect it to, but it was worth a shot I guess.

The issues:

Console Output:

OLD MAP NAME: Highash Plains A
NEW MAP NAME: Highash Plains A

SIZE OF CURRENT LAYOUT: 0
SIZE OF PLAINS A: 10
Name of map: Highash Plains A

The character class does initialize the curMap member, and calls the default constructor to do so. This is intended functionality, because it doesn't matter what map the player is on during setup. However, upon trying to set the map to another precreated Map instance (using SetMap(), everything goes downhill from there. According to the console logging, curMap's name was set to the correct name (OLD MAP NAME) and it maintained this when set to the new map. But, the layout returns a null vector whereas a log of the direct size of the target vector gives the proper value. What is going on, and how can I fix it?

Body:
solved: Your problem was that the constructor for HighplainsA was being called before your constructor for plainsLayout. That's because all the constructors are in the global scope, so the order they're run is down to pure luck. It's an example of why having static variables in the global scope is just a terrible idea in general.

When I put debug statements into the constructor for Map, the layout data was empty. This is because the layout data's own constructor had not been executed yet, it was an empty vector. Once you hit main, however, all the constructors have been run, so it appeared that the layout was correct. It just wasn't correct when the Maps were created.

Note that this is an insidious error you can come across if you try and do the right thing and change a raw const char*[] table of strings, into a vector variable. A raw char* table doesn't have a constructor, it's some memory addresses that are determined at compile time, whereas vectors have to call a constructor before they're valid. One way to resolve that issue would have been to store a reference to the layout vector in the Map instead of copying it. That way by the time you actually accessed it in main, all the data would have been constructed, and the global values would merely be connecting the dots.

However, don't rely on globals at all, because any time you gave a class type that has a constructor then it must be called at the start of your program. This is especially bad if you use another object that has a constructor, such as your vector for layout, and you use that in the constructor for another object that's also in the global scope. It's anyone's guess which one will run first.

Basically, you want to create initialization functions for all data that relies on other data. Then you're able to manually control the order in which the data is initialized.

~~~

Some other advice is to minimize the number of copies of the map you're creating when you access the map:

Map &Character::GetMap(){
    return curMap;
}

^ this returns a reference to the actual map. You were making another copy every time this was called before, then the copy gets deleted when it was finished being used.

As for storing the map. Currently, Character also has a copy of the map. This is not the same thing as your map object that's not in the Character. I don't know if that's by design but you probably didn't intend it to be. The map needs to be used by many classes, e.g. enemies, as well as the character. So each character should not have an entire copy of the map.

References can be stored in the class, but only when the object is created, so if you used a reference to store the map, you  couldn't change it after creating your character. Pointers however are like references, but can be changed while it's running. e.g. you could do this:

class Character
{
    Map *currMap; // * here specifies that it is a pointer

    void setMap(Map &newMap) // & here specifies that it is a reference
    {
        currMap = &newMap; // & here, turns a reference into a pointer
    }

    Map &Character::GetMap() // & here, is returning a reference
    {
        return *curMap; // * here, turns a pointer into a reference
    }
}

The pointer *currmap holds the address of a map. A references &newMap is being passed in, then the memory address (&newMap) is being saved in currMap. don't get too confused about the * and &, they're used in slightly different contexts here, so you just need to memorize which one for which occasion. To access a subvalue from a pointer you can do it one of these ways:

currMap->name; // get a subvalue from a pointer

(*currMap).name; // * on the left here turns a pointer into a reference


问:
How to test that a function is wrapped with a decorator (javascript)
I've written and used a decorator in my project, and I'm now trying to test that the functions that are wrapped with the decorator are wrapped with the decorator.

I guess I could test that what is happening within the decorator is happening, which I already know how to do, but my preference would be to mock out the decorator entirely and just assert that the function is being wrapped with it.

Does anyone know how to go about doing this (hopefully with sinon/chai)?

答:
There is no metadata about objects that they were decorated by any specific function - decorators are just syntactic sugar and could be applied in a different way as well.

So yes, asserting that what should happen in the decorator actually did happen is the only way. You can mock the decorator and test explicitly that it was applied by setting a specific flag or even checking the arguments and return value of the decorator, but you probably should not. Decorators are an implementation detail, don't test for them - test for the behaviours that the decorator provides.


问:
ASP.NET "Could not Load Type" just on Server
I have a ASP.Net 3.5 host. I just opened a new, C# Web project in visual studio 2010. I changed customerror to None and delete authentication mode line and select None in server control panel. Project works on local machine and says Hello World when I build and deploy in to server via FTP, I get an error it says Could not Load Type '_Default'
<%@ page language="C#" autoeventwireup="true" CodeFile="Default.aspx.cs" inherits="WebApplication._Default" %>

my namespace is WebApplication and in class name is _Default Default.aspx.cs,

It works when I start in ISS, but It cannot start on server.

答:
This error is always related to a bad deployment.  Either that code file wasn't published or your missing an assembly somewhere.

Also, you might want to check to verify the server does indeed have all of the 3.5 stuff loaded on it.

ContentLicense: CC BY-SA 2.5


问:
How to package a Kivy app with Pyinstaller
I have a lot of troubles following the instructions form the Kivy website, many steps aren't explained like what should I answer to the warning.

```<code>WARNING: The output directory "..." and ALL ITS CONTENTS will be REMOVED! Continue? (y/n)
</code>```

Even if I choose y, the folder isn't removed.

Also should I always add these lines:

from kivy.deps import sdl2, glew

Tree('C:\\Users\\<username>\\Desktop\\MyApp\\'),

*[Tree(p) for p in (sdl2.dep_bins + glew.dep_bins)]

in the .spec file? Why are they necessary?

Not many info is available for Kivy.

答:
Because I spent a lot of time understanding how I should package my app, here are some instructions that would have really helped me.

Some info are available at http://pythonhosted.org/PyInstaller/

Python 3.6 as of march 2017
Because packaging my app gave me the error IndexError: tuple index out of range, I had to install the developement version of PyInstaller:

```<code>pip install https://github.com/pyinstaller/pyinstaller/archive/develop.zip
</code>```

Step 1:

I moved all the files of  MyApp in a folder "C:\Users\<username>\Desktop\MyApp": the .py, the .kv and the images and I created an icon.ico.
I created another folder C:\Users\<username>\Desktop\MyPackagedApp. In this folder I press Shift+right click and select open command window here.

Then I pasted this:

```<code>python -m PyInstaller --name MyApp --icon "C:\Users\<username>\Desktop\MyApp\icon.ico" "C:\Users\<username>\Desktop\MyApp\myapp.py"
</code>```

This creates two folders, build and dist, and a .spec file. In dist/MyApp, I can find a .exe. Apparently, if my app is really simple (just one label), the packaged app can works without the Step 2.

Step 2:

The second step involves editing the .spec file. Here is an exemple of mine.
(cf Step 3, for the explanations about my_hidden_modules)

I go back to the cmd, and enter

```<code>python -m MyApp myapp.spec
</code>```

I then got this warning:

```<code>WARNING: The output directory "..." and ALL ITS CONTENTS will be REMOVED! Continue? (y/n)
</code>```

I enter y and then press enter.

Because I choosed y, I was surpised that the folder build was still there and that the dist/MyApp was still containing many files. But this is normal. PyInstaller can output a single file .exe or a single folder which contains all the script’s dependencies and an executable file. But the default output is a single folder with multiple files.

Step 3: adding hidden modules

When I click on the myapp.exe in  dist/MyApp, the app crashed. In the log C:\Users\.kivy\logs\ I could find 2 errors: ModuleNotFoundError: No module named 'win32timezone' and SystemError: <class '_frozen_importlib._ModuleLockManager'>.
Because of this I had to edit the .spec file and add these lines:

```<code>my_hidden_modules = [
         ( 'C:\\Users\\<username>\\AppData\\Local\\Programs\\Python\\Python36\\Lib\\site-packages\\win32\\lib\\win32timezone.py', '.' )
         ]
</code>```

in a = Analysis I changed datas = [] to datas = my_hidden_modules,

Apparently this is because I used a FileChooser widget.

ContentLicense: CC BY-SA 4.0

Body:
I have a lot of troubles following the instructions form the Kivy website, many steps aren't explained like what should I answer to the warning.

WARNING: The output directory "..." and ALL ITS CONTENTS will be REMOVED! Continue? (y/n)

Even if I choose y, the folder isn't removed.

Also should I always add these lines:

from kivy.deps import sdl2, glew

Tree('C:\\Users\\<username>\\Desktop\\MyApp\\'),

*[Tree(p) for p in (sdl2.dep_bins + glew.dep_bins)]

in the .spec file? Why are they necessary?

Not many info is available for Kivy.

Body:
Because I spent a lot of time understanding how I should package my app, here are some instructions that would have really helped me.

Some info are available at http://pythonhosted.org/PyInstaller/

Python 3.6 as of march 2017
Because packaging my app gave me the error IndexError: tuple index out of range, I had to install the developement version of PyInstaller:

pip install https://github.com/pyinstaller/pyinstaller/archive/develop.zip

Step 1:

I moved all the files of  MyApp in a folder "C:\Users\<username>\Desktop\MyApp": the .py, the .kv and the images and I created an icon.ico.
I created another folder C:\Users\<username>\Desktop\MyPackagedApp. In this folder I press Shift+right click and select open command window here.

Then I pasted this:

python -m PyInstaller --name MyApp --icon "C:\Users\<username>\Desktop\MyApp\icon.ico" "C:\Users\<username>\Desktop\MyApp\myapp.py"

This creates two folders, build and dist, and a .spec file. In dist/MyApp, I can find a .exe. Apparently, if my app is really simple (just one label), the packaged app can works without the Step 2.

Step 2:

The second step involves editing the .spec file. Here is an exemple of mine.
(cf Step 3, for the explanations about my_hidden_modules)

I go back to the cmd, and enter

python -m MyApp myapp.spec

I then got this warning:

WARNING: The output directory "..." and ALL ITS CONTENTS will be REMOVED! Continue? (y/n)

I enter y and then press enter.

Because I choosed y, I was surpised that the folder build was still there and that the dist/MyApp was still containing many files. But this is normal. PyInstaller can output a single file .exe or a single folder which contains all the script’s dependencies and an executable file. But the default output is a single folder with multiple files.

Step 3: adding hidden modules

When I click on the myapp.exe in  dist/MyApp, the app crashed. In the log C:\Users\.kivy\logs\ I could find 2 errors: ModuleNotFoundError: No module named 'win32timezone' and SystemError: <class '_frozen_importlib._ModuleLockManager'>.
Because of this I had to edit the .spec file and add these lines:

my_hidden_modules = [
         ( 'C:\\Users\\<username>\\AppData\\Local\\Programs\\Python\\Python36\\Lib\\site-packages\\win32\\lib\\win32timezone.py', '.' )
         ]

in a = Analysis I changed datas = [] to datas = my_hidden_modules,

Apparently this is because I used a FileChooser widget.


问:
Centering elements in navigation header html css
I have made a navigation header (i.d.k. how you call it) and I want some text to be in the middle of it.

It basically is a black bar, with some navigation buttons on the right (e.g. Home, about us, info, gallery...) a logo on the left, and now I want some text in the middle of that bar. I can't get it to work.

This is the code I have so far.

/* Global settings */

* {
  font-family: Roboto;
  padding: 0;
  margin: 0;
}

a {
  text-decoration: none;
}

/* Header settings */

.header {
  height: 50px;
  width: 100%;
  background-color: #212121;
  position: fixed;
  text-align: center;
}

.header ul {
  height: 100%;
  float: right;
  position: relative;
  right: 50px;
}

.header li {
  display: inline-block;
  height: 100%;
  width: 75px;
  text-align: center;
}

.header li:hover {
  background-color: #616161;
}

.header a {
  display: block;
  color: #FAFAFA;
  height: 100%;
  line-height: 50px;
  border: 1px solid orange;
}

.header img {
  height: 100%;
  color: #FAFAFA;
  float: left;
}

.header h1 {
  color: #FAFAFA;
  Line-height: 50px;
  display: inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="header">
    <h1>The text I want to be centered</h1>
    <ul>
      <li>Home</li>
      <li>Info</li>
      <li>Contact</li>
      <li>About</li>
    </ul>
    <img src="" alt="Logo" />
  </div>
</body></code>```

答:
You can try this:

HTML

```<code><body>
  <div class="header">
     <img src="" alt="Logo" />
     <h1>The text I want to be centered</h1>
     <ul>
       <li><a href="">Home</a></li>
       <li><a href="">Info</a></li>
       <li><a href="">Contact</a></li>
       <li><a href="">About</a></li>
     </ul>
  </div>
</body>
</code>```

CSS

```<code>* {
  font-family: Roboto;
  padding: 0;
  margin: 0;
}

a {
  text-decoration: none;
}

/* Header settings */
.header {
  width: 100%;
  background-color: #212121;
  position: fixed;
  text-align: center;
  display:flex;
  justify-content:space-between;
  padding:0 10px;
  box-sizing: border-box;
}

.header ul {
  height: 100%;
  position: relative;
}

.header li {
  display: inline-block;
  height: 100%;
  width: 75px;
  text-align: center;
}

.header li:hover {
  background-color: #616161;
}

.header a {
  display: block;
  color: #FAFAFA;
  height: 100%;
  line-height: 50px;
  border: 1px solid orange;
}

.header img {
  height: 100%;
  color: #FAFAFA;
}

.header h1 {
  color: #FAFAFA;
  line-height: 50px;
  display: inline-block;
}
</code>```

What the above will do is put the text at equal distances from the logo and menu. So, the text won't be precisely centered, but will probably look more "correct".

Body:
I have made a navigation header (i.d.k. how you call it) and I want some text to be in the middle of it.

It basically is a black bar, with some navigation buttons on the right (e.g. Home, about us, info, gallery...) a logo on the left, and now I want some text in the middle of that bar. I can't get it to work.

This is the code I have so far.

/* Global settings */

* {
  font-family: Roboto;
  padding: 0;
  margin: 0;
}

a {
  text-decoration: none;
}

/* Header settings */

.header {
  height: 50px;
  width: 100%;
  background-color: #212121;
  position: fixed;
  text-align: center;
}

.header ul {
  height: 100%;
  float: right;
  position: relative;
  right: 50px;
}

.header li {
  display: inline-block;
  height: 100%;
  width: 75px;
  text-align: center;
}

.header li:hover {
  background-color: #616161;
}

.header a {
  display: block;
  color: #FAFAFA;
  height: 100%;
  line-height: 50px;
  border: 1px solid orange;
}

.header img {
  height: 100%;
  color: #FAFAFA;
  float: left;
}

.header h1 {
  color: #FAFAFA;
  Line-height: 50px;
  display: inline-block;
}

The text I want to be centered

Home

Info

Contact

About

Body:
You can try this:

HTML

<body>
  <div class="header">
     <img src="" alt="Logo" />
     <h1>The text I want to be centered</h1>
     <ul>
       <li><a href="">Home</a></li>
       <li><a href="">Info</a></li>
       <li><a href="">Contact</a></li>
       <li><a href="">About</a></li>
     </ul>
  </div>
</body>

CSS

* {
  font-family: Roboto;
  padding: 0;
  margin: 0;
}

a {
  text-decoration: none;
}

/* Header settings */
.header {
  width: 100%;
  background-color: #212121;
  position: fixed;
  text-align: center;
  display:flex;
  justify-content:space-between;
  padding:0 10px;
  box-sizing: border-box;
}

.header ul {
  height: 100%;
  position: relative;
}

.header li {
  display: inline-block;
  height: 100%;
  width: 75px;
  text-align: center;
}

.header li:hover {
  background-color: #616161;
}

.header a {
  display: block;
  color: #FAFAFA;
  height: 100%;
  line-height: 50px;
  border: 1px solid orange;
}

.header img {
  height: 100%;
  color: #FAFAFA;
}

.header h1 {
  color: #FAFAFA;
  line-height: 50px;
  display: inline-block;
}

What the above will do is put the text at equal distances from the logo and menu. So, the text won't be precisely centered, but will probably look more "correct".


问:
Unable to deserialize my json
This is my class

Initial one which actually needs to be transformed to good json data.
This is the initial bad one

```<code>{
    "channels": {
        "heart-rate": {
            "events": {
                "$type": "System.Collections.Generic.List`1[[Project.Model.Activity+Channel+Event, Project]], mscorlib",
                "$values": [{
                        "$type": "Project.Model.ChannelEvents.HeartRateChannelEvent, LTF.MyPlan.ActivityUtil",
                        "beatsPerMinute": 40,
                        "offset": 0
                    }
                ]
            }
        },
        "location": {
            "events": {
                "$type": "System.Collections.Generic.List`1[[Project.Model.Activity+Channel+Event, Project]], mscorlib",
                "$values": [{
                        "$type": "Project.Model.ChannelEvents.LocationChannelEvent, Project",
                        "latitude": 0.0,
                        "longitude": 0.0,
                        "offset": 0
                    }
                ]
            }
        }
    }
}

public class LocationChannelEvent : Activity.Channel.Event
{
    public double Latitude { get; set; }
    public double Longitude { get; set; }
    public float? Distance { get; set; }
    public float? Altitude { get; set; }

    /// <summary>
    /// Speed in m/s
    /// </summary>
    public float? Speed { get; set; }
</code>```

This is my json data, which i am unable to deserialize. I keep receiving the default values, even when i change

```<code>{

"location": {
            "events": {
                "$type": "System.Collections.Generic.List`1[[Project.Model.Activity+Channel+Event, Project]], mscorlib",
                "$values": [{
                        "$type": "Project.Model.ChannelEvents.LocationChannelEvent, Project",
                        "latitude": 0.0,
                        "longitude": 0.0,
                        "offset": 0
            ]
        }
    }
}
</code>```

My Custom Coverter

```<code>public class CompactListConverter : JsonConverter
    {
        public const string TypeKey = "type";
        public const string StructureKey = "structure";
        public const string ListKey = "list";

    /// <summary>
    /// Only convert lists of non-enumerable class types.
    /// </summary>
    /// <param name="objectType"></param>
    /// <returns></returns>
    public override bool CanConvert(Type objectType)
    {
        var objectTypeInfo = objectType.GetTypeInfo();

        if (objectTypeInfo.IsGenericType && objectType.GetGenericTypeDefinition() == typeof(List<>))
        {
            var itemTypeInfo = objectTypeInfo.GenericTypeArguments.Single().GetTypeInfo();
            if (itemTypeInfo.IsClass && !typeof(IEnumerable).GetTypeInfo().IsAssignableFrom(itemTypeInfo))
            {
                return true;
            }
        }
        return false;
    }

    /// <summary>
    ///  Generates a wrapper object containing type, structure, and the condensed list.
    /// </summary>
    /// <param name="writer"></param>
    /// <param name="value"></param>
    /// <param name="serializer"></param>
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var list = (IList)value;
        if (list.Count > 0)
        {
            var array = new JArray();
            var wrapper = GetWrapper(list, serializer);

            foreach (var item in list)
            {
                var obj = JObject.FromObject(item, serializer);
                var itemValues = new JArray();
                foreach (var prop in obj.Properties())
                {
                    itemValues.Add(prop.Value);
                }
                array.Add(itemValues);
            }

            wrapper.Add(ListKey, array);
            wrapper.WriteTo(writer);
        }
        else
        {
            new JObject().WriteTo(writer);
        }
    }

    private JObject GetWrapper(IList list, JsonSerializer serializer)
    {
        var wrapper = new JObject {{TypeKey, list[0].GetType().AssemblyQualifiedName}};

        var keys = new JArray();

        var first = JObject.FromObject(list[0], serializer);
        foreach (var prop in first.Properties())
        {
            keys.Add(new JValue(prop.Name));
        }

        wrapper.Add(StructureKey, keys);

        return wrapper;
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var wrapper = JObject.Load(reader);
        var itemType = Type.GetType(wrapper.GetValue(TypeKey).ToObject<string>());
        var array = wrapper.GetValue(ListKey) as JArray;

        var list = existingValue as IList ?? (IList) Activator.CreateInstance(typeof (List<>).MakeGenericType(new[] {itemType}));

        if (array != null && array.Count > 0)
        {
            var keys = wrapper.GetValue(StructureKey) as JArray ?? new JArray();
            foreach (var itemValues in array.Children<JArray>())
            {
                var item = new JObject();
                for (var i = 0; i < keys.Count; i++)
                {
                    item.Add(new JProperty(keys[i].ToString(), itemValues[i]));
                }

                list.Add(item.ToObject(itemType, serializer));
            }
        }
        return list;
    }
}

public class ChannelCompactingConverter : CompactListConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return base.CanConvert(objectType)
                && typeof(IList<Activity.Channel.Event>).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo());
        }
    }
</code>```

答:
Well as far as I'm familiar with json these two things the class and the json are two complete different things! So it's clear that it can't be serialize as that.

What I do in such cases is that I deserialize the json as a dynamic object and then see the object that C# creates and compare it with my class. You can do the same thing like this:

```<code>dynamic res = JsonConvert.Deserialize(json);
</code>```

You can then place a breakpoint here and see what deserializer gives you.

Title: Unable to deserialize my json

Body:
This is my class

Initial one which actually needs to be transformed to good json data.
This is the initial bad one

{
    "channels": {
        "heart-rate": {
            "events": {
                "$type": "System.Collections.Generic.List`1[[Project.Model.Activity+Channel+Event, Project]], mscorlib",
                "$values": [{
                        "$type": "Project.Model.ChannelEvents.HeartRateChannelEvent, LTF.MyPlan.ActivityUtil",
                        "beatsPerMinute": 40,
                        "offset": 0
                    }
                ]
            }
        },
        "location": {
            "events": {
                "$type": "System.Collections.Generic.List`1[[Project.Model.Activity+Channel+Event, Project]], mscorlib",
                "$values": [{
                        "$type": "Project.Model.ChannelEvents.LocationChannelEvent, Project",
                        "latitude": 0.0,
                        "longitude": 0.0,
                        "offset": 0
                    }
                ]
            }
        }
    }
}

public class LocationChannelEvent : Activity.Channel.Event
{
    public double Latitude { get; set; }
    public double Longitude { get; set; }
    public float? Distance { get; set; }
    public float? Altitude { get; set; }

    ///
    /// Speed in m/s
    ///
    public float? Speed { get; set; }

This is my json data, which i am unable to deserialize. I keep receiving the default values, even when i change

{

"location": {
            "events": {
                "$type": "System.Collections.Generic.List`1[[Project.Model.Activity+Channel+Event, Project]], mscorlib",
                "$values": [{
                        "$type": "Project.Model.ChannelEvents.LocationChannelEvent, Project",
                        "latitude": 0.0,
                        "longitude": 0.0,
                        "offset": 0
            ]
        }
    }
}

My Custom Coverter

public class CompactListConverter : JsonConverter
    {
        public const string TypeKey = "type";
        public const string StructureKey = "structure";
        public const string ListKey = "list";

    ///
    /// Only convert lists of non-enumerable class types.
    ///
    /// <param name="objectType"></param>
    /// <returns></returns>
    public override bool CanConvert(Type objectType)
    {
        var objectTypeInfo = objectType.GetTypeInfo();

        if (objectTypeInfo.IsGenericType && objectType.GetGenericTypeDefinition() == typeof(List<>))
        {
            var itemTypeInfo = objectTypeInfo.GenericTypeArguments.Single().GetTypeInfo();
            if (itemTypeInfo.IsClass && !typeof(IEnumerable).GetTypeInfo().IsAssignableFrom(itemTypeInfo))
            {
                return true;
            }
        }
        return false;
    }

    ///
    ///  Generates a wrapper object containing type, structure, and the condensed list.
    ///
    /// <param name="writer"></param>
    /// <param name="value"></param>
    /// <param name="serializer"></param>
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var list = (IList)value;
        if (list.Count > 0)
        {
            var array = new JArray();
            var wrapper = GetWrapper(list, serializer);

            foreach (var item in list)
            {
                var obj = JObject.FromObject(item, serializer);
                var itemValues = new JArray();
                foreach (var prop in obj.Properties())
                {
                    itemValues.Add(prop.Value);
                }
                array.Add(itemValues);
            }

            wrapper.Add(ListKey, array);
            wrapper.WriteTo(writer);
        }
        else
        {
            new JObject().WriteTo(writer);
        }
    }

    private JObject GetWrapper(IList list, JsonSerializer serializer)
    {
        var wrapper = new JObject {{TypeKey, list[0].GetType().AssemblyQualifiedName}};

        var keys = new JArray();

        var first = JObject.FromObject(list[0], serializer);
        foreach (var prop in first.Properties())
        {
            keys.Add(new JValue(prop.Name));
        }

        wrapper.Add(StructureKey, keys);

        return wrapper;
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var wrapper = JObject.Load(reader);
        var itemType = Type.GetType(wrapper.GetValue(TypeKey).ToObject<string>());
        var array = wrapper.GetValue(ListKey) as JArray;

        var list = existingValue as IList ?? (IList) Activator.CreateInstance(typeof (List<>).MakeGenericType(new[] {itemType}));

        if (array != null && array.Count > 0)
        {
            var keys = wrapper.GetValue(StructureKey) as JArray ?? new JArray();
            foreach (var itemValues in array.Children<JArray>())
            {
                var item = new JObject();
                for (var i = 0; i < keys.Count; i++)
                {
                    item.Add(new JProperty(keys[i].ToString(), itemValues[i]));
                }

                list.Add(item.ToObject(itemType, serializer));
            }
        }
        return list;
    }
}

public class ChannelCompactingConverter : CompactListConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return base.CanConvert(objectType)
                && typeof(IList<Activity.Channel.Event>).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo());
        }
    }

Body:
Well as far as I'm familiar with json these two things the class and the json are two complete different things! So it's clear that it can't be serialize as that.

What I do in such cases is that I deserialize the json as a dynamic object and then see the object that C# creates and compare it with my class. You can do the same thing like this:

dynamic res = JsonConvert.Deserialize(json);

You can then place a breakpoint here and see what deserializer gives you.


问:
finding lib directory during common test
My question is, how should my Erlang app reliably find a binary in the priv directory, not just in production; when installed properly, but during common test?

I realised today when I added a travis-ci configuration to an old Erlang app and pushed it to git-hub, that the process by which it works locally for me, is a little more fragile than I thought. The travis-ci build failed because it, not unreasonably, checked out my repo into a directory named after the repo, which is of the form erlang-APP. Locally my app is in a directory called APP-VSN though.

The result of this is that a call to code:lib_dir(APP) returns a correct result during the common test run locally, but if I rename my current directory to erlang-APP instead of APP-VSN (or just APP works too) my local build fails, just like it does for travis-ci, because code:lib_dir(APP) returns {error,bad_name}. The behaviour as though .. is added to the library path for rebar ct.

Renaming my github repo from erlang-APP to APP resolves the travis-ci build failure... but knowing the build tests only pass depending on the name of the directory the repo is checked out into doesn't sit right with me.

答: One way could be to use a soft link (either in the repo under version control, or created when initializing the tests), and make your Erlang code path go via the link. E.g., "./APP" -> ".", or "./lib/APP" -> "..".</p>


问:
C: casting to new structure vs casting to defined structure
my question is simple, does this

```<code>typedef struct {a;b;c;d;}bar;
((bar*)ANOTHERSTRUCTPOINTER)->a=1;
((bar*)ANOTHERSTRUCTPOINTER2)->a=1;
//<...>
((bar*)ANOTHERSTRUCTPOINTERn)->a=1;
</code>```

has the same execution time as this?

```<code>((struct {a;b;c;d;}*)ANOTHERSTRUCTPOINTER)->a=1;
((struct {a;b;c;d;}*)ANOTHERSTRUCTPOINTER2)->a=1;
//<...>
((struct {a;b;c;d;}*)ANOTHERSTRUCTPOINTERn)->a=1;
</code>```

please mind that this is just an example, so don't just question the fact i didn't use an array

答: Yes, they mean the same thing and should compile into the same executable code.</p>

Body:
my question is simple, does this

typedef struct {a;b;c;d;}bar;
((bar*)ANOTHERSTRUCTPOINTER)->a=1;
((bar*)ANOTHERSTRUCTPOINTER2)->a=1;
//<...>
((bar*)ANOTHERSTRUCTPOINTERn)->a=1;

has the same execution time as this?

((struct {a;b;c;d;}*)ANOTHERSTRUCTPOINTER)->a=1;
((struct {a;b;c;d;}*)ANOTHERSTRUCTPOINTER2)->a=1;
//<...>
((struct {a;b;c;d;}*)ANOTHERSTRUCTPOINTERn)->a=1;

please mind that this is just an example, so don't just question the fact i didn't use an array


问:
Android - Handle "Enter" in an EditText
I am wondering if there is a way to handle the user pressing Enter while typing in an EditText, something like the onSubmit HTML event.

Also wondering if there is a way to manipulate the virtual keyboard in such a way that the "Done" button is labeled something else (for example "Go") and performs a certain action when clicked (again, like onSubmit).

答:
This should work </p>

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

           @Override
           public void afterTextChanged(Editable s) {}

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

           @Override
           public void onTextChanged(CharSequence s, int start,
             int before, int count) {
               if( -1 != input.getText().toString().indexOf( "\n" ) ){
                   input.setText("Enter was pressed!");
                    }
           }
          });
</code>```

Title: Android - Handle "Enter" in an EditText

Body:
This should work

input.addTextChangedListener(new TextWatcher() {

           @Override
           public void afterTextChanged(Editable s) {}

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

           @Override
           public void onTextChanged(CharSequence s, int start,
             int before, int count) {
               if( -1 != input.getText().toString().indexOf( "\n" ) ){
                   input.setText("Enter was pressed!");
                    }
           }
          });


问:
Get the mouse coordinates when clicking on canvas
A common question, but I still need help. I'm trying to get and store the mouse coordinates when someone clicks within the canvas.

my HTML

```<code><canvas id="puppyCanvas" width="500" height="500" style="border:2px solid black" onclick = "storeGuess(event)"></canvas>
</code>```

and my javascript

```<code>//setup canvas
var canvasSetup = document.getElementById("puppyCanvas");
var ctx = canvasSetup.getContext("2d");

guessX = 0;//stores user's click on canvas
 guessY = 0;//stores user's click on canvas

function storeGuess(event){
    var x = event.clientX - ctx.canvas.offsetLeft;
    var y = event.clientY - ctx.canvas.offsetTop;
    /*guessX = x;
    guessY = y;*/

    console.log("x coords:" + x + ", y coords" + y);
</code>```

I've read loads of forums, w3schools, and videos on this. I'm close to figuring it out, but I'm missing something. I can get the coordinates of the page if I delete the ctx.canvas.offsetLeft and ctx.canvas.offsetTop. But i need to incorporate those somehow to get the coordinates of the canvas, and then store then into the variables guessX and guessY.

答:
You could achieve that by using the offsetX and offsetY property of MouseEvent

//setup canvas
var canvasSetup = document.getElementById("puppyCanvas");
var ctx = canvasSetup.getContext("2d");
guessX = 0; //stores user's click on canvas
guessY = 0; //stores user's click on canvas
function storeGuess(event) {
    var x = event.offsetX;
    var y = event.offsetY;
    guessX = x;
    guessY = y;
    console.log("x coords: " + guessX + ", y coords: " + guessY);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="puppyCanvas" width="500" height="500" style="border:2px solid black" onclick="storeGuess(event)"></canvas></code>```

Body:
A common question, but I still need help. I'm trying to get and store the mouse coordinates when someone clicks within the canvas.

my HTML

<canvas id="puppyCanvas" width="500" height="500" style="border:2px solid black" onclick = "storeGuess(event)"></canvas>

and my javascript

//setup canvas
var canvasSetup = document.getElementById("puppyCanvas");
var ctx = canvasSetup.getContext("2d");

guessX = 0;//stores user's click on canvas
 guessY = 0;//stores user's click on canvas

function storeGuess(event){
    var x = event.clientX - ctx.canvas.offsetLeft;
    var y = event.clientY - ctx.canvas.offsetTop;
    /*guessX = x;
    guessY = y;*/

    console.log("x coords:" + x + ", y coords" + y);

I've read loads of forums, w3schools, and videos on this. I'm close to figuring it out, but I'm missing something. I can get the coordinates of the page if I delete the ctx.canvas.offsetLeft and ctx.canvas.offsetTop. But i need to incorporate those somehow to get the coordinates of the canvas, and then store then into the variables guessX and guessY.

Body:
You could achieve that by using the offsetX and offsetY property of MouseEvent

//setup canvas
var canvasSetup = document.getElementById("puppyCanvas");
var ctx = canvasSetup.getContext("2d");
guessX = 0; //stores user's click on canvas
guessY = 0; //stores user's click on canvas
function storeGuess(event) {
    var x = event.offsetX;
    var y = event.offsetY;
    guessX = x;
    guessY = y;
    console.log("x coords: " + guessX + ", y coords: " + guessY);
}

<canvas id="puppyCanvas" width="500" height="500" style="border:2px solid black" onclick="storeGuess(event)"></canvas>


问:
How does java.util.Arrays handle sorting an ArrayList (length vs size)?
I've been looking through the source code for java.util.Arrays and when sorting it always refers to the length of the array (which for an ArrayList I assume refers to the length of the E[] data (transient) field.
But shouldn't it actually refer to the size field, given that they aren't always equal to each other.</p>

答:
when sorting it always refers to the length of the array

No it doesn't. For every datatype there is an overload of Arrays.sort which accepts fromIndex and toIndex parameters, specifying the exact portion of the array to sort, such as Arrays.sort(Object[] a, int fromIndex, int toIndex, Comparator<? super T> c).

That is the method called by ArrayList.sort:

```<code>public void sort(Comparator<? super E> c) {
    final int expectedModCount = modCount;
    Arrays.sort((E[]) elementData, 0, size, c);
    if (modCount != expectedModCount) {
        throw new ConcurrentModificationException();
    }
    modCount++;
}
</code>```

The ArrayList passes its own size variable directly to the sorting method.

For a List which does not override its sort method, the default implementation first dumps the contents to a temporary array and sorts that:

The default implementation obtains an array containing all elements in this list, sorts the array, and iterates over this list resetting each element from the corresponding position in the array. (This avoids the n2 log(n) performance that would result from attempting to sort a linked list in place.)

```<code>default void sort(Comparator<? super E> c) {
    Object[] a = this.toArray();
    Arrays.sort(a, (Comparator) c);
    ListIterator<E> i = this.listIterator();
    for (Object e : a) {
        i.next();
        i.set((E) e);
    }
}
</code>```

Beginning in Java 8, the old method Collections.sort(list) just invokes list.sort(null).

Body:
when sorting it always refers to the length of the array

No it doesn't. For every datatype there is an overload of Arrays.sort which accepts fromIndex and toIndex parameters, specifying the exact portion of the array to sort, such as Arrays.sort(Object[] a, int fromIndex, int toIndex, Comparator<? super T> c).

That is the method called by ArrayList.sort:

public void sort(Comparator<? super E> c) {
    final int expectedModCount = modCount;
    Arrays.sort((E[]) elementData, 0, size, c);
    if (modCount != expectedModCount) {
        throw new ConcurrentModificationException();
    }
    modCount++;
}

The ArrayList passes its own size variable directly to the sorting method.

For a List which does not override its sort method, the default implementation first dumps the contents to a temporary array and sorts that:

The default implementation obtains an array containing all elements in this list, sorts the array, and iterates over this list resetting each element from the corresponding position in the array. (This avoids the n2 log(n) performance that would result from attempting to sort a linked list in place.)

default void sort(Comparator<? super E> c) {
    Object[] a = this.toArray();
    Arrays.sort(a, (Comparator) c);
    ListIterator<E> i = this.listIterator();
    for (Object e : a) {
        i.next();
        i.set((E) e);
    }
}

Beginning in Java 8, the old method Collections.sort(list) just invokes list.sort(null).


问:
SQL - Counting rows based on specific digit value in a field
I am using Oracle database.

In my table t_mytable, I have one field myfield and this field has string values like 00101110010.

I need to count the rows which has ""4th digit of myfield value is 1".

For instance,

```<code>myfield
-------
00101110010
00111110010
00101101010
00101110010
00111111110
</code>```

For above data, count should be 2 because 2 rows has fourth bit as 1 (I started from 1 not 0 while determining first digit).

How can I do this in sql?

答:
if myfield is a string  you can use substr for extract the fourth char</p>

```<code>select count(*)
from t_mytable
where substr(myfield, 4,1) ='1';
</code>```

Body:
I am using Oracle database.

In my table t_mytable, I have one field myfield and this field has string values like 00101110010.

I need to count the rows which has ""4th digit of myfield value is 1".

For instance,

myfield
-------
00101110010
00111110010
00101101010
00101110010
00111111110

For above data, count should be 2 because 2 rows has fourth bit as 1 (I started from 1 not 0 while determining first digit).

How can I do this in sql?

Body:
if myfield is a string  you can use substr for extract the fourth char

select count(*)
from t_mytable
where substr(myfield, 4,1) ='1';


问:
How to group comma seperated columns into one single string in a unix for loop
I am working with a pipe separated list(text file), which looks like

```<code>recipename|category|list_items
-------------------------------------------
veg_quesadilla|groupA|lettuce, spinach, beans
burrito_bowl|groupA|brown_rice, black_beans, lettuce, pepper
french_fries|groupB
beverage|groupC|pepsi
</code>```

I have below statement

```<code>for recipename in `head -4 list_catalog.txt | awk -F "|" '{print $1}'`
do
if [ `cat list_catalog.txt | grep $recipename |  awk -F "|" '{print $3}'` != NULL ]
then
    for list_items in `cat list_catalog.txt | grep $recipename | awk -F "|" '{print $3}'`
do
echo -e ${list_items}
done
fi
done
</code>```

In the first loop, i am iterating over each recipe name, and i am checking if the list_items exists for each recipe. If yes, then i want to print all the column seperated items as one string, instead of seperated items. I mean all the comma separated items (which starts after second pipe symbol) as one string

Like this:

```<code>lettuce, spinach, beans
</code>```

Instead of:

```<code>lettuce,
spinach,
beans
</code>```

And when i run the code i am getting error,

```<code>line 3: [: too many arguments
</code>```

Not sure, if i am doing right with AWK or not. Please correct me.

答:
You have several problems with your code.

```<code>if [ cat `list_catalog.txt | grep $recipename |  awk -F "|" '{print $3}'` != NULL ]
</code>```

Your command inside the command-substitution quotes starts with list_catalog.txt as if it's the command. You probably meant to put cat inside the command-substitution quotes. Maybe that was just a mistake as you typed this question into Stack Overflow, because it gives a different error than the one you reported.

```<code>myscript.sh: line 3: list_catalog.txt: command not found
</code>```

Even if you fix that, it generates an invalid test. You can spot it if you run sh with debugging output:

```<code>$ sh -x myscript.sh
...
+ '[' lettuce, spinach, beans '!=' NULL ']'
myscript.sh: line 3: [: too many arguments
...
</code>```

The words returned by your command substitution are not quoted, so they show up as separate words. You can't have three words as the left hand side of the != operator.

To fix this, put the command-substitution inside quotes, so whatever it returns will be treated as one string.

```<code>if [ "`cat list_catalog.txt | grep $recipename |  awk -F '|' '{print $3}'`" != NULL ]
</code>```

All that said, I can't tell why you're doing this at all. The input file already has your list_items on a single line, which appears to be your goal.

Body:
I am working with a pipe separated list(text file), which looks like

recipename|category|list_items
-------------------------------------------
veg_quesadilla|groupA|lettuce, spinach, beans
burrito_bowl|groupA|brown_rice, black_beans, lettuce, pepper
french_fries|groupB
beverage|groupC|pepsi

I have below statement

for recipename in `head -4 list_catalog.txt | awk -F "|" '{print $1}'`
do
if [ `cat list_catalog.txt | grep $recipename |  awk -F "|" '{print $3}'` != NULL ]
then
    for list_items in `cat list_catalog.txt | grep $recipename | awk -F "|" '{print $3}'`
do
echo -e ${list_items}
done
fi
done

In the first loop, i am iterating over each recipe name, and i am checking if the list_items exists for each recipe. If yes, then i want to print all the column seperated items as one string, instead of seperated items. I mean all the comma separated items (which starts after second pipe symbol) as one string

Like this:

lettuce, spinach, beans

Instead of:

lettuce,
spinach,
beans

And when i run the code i am getting error,

line 3: [: too many arguments

Not sure, if i am doing right with AWK or not. Please correct me.

Body:
You have several problems with your code.

if [ cat `list_catalog.txt | grep $recipename |  awk -F "|" '{print $3}'` != NULL ]

Your command inside the command-substitution quotes starts with list_catalog.txt as if it's the command. You probably meant to put cat inside the command-substitution quotes. Maybe that was just a mistake as you typed this question into Stack Overflow, because it gives a different error than the one you reported.

myscript.sh: line 3: list_catalog.txt: command not found

Even if you fix that, it generates an invalid test. You can spot it if you run sh with debugging output:

$ sh -x myscript.sh
...
+ '[' lettuce, spinach, beans '!=' NULL ']'
myscript.sh: line 3: [: too many arguments
...

The words returned by your command substitution are not quoted, so they show up as separate words. You can't have three words as the left hand side of the != operator.

To fix this, put the command-substitution inside quotes, so whatever it returns will be treated as one string.

if [ "`cat list_catalog.txt | grep $recipename |  awk -F '|' '{print $3}'`" != NULL ]

All that said, I can't tell why you're doing this at all. The input file already has your list_items on a single line, which appears to be your goal.


问:
IQKeyboardManager - Shifting UITextView up too far
I'm using IQKeyboardManager to make keyboard management simple for a notes view controller I have (contains a large UITextView). Once the keyboard is active, however, the screen is shifted up unnecessarily. I'd like for the screen to stay how it is before the keyboard is active (see image below), and only have the UITextView scroll once the user's typing would be covered by the keyboard.

Before keyboard is active

When the keyboard is active (view scrolled up, covering "Notes" and Navigation Bar)

I don't want the Navigation Bar or the "Notes" label to be covered up, but I couldn't find a setting in IQKeyboardManager to stop the UITextView from being pushed all the way to the top.

How can I prevent the view from shifting up so far when the keyboard is made active?

EDIT: I should note that I'm not opposed to removing IQKeyboardManager, I just thought it would make dealing with this either. I mainly just need a way for my UITextView to automatically scroll when the user types something that would go underneath the keyboard.

UPDATE: I solved my problem without IQKeyboardManager by adjusting the contentInset of my UITextView depending on whether or not the keyboard is visible.

答:
If you want the screen to stay how it was you can disable the movement behavior for your class with IQKeyboardManager.sharedManager().disabledDistanceHandlingClasses property for example:

```<code>/* Probably in your AppDelegate where you setup the keyboard */

IQKeyboardManager.sharedManager().enable = true
IQKeyboardManager.sharedManager().disabledDistanceHandlingClasses = [YourViewController.self]
</code>```

Body:
If you want the screen to stay how it was you can disable the movement behavior for your class with IQKeyboardManager.sharedManager().disabledDistanceHandlingClasses property for example:

/* Probably in your AppDelegate where you setup the keyboard */

IQKeyboardManager.sharedManager().enable = true
IQKeyboardManager.sharedManager().disabledDistanceHandlingClasses = [YourViewController.self]


问:
How to append two stringBuilders?
Is there a way to append two string builders?
And if so - does it perform better than appending a string to a StringBuilder ? </p>

答:
If the StringBuilder is large, then this will minimize string-allocations (especially if you can provide a reusable char-buffer):</p>

```<code>    public static void CopyTo(this StringBuilder source, StringBuilder dest)
    {
        char[] buffer = new char[Math.Min(source.Length, 1024)];
        CopyTo(source, dest, buffer);
    }

    public static void CopyTo(this StringBuilder source, StringBuilder dest, char[] buffer)
    {
        dest.EnsureCapacity(dest.Length + source.Length);
        for (int i = 0; i < source.Length; i += buffer.Length)
        {
            int charCount = Math.Min(source.Length - i, buffer.Length);
            source.CopyTo(i, buffer, 0, charCount);
            dest.Append(buffer, 0, charCount);
        }
    }
</code>```

Title: How to append two stringBuilders?

Body:
If the StringBuilder is large, then this will minimize string-allocations (especially if you can provide a reusable char-buffer):

    public static void CopyTo(this StringBuilder source, StringBuilder dest)
    {
        char[] buffer = new char[Math.Min(source.Length, 1024)];
        CopyTo(source, dest, buffer);
    }

    public static void CopyTo(this StringBuilder source, StringBuilder dest, char[] buffer)
    {
        dest.EnsureCapacity(dest.Length + source.Length);
        for (int i = 0; i < source.Length; i += buffer.Length)
        {
            int charCount = Math.Min(source.Length - i, buffer.Length);
            source.CopyTo(i, buffer, 0, charCount);
            dest.Append(buffer, 0, charCount);
        }
    }


问:
dynamically assign image src to a canvas
I am trying to initialize a php variable to image source gotten from a database loop. this is the snippet of code I am using to do that

```<code><?php foreach($load_preview as $item): ?>
    <div class="store-item">
        <?php var imgSrc = base_url()."thumbs/".$item["filename"]; ?>//having syntaxt error at this line
            <a href="<?php echo site_url()."/"."accessories/preview/".$item["id"];?>">
                <canvas width="450" height="450" id="canvas">Sorry, no canvas available</canvas>
            </a>
        </div>
    <?php endforeach; ?>
</code>```

I am reassigning the above into a javascript code code to draw a canvas for zooming as shown

```<code>/**
 * START
 */
var img = document.createElement('img');
img.onload = function() {
    iw = 500;
    ih = 500;
    canvas.width = (iw / 2 - 1.5)|0; //compensate for rounding errors
    canvas.height = (ih / 2 - 1.5)|0;
    doCanvas();
    canvas.addEventListener('mouseout', doCanvas, false);
    canvas.addEventListener('mousemove', move, false);
}
img.src = "<?php echo imgSrc ?>";//retrieve the assigned variable here in the javascript assignment

</script>
</code>```

this looks a little bit confusing to me. can someone please assist

答:
This line is wrong:

```<code><?php var imgSrc = base_url()."thumbs/".$item["filename"]; ?>
</code>```

It probably should be like this:

```<code>var imgSrc = '<?php echo base_url()."thumbs/".$item["filename"]; ?>';
</code>```

Body:
I am trying to initialize a php variable to image source gotten from a database loop. this is the snippet of code I am using to do that

<?php foreach($load_preview as $item): ?>

        <?php var imgSrc = base_url()."thumbs/".$item["filename"]; ?>//having syntaxt error at this line
            <a href="<?php echo site_url()."/"."accessories/preview/".$item["id"];?>">
                <canvas width="450" height="450" id="canvas">Sorry, no canvas available</canvas>

    <?php endforeach; ?>

I am reassigning the above into a javascript code code to draw a canvas for zooming as shown

/**
 * START
 */
var img = document.createElement('img');
img.onload = function() {
    iw = 500;
    ih = 500;
    canvas.width = (iw / 2 - 1.5)|0; //compensate for rounding errors
    canvas.height = (ih / 2 - 1.5)|0;
    doCanvas();
    canvas.addEventListener('mouseout', doCanvas, false);
    canvas.addEventListener('mousemove', move, false);
}
img.src = "<?php echo imgSrc ?>";//retrieve the assigned variable here in the javascript assignment

</script>

this looks a little bit confusing to me. can someone please assist

Body:
This line is wrong:

<?php var imgSrc = base_url()."thumbs/".$item["filename"]; ?>

It probably should be like this:

var imgSrc = '<?php echo base_url()."thumbs/".$item["filename"]; ?>';


问:
Stuck at 36th exercise of Learn Python the Hard Way
This is the code I have written for Learn Python the Hard Way exercise 36. But I am not able to run the code in the door_1 function. If I choose 3 as an option and then left or right anything which is then stored in dir, the output is "lion ate you", no matter what I type.

```<code>from sys import exit #importing module from lib

def Tadaa():
    print "This is a place where you will get a surprise"
    next = int(raw_input("Enter any number from 1-10 :"))
    if next <= 10:
        if next % 2 == 0 :
            print "You will be buying me a shake :)."
        else :
            print "You will be getting a shake by me."
    else :
        print "Do it correctly."

def door_1():
    print "There are 3 doors . Choose any door from the the remaining three doors"
    print "Lets hope for the best "
    next = raw_input("Enter your option :")
    if next == "1":
        print "abc "
    elif next == "2":
        print "abc"
    elif next == "3":
        print "You have entered 3rd door ."
        print "Here are 2 doors one on left and one on right."

        dir = raw_input("Choose which door do you wnat to enter :")

        if dir == "left" or "Left":
            print "Lion ate you . You are dead ."
        elif dir == "right" or "Right" :
            print "You will be getting a surprise"
            Tadaa()
        else :
            print "abc"
    else :
        print "abc"

def door_2():
    print "There are two doors A and B which will decide your fate"

    next = raw_input("Enter the door ")

    if next == "A" or "a":
        door_1()
    elif next == "B" or "b":
        print "You are back from where you have started"
        start()
    else :
        print "I got no idea what that means."
        exit(0)

def start():
    print "You are in dark room"
    print "There is a door to your right and left ."
    print "Which one do you take"

    next = raw_input("> ")

    if next == "Right" or "right":
        door_2()
    elif next == "Left" or "left":
        door_1()
    else :
        print "abc"
start()
</code>```

答:
The problem is your statement:

```<code>if dir=="left" or "Left":
</code>```

What you want is

```<code>if dir=="left" or dir=="Left":
</code>```

In effect, what just doing or "Left" is doing, is checking whether a string that you've just created exists or not. Put another way, its similar to:

```<code>x='Left'
if x:
</code>```

X does exist, so if X is True.

The crux here is to always evaluate statements in quantum, and when you're using and in conjunction with or statements, make sure you use brackets to be explicit. if statement_one or statement_two.

Body:
This is the code I have written for Learn Python the Hard Way exercise 36. But I am not able to run the code in the door_1 function. If I choose 3 as an option and then left or right anything which is then stored in dir, the output is "lion ate you", no matter what I type.

from sys import exit #importing module from lib

def Tadaa():
    print "This is a place where you will get a surprise"
    next = int(raw_input("Enter any number from 1-10 :"))
    if next <= 10:
        if next % 2 == 0 :
            print "You will be buying me a shake :)."
        else :
            print "You will be getting a shake by me."
    else :
        print "Do it correctly."

def door_1():
    print "There are 3 doors . Choose any door from the the remaining three doors"
    print "Lets hope for the best "
    next = raw_input("Enter your option :")
    if next == "1":
        print "abc "
    elif next == "2":
        print "abc"
    elif next == "3":
        print "You have entered 3rd door ."
        print "Here are 2 doors one on left and one on right."

        dir = raw_input("Choose which door do you wnat to enter :")

        if dir == "left" or "Left":
            print "Lion ate you . You are dead ."
        elif dir == "right" or "Right" :
            print "You will be getting a surprise"
            Tadaa()
        else :
            print "abc"
    else :
        print "abc"

def door_2():
    print "There are two doors A and B which will decide your fate"

    next = raw_input("Enter the door ")

    if next == "A" or "a":
        door_1()
    elif next == "B" or "b":
        print "You are back from where you have started"
        start()
    else :
        print "I got no idea what that means."
        exit(0)

def start():
    print "You are in dark room"
    print "There is a door to your right and left ."
    print "Which one do you take"

    next = raw_input("> ")

    if next == "Right" or "right":
        door_2()
    elif next == "Left" or "left":
        door_1()
    else :
        print "abc"
start()

Body:
The problem is your statement:

if dir=="left" or "Left":

What you want is

if dir=="left" or dir=="Left":

In effect, what just doing or "Left" is doing, is checking whether a string that you've just created exists or not. Put another way, its similar to:

x='Left'
if x:

X does exist, so if X is True.

The crux here is to always evaluate statements in quantum, and when you're using and in conjunction with or statements, make sure you use brackets to be explicit. if statement_one or statement_two.