问:
Retrofit socket timeout exception while uploading larger files using multipart
I am facing the issue of socket timeout exception while using retrofit 2.0.2 library and okhttp 2.3.0. I am trying to upload the image file which is between 500kb to 1.5mb it is uploading successfully.but when i tried to upload video file which is greater than 5mb i am getting this exception.

I used httpclient for connection settings as below.

```<code>public static OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .connectTimeout(0, TimeUnit.SECONDS)
            .writeTimeout(0, TimeUnit.SECONDS)
            .readTimeout(0, TimeUnit.SECONDS)
            .build();
</code>```

please suggest me to upload larger files without this issue.Thanks in advance

答:
you can provide the time in seconds as follows

public class ApiClient {

```<code>public static final String BASE_URL = "your_url";
public static Retrofit retrofit = null;

public static Retrofit getApiClient() {
    if (retrofit == null) {
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .build();
        return new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

    }

        return retrofit;
}
</code>```

}

i've given 60 seconds

Body:
I am facing the issue of socket timeout exception while using retrofit 2.0.2 library and okhttp 2.3.0. I am trying to upload the image file which is between 500kb to 1.5mb it is uploading successfully.but when i tried to upload video file which is greater than 5mb i am getting this exception.

I used httpclient for connection settings as below.

public static OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .connectTimeout(0, TimeUnit.SECONDS)
            .writeTimeout(0, TimeUnit.SECONDS)
            .readTimeout(0, TimeUnit.SECONDS)
            .build();

please suggest me to upload larger files without this issue.Thanks in advance

Body:
you can provide the time in seconds as follows

public class ApiClient {

public static final String BASE_URL = "your_url";
public static Retrofit retrofit = null;

public static Retrofit getApiClient() {
    if (retrofit == null) {
        OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .build();
        return new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

    }

        return retrofit;
}

}

i've given 60 seconds


来源: stackexchange

问:
how to use Mongodb Single instance with multiple dbs in spring-boot
I have a situation where I have multiple clients connecting to my application and I want to give each one their own "schema/database" in the same Mongo server.

My configuration class:

```<code>@Configuration
public class MongoDbConfiguration {

@Bean
@Primary
public MongoDbFactory mongoDbFactory() throws UnknownHostException {
    return new MultiTenantMongoDbFactory();
}

@Bean
@Primary
public MongoTemplate mongoTemplate() throws UnknownHostException {
    return new MongoTemplate(mongoDbFactory());
}
}
</code>```

Multitenant Db Factory

```<code>public class MultiTenantMongoDbFactory extends SimpleMongoDbFactory {

public MultiTenantMongoDbFactory() throws UnknownHostException {
    super(getMongoClient(), TenantContext.getTenant());
}

@Override
public DB getDb() throws DataAccessException {
    String tenant = TenantContext.getTenant();
    return getDb(tenant);

}

private static MongoClient getMongoClient() {
    String tenant = TenantContext.getTenant();
    System.out.println("Database name in factory class :"+tenant);
    if (tenant.equalsIgnoreCase("ncet")) {
        MongoCredential mongoCredential = MongoCredential.createCredential("user1", "db1",
                "pwd1".toCharArray());
        ServerAddress serverAddress = new ServerAddress("localhost", 27017);
        MongoClient mongoClient = new MongoClient(serverAddress, Arrays.asList(mongoCredential));
        return mongoClient;
    }else{
        MongoCredential mongoCredential = MongoCredential.createCredential("user1", "db2",
                "pwd2".toCharArray());
        ServerAddress serverAddress = new ServerAddress("localhost", 27017);
        MongoClient mongoClient = new MongoClient(serverAddress, Arrays.asList(mongoCredential));
        return mongoClient;
    }

}
</code>```

Each database has credentials

答:
Your sample doesn't work because getMongoClient() invokes only once during startup, but you need to change it in runtime based on active tenant. It's pretty straightforward to implement dedicated MongoDbFactory for multi-tenancy based on spring SimpleMongoDbFactory as example. You can add more logic to it if needed (for writeConcern, etc).
There are two tenants (east and west) in this sample. Each tenant has its own MongoClient with corresponding database name and credentials configured in MongoConfig. TenantDataFactory returns tenant related information based on current Tenant in TenantContext. DB object is created using MongoClient and database name from TenantData returned by TenantDataFactory.

```<code>public class MultiTenantMongoDbFactory implements MongoDbFactory {

  private PersistenceExceptionTranslator exceptionTranslator;
  private TenantDataFactory tenantDataFactory;

  public MultiTenantMongoDbFactory(TenantDataFactory tenantDataFactory) {
    this.exceptionTranslator = new MongoExceptionTranslator();
    this.tenantDataFactory = tenantDataFactory;
  }

  @Override
  public DB getDb(String dbName) throws DataAccessException {
    return getDb();
  }

  @Override
  public DB getDb() throws DataAccessException {
    Tenant tenant = TenantContext.getCurrentTenant();
    TenantData tenantData = tenantDataFactory.getTenantData(tenant);
    return MongoDbUtils.getDB(tenantData.getClient(), tenantData.getDbName());
  }

  @Override
  public PersistenceExceptionTranslator getExceptionTranslator() {
    return exceptionTranslator;
  }
}

public class TenantDataFactory {

  private Map<Tenant, TenantData> tenantDataMap;

  public TenantDataFactory(Map<Tenant, TenantData> tenantDataMap) {
    this.tenantDataMap = Collections.unmodifiableMap(tenantDataMap);
  }

  public TenantData getTenantData(Tenant tenant) {
    TenantData tenantData = tenantDataMap.get(tenant);
    if (tenantData == null) {
      // or return default tenant
      throw new IllegalArgumentException("Unsupported tenant " + tenant);
    }
    return tenantData;
  }
}

public enum Tenant {
  EAST, WEST
}

public class TenantData {

  private final String dbName;
  private final MongoClient client;

  public TenantData(String dbName, MongoClient client) {
    this.dbName = dbName;
    this.client = client;
  }

  public String getDbName() {
    return dbName;
  }

  public MongoClient getClient() {
    return client;
  }
}

public class TenantContext {

  private static ThreadLocal<Tenant> currentTenant = new ThreadLocal<>();

  public static void setCurrentTenant(Tenant tenant) {
    currentTenant.set(tenant);
  }

  public static Tenant getCurrentTenant() {
    return currentTenant.get();
  }
}

@Configuration
public class MongoConfig {

  @Bean(name = "eastMongoClient", destroyMethod = "close")
  public MongoClient eastMongoClient() {
    return new MongoClient(new ServerAddress("127.0.0.1", 27017),
        Collections.singletonList(MongoCredential.createCredential("user1", "east", "password1".toCharArray())));
  }

  @Bean(name = "westMongoClient", destroyMethod = "close")
  public MongoClient westMongoClient() {
    return new MongoClient(new ServerAddress("127.0.0.1", 27017),
        Collections.singletonList(MongoCredential.createCredential("user2", "west", "password2".toCharArray())));
  }

  @Bean
  public TenantDataFactory tenantDataFactory(@Qualifier("eastMongoClient") MongoClient eastMongoClient,
                                             @Qualifier("westMongoClient") MongoClient westMongoClient) {
    Map<Tenant, TenantData> tenantDataMap = new HashMap<>();
    tenantDataMap.put(Tenant.EAST, new TenantData("east", eastMongoClient));
    tenantDataMap.put(Tenant.WEST, new TenantData("west", westMongoClient));
    return new TenantDataFactory(tenantDataMap);
  }

  @Bean
  public MongoDbFactory mongoDbFactory(@Autowired TenantDataFactory tenantDataFactory) {
    return new MultiTenantMongoDbFactory(tenantDataFactory);
  }

  @Bean
  public MongoTemplate mongoTemplate(@Autowired MongoDbFactory mongoDbFactory) {
    return new MongoTemplate(mongoDbFactory);
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a situation where I have multiple clients connecting to my application and I want to give each one their own "schema/database" in the same Mongo server.

My configuration class:

@Configuration
public class MongoDbConfiguration {

@Bean
@Primary
public MongoDbFactory mongoDbFactory() throws UnknownHostException {
    return new MultiTenantMongoDbFactory();
}

@Bean
@Primary
public MongoTemplate mongoTemplate() throws UnknownHostException {
    return new MongoTemplate(mongoDbFactory());
}
}

Multitenant Db Factory

public class MultiTenantMongoDbFactory extends SimpleMongoDbFactory {

public MultiTenantMongoDbFactory() throws UnknownHostException {
    super(getMongoClient(), TenantContext.getTenant());
}

@Override
public DB getDb() throws DataAccessException {
    String tenant = TenantContext.getTenant();
    return getDb(tenant);

}

private static MongoClient getMongoClient() {
    String tenant = TenantContext.getTenant();
    System.out.println("Database name in factory class :"+tenant);
    if (tenant.equalsIgnoreCase("ncet")) {
        MongoCredential mongoCredential = MongoCredential.createCredential("user1", "db1",
                "pwd1".toCharArray());
        ServerAddress serverAddress = new ServerAddress("localhost", 27017);
        MongoClient mongoClient = new MongoClient(serverAddress, Arrays.asList(mongoCredential));
        return mongoClient;
    }else{
        MongoCredential mongoCredential = MongoCredential.createCredential("user1", "db2",
                "pwd2".toCharArray());
        ServerAddress serverAddress = new ServerAddress("localhost", 27017);
        MongoClient mongoClient = new MongoClient(serverAddress, Arrays.asList(mongoCredential));
        return mongoClient;
    }

}

Each database has credentials

Body:
Your sample doesn't work because getMongoClient() invokes only once during startup, but you need to change it in runtime based on active tenant. It's pretty straightforward to implement dedicated MongoDbFactory for multi-tenancy based on spring SimpleMongoDbFactory as example. You can add more logic to it if needed (for writeConcern, etc).
There are two tenants (east and west) in this sample. Each tenant has its own MongoClient with corresponding database name and credentials configured in MongoConfig. TenantDataFactory returns tenant related information based on current Tenant in TenantContext. DB object is created using MongoClient and database name from TenantData returned by TenantDataFactory.

public class MultiTenantMongoDbFactory implements MongoDbFactory {

  private PersistenceExceptionTranslator exceptionTranslator;
  private TenantDataFactory tenantDataFactory;

  public MultiTenantMongoDbFactory(TenantDataFactory tenantDataFactory) {
    this.exceptionTranslator = new MongoExceptionTranslator();
    this.tenantDataFactory = tenantDataFactory;
  }

  @Override
  public DB getDb(String dbName) throws DataAccessException {
    return getDb();
  }

  @Override
  public DB getDb() throws DataAccessException {
    Tenant tenant = TenantContext.getCurrentTenant();
    TenantData tenantData = tenantDataFactory.getTenantData(tenant);
    return MongoDbUtils.getDB(tenantData.getClient(), tenantData.getDbName());
  }

  @Override
  public PersistenceExceptionTranslator getExceptionTranslator() {
    return exceptionTranslator;
  }
}

public class TenantDataFactory {

  private Map<Tenant, TenantData> tenantDataMap;

  public TenantDataFactory(Map<Tenant, TenantData> tenantDataMap) {
    this.tenantDataMap = Collections.unmodifiableMap(tenantDataMap);
  }

  public TenantData getTenantData(Tenant tenant) {
    TenantData tenantData = tenantDataMap.get(tenant);
    if (tenantData == null) {
      // or return default tenant
      throw new IllegalArgumentException("Unsupported tenant " + tenant);
    }
    return tenantData;
  }
}

public enum Tenant {
  EAST, WEST
}

public class TenantData {

  private final String dbName;
  private final MongoClient client;

  public TenantData(String dbName, MongoClient client) {
    this.dbName = dbName;
    this.client = client;
  }

  public String getDbName() {
    return dbName;
  }

  public MongoClient getClient() {
    return client;
  }
}

public class TenantContext {

  private static ThreadLocal<Tenant> currentTenant = new ThreadLocal<>();

  public static void setCurrentTenant(Tenant tenant) {
    currentTenant.set(tenant);
  }

  public static Tenant getCurrentTenant() {
    return currentTenant.get();
  }
}

@Configuration
public class MongoConfig {

  @Bean(name = "eastMongoClient", destroyMethod = "close")
  public MongoClient eastMongoClient() {
    return new MongoClient(new ServerAddress("127.0.0.1", 27017),
        Collections.singletonList(MongoCredential.createCredential("user1", "east", "password1".toCharArray())));
  }

  @Bean(name = "westMongoClient", destroyMethod = "close")
  public MongoClient westMongoClient() {
    return new MongoClient(new ServerAddress("127.0.0.1", 27017),
        Collections.singletonList(MongoCredential.createCredential("user2", "west", "password2".toCharArray())));
  }

  @Bean
  public TenantDataFactory tenantDataFactory(@Qualifier("eastMongoClient") MongoClient eastMongoClient,
                                             @Qualifier("westMongoClient") MongoClient westMongoClient) {
    Map<Tenant, TenantData> tenantDataMap = new HashMap<>();
    tenantDataMap.put(Tenant.EAST, new TenantData("east", eastMongoClient));
    tenantDataMap.put(Tenant.WEST, new TenantData("west", westMongoClient));
    return new TenantDataFactory(tenantDataMap);
  }

  @Bean
  public MongoDbFactory mongoDbFactory(@Autowired TenantDataFactory tenantDataFactory) {
    return new MultiTenantMongoDbFactory(tenantDataFactory);
  }

  @Bean
  public MongoTemplate mongoTemplate(@Autowired MongoDbFactory mongoDbFactory) {
    return new MongoTemplate(mongoDbFactory);
  }
}


问:
Rendering optimization using nested state in React
I have a React app where I believe -though not certain- that "nested state" causes me delays.

Here's the thing:

I keep my state in a variable called dataset.

dataset is an array of objects like this:

```<code>(5) [{…}, {…}, {…}, {…}, {…}]
</code>```

and each object has the following structure:

```<code>{id: '5', name: 'Bob', url: 'http://example.com', paid: 'yes'}
</code>```

Finally my render method displays the data in a table:

...
{dataset.map((entry) => (
    ...

{entry.name} has paid: {entry.paid}

    ...
))}
```

<p>It all seems to be working fine but then whenever I need to update the state because presumably user number 5 didn't pay this month I do this:</p>

<pre class="lang-js prettyprint-override"><code>// copy current state
let new_dataset = this.state.dataset.slice();

// modify the copy
new_dataset[5].paid = !this.state.dataset[5].paid;

// replace old state with the modified copy
this.setState({
    dataset: new_dataset
});
</code>```

However here's the problem:

Will React update all 5 rows or just the row holding the object I modified?

Wouldn't it be a waste to have react update 10000 rows just for a small change in one row? What's the best practice for such scenarios?

Thanks in advance.

P.S. I have already looked at how to Avoid Reconciliation but I'm not sure how to apply in this case.

答:
Will React update all 5 rows or just the row holding the object I
  modified?

No it doesn't react render all the 5 rows again. Rather react optimises on a number of things to not render the same changes again. One such thing is a key attribute. Also React runs a diffing algorithm to render only the changes

Body:
I have a React app where I believe -though not certain- that "nested state" causes me delays.

Here's the thing:

I keep my state in a variable called dataset.

dataset is an array of objects like this:

(5) [{…}, {…}, {…}, {…}, {…}]

and each object has the following structure:

{id: '5', name: 'Bob', url: 'http://example.com', paid: 'yes'}

Finally my render method displays the data in a table:

...
{dataset.map((entry) => (
    ...

{entry.name} has paid: {entry.paid}

    ...
))}

It all seems to be working fine but then whenever I need to update the state because presumably user number 5 didn't pay this month I do this:

// copy current state
let new_dataset = this.state.dataset.slice();

// modify the copy
new_dataset[5].paid = !this.state.dataset[5].paid;

// replace old state with the modified copy
this.setState({
    dataset: new_dataset
});

However here's the problem:

Will React update all 5 rows or just the row holding the object I modified?

Wouldn't it be a waste to have react update 10000 rows just for a small change in one row? What's the best practice for such scenarios?

Thanks in advance.

P.S. I have already looked at how to Avoid Reconciliation but I'm not sure how to apply in this case.


问:
Modify HTML and PHP with preg_replace
I have this HTML / PHP content (as a string):

```<code><html>
    <?php my_class->my_function('test.php', 'value1', 'value2');
    <?php my_class->my_function('test2.php', 3);
</html>
</code>```

What my_class->my_function does is including content depending on the values sent.

It could look something like this

```<code>function my_function($file, $value1, $value2)
{
    include $file . $value1 . $value2;
}
</code>```

The result of my_function should be outputted, instead of the function call.

The result should be

```<code><html>
    <?php
        /* Content from file test.php */
        echo 'This file is test.php, with value1 and value2';
    ?>
    <?php
        /* Content from file test2.php */
        echo 'This file is test2.php, with value 3';
    ?>
</html>
</code>```

I guess I need some kind of preg_replace in combination with eval, include or get_file_contents.

答:
Uncomplete answer. This is what I got at first when using explode. It works BUT when adding multiple values to the function it creates bugs. One or two values it can handle. Not more and it's too complex for me to handle.

```<code>function include_layout2($part, $file = '/index.php')
{

    $url = get_layout2($part, $file);
    if(file_exists($url))
    {
        return get_include_contents( $url );
    }
}

function get_layout2($part, $file = '/index.php')
{
    $layout_theme = 'default';
    $addmod_layout = get_option('addmod_layout');
    $layout = $addmod_layout['styles'][$layout_theme][$part]['layout'];
    $layout = (!empty($layout)) ? $layout : 'default';
    $url = TEMPLATEPATH . '/styles/' . $part . '/' . $layout . $file;
    if(file_exists($url))
    {
        return $url;
    }
}

function generate_content($layout = 'index')
{
    $content = include_layout2($layout);
    $content_a = explode("<?php addmod_include('", $content);

    $save_for_later = $content;
    $counter = 0;
    while(count($content_a) > 1)
    {
        $content_a = explode("<?php addmod_include('", $save_for_later);
        $output = '';
        $save_for_later = '';
        for($i = 0; $i < sizeof($content_a); $i++)
        {
            $content_b = explode("'); ?>", $content_a[$i], 2);
            if(isset($content_b[0]) && !empty($content_b[0]))
            {
                $include_test = include_layout2($content_b[0]);
                if(isset($include_test))
                {
                    $content_b[0] = include_layout2($content_b[0]);
                }
                else
                {
                    $new_layout = explode("addmod_include('", $content_b[0]);
                    $new_file = explode("addmod_include(', '", $content_b[0]);

                    if(isset($new_layout[0]) && isset($new_file[1]))
                    {
                        $content_b[0] = include_layout2($new_layout[0], $new_file[1]);
                    }
                    else
                    {
                        $content_b[0] .=  "'); ?>";
                    }
                }
            }
            $content = implode($content_b);
            $output .= $content;
            $save_for_later .= $content;
        }

        $counter++;
    }
    return $output;
}
echo generate_content();
</code>```

Don't try to run the code because it's a little dependent of some other stuff.

I don't know if that makes it more clear what I need to do?

ContentLicense: CC BY-SA 2.5

Title: Modify HTML and PHP with preg_replace

Body:
I have this HTML / PHP content (as a string):

    <?php my_class->my_function('test.php', 'value1', 'value2');
    <?php my_class->my_function('test2.php', 3);

What my_class->my_function does is including content depending on the values sent.

It could look something like this

function my_function($file, $value1, $value2)
{
    include $file . $value1 . $value2;
}

The result of my_function should be outputted, instead of the function call.

The result should be

    <?php
        /* Content from file test.php */
        echo 'This file is test.php, with value1 and value2';
    ?>
    <?php
        /* Content from file test2.php */
        echo 'This file is test2.php, with value 3';
    ?>

I guess I need some kind of preg_replace in combination with eval, include or get_file_contents.

Body:
Uncomplete answer. This is what I got at first when using explode. It works BUT when adding multiple values to the function it creates bugs. One or two values it can handle. Not more and it's too complex for me to handle.

function include_layout2($part, $file = '/index.php')
{

    $url = get_layout2($part, $file);
    if(file_exists($url))
    {
        return get_include_contents( $url );
    }
}

function get_layout2($part, $file = '/index.php')
{
    $layout_theme = 'default';
    $addmod_layout = get_option('addmod_layout');
    $layout = $addmod_layout['styles'][$layout_theme][$part]['layout'];
    $layout = (!empty($layout)) ? $layout : 'default';
    $url = TEMPLATEPATH . '/styles/' . $part . '/' . $layout . $file;
    if(file_exists($url))
    {
        return $url;
    }
}

function generate_content($layout = 'index')
{
    $content = include_layout2($layout);
    $content_a = explode("<?php addmod_include('", $content);

    $save_for_later = $content;
    $counter = 0;
    while(count($content_a) > 1)
    {
        $content_a = explode("<?php addmod_include('", $save_for_later);
        $output = '';
        $save_for_later = '';
        for($i = 0; $i < sizeof($content_a); $i++)
        {
            $content_b = explode("'); ?>", $content_a[$i], 2);
            if(isset($content_b[0]) && !empty($content_b[0]))
            {
                $include_test = include_layout2($content_b[0]);
                if(isset($include_test))
                {
                    $content_b[0] = include_layout2($content_b[0]);
                }
                else
                {
                    $new_layout = explode("addmod_include('", $content_b[0]);
                    $new_file = explode("addmod_include(', '", $content_b[0]);

                    if(isset($new_layout[0]) && isset($new_file[1]))
                    {
                        $content_b[0] = include_layout2($new_layout[0], $new_file[1]);
                    }
                    else
                    {
                        $content_b[0] .=  "'); ?>";
                    }
                }
            }
            $content = implode($content_b);
            $output .= $content;
            $save_for_later .= $content;
        }

        $counter++;
    }
    return $output;
}
echo generate_content();

Don't try to run the code because it's a little dependent of some other stuff.

I don't know if that makes it more clear what I need to do?


问:
BaseAdapter On Scroll Refresh Data in ListView
I'm Very new to Java and android... I'm Try to create an ListView using BaseAdapter List being created successfully i have a EditText along with button for each list item but the real problem is when i put some data into editText Field and scroll down to change value of last list item then i go back to the top it refreshes the data to default value it doesn't contain the value which was entered by user before scrolling down

My BaseAdaper Code

```<code>    class CoustomAdptr extends BaseAdapter{

    String[] dates;
    Integer[] inventory;
    Integer totalrooms;
    public CoustomAdptr(RoomFragment roomFragment, String[] dates, Integer[] inventory, Integer totalrooms) {
        this.dates = dates;
        this.inventory = inventory;
        this.totalrooms = totalrooms;
    }

    @Override
    public int getCount() {
        return dates.length;
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(final int i, View view, ViewGroup viewGroup) {

        view = getLayoutInflater().inflate(R.layout.inventory_listview,null);
        TextView textView = (TextView) view.findViewById(R.id.roomListViewText);
        final EditText editText = (EditText) view.findViewById(R.id.roomListInventory);
        final Button updateButton = (Button) view.findViewById(R.id.roomListViewInventoryUpdateButton);
        if(inventory[i] == 0){
            editText.setBackgroundColor(getResources().getColor(R.color.SoldOut));
            editText.setTextColor(getResources().getColor(R.color.SoldOutTextColor));
        } else if(inventory[i] < totalrooms){
            editText.setBackgroundColor(getResources().getColor(R.color.invetory));
            editText.setTextColor(getResources().getColor(R.color.invetoryTextColor));
        } else if(inventory[i] == totalrooms){
            editText.setBackgroundColor(getResources().getColor(R.color.fullInventory));
            editText.setTextColor(getResources().getColor(R.color.fullInventoryTextColor));
        }

        editText.setText(String.valueOf(inventory[i]));
        textView.setText(dates[i]);
        updateButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //String name = editText.getText().toString();
                //String name1 = dates[i];
                //String name2 = getArguments().getString("room_id");
                updateButton.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_done_black_24dp,0,0,0);
                //updateButton.setBackgroundColor(getResources().getColor(R.color.SoldOut));
                updateButton.setText("Updated");
                updateButton.setEnabled(false);
                Toast.makeText(getContext(), "Update Inventory Button Clicked", Toast.LENGTH_LONG).show();
            }
        });
        return view;
    }
}
</code>```

This is How Im Passing Data to My Adapter

```<code>JSONObject jObj = parentObject.getJSONObject("success");
JSONObject jObj2 = jObj.getJSONObject("data");
JSONArray arrajson = jObj2.getJSONArray("inventories");
String arrayCount = Integer.toString(arrajson.length());
String[] dates = new String[arrajson.length()];
Integer[] inventory = new Integer[arrajson.length()];
Integer totalrooms = new Integer(jObj2.getInt("total_room"));
for (int i=0; i<arrajson.length();i++){
     JSONObject jsonObject = arrajson.getJSONObject(i);
     dates[i] = jsonObject.getString("date");
     inventory[i] = jsonObject.getInt("inventory");
}
CoustomAdptr coustomAdptr = new CoustomAdptr(RoomFragment.this,dates,inventory,totalrooms);
listView.setAdapter(coustomAdptr);
</code>```

Help Needed :- I Want to retain same visible and Value of edittext as users enters on scroll up or down... i hope i was able to explain my problem clearly

答:
After clicking a button, save it's state in a boolean array or somewhere else. And inside getView method, check if this button was previously clicked or not then setup your view accordingly.

It would be better if you create a model class for rows.

Body:
I'm Very new to Java and android... I'm Try to create an ListView using BaseAdapter List being created successfully i have a EditText along with button for each list item but the real problem is when i put some data into editText Field and scroll down to change value of last list item then i go back to the top it refreshes the data to default value it doesn't contain the value which was entered by user before scrolling down

My BaseAdaper Code

    class CoustomAdptr extends BaseAdapter{

    String[] dates;
    Integer[] inventory;
    Integer totalrooms;
    public CoustomAdptr(RoomFragment roomFragment, String[] dates, Integer[] inventory, Integer totalrooms) {
        this.dates = dates;
        this.inventory = inventory;
        this.totalrooms = totalrooms;
    }

    @Override
    public int getCount() {
        return dates.length;
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(final int i, View view, ViewGroup viewGroup) {

        view = getLayoutInflater().inflate(R.layout.inventory_listview,null);
        TextView textView = (TextView) view.findViewById(R.id.roomListViewText);
        final EditText editText = (EditText) view.findViewById(R.id.roomListInventory);
        final Button updateButton = (Button) view.findViewById(R.id.roomListViewInventoryUpdateButton);
        if(inventory[i] == 0){
            editText.setBackgroundColor(getResources().getColor(R.color.SoldOut));
            editText.setTextColor(getResources().getColor(R.color.SoldOutTextColor));
        } else if(inventory[i] < totalrooms){
            editText.setBackgroundColor(getResources().getColor(R.color.invetory));
            editText.setTextColor(getResources().getColor(R.color.invetoryTextColor));
        } else if(inventory[i] == totalrooms){
            editText.setBackgroundColor(getResources().getColor(R.color.fullInventory));
            editText.setTextColor(getResources().getColor(R.color.fullInventoryTextColor));
        }

        editText.setText(String.valueOf(inventory[i]));
        textView.setText(dates[i]);
        updateButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //String name = editText.getText().toString();
                //String name1 = dates[i];
                //String name2 = getArguments().getString("room_id");
                updateButton.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_done_black_24dp,0,0,0);
                //updateButton.setBackgroundColor(getResources().getColor(R.color.SoldOut));
                updateButton.setText("Updated");
                updateButton.setEnabled(false);
                Toast.makeText(getContext(), "Update Inventory Button Clicked", Toast.LENGTH_LONG).show();
            }
        });
        return view;
    }
}

This is How Im Passing Data to My Adapter

JSONObject jObj = parentObject.getJSONObject("success");
JSONObject jObj2 = jObj.getJSONObject("data");
JSONArray arrajson = jObj2.getJSONArray("inventories");
String arrayCount = Integer.toString(arrajson.length());
String[] dates = new String[arrajson.length()];
Integer[] inventory = new Integer[arrajson.length()];
Integer totalrooms = new Integer(jObj2.getInt("total_room"));
for (int i=0; i<arrajson.length();i++){
     JSONObject jsonObject = arrajson.getJSONObject(i);
     dates[i] = jsonObject.getString("date");
     inventory[i] = jsonObject.getInt("inventory");
}
CoustomAdptr coustomAdptr = new CoustomAdptr(RoomFragment.this,dates,inventory,totalrooms);
listView.setAdapter(coustomAdptr);

Help Needed :- I Want to retain same visible and Value of edittext as users enters on scroll up or down... i hope i was able to explain my problem clearly


问:
run PHPunit from cmd file
I had create a cmd file:

```<code>phpunit Test.php > myTest.txt
</code>```

It work when i run is directly. But when exec with PHP code:

```<code>exec("cmd.cmd");
</code>```

a file myTest.txt created, but it blank

答:
Most likely because phpUnit is not run when you call it via php (this could be due to security privileges).

Try

```<code>$output = '';
exec("cmd.cmd", $output);
echo $output;
</code>```

And see what the execution actually returned, also you might need to specify a path since exec might run from the PHP execution path, not your PHP webroot where the file exists.

Title: run PHPunit from cmd file

Body:
I had create a cmd file:

phpunit Test.php > myTest.txt

It work when i run is directly. But when exec with PHP code:

exec("cmd.cmd");

a file myTest.txt created, but it blank

Body:
Most likely because phpUnit is not run when you call it via php (this could be due to security privileges).

Try

$output = '';
exec("cmd.cmd", $output);
echo $output;

And see what the execution actually returned, also you might need to specify a path since exec might run from the PHP execution path, not your PHP webroot where the file exists.


问:
React:Do I make one line html as component or not?
Suppose I have one p tag which is used(with different class) so many times in web pages. So should I make it component or not?

If I make it component, then in future if I have to wrapped it inside suppose div tag then I only have to make changes as one place, otherwise I have to change it at every place.

Suppose I have 50 p tag in my parent component and if I make p tag component and use at wherever needed, then for all 50 time it will call that component(p tag component) which can be avoid if directly use p tag(which is I guess good for performance compare to former one).

答: There is no reason to wrap native DOM elements inside React components. Just use them directly.</p>


问:
Laravel 5.5 conditional redirect on register
I am using Laravel 5.5 and I want to redirect the uses when they register on different route depending on whether it has custom session or not
I managed to do that in the LoginController like so:

```<code>protected $redirectTo = '/';

    protected function redirectTo()
    {
        if (Session::has('userRequest')) {
            return route('request');
        }

        if (Auth::user()->role->name == 'admin') {
            return route('admin-dashboard');
        }

        if (Auth::user()->role->name == 'dealer') {
            return route('my-requests');
        }
    }
</code>```

But when I try this in the RegisterController:

```<code>protected $redirectTo = '/';

    protected function redirectTo()
    {
        if (Session::has('userRequest')) {
            return route('request');
        }
    }
</code>```

It throws Object of class Illuminate\Routing\Redirector could not be converted to string exception

答:
Method redirectTo must return a route/string. When the session does not have userRequest, the method returns null causing this error.

edit the method to be:

```<code>protected function redirectTo()
{
    if (\Session::has('userRequest')) {
        return route('request');
    }
    return $this->redirectTo; // or any route you want.
}
</code>```

Body:
I am using Laravel 5.5 and I want to redirect the uses when they register on different route depending on whether it has custom session or not
I managed to do that in the LoginController like so:

protected $redirectTo = '/';

    protected function redirectTo()
    {
        if (Session::has('userRequest')) {
            return route('request');
        }

        if (Auth::user()->role->name == 'admin') {
            return route('admin-dashboard');
        }

        if (Auth::user()->role->name == 'dealer') {
            return route('my-requests');
        }
    }

But when I try this in the RegisterController:

protected $redirectTo = '/';

    protected function redirectTo()
    {
        if (Session::has('userRequest')) {
            return route('request');
        }
    }

It throws Object of class Illuminate\Routing\Redirector could not be converted to string exception

Body:
Method redirectTo must return a route/string. When the session does not have userRequest, the method returns null causing this error.

edit the method to be:

protected function redirectTo()
{
    if (\Session::has('userRequest')) {
        return route('request');
    }
    return $this->redirectTo; // or any route you want.
}


问:
Dynamically Sorting with LINQ
I have a collection of CLR objects. The class definition for the object has three properties: FirstName, LastName, BirthDate.

I have a string that reflects the name of the property the collection should be sorted by. In addition, I have a sorting direction. How do I dynamically apply this sorting information to my collection? Please note that sorting could be multi-layer, so for instance I could sort by LastName, and then by FirstName.

Currently, I'm trying the following without any luck:

```<code>var results = myCollection.OrderBy(sortProperty);
</code>```

However, I'm getting a message that says:

... does not contain a defintion for 'OrderBy'  and the best extension method overload ... has some invalid arguments.

答:
you can do this with Linq</p>

```<code>var results = from c in myCollection
    orderby c.SortProperty
    select c;
</code>```

Title: Dynamically Sorting with LINQ

Body:
I have a collection of CLR objects. The class definition for the object has three properties: FirstName, LastName, BirthDate.

I have a string that reflects the name of the property the collection should be sorted by. In addition, I have a sorting direction. How do I dynamically apply this sorting information to my collection? Please note that sorting could be multi-layer, so for instance I could sort by LastName, and then by FirstName.

Currently, I'm trying the following without any luck:

var results = myCollection.OrderBy(sortProperty);

However, I'm getting a message that says:

... does not contain a defintion for 'OrderBy'  and the best extension method overload ... has some invalid arguments.

Body:
you can do this with Linq

var results = from c in myCollection
    orderby c.SortProperty
    select c;


问:
Angular httpClient: Reformat date in json
I have an object with a property of kind date. If I post it with httpClient.post(...) the date property has it's natural string representation. How can I adopt it to a format that the server understands?</p>

答:
Simply change the date format before sending it in httpClient.post like this:

You can give your date from your object in its input argument, I'm hardcoding a date string here:

```<code>var date = new Date('2010-10-11T00:00:00+05:30');

var formattedDateString = (date.getMonth() + 1) + '-' + date.getDate() + '-' +  date.getFullYear();

var dateToSend = new Date(formattedDateString);
</code>```

Now you can attach this date in post request.

Body:
Simply change the date format before sending it in httpClient.post like this:

You can give your date from your object in its input argument, I'm hardcoding a date string here:

var date = new Date('2010-10-11T00:00:00+05:30');

var formattedDateString = (date.getMonth() + 1) + '-' + date.getDate() + '-' +  date.getFullYear();

var dateToSend = new Date(formattedDateString);

Now you can attach this date in post request.


问:
NERDTree: Opening a file below the file explorer
I'm using NERDTree and (1) want to have the following layout in a single window to save the resolution in the horizontal direction. Does NERDTree support such a layout? In addition, I need to (2) arrange the display ratio in the vertical direction.

```<code>-----------------------------------
|                                 |
|  File Explorer:                 |
|                                 |
|    Always open.                 |
|                                 |
-----------------------------------
|                                 |
|  Multiple Files:                |
|                                 |
|    Only a single file is        |
|    displayed. You can display   |
|    a specific file in the       |
|    buffer invoking ":b [n]".    |
|                                 |
-----------------------------------
</code>```

By default NEDTree opens files on the right of the file explorer as follows:

```<code>-----------------------------------
|        |                        |
|        |                        |
|        |                        |
|  F.E.  |  Multiple Files        |
|        |                        |
|        |                        |
|        |                        |
-----------------------------------
</code>```

答:
I do not use nerdtree, but a quick search in the source shows following lines:

```<code>call s:initVariable("g:NERDTreeWinPos", "left")
call s:initVariable("g:NERDTreeWinSize", 31)
</code>```

So i bet you can use this in your .vimrc:

```<code>let g:NERDTreeWinPos = "top"
let g:NERDTreeWinSize = X
</code>```

For the ration you can do some math with the &lines variable.
However you will have to do this in two autocmds VimResized and BufEnter and probably BufNew too.
There are a lot of questions and answers about autocmd on SO so i will not explain it any further unless you need some specific help.

Body:
I'm using NERDTree and (1) want to have the following layout in a single window to save the resolution in the horizontal direction. Does NERDTree support such a layout? In addition, I need to (2) arrange the display ratio in the vertical direction.

-----------------------------------
|                                 |
|  File Explorer:                 |
|                                 |
|    Always open.                 |
|                                 |
-----------------------------------
|                                 |
|  Multiple Files:                |
|                                 |
|    Only a single file is        |
|    displayed. You can display   |
|    a specific file in the       |
|    buffer invoking ":b [n]".    |
|                                 |
-----------------------------------

By default NEDTree opens files on the right of the file explorer as follows:

-----------------------------------
|        |                        |
|        |                        |
|        |                        |
|  F.E.  |  Multiple Files        |
|        |                        |
|        |                        |
|        |                        |
-----------------------------------

Body:
I do not use nerdtree, but a quick search in the source shows following lines:

call s:initVariable("g:NERDTreeWinPos", "left")
call s:initVariable("g:NERDTreeWinSize", 31)

So i bet you can use this in your .vimrc:

let g:NERDTreeWinPos = "top"
let g:NERDTreeWinSize = X

For the ration you can do some math with the &lines variable.
However you will have to do this in two autocmds VimResized and BufEnter and probably BufNew too.
There are a lot of questions and answers about autocmd on SO so i will not explain it any further unless you need some specific help.


问:
Better way to secure REST resources in Spring?
I have a RESTful service that exposes resources like /user/{id}

Now, the user can provide the credentials, get the token and access the resource. However, once authenticated, the user can access the resources for any id.

Meaning, user1 can access the URIs like /user/1 as well as user/2 and so on. I ended up using a Principal in the controller methods and started checking the id of the Principal with the id the user is trying to access.

Further, the user has multiple resources associated with it. Say, user1 owns res1 and res2, user2 owns res3 and res4. These can be accessed via /user/1/res/2. I need a way where I can prevent /user/1/res/3 as res3 is owned by user1 and not user2.

But I believe that this problem is very common and I am not really convinced with my solution.

Is there a better way to deal with this problem?

Thanks

答:
This is a common problem with varied solutions. Also its not a problem related to REST alone. We have had this ever since apps exist. Employee can see his salary slip, leave records, etc but not another employee's.
One solution I like the most is 'security in depth'. This idea comes from how I have seen this work in banking systems for decades. This needs to get supported in the DB layer first.
You would need a table design like this example (or whatever your app's entity hierarchical structure is):

```<code>Organisation
-Dept
--user
</code>```

And all non-master tables need to have a relation to one of these entities. Example:

```<code>Payslip -> user
Leave record -> user
Manager -> dept
HR Manager -> org
</code>```

etc...

You would need another table to map out the basic access levels (This can get complex if we need to implement different sub access levels)

```<code>user1:dept2:org1
user2:dept2:org1
</code>```

(I have seen some implementations that send this table's info as part of an encrypted access token that is used on every access request if the access has to be sessionless.)

You have not mentioned a framework/language but most languages have a database layer. For example if the DB layer is hibernate-java. There are interceptors (https://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/Interceptor.html#onPrepareStatement(java.lang.String)) that can be used to modify the query thats being executed.
Every query to DB will go with additional where-clause for these relationship keys.
We can get clever with Spring AOP, REST interceptors and a lot of other techniques on top of this basic architecture to enforce this security.
Idea will be that DB layer does not return data thats not accessible to the logged in user principal irrespective of what queries higher layer code uses.
if this is in place, a REST GET call for

/payslip/user1/Jan-2017

will end up with a 404 and not a 403.
Expecting this to be solved by a framework or a superficial set of interceptors is both risky and not future proof. We end up continuously tweaking the interceptors as the url patterns evolve.

Addition to show table examples:

```<code>ACL table
user, uid, dept, org
--------------------
jhon, 1  , 1   , 1
mary, 2  , 2   , 1
will, 3  , 2   , 1

Payslip table
--------------
month, net, deductions,..., uid
-------------------------------------
Jan  , 200, 15.5      ,..., 3
Feb  , 200, 15.5      ,..., 3

Project table
-------------
pname, pstart, pbudget, dept
------------------------------------
mark1, 12/21 , 20000  , 2
markx, 12/31 , 40000  , 2
</code>```

Body:
This is a common problem with varied solutions. Also its not a problem related to REST alone. We have had this ever since apps exist. Employee can see his salary slip, leave records, etc but not another employee's.
One solution I like the most is 'security in depth'. This idea comes from how I have seen this work in banking systems for decades. This needs to get supported in the DB layer first.
You would need a table design like this example (or whatever your app's entity hierarchical structure is):

Organisation
-Dept
--user

And all non-master tables need to have a relation to one of these entities. Example:

Payslip -> user
Leave record -> user
Manager -> dept
HR Manager -> org

etc...

You would need another table to map out the basic access levels (This can get complex if we need to implement different sub access levels)

user1:dept2:org1
user2:dept2:org1

(I have seen some implementations that send this table's info as part of an encrypted access token that is used on every access request if the access has to be sessionless.)

You have not mentioned a framework/language but most languages have a database layer. For example if the DB layer is hibernate-java. There are interceptors (https://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/Interceptor.html#onPrepareStatement(java.lang.String)) that can be used to modify the query thats being executed.
Every query to DB will go with additional where-clause for these relationship keys.
We can get clever with Spring AOP, REST interceptors and a lot of other techniques on top of this basic architecture to enforce this security.
Idea will be that DB layer does not return data thats not accessible to the logged in user principal irrespective of what queries higher layer code uses.
if this is in place, a REST GET call for

/payslip/user1/Jan-2017

will end up with a 404 and not a 403.
Expecting this to be solved by a framework or a superficial set of interceptors is both risky and not future proof. We end up continuously tweaking the interceptors as the url patterns evolve.

Addition to show table examples:

ACL table
user, uid, dept, org
--------------------
jhon, 1  , 1   , 1
mary, 2  , 2   , 1
will, 3  , 2   , 1

Payslip table
--------------
month, net, deductions,..., uid
-------------------------------------
Jan  , 200, 15.5      ,..., 3
Feb  , 200, 15.5      ,..., 3

Project table
-------------
pname, pstart, pbudget, dept
------------------------------------
mark1, 12/21 , 20000  , 2
markx, 12/31 , 40000  , 2


问:
DBCC CHECKIDENT Sets Identity to 0
I'm using this code to reset the identity on a table:

```<code>DBCC CHECKIDENT('TableName', RESEED, 0)
</code>```

This works fine most of the time, with the first insert I do inserting 1 into the Id column. However, if I drop the DB and recreate it (using scripts I've written) and then call DBCC CHECKIDENT, the first item inserted will have an ID of 0.

Any ideas?

EDIT: After researching I found out I didn't read the documentation properly - "The current identity value is set to the new_reseed_value. If no rows have been inserted to the table since it was created, the first row inserted after executing DBCC CHECKIDENT will use new_reseed_value as the identity. Otherwise, the next row inserted will use new_reseed_value + 1. "

答:
Change statement to </p>

```<code>  DBCC CHECKIDENT('TableName', RESEED, 1)
</code>```

<p>This will start from 2 (or 1 when you recreate table), but it will never be 0. </p>

ContentLicense: CC BY-SA 4.0

Title: DBCC CHECKIDENT Sets Identity to 0

Body:
I'm using this code to reset the identity on a table:

DBCC CHECKIDENT('TableName', RESEED, 0)

This works fine most of the time, with the first insert I do inserting 1 into the Id column. However, if I drop the DB and recreate it (using scripts I've written) and then call DBCC CHECKIDENT, the first item inserted will have an ID of 0.

Any ideas?

EDIT: After researching I found out I didn't read the documentation properly - "The current identity value is set to the new_reseed_value. If no rows have been inserted to the table since it was created, the first row inserted after executing DBCC CHECKIDENT will use new_reseed_value as the identity. Otherwise, the next row inserted will use new_reseed_value + 1. "

Body:
Change statement to

  DBCC CHECKIDENT('TableName', RESEED, 1)

This will start from 2 (or 1 when you recreate table), but it will never be 0.

OwnerDisplayName: dmajkic


问:
How can I get TFS2010 to run MSDEPLOY for me through MSBUILD?
There is an excellent PDC talk available here from Vishal Joshi which describes the new MSDEPLOY features in Visual Studio 2010 - as well as how to deploy an application within TFS. (There's also a great talk from Scott Hanselman but he doesn't go into TFS).

You can use MSBUILD within TFS2010 to call through to MSDEPLOY to deploy your package to IIS. This is done by means of parameters to MSBUILD.

The talk explains some of the command line parameters such as :

```<code>/p:DeployOnBuild
/p:DeployTarget=MsDeployPublish
/p:CreatePackageOnPublish=True
/p:MSDeployPublishMethod=InProc
/p:MSDeployServiceURL=localhost
/p:DeployIISAppPath="Default Web Site"
</code>```

But where is the documentation for this - I can't find any?

I've been spending all day trying to get this to work and can't quite get it right and keep ending up with various errors. If I run the package's cmd file it deploys perfectly. If I run WebDeploy through Visual Studio it also works perfectly.

But I want to get the whole deployment running through msbuild using these arguments and not a separate call to msdeploy or running the package .cmd file. How can I do this?

PS. Yes I do have the Web Deployment Agent Service running. I also have the management service running under IIS. I've tried using both.

Args I'm using :

```<code>/p:DeployOnBuild=True
/p:DeployTarget=MsDeployPublish
/p:Configuration=Release
/p:CreatePackageOnPublish=True
/p:DeployIisAppPath=staging.example.com
/p:MsDeployServiceUrl=https://staging.example.com:8172/msdeploy.axd
/p:AllowUntrustedCertificate=True
</code>```

giving me :

C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.targets (2660): VsMsdeploy failed.(Remote agent (URL https://staging.example.com:8172/msdeploy.axd?site=staging.example.com) could not be contacted.  Make sure the remote agent service is installed and started on the target computer.) Error detail: Remote agent (URL https://staging.example.com:8172/msdeploy.axd?site=staging.example.com) could not be contacted.  Make sure the remote agent service is installed and started on the target computer. An unsupported response was received. The response header 'MSDeploy.Response' was '' but 'v1' was expected. The remote server returned an error: (401) Unauthorized.

答:
For me the problem was that Web Deployment Agent Service was not started.

A simple net start msdepsvc fixed it. You could also set startup mode to Automatic on this service.

The arguments I'm using are:

```<code>/p:DeployOnBuild=True
/p:DeployTarget=MsDeployPublish
/p:MSDeployPublishMethod=RemoteAgent
/p:MSDeployServiceUrl=stagingserver
/p:DeployIisAppPath=test.local
/p:UserName=
</code>```

You only need to specify the server name, and not the full path (no http needed).

Note that UserName is left empty to work around a bug with NTLM authentication (this way it uses the credentials of the TFS build agent for the deployment). see the accepted answer here

Body:
There is an excellent PDC talk available here from Vishal Joshi which describes the new MSDEPLOY features in Visual Studio 2010 - as well as how to deploy an application within TFS. (There's also a great talk from Scott Hanselman but he doesn't go into TFS).

You can use MSBUILD within TFS2010 to call through to MSDEPLOY to deploy your package to IIS. This is done by means of parameters to MSBUILD.

The talk explains some of the command line parameters such as :

/p:DeployOnBuild
/p:DeployTarget=MsDeployPublish
/p:CreatePackageOnPublish=True
/p:MSDeployPublishMethod=InProc
/p:MSDeployServiceURL=localhost
/p:DeployIISAppPath="Default Web Site"

But where is the documentation for this - I can't find any?

I've been spending all day trying to get this to work and can't quite get it right and keep ending up with various errors. If I run the package's cmd file it deploys perfectly. If I run WebDeploy through Visual Studio it also works perfectly.

But I want to get the whole deployment running through msbuild using these arguments and not a separate call to msdeploy or running the package .cmd file. How can I do this?

PS. Yes I do have the Web Deployment Agent Service running. I also have the management service running under IIS. I've tried using both.

Args I'm using :

/p:DeployOnBuild=True
/p:DeployTarget=MsDeployPublish
/p:Configuration=Release
/p:CreatePackageOnPublish=True
/p:DeployIisAppPath=staging.example.com
/p:MsDeployServiceUrl=https://staging.example.com:8172/msdeploy.axd
/p:AllowUntrustedCertificate=True

giving me :

C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.targets (2660): VsMsdeploy failed.(Remote agent (URL https://staging.example.com:8172/msdeploy.axd?site=staging.example.com) could not be contacted.  Make sure the remote agent service is installed and started on the target computer.) Error detail: Remote agent (URL https://staging.example.com:8172/msdeploy.axd?site=staging.example.com) could not be contacted.  Make sure the remote agent service is installed and started on the target computer. An unsupported response was received. The response header 'MSDeploy.Response' was '' but 'v1' was expected. The remote server returned an error: (401) Unauthorized.

Body:
For me the problem was that Web Deployment Agent Service was not started.

A simple net start msdepsvc fixed it. You could also set startup mode to Automatic on this service.

The arguments I'm using are:

/p:DeployOnBuild=True
/p:DeployTarget=MsDeployPublish
/p:MSDeployPublishMethod=RemoteAgent
/p:MSDeployServiceUrl=stagingserver
/p:DeployIisAppPath=test.local
/p:UserName=

You only need to specify the server name, and not the full path (no http needed).

Note that UserName is left empty to work around a bug with NTLM authentication (this way it uses the credentials of the TFS build agent for the deployment). see the accepted answer here


问:
JSON Array request cannot be applied error listener
I am newbie at Android programming, I have used Google Volley library for calling API and now I have some problem in my Android code. There is JSON error occurred
 here

HERE MY CODE :

```<code>private void loadJson()
    {
        pd.setMessage("Mengambil Data");
        pd.setCancelable(false);
        pd.show();

        JsonArrayRequest reqData = new JsonArrayRequest(Request.Method.POST, ServerAPI.URL_DATA,null,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        pd.cancel();
                        Log.d("volley","response : " + response.toString());
                        for(int i = 0 ; i < response.length(); i++)
                        {
                            try {
                                JSONObject data = response.getJSONObject(i);
                                ModelData md = new ModelData();
                                md.setNpm(data.getString("npm"));
                                md.setNama(data.getString("nama"));
                                md.setProdi(data.getString("prodi"));
                                md.setFakultas(data.getString("fakultas"));
                                mItems.add(md);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        mAdapter.notifyDataSetChanged();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        pd.cancel();
                        Log.d("volley", "error : " + error.getMessage());
                    }
                });

        AppController.getInstance().addToRequestQueue(reqData);
    }
</code>```

答:
The arguments are wrong in your JsonArrayRequest (you have to pass a String for the URL).
Try something like this :</p>

```<code>private void loadJson()
{
    pd.setMessage("Mengambil Data");
    pd.setCancelable(false);
    pd.show();

    JsonArrayRequest reqData = new JsonArrayRequest(ServerAPI.URL_DATA,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    pd.cancel();
                    Log.d("volley","response : " + response.toString());
                    for(int i = 0 ; i < response.length(); i++)
                    {
                        try {
                            JSONObject data = response.getJSONObject(i);
                            ModelData md = new ModelData();
                            md.setNpm(data.getString("npm"));
                            md.setNama(data.getString("nama"));
                            md.setProdi(data.getString("prodi"));
                            md.setFakultas(data.getString("fakultas"));
                            mItems.add(md);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    mAdapter.notifyDataSetChanged();
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    pd.cancel();
                    Log.d("volley", "error : " + error.getMessage());
                }
            });

    AppController.getInstance().addToRequestQueue(reqData);
}
</code>```

Body:
I am newbie at Android programming, I have used Google Volley library for calling API and now I have some problem in my Android code. There is JSON error occurred
 here

HERE MY CODE :

private void loadJson()
    {
        pd.setMessage("Mengambil Data");
        pd.setCancelable(false);
        pd.show();

        JsonArrayRequest reqData = new JsonArrayRequest(Request.Method.POST, ServerAPI.URL_DATA,null,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        pd.cancel();
                        Log.d("volley","response : " + response.toString());
                        for(int i = 0 ; i < response.length(); i++)
                        {
                            try {
                                JSONObject data = response.getJSONObject(i);
                                ModelData md = new ModelData();
                                md.setNpm(data.getString("npm"));
                                md.setNama(data.getString("nama"));
                                md.setProdi(data.getString("prodi"));
                                md.setFakultas(data.getString("fakultas"));
                                mItems.add(md);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                        mAdapter.notifyDataSetChanged();
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        pd.cancel();
                        Log.d("volley", "error : " + error.getMessage());
                    }
                });

        AppController.getInstance().addToRequestQueue(reqData);
    }

Body:
The arguments are wrong in your JsonArrayRequest (you have to pass a String for the URL).
Try something like this :

private void loadJson()
{
    pd.setMessage("Mengambil Data");
    pd.setCancelable(false);
    pd.show();

    JsonArrayRequest reqData = new JsonArrayRequest(ServerAPI.URL_DATA,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    pd.cancel();
                    Log.d("volley","response : " + response.toString());
                    for(int i = 0 ; i < response.length(); i++)
                    {
                        try {
                            JSONObject data = response.getJSONObject(i);
                            ModelData md = new ModelData();
                            md.setNpm(data.getString("npm"));
                            md.setNama(data.getString("nama"));
                            md.setProdi(data.getString("prodi"));
                            md.setFakultas(data.getString("fakultas"));
                            mItems.add(md);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    mAdapter.notifyDataSetChanged();
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    pd.cancel();
                    Log.d("volley", "error : " + error.getMessage());
                }
            });

    AppController.getInstance().addToRequestQueue(reqData);
}


问:
yahoo finance stock price NSE,BSE rest-api
Am trying to create a program that fetches data from yahoo finance all stock data.
I found one rest API that gives me a stock price but I have to pass two parameters ex. if I have to get Apple stock price I have to pass Apple and stock name but I want all stock data so how do I get ?? </p>

<p>can anyone help me thanks in advance </p>

答:
Unfortunately there isn't any official source of tickers or method of getting them.

You can use this script link to download tickers but as creator mentioned:

it is not possible to get all the symbols due to limitations set by
  Yahoo. About 75%-90% of all symbols are gathered using this script
  depending on type.

And it also downloads some no longer existing or inaccessible tickers.

From this site link you can download list of almost all tickers but about 30% of tickers are either in wrong category or aren't working. Checking whether ticker exists is easy because when API returns no data then we can deduce that ticker is incorrect. But checking if category is appropriate is a bit more complicated.

I've filtered tickers from the second site but only ETFs and Mutual Funds, you can find them on my GitHub. Those files contain about 99% of ETFs and Mututal Funds avaiable on Yahoo. I might consider filtering stocks later and then I'll upload them with script too. Be aware that filtering tickers is impossible on one run without for example VPN because Yahoo limits request to about 10k-20k per day and there are about 20k tickers per category and checking each ticker requires 2 requests.

Body:
Am trying to create a program that fetches data from yahoo finance all stock data.
I found one rest API that gives me a stock price but I have to pass two parameters ex. if I have to get Apple stock price I have to pass Apple and stock name but I want all stock data so how do I get ??

can anyone help me thanks in advance


问:
React native app stuck on splash screen on device but works in simulator
My React Native app works in the XCode simulator with no issues, but when I run in a physical device, my iPhone, there's a problem. The app launches and gets stuck on the React Native splash screen, the after 10-15 seconds the app crashes/closes. What's the cause of this and how can I prevent it? </p>

答:
I was having the same issue.

What I did was in Xcode go to Products -> Scheme -> Edit Scheme -> Select the Run tab -> Change the build configuration to Release ( default it was debug mode ) and run the app in the device.

It was much faster and run it as like a native app.


问:
Using both AND, OR in If condition Javascript
Similar questions haven't justified my actual question.
I have a If condition where if it satisfies 2 conditions it should set value as A else B. Below is the code block describing my question

```<code>if(($form[0].lang.value==SPN||PTB||GRM) && ("1" == "<awi:script script='IsTranslationON'/>"))
    {
    $form[0].$rtag.value = "Test"+$form[0].lang.value+"_"+$form[1].take1.value+"_SUPPORT_Translation";
     }
    else
      {$form[0].$rtag.value = "Test"+$form[0].lang.value+"_"+$form[1].take1.value+"_SUPPORT";}
 //Submit form
      submit=false;
      if(submit){$form[0].submit()}else{alert($form[0].$rtag.value)}
</code>```

Issue is - evrytime it gets deiplayed only statement from If condition. It is not checking value with $lang.value
Does any of the mates help me checking my if condition please.
EDIT- The value I am getting in alert box is "Test_IND_GENERAL_SUPPORT_Translation".

答:
This is comparision I am doing and " " are must.Every suggestion here helped me to dig in.
I am in intermediate stage yet.</p>

```<code>(($form[0].lang.value=="SPN"||$form[0].lang.value=="PTB"||$form[0].lang.value=="GRM")
</code>```

Body:
Similar questions haven't justified my actual question.
I have a If condition where if it satisfies 2 conditions it should set value as A else B. Below is the code block describing my question

if(($form[0].lang.value==SPN||PTB||GRM) && ("1" == "<awi:script script='IsTranslationON'/>"))
    {
    $form[0].$rtag.value = "Test"+$form[0].lang.value+"_"+$form[1].take1.value+"_SUPPORT_Translation";
     }
    else
      {$form[0].$rtag.value = "Test"+$form[0].lang.value+"_"+$form[1].take1.value+"_SUPPORT";}
 //Submit form
      submit=false;
      if(submit){$form[0].submit()}else{alert($form[0].$rtag.value)}

Issue is - evrytime it gets deiplayed only statement from If condition. It is not checking value with $lang.value
Does any of the mates help me checking my if condition please.
EDIT- The value I am getting in alert box is "Test_IND_GENERAL_SUPPORT_Translation".

Body:
This is comparision I am doing and " " are must.Every suggestion here helped me to dig in.
I am in intermediate stage yet.

(($form[0].lang.value=="SPN"||$form[0].lang.value=="PTB"||$form[0].lang.value=="GRM")


问:
Linux command to split each lines in a file based on a character and write only the specified columns to another file
Suppose the input file file.txt is  </p>

```<code>abc/def/ghi/jkl/mno
pqr/st/u/vwxy/z
bla/123/45678/9
</code>```

<p>How to split the lines based on the character '/' and write the specified columns (here it is second and fourth) to another file so that the file should look like  </p>

```<code>def jkl
st  vwxy
123  9
</code>```

答:
You can use perl, for example:

```<code>cat file.txt | perl -ne 'chomp(@cols = split("/", $_)); print "@cols[1, 3]\n";' > output
</code>```

Body:
Suppose the input file file.txt is

abc/def/ghi/jkl/mno
pqr/st/u/vwxy/z
bla/123/45678/9

How to split the lines based on the character '/' and write the specified columns (here it is second and fourth) to another file so that the file should look like

def jkl
st  vwxy
123  9

Body:
You can use perl, for example:

cat file.txt | perl -ne 'chomp(@cols = split("/", $_)); print "@cols[1, 3]\n";' > output


问:
How to display name onmouseover in a marker : Google Map API
I have added multiple marker in my google map using google map library.It's working properly but my issue is that, i want to display a name onmouseover of a marker.And i have tried like this.

Code:

```<code>    $config['zoom'] = 'auto';
    $this->googlemaps->initialize($config);
    $i = 0;
    while($i < $rs){
    $marker = array();
    $marker['position'] = $data['tunnelsname'][$i]->name;
    $marker['onmouseover'] = 'hii';
    $x = $data['tunnelsname'][$i]->name;
    $name = strtolower(str_replace(' ','-',$data['tunnelsname'][$i]->name));
    $id = $data['tunnelsname'][$i]->id;
    $marker['infowindow_content'] = '<a href = "'.BASEURL.'tunnel/'.$name.'/'.$id.'">'.$x.'</a>';
    $marker['clickable'] = TRUE;
    $this->googlemaps->add_marker($marker);
    $i++;
    }
    $data['map'] = $this->googlemaps->create_map();
</code>```

I am trying to display hii onmouseover on each marker.But unable to get a desirable result.Please help me to get this.

Any help will be appreciated. Thanks in advance.

答:
I believe user interaction such as "mouseover" are much easier to implement using client-side implementation. Check When to use client-side geocoding and When to use server-side geocoding.

Sample code:

```<code>marker.addListener('mouseover', function() {
    infoWindow.setContent('<p>hii</p>');
    infowindow.open(map, this);
});

// assuming you also want to hide the infowindow when user mouses-out
marker.addListener('mouseout', function() {
    infowindow.close();
});
</code>```

Check Maps JavaScript API
 Events for more info.

Body:
I have added multiple marker in my google map using google map library.It's working properly but my issue is that, i want to display a name onmouseover of a marker.And i have tried like this.

Code:

    $config['zoom'] = 'auto';
    $this->googlemaps->initialize($config);
    $i = 0;
    while($i < $rs){
    $marker = array();
    $marker['position'] = $data['tunnelsname'][$i]->name;
    $marker['onmouseover'] = 'hii';
    $x = $data['tunnelsname'][$i]->name;
    $name = strtolower(str_replace(' ','-',$data['tunnelsname'][$i]->name));
    $id = $data['tunnelsname'][$i]->id;
    $marker['infowindow_content'] = ''.$x.'';
    $marker['clickable'] = TRUE;
    $this->googlemaps->add_marker($marker);
    $i++;
    }
    $data['map'] = $this->googlemaps->create_map();

I am trying to display hii onmouseover on each marker.But unable to get a desirable result.Please help me to get this.

Any help will be appreciated. Thanks in advance.

Body:
I believe user interaction such as "mouseover" are much easier to implement using client-side implementation. Check When to use client-side geocoding and When to use server-side geocoding.

Sample code:

marker.addListener('mouseover', function() {
    infoWindow.setContent('<p>hii</p>');
    infowindow.open(map, this);
});

// assuming you also want to hide the infowindow when user mouses-out
marker.addListener('mouseout', function() {
    infowindow.close();
});

Check Maps JavaScript API
 Events for more info.


问:
Dependency Injection in Azure WebJobs SDK when using NoAutomaticTrigger?
I am building an Azure WebJob that will run continuously. I want the WebJob to use the same style of DI as ASP.NET Core. I found this answer (Dependency injection using Azure WebJobs SDK?) on how to get DI/IoC working by using a custom IJobActivator. I also found this answer (Azure WebJobs - No functions found - How do I make a trigger-less job?) on using NoAutomaticTrigger to configure a continuously running Web Job.

The problem is that the NoAutomaticTrigger approach uses static methods, which is not compatible with DI/IoC. I assume that is because there is nothing that would cause the service with the NoAutomaticTrigger method to get resolved (like a queue message). I feel like ITypeLocator might be a path forward, but that is just a hunch.

The JobHost.Call method used in other NoAutomaticTrigger examples is limited to a static method. How do I have a service that is resolved via DI that gets resolved and called from a call on JobHost (or some other method) in Program.cs?

The solution that Iza Eddi-son Atsou suggested below works, with one wrinkle. I am used to registering my services via an interface on the service. Something like

```<code>serviceCollection.AddSingleton<IApplication, Application>();
</code>```

The problem with this is that if the NoAutomaticTrigger attribute is on the interface, the SDK blows up. The solution is to add the attribute to the class, and register the class as itself.

```<code>serviceCollection.AddSingleton<Application>();
</code>```

Once that change is made, the solution in the answer works great.

答:
The WebJobs SDK now supports instance methods to be triggered instead of only static methods. The NoAutomaticTrigger method don't need to be static anymore. Update the SDK, use the custom IJobActivator approach you found and remember to register you Functions class and of course your other dependencies.

Example Program class:

```<code>class Program
{

    static void Main()
    {
        var container = new UnityContainer();

        //the instance to be injected
        var systemClient = new JobSystemClient
        {
            UserName = "admin",
            PassWord = "admin1234"
        };

        container.RegisterInstance<ISystemClient>(systemClient);

        //Registration of the Functions class
        container.RegisterType<Functions>();

        var activator = new UnityJobActivator(container);

        var config = new JobHostConfiguration();
        config.JobActivator = activator;

        var host = new JobHost(config);
        // The following code will invoke a function called ManualTrigger and
        // pass in data (value in this case) to the function
        host.Call(typeof(Functions).GetMethod("ManualTrigger"), new { value = 20 });

        host.RunAndBlock();

    }
}
</code>```

sample Function class:

```<code>public class Functions
{
    private readonly ISystemClient _systemClient;
    public Functions(ISystemClient systemClient)
    {
        _systemClient = systemClient;
    }

    //Not static anymore
    [NoAutomaticTrigger]
    public void ManualTrigger(TextWriter log, int value, [Queue("queue")] out string message)
    {
        log.WriteLine("Function is invoked with value={0}", value);
        message = value.ToString();
        log.WriteLine("username:{0} and password:{1}", _systemClient.UserName, _systemClient.PassWord);
    }
}
</code>```

and here is the output:

```<code>Found the following functions:
TestWebJob.Functions.ManualTrigger
Executing 'Functions.ManualTrigger' (Reason='This function was programmatically called via the host APIs.', Id=bf9aedc0-89d1-4ba0-a33e-9b23e0d7b8a2)
Function is invoked with value=20
Following message will be written on the Queue=20
username:admin and password:admin1234
Executed 'Functions.ManualTrigger' (Succeeded, Id=bf9aedc0-89d1-4ba0-a33e-9b23e0d7b8a2)
Job host started
</code>```

Body:
I am building an Azure WebJob that will run continuously. I want the WebJob to use the same style of DI as ASP.NET Core. I found this answer (Dependency injection using Azure WebJobs SDK?) on how to get DI/IoC working by using a custom IJobActivator. I also found this answer (Azure WebJobs - No functions found - How do I make a trigger-less job?) on using NoAutomaticTrigger to configure a continuously running Web Job.

The problem is that the NoAutomaticTrigger approach uses static methods, which is not compatible with DI/IoC. I assume that is because there is nothing that would cause the service with the NoAutomaticTrigger method to get resolved (like a queue message). I feel like ITypeLocator might be a path forward, but that is just a hunch.

The JobHost.Call method used in other NoAutomaticTrigger examples is limited to a static method. How do I have a service that is resolved via DI that gets resolved and called from a call on JobHost (or some other method) in Program.cs?

The solution that Iza Eddi-son Atsou suggested below works, with one wrinkle. I am used to registering my services via an interface on the service. Something like

serviceCollection.AddSingleton<IApplication, Application>();

The problem with this is that if the NoAutomaticTrigger attribute is on the interface, the SDK blows up. The solution is to add the attribute to the class, and register the class as itself.

serviceCollection.AddSingleton<Application>();

Once that change is made, the solution in the answer works great.

Body:
The WebJobs SDK now supports instance methods to be triggered instead of only static methods. The NoAutomaticTrigger method don't need to be static anymore. Update the SDK, use the custom IJobActivator approach you found and remember to register you Functions class and of course your other dependencies.

Example Program class:

class Program
{

    static void Main()
    {
        var container = new UnityContainer();

        //the instance to be injected
        var systemClient = new JobSystemClient
        {
            UserName = "admin",
            PassWord = "admin1234"
        };

        container.RegisterInstance<ISystemClient>(systemClient);

        //Registration of the Functions class
        container.RegisterType<Functions>();

        var activator = new UnityJobActivator(container);

        var config = new JobHostConfiguration();
        config.JobActivator = activator;

        var host = new JobHost(config);
        // The following code will invoke a function called ManualTrigger and
        // pass in data (value in this case) to the function
        host.Call(typeof(Functions).GetMethod("ManualTrigger"), new { value = 20 });

        host.RunAndBlock();

    }
}

sample Function class:

public class Functions
{
    private readonly ISystemClient _systemClient;
    public Functions(ISystemClient systemClient)
    {
        _systemClient = systemClient;
    }

    //Not static anymore
    [NoAutomaticTrigger]
    public void ManualTrigger(TextWriter log, int value, [Queue("queue")] out string message)
    {
        log.WriteLine("Function is invoked with value={0}", value);
        message = value.ToString();
        log.WriteLine("username:{0} and password:{1}", _systemClient.UserName, _systemClient.PassWord);
    }
}

and here is the output:

Found the following functions:
TestWebJob.Functions.ManualTrigger
Executing 'Functions.ManualTrigger' (Reason='This function was programmatically called via the host APIs.', Id=bf9aedc0-89d1-4ba0-a33e-9b23e0d7b8a2)
Function is invoked with value=20
Following message will be written on the Queue=20
username:admin and password:admin1234
Executed 'Functions.ManualTrigger' (Succeeded, Id=bf9aedc0-89d1-4ba0-a33e-9b23e0d7b8a2)
Job host started


问:
DDL scripts in a transaction block takes effect even when there are errors
I have some sql script files where i am making some DDL changes as part of commit block

```<code>BEGIN TRANSACTION

-- CREATE/ALTER TABLE, COLUMNS, CONTRAINTS etc etc
COMMIT
</code>```

Sometime when script fail, i still see the changes in DDL applied in database although this whole thing is in transaction block. What am I missing here?

答:
Just because a particular statement causes an error, that doesn't mean that other statements won't also execute. Look at the documentation for XACT_ABORT:

In the first set of statements, the error is generated, but the other statements execute successfully and the transaction is successfully committed

If you want to rollback a transaction when an error occurs, you need to enclose your code in a TRY...CATCH block (or older style, check @@ERROR after ever statement, and goto a label where a ROLLBACK will occur).

Body:
I have some sql script files where i am making some DDL changes as part of commit block

BEGIN TRANSACTION

-- CREATE/ALTER TABLE, COLUMNS, CONTRAINTS etc etc
COMMIT

Sometime when script fail, i still see the changes in DDL applied in database although this whole thing is in transaction block. What am I missing here?


问:
Differentiate session timeout in codeigniter
Is is possible to have two user data to have different timeout/expiry time? Let say first data "param_1" expired in 1 day and "param_2" expired in a month. How to do that with CI session library. Something that might be like this</p>

```<code>$this->session->set_userdata('param_1', 86400);  // seconds in a day
$this->session->set_userdata('param_2', 2592000); // seconds in a month
</code>```

答:
This is possible via "Tempdata":

```<code>$this->session->tempdata($key, $value, $validForTime);
</code>```

However, a single session should not last more than a few hours to maybe a day. If you want some variable to persist for longer than that, sessions are absolutely the wrong tool to use for that.

Body:
Is is possible to have two user data to have different timeout/expiry time? Let say first data "param_1" expired in 1 day and "param_2" expired in a month. How to do that with CI session library. Something that might be like this

$this->session->set_userdata('param_1', 86400);  // seconds in a day
$this->session->set_userdata('param_2', 2592000); // seconds in a month

Body:
This is possible via "Tempdata":

$this->session->tempdata($key, $value, $validForTime);

However, a single session should not last more than a few hours to maybe a day. If you want some variable to persist for longer than that, sessions are absolutely the wrong tool to use for that.


问:
Can't extract data from Json
I can't extract data from json that I got from an api.
I tried for hours, tried all kinds of formats. Read Stackoverflow threads like How do I extract data from JSON with PHP?, but I can't see what I am doing wrong.

This is the code so far:

```<code>$api_results = '{"status":"0000","data":{"opening_price":"6998000","closing_price":"7270000","min_price":"6750000","max_price":"7997000","average_price":"7188302.5804","units_traded":"78484.9241002","volume_1day":"78484.9241002","volume_7day":"335611.84181738","buy_price":"7268000","sell_price":"7274000","date":"1510563513031"}}';

$results = json_decode($api_results, true);

// Some variations I tried:
var_dump($results->status[1]);
var_dump($results->data[1]->opening_price);
var_dump($results["data"][1]["opening_price"]);
</code>```

End result: NULL NULL NULL

What am I doing wrong?

Thanks for the answers! I will upvote the working ones. Seems I got confused in the formating!

答:
```<code><?php

$api_results = '{"status":"0000","data":{"opening_price":"6998000","closing_price":"7270000","min_price":"6750000","max_price":"7997000","average_price":"7188302.5804","units_traded":"78484.9241002","volume_1day":"78484.9241002","volume_7day":"335611.84181738","buy_price":"7268000","sell_price":"7274000","date":"1510563513031"}}';

$results = json_decode($api_results, true);
print_r($results['status']);
echo "</br>";
print_r($results['data']['opening_price']);
</code>```

Try access your array that way.

The output is :

```<code>0000
6998000
</code>```

Keep an eye for the nested arrays. You need to access their parent array first in order to get their values.

Title: Can't extract data from Json

Body:
I can't extract data from json that I got from an api.
I tried for hours, tried all kinds of formats. Read Stackoverflow threads like How do I extract data from JSON with PHP?, but I can't see what I am doing wrong.

This is the code so far:

$api_results = '{"status":"0000","data":{"opening_price":"6998000","closing_price":"7270000","min_price":"6750000","max_price":"7997000","average_price":"7188302.5804","units_traded":"78484.9241002","volume_1day":"78484.9241002","volume_7day":"335611.84181738","buy_price":"7268000","sell_price":"7274000","date":"1510563513031"}}';

$results = json_decode($api_results, true);

// Some variations I tried:
var_dump($results->status[1]);
var_dump($results->data[1]->opening_price);
var_dump($results["data"][1]["opening_price"]);

End result: NULL NULL NULL

What am I doing wrong?

Thanks for the answers! I will upvote the working ones. Seems I got confused in the formating!

Body:
<?php

$api_results = '{"status":"0000","data":{"opening_price":"6998000","closing_price":"7270000","min_price":"6750000","max_price":"7997000","average_price":"7188302.5804","units_traded":"78484.9241002","volume_1day":"78484.9241002","volume_7day":"335611.84181738","buy_price":"7268000","sell_price":"7274000","date":"1510563513031"}}';

$results = json_decode($api_results, true);
print_r($results['status']);
echo "</br>";
print_r($results['data']['opening_price']);

Try access your array that way.

The output is :

0000
6998000

Keep an eye for the nested arrays. You need to access their parent array first in order to get their values.


问:
Assigning a number to a name without enumerating and printing a name based on that number
What I am trying to do is using n as the number of characters in list "Roles", print out the number n and the role next to it. Is there a way I can later, depending on the number I ask for, get a character that is "assigned"  to that number. I tried using enumerate, but I wasn't able to call the enumerated roles later with if/while/for or if I wanted to print them. I also tried using dictionary but you can't use append for dictionary. If it's possible to call the enumerated Roles, I would like to know how I can do that, if not I go back to my original question. Here's the code I'm using:

```<code>import random
Roles = ["One", "Two", "Three", "Four"]
SheriffList = []
Alive = []
for n in range(0, len(Roles)):
    random.shuffle(Roles)
    Role = random.choice(Roles)
    Alive.append(Roles.pop(Roles.index(Role)))
    Role2 = n,Role
    print(Role2)
    SheriffList.append(Role2)
    n += 1
    if n == len(Roles):
        random.shuffle(Alive)
        random.choice(Alive)

print(SheriffList)
   [(0, 'One'), (1, 'Four'), (2, 'Three'), (3, 'Two')]
k = int(input("Choose a number:"))
</code>```

Now I want k (The number I choose), to be able to print me back the role that was assigned to it For example if I assign 1 to "k", it will send me 'Four'. I'm sorry if the question was already asked before, I just wasn't able to find what I needed.

答:
You actually don't need to do much, you could just keep a list. If you want 'One' to be at index 1, you could append a None:

```<code>>>> Roles = [None, "One", "Two", "Three", "Four"]
>>> Roles[2]
'Two'
>>> Roles[3]
'Three'
</code>```

You could shuffle the list before appending None:

```<code>>>> roles = ["One", "Two", "Three", "Four"]
>>> random.shuffle(roles)
>>> roles
['Three', 'Four', 'Two', 'One']
>>> roles = [None] + roles
>>> roles[3]
'Two'
>>> roles[2]
'Four'
>>> roles[1]
'Three'
>>> roles[4]
'One'
</code>```

Body:
What I am trying to do is using n as the number of characters in list "Roles", print out the number n and the role next to it. Is there a way I can later, depending on the number I ask for, get a character that is "assigned"  to that number. I tried using enumerate, but I wasn't able to call the enumerated roles later with if/while/for or if I wanted to print them. I also tried using dictionary but you can't use append for dictionary. If it's possible to call the enumerated Roles, I would like to know how I can do that, if not I go back to my original question. Here's the code I'm using:

import random
Roles = ["One", "Two", "Three", "Four"]
SheriffList = []
Alive = []
for n in range(0, len(Roles)):
    random.shuffle(Roles)
    Role = random.choice(Roles)
    Alive.append(Roles.pop(Roles.index(Role)))
    Role2 = n,Role
    print(Role2)
    SheriffList.append(Role2)
    n += 1
    if n == len(Roles):
        random.shuffle(Alive)
        random.choice(Alive)

print(SheriffList)
   [(0, 'One'), (1, 'Four'), (2, 'Three'), (3, 'Two')]
k = int(input("Choose a number:"))

Now I want k (The number I choose), to be able to print me back the role that was assigned to it For example if I assign 1 to "k", it will send me 'Four'. I'm sorry if the question was already asked before, I just wasn't able to find what I needed.

Body:
You actually don't need to do much, you could just keep a list. If you want 'One' to be at index 1, you could append a None:

>>> Roles = [None, "One", "Two", "Three", "Four"]
>>> Roles[2]
'Two'
>>> Roles[3]
'Three'

You could shuffle the list before appending None:

>>> roles = ["One", "Two", "Three", "Four"]
>>> random.shuffle(roles)
>>> roles
['Three', 'Four', 'Two', 'One']
>>> roles = [None] + roles
>>> roles[3]
'Two'
>>> roles[2]
'Four'
>>> roles[1]
'Three'
>>> roles[4]
'One'