问:
How do I compile C# code as a library instead of an executable?
I have a C# console application in Visual Studio 2010. It has a Main() method as well as a bunch of utility classes. I'd like those utility classes to be available to other solutions. From reading online it seems that I need to compile it as a Class Library (DLL). So here's what I did:

Went in Visual Studio to "Project > [ProjectName] Properties > Application" and changed "Output type" from "Console Application" to "Class Library"

Rebuilt; ProjectName.dll was created in bin/Debug.

Created a new Console Application

Solution Explorer > Add Reference > browse to ProjectName.DLL, select it.

However, neither IntelliSense nor the Object Browser could find the classes inside that DLL.

I tried recompiling several different Console Applications as Class Libraries and got the same result. I also noticed that it works if I initially create the solution as a Class Library, but not if I convert it to one later.

Any tips?

答: You do not need to build it as a dll. VS 2010 (and IIRC 2008) allow referencing exe assemblies. All you need is for they relevant types to be declared public - top-level classes defualt to internal if you don't add a specifier.


来源: stackexchange

问:
Appium unable to identify element using resource-id
Appium is unable to identify an element using the id locator(resource-id) instead we can identify the same using Accessibility Id locator.

Please refer to attached image.enter image description here

答:
Appium doesn't support if you have some like $ in ID. Can you post your full ID.
Please try it with findElementById method as follow:

```<code>driver.findElementById("alertTitle");
</code>```

If it is not working use class name to find element and use index to locate your element.

```<code>List<WebElement> allElements=driver.findElementsByClassName("android.view.View");
</code>```

And get element using Index from above list.

```<code>WebElement yourElement= allElements.get(Required_Index);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Appium doesn't support if you have some like $ in ID. Can you post your full ID.
Please try it with findElementById method as follow:

driver.findElementById("alertTitle");

If it is not working use class name to find element and use index to locate your element.

List<WebElement> allElements=driver.findElementsByClassName("android.view.View");

And get element using Index from above list.

WebElement yourElement= allElements.get(Required_Index);


问:
How can i Show / Hide Div when i navigate from initial page to another and then come back to initial page?
I have multiple html pages
I have some specific content in Home page, its content should not be changed when the page is refreshed or reloaded.
But when I navigate to other pages and then come back to Home page, I would like to show / hide div or section of html in the Home page.
How this can be achieved?</p>

答:
Add a querystring to the url using JS on page B, then check for it on page A and remove/modify content as needed:</p>

```<code>// Set url parameter:

var myURL = document.location;
document.location = myURL + "?a=parameter";

// Check for url parameter:

function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}
</code>```

Body:
Add a querystring to the url using JS on page B, then check for it on page A and remove/modify content as needed:

// Set url parameter:

var myURL = document.location;
document.location = myURL + "?a=parameter";

// Check for url parameter:

function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}


问:
Firestore listener initialized with LifeCycleOwner argument misses updates when activity is paused
In my app I'm using a Firestore listener to listen for changes to a certain document. I init this listener using a LifeCycleOwner argument:

```<code>FireUtil.Events.getEvent( mEventKey ).addSnapshotListener( EventMainActivity.this, (documentSnapshot, e)
</code>```

When I make change to this document in another activity (the one in which I added the listener is paused), and return to the initial activity, changes are not visible (a restart of the activity is required).

When I remove the life-cycle owner argument, the listener is triggered and changes are visible (but I need to manually clean the listener).

Is this intended behavior, or am I missing something?

答: Solved this by moving the addSnapshotListener call (including he lifecycle owner argument) from the onCreate() to the onStart() method.

Body:
In my app I'm using a Firestore listener to listen for changes to a certain document. I init this listener using a LifeCycleOwner argument:

FireUtil.Events.getEvent( mEventKey ).addSnapshotListener( EventMainActivity.this, (documentSnapshot, e)

When I make change to this document in another activity (the one in which I added the listener is paused), and return to the initial activity, changes are not visible (a restart of the activity is required).

When I remove the life-cycle owner argument, the listener is triggered and changes are visible (but I need to manually clean the listener).

Is this intended behavior, or am I missing something?


问:
CoreML converted keras model requests multi array input instead of image in Xcode
this is actually my first post on Stackoverflow and i am pretty new to Machine Learning. I am currently trying to train a convolutional neural network for simple image classification tasks, using VGG16.
It is based on this tutorial: http://www.codesofinterest.com/2017/08/bottleneck-features-multi-class-classification-keras.html.
My objective is to convert this model to CoreML and use it for image classification on iOS.

After some struggle i was able to successfully convert the Keras model to a CoreML model by using following conversion lines:

coreml_model = coremltools.converters.keras.convert('Model Path',image_input_names = 'data',class_labels = 'class path')

However after copying the CoreML model into Xcode, it requests a multiarray with shape 512,1,1 ( i guess this occurs due to the image-array formatting of the neural network)
There were several other posts mentioning that it is important to use specific versions of keras,tensorflow and python(2.7) mentioned here
This did not change the issue.

In the Apple Developer forum they suggested to change the conversion code to following lines:

coreml_model = coremltools.converters.keras.convert('Model path',input_names='data',image_input_names = 'data',is_bgr=True,class_labels = 'Class path')

This in fact seemed to change something, however now i am not able to convert my keras model to a CoreML Model, getting this specific error:

ValueError: Channel Value 512 not supported for image inputs

Now it seems like the issue lies in the code of the convolutional neural network. Some suggested that this might occur due to dim_ordering of keras (which is last channel in my case) and/or the input shape. However, at least the input_shape looks like an image.

Anyone has an idea how to change the input from multi array to an image successfully?

Thanks in advance for any suggestion.

答:
It looks like the model you have created does not accept images but a vector of 512 elements, since the first "real" layer is a Dense layer and dense (or fully-connected layers) take 1-dimensional vectors as input, not 2-dimensional images.

But there is a bigger problem here: you fine-tuned VGG16 using bottleneck features, which is OK. But to make predictions on new images you need the entire model, i.e. not just the small classifier model that you trained but also all the VGG16 layers. But you're not converting the entire model, only the classifier part.

This means your app now expects bottleneck features as input, not images. And those bottleneck features are 512-element vectors.


问:
Compatible, active, open-source jQuery Gallery
I am looking for a jQuery gallery and want to be sure that this is compatible with all major browsers, well-documented, and preferably evolving as jQuery evolves. So preferably well-established, larger projects. I have found many galleries, but it is difficult to find the ones that comply with this. Many I have seen have not been changed since 2009. So my question is which are the larger, more established jQuery gallery projects?

Thanks!

答:
You can check these out:

http://www.queness.com/post/222/10-jquery-photo-gallery-and-slider-plugins

http://www.webanddesigners.com/15-jquery-slideshow-and-plugins

http://blueprintds.com/2009/01/20/top-14-jquery-photo-slideshow-gallery-plugins/

ContentLicense: CC BY-SA 2.5


问:
Validation accuracy does not make sense
My data set is the following:
Training set: 5589 images
Validation set: 1398 images
Test set: 1996 images
Size: 1156,256,1
The problem is a binary classification problem. I got some results (reaching ~83% accuracy in test set) using hot-encoded target arrays [0,1],[1,0]. Realizing how stupid this was I changed target arrays to binary form [0] or 1 and changing categorical_crossentropy to binary crossentropy.

With this approach the validation accuracy gets stuck at 82.05% no matter what learning rate I use and the training accuracy gets stuck at 25.80%. Of course, this has no sense, and the in the test set accuracy is around ~30%.

Why can be this happening? I checked both training data and metadata and they are correct. I post my code below.

inp = Input(shape=input_shape)
out = Conv2D(16, (5, 5),activation = 'relu', kernel_initializer='glorot_uniform', kernel_regularizer=regularizers.l2(0.01), padding='same')(inp)
out = MaxPooling2D(pool_size=(2, 2))(out)
out = Dropout(0.5)(out)

out = Conv2D(32, (3, 3),activation = 'relu',kernel_initializer='glorot_uniform',kernel_regularizer=regularizers.l2(0.01), padding='same')(out)
out = MaxPooling2D(pool_size=(2, 2))(out)
out = Dropout(0.5)(out)

out = Conv2D(32, (3, 3),activation = 'relu',kernel_initializer='glorot_uniform',kernel_regularizer=regularizers.l2(0.01), padding='same')(out)
out = Dropout(0.5)(out)

out = Conv2D(64, (3, 3), activation = 'relu',kernel_initializer='glorot_uniform',kernel_regularizer=regularizers.l2(0.01), padding='same')(out)
out = Conv2D(64, (3, 3),activation = 'relu', kernel_initializer='glorot_uniform',kernel_regularizer=regularizers.l2(0.01), padding='same')(out)
out = MaxPooling2D(pool_size=(2, 2))(out)

out = Conv2D(128, (3, 3), activation = 'relu',kernel_initializer='glorot_uniform',kernel_regularizer=regularizers.l2(0.01), padding='same')(out)
out = Conv2D(128, (3, 3),activation = 'relu', kernel_initializer='glorot_uniform',kernel_regularizer=regularizers.l2(0.01), padding='same')(out)
out = MaxPooling2D(pool_size=(2, 2))(out)

out = Conv2D(256, (3, 3),activation = 'relu', kernel_initializer='glorot_uniform',kernel_regularizer=regularizers.l2(0.01), padding='same')(out)
out = Conv2D(256, (3, 3), activation = 'relu',kernel_initializer='glorot_uniform',kernel_regularizer=regularizers.l2(0.01), padding='same')(out)
out = MaxPooling2D(pool_size=(2, 2))(out)
out = Conv2D(512, (3, 3), activation = 'relu',kernel_initializer='glorot_uniform', kernel_regularizer=regularizers.l2(0.01), padding='same')(out)
out = MaxPooling2D(pool_size=(2, 2))(out)

out = Flatten()(out)
out = Dropout(0.5)(out)
dense1 = Dense(1, activation="softmax")(out)
model = Model(inputs = inp, outputs = dense1)
```

And the epochs look like this:
Epochs

答:
Change your last activation from softmax to sigmoid, like

```<code>dense1 = Dense(1, activation="sigmoid")(out)
</code>```

and try lowering your learning rate

```<code>model.compile(optimizer=Adam(lr=0.0001), loss='binary_crossentropy',  metrics=['accuracy'])
</code>```

Title: Validation accuracy does not make sense

Body:
My data set is the following:
Training set: 5589 images
Validation set: 1398 images
Test set: 1996 images
Size: 1156,256,1
The problem is a binary classification problem. I got some results (reaching ~83% accuracy in test set) using hot-encoded target arrays [0,1],[1,0]. Realizing how stupid this was I changed target arrays to binary form [0] or 1 and changing categorical_crossentropy to binary crossentropy.

With this approach the validation accuracy gets stuck at 82.05% no matter what learning rate I use and the training accuracy gets stuck at 25.80%. Of course, this has no sense, and the in the test set accuracy is around ~30%.

Why can be this happening? I checked both training data and metadata and they are correct. I post my code below.

inp = Input(shape=input_shape)
out = Conv2D(16, (5, 5),activation = 'relu', kernel_initializer='glorot_uniform', kernel_regularizer=regularizers.l2(0.01), padding='same')(inp)
out = MaxPooling2D(pool_size=(2, 2))(out)
out = Dropout(0.5)(out)

out = Conv2D(32, (3, 3),activation = 'relu',kernel_initializer='glorot_uniform',kernel_regularizer=regularizers.l2(0.01), padding='same')(out)
out = MaxPooling2D(pool_size=(2, 2))(out)
out = Dropout(0.5)(out)

out = Conv2D(32, (3, 3),activation = 'relu',kernel_initializer='glorot_uniform',kernel_regularizer=regularizers.l2(0.01), padding='same')(out)
out = Dropout(0.5)(out)

out = Conv2D(64, (3, 3), activation = 'relu',kernel_initializer='glorot_uniform',kernel_regularizer=regularizers.l2(0.01), padding='same')(out)
out = Conv2D(64, (3, 3),activation = 'relu', kernel_initializer='glorot_uniform',kernel_regularizer=regularizers.l2(0.01), padding='same')(out)
out = MaxPooling2D(pool_size=(2, 2))(out)

out = Conv2D(128, (3, 3), activation = 'relu',kernel_initializer='glorot_uniform',kernel_regularizer=regularizers.l2(0.01), padding='same')(out)
out = Conv2D(128, (3, 3),activation = 'relu', kernel_initializer='glorot_uniform',kernel_regularizer=regularizers.l2(0.01), padding='same')(out)
out = MaxPooling2D(pool_size=(2, 2))(out)

out = Conv2D(256, (3, 3),activation = 'relu', kernel_initializer='glorot_uniform',kernel_regularizer=regularizers.l2(0.01), padding='same')(out)
out = Conv2D(256, (3, 3), activation = 'relu',kernel_initializer='glorot_uniform',kernel_regularizer=regularizers.l2(0.01), padding='same')(out)
out = MaxPooling2D(pool_size=(2, 2))(out)
out = Conv2D(512, (3, 3), activation = 'relu',kernel_initializer='glorot_uniform', kernel_regularizer=regularizers.l2(0.01), padding='same')(out)
out = MaxPooling2D(pool_size=(2, 2))(out)

out = Flatten()(out)
out = Dropout(0.5)(out)
dense1 = Dense(1, activation="softmax")(out)
model = Model(inputs = inp, outputs = dense1)

And the epochs look like this:
Epochs

Body:
Change your last activation from softmax to sigmoid, like

dense1 = Dense(1, activation="sigmoid")(out)

and try lowering your learning rate

model.compile(optimizer=Adam(lr=0.0001), loss='binary_crossentropy',  metrics=['accuracy'])


问:
Laravel 5.5: Authorization with pivot table
I have four table users, groups, posts, and group_user. Users can follow different groups. The group_user table is for many-to-many relationship.

Every post belongs to a group and a user. I want that a user can only post a post on a group if he follows that group. I can easily check using if statement that whether a user follows that group or not. But how can I authorize the user for posting using policies.

答:
Create a policy:php artisan make:policy.

Register policy:

```<code>class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        Post::class => PostPolicy::class,
    ];
</code>```

In your policy the logic, for instance:

```<code>public function create(User $user, Post $post)
{
    $groupsOfUser = $user->groups()->get();

    foreach ($groupsOfUser as $group) {
        if($group->id == request('groupId'))return true;
    }
}
</code>```

And in your Controller:

```<code>public function store(Post $post, $groupId)
{
    $this->authorize('create', $post);

    Post::create([
        'user_id' =>auth()->id(),
        'group_id' => $groupId,
        'title' => 'sometitle',
    ]);
}
</code>```

And i have tested it with route:

```<code>Route::get('/post/{groupId}', 'PostController@store');
</code>```

But you may be getting groupId via input, but you get the idea.

Body:
Create a policy:php artisan make:policy.

Register policy:

class AuthServiceProvider extends ServiceProvider
{
    /**
     * The policy mappings for the application.
     *
     * @var array
     */
    protected $policies = [
        Post::class => PostPolicy::class,
    ];

In your policy the logic, for instance:

public function create(User $user, Post $post)
{
    $groupsOfUser = $user->groups()->get();

    foreach ($groupsOfUser as $group) {
        if($group->id == request('groupId'))return true;
    }
}

And in your Controller:

public function store(Post $post, $groupId)
{
    $this->authorize('create', $post);

    Post::create([
        'user_id' =>auth()->id(),
        'group_id' => $groupId,
        'title' => 'sometitle',
    ]);
}

And i have tested it with route:

Route::get('/post/{groupId}', 'PostController@store');

But you may be getting groupId via input, but you get the idea.


问:
Visual Studio build with batch without hardcoding paths
I've got a public git repository and I want to add a batch file that would automatically build the solution using VisualStudio. This means I don't want to hardcode the paths there as different users might use different versions of VisualStudio. Is there a way to check for the existing VS installations and use the newest version?

I know that \HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\%VERSION% could be used, but I don't know how to loop through the versions and use latest one.

答:
You can use vswhere to query a specific visual studio version.

Find the latest version:

```<code>vswhere -latest
</code>```

Find the latest version within a certain range 14.0 (2015) to 15.* (2017):

```<code>vswhere -version [14.0,16.0)
</code>```

This uses the same syntax as NuGet uses for dependencies.

To capture the location in a batch file, use:

```<code>for /f "usebackq tokens=1* delims=: " %%i in (`vswhere -latest -requires Microsoft.Component.MSBuild`) do (
  if /i "%%i"=="installationPath" set InstallDir=%%j
)
</code>```

To find a version that includes a specific feature, use the -requires option. The above option searches for a version that ships with MsBuild.

Body:
You can use vswhere to query a specific visual studio version.

Find the latest version:

vswhere -latest

Find the latest version within a certain range 14.0 (2015) to 15.* (2017):

vswhere -version [14.0,16.0)

This uses the same syntax as NuGet uses for dependencies.

To capture the location in a batch file, use:

for /f "usebackq tokens=1* delims=: " %%i in (`vswhere -latest -requires Microsoft.Component.MSBuild`) do (
  if /i "%%i"=="installationPath" set InstallDir=%%j
)

To find a version that includes a specific feature, use the -requires option. The above option searches for a version that ships with MsBuild.


问:
How do I get a stored procedure output parameter that is an array to work?
I have been developing Java/JDBC calls to stored procedures with some success. However I am stuck when an output parameter is an array of strings. I have been successful with scalar types as input and output parameters, as well as an array of strings as an input parameter.

Here's the PL/SQL code I have:

```<code>TYPE StringArray IS TABLE OF VARCHAR2(32767) INDEX BY BINARY_INTEGER;

create or replace package body
test is
  procedure upper(
    in_array     in StringArray,
    out_array    out StringArray
  ) is
    tmp StringArray := in_array;
  begin
    for i in 0..(tmp.count-1) loop
      tmp(i) := UPPER(tmp(i));
    end loop;
    out_array := tmp;
  end;
end test;
</code>```

Here's the Java code I have:

```<code>public void testString(Connection connection) {
    String[] values = { "alpha", "beta", "gamma" };
    try {
       CallableStatement callableStatement = connection.prepareCall("begin test.upper(?, ?); end;");
       DelegatingConnection<OracleConnection> delegatingConnection = (DelegatingConnection<OracleConnection>) new DelegatingConnection(connection);
       OracleConnection oracleConnection = (OracleConnection) delegatingConnection.getInnermostDelegate();
       Array input oracleConnection.createOracleArray("STRINGARRAY", values);
       callableStatement.setObject("in_array", input);
       callableStatement.registerOutParameter("out_array", Types.ARRAY, "STRINGARRAY");
       callableStatement.execute();
       Array output = (Array)callableStatement.getObject("out_array");
       String[] result = (String[])output.getArray();
       System.out.println("Length: " + result.length);  // Prints "Length: 3"
       System.out.println("First: " + result[0]);       // Prints "First: null"
    } (catch SQLException e) {
       // Handle error
    }
}
</code>```

If I call the PL/SQL stored procedure from an SQL script directly it works. So I think the stored procedure itself is okay.

If I call the stored procedure via JDBC it completes normally. Using debug statements, I have confirmed that values is correctly sent from the Java client to the stored procedure into in_array. That is, an array of length 3 with the appropriate values is received. As best as I can tell, out_array is sent back to the Java client. However, something goes wrong. result is of size 3 but all the elements are null.

If I inspect output, I can see that internally it has a byte[] of length 38. Sub-sequences of these bytes map to "ALPHA", "BETA" and "GAMMA". So it looks like the data makes it back to the client but it is not converted into a String[] correctly.

What am I doing wrong?

答:
Do not use an Associative Array - use a Collection:

```<code>CREATE TYPE StringArray IS TABLE OF VARCHAR2(4000);
CREATE TYPE CLOBArray   IS TABLE OF CLOB;
</code>```

Then you can do:

```<code>public void testString(Connection connection) {
  String[] values = { "alpha", "beta", "gamma" };
  try {
    OracleConnection oc = (OracleConnection) connection;

    ARRAY stringArray = oc.createARRAY( "STRINGARRAY", values ); // Upper case identifier

    OracleCallableStatement st = (OracleCallableStatement) oc.prepareCall(
      "begin test.upper( :in_array, :out_array ); end;"
    );

    st.setARRAYAtName( "in_array", stringArray );
    st.registerOutParameter( "out_array", Types.ARRAY, "STRINGARRAY"); // Upper case again
    st.execute();

    String[] result = (String[])st.getARRAY( 2 ).getArray();

    System.out.println("Length: " + result.length);
    System.out.println("First: " + result[0]);
  } (catch SQLException e) {
    // Handle error
  }
}
</code>```

If you must use a PL/SQL associative array as an input to your procedure then write a function that takes a collection and outputs an associative array of the appropriate type and then call that:

```<code>BEGIN TEST.UPPER( TO_ASSOC_ARRAY( :in_collection ), :out_array ); END;
</code>```

Note: This answer is assuming using the Oracle driver in ojdbc6.jar which does not appear to have the OracleConnection.createOracleArray() method but it will, hopefully, be portable changing oracle.sql.ARRAY to java.sql.Array and using the newer methods.

Body:
I have been developing Java/JDBC calls to stored procedures with some success. However I am stuck when an output parameter is an array of strings. I have been successful with scalar types as input and output parameters, as well as an array of strings as an input parameter.

Here's the PL/SQL code I have:

TYPE StringArray IS TABLE OF VARCHAR2(32767) INDEX BY BINARY_INTEGER;

create or replace package body
test is
  procedure upper(
    in_array     in StringArray,
    out_array    out StringArray
  ) is
    tmp StringArray := in_array;
  begin
    for i in 0..(tmp.count-1) loop
      tmp(i) := UPPER(tmp(i));
    end loop;
    out_array := tmp;
  end;
end test;

Here's the Java code I have:

public void testString(Connection connection) {
    String[] values = { "alpha", "beta", "gamma" };
    try {
       CallableStatement callableStatement = connection.prepareCall("begin test.upper(?, ?); end;");
       DelegatingConnection<OracleConnection> delegatingConnection = (DelegatingConnection<OracleConnection>) new DelegatingConnection(connection);
       OracleConnection oracleConnection = (OracleConnection) delegatingConnection.getInnermostDelegate();
       Array input oracleConnection.createOracleArray("STRINGARRAY", values);
       callableStatement.setObject("in_array", input);
       callableStatement.registerOutParameter("out_array", Types.ARRAY, "STRINGARRAY");
       callableStatement.execute();
       Array output = (Array)callableStatement.getObject("out_array");
       String[] result = (String[])output.getArray();
       System.out.println("Length: " + result.length);  // Prints "Length: 3"
       System.out.println("First: " + result[0]);       // Prints "First: null"
    } (catch SQLException e) {
       // Handle error
    }
}

If I call the PL/SQL stored procedure from an SQL script directly it works. So I think the stored procedure itself is okay.

If I call the stored procedure via JDBC it completes normally. Using debug statements, I have confirmed that values is correctly sent from the Java client to the stored procedure into in_array. That is, an array of length 3 with the appropriate values is received. As best as I can tell, out_array is sent back to the Java client. However, something goes wrong. result is of size 3 but all the elements are null.

If I inspect output, I can see that internally it has a byte[] of length 38. Sub-sequences of these bytes map to "ALPHA", "BETA" and "GAMMA". So it looks like the data makes it back to the client but it is not converted into a String[] correctly.

What am I doing wrong?

Body:
Do not use an Associative Array - use a Collection:

CREATE TYPE StringArray IS TABLE OF VARCHAR2(4000);
CREATE TYPE CLOBArray   IS TABLE OF CLOB;

Then you can do:

public void testString(Connection connection) {
  String[] values = { "alpha", "beta", "gamma" };
  try {
    OracleConnection oc = (OracleConnection) connection;

    ARRAY stringArray = oc.createARRAY( "STRINGARRAY", values ); // Upper case identifier

    OracleCallableStatement st = (OracleCallableStatement) oc.prepareCall(
      "begin test.upper( :in_array, :out_array ); end;"
    );

    st.setARRAYAtName( "in_array", stringArray );
    st.registerOutParameter( "out_array", Types.ARRAY, "STRINGARRAY"); // Upper case again
    st.execute();

    String[] result = (String[])st.getARRAY( 2 ).getArray();

    System.out.println("Length: " + result.length);
    System.out.println("First: " + result[0]);
  } (catch SQLException e) {
    // Handle error
  }
}

If you must use a PL/SQL associative array as an input to your procedure then write a function that takes a collection and outputs an associative array of the appropriate type and then call that:

BEGIN TEST.UPPER( TO_ASSOC_ARRAY( :in_collection ), :out_array ); END;

Note: This answer is assuming using the Oracle driver in ojdbc6.jar which does not appear to have the OracleConnection.createOracleArray() method but it will, hopefully, be portable changing oracle.sql.ARRAY to java.sql.Array and using the newer methods.


问:
Xcode Organizer: can not use iPhone (dyld_shared_cache_extract_dylibs failed)
When plugging my iPhone in and starting the Xcode organizer, a yellow circle next to the device show me that "This device is busy or otherwise unusable by Xcode."
The Organizer is then processing two files (the second one takes quite a while to finish) and afterwards I get the error message as shown in the screenshot.

I tried to google for that error message ("dyld_shared_cache_extract_dylibs failed") but could not find anything useful.
I tried a couple things: repair permissions of my harddrive and run "sudo update_dyld_shared_cache -force". Still getting the error message.

I am running iOS 4.2.1 and Xcode 3.2.5. I have not updated Xcode after updating from 4.2 to 4.2.1 (I think).

The Xcode console is empty but the regular OS X console shows this:

```<code>1/22/11 10:56:19 PM     Xcode[4187]     Started symbol copying process
1/22/11 10:56:19 PM     Xcode[4187]     Skipped copying file 1 of 2 ("processed" sentinal found)
1/22/11 10:56:19 PM     Xcode[4187]     Skipped processing file 1 of 2 ("processed" sentinal found)
1/22/11 10:56:19 PM     Xcode[4187]     Skipped copying file 2 of 2 ("copied" sentinal found)
1/22/11 10:56:19 PM     Xcode[4187]     Started processing file 2 of 2
1/22/11 10:56:20 PM     [0x0-0x4d04d].com.apple.Xcode[4187]     arch already exists in fat dylib
1/22/11 10:56:20 PM     [0x0-0x4d04d].com.apple.Xcode[4187]     arch already exists in fat dylib
1/22/11 10:56:20 PM     [0x0-0x4d04d].com.apple.Xcode[4187]     arch already exists in fat dylib
1/22/11 10:56:21 PM     [0x0-0x4d04d].com.apple.Xcode[4187]     arch already exists in fat dylib
1/22/11 10:56:21 PM     [0x0-0x4d04d].com.apple.Xcode[4187]     arch already exists in fat dylib
1/22/11 10:56:22 PM     [0x0-0x4d04d].com.apple.Xcode[4187]     arch already exists in fat dylib
1/22/11 10:56:22 PM     [0x0-0x4d04d].com.apple.Xcode[4187]     arch already exists in fat dylib
1/22/11 10:56:22 PM     [0x0-0x4d04d].com.apple.Xcode[4187]     arch already exists in fat dylib
1/22/11 10:56:23 PM     [0x0-0x4d04d].com.apple.Xcode[4187]     arch already exists in fat dylib
1/22/11 10:56:23 PM     [0x0-0x4d04d].com.apple.Xcode[4187]     arch already exists in fat dylib
1/22/11 10:56:23 PM     [0x0-0x4d04d].com.apple.Xcode[4187]     arch already exists in fat dylib
</code>```

This error message is then repeated constantly.

答:
With the help of somebody at the Apple Developer Forums I was able to fix the problem by removing the "/Developer/Platforms/iPhoneOS.platform/DeviceSupport/4.2.1 (8C148)" folder. Xcode then re-added the symbols automatically and the error disappeared.
For more information see this thread.</p>

Body:
When plugging my iPhone in and starting the Xcode organizer, a yellow circle next to the device show me that "This device is busy or otherwise unusable by Xcode."
The Organizer is then processing two files (the second one takes quite a while to finish) and afterwards I get the error message as shown in the screenshot.

I tried to google for that error message ("dyld_shared_cache_extract_dylibs failed") but could not find anything useful.
I tried a couple things: repair permissions of my harddrive and run "sudo update_dyld_shared_cache -force". Still getting the error message.

I am running iOS 4.2.1 and Xcode 3.2.5. I have not updated Xcode after updating from 4.2 to 4.2.1 (I think).

The Xcode console is empty but the regular OS X console shows this:

1/22/11 10:56:19 PM     Xcode[4187]     Started symbol copying process
1/22/11 10:56:19 PM     Xcode[4187]     Skipped copying file 1 of 2 ("processed" sentinal found)
1/22/11 10:56:19 PM     Xcode[4187]     Skipped processing file 1 of 2 ("processed" sentinal found)
1/22/11 10:56:19 PM     Xcode[4187]     Skipped copying file 2 of 2 ("copied" sentinal found)
1/22/11 10:56:19 PM     Xcode[4187]     Started processing file 2 of 2
1/22/11 10:56:20 PM     [0x0-0x4d04d].com.apple.Xcode[4187]     arch already exists in fat dylib
1/22/11 10:56:20 PM     [0x0-0x4d04d].com.apple.Xcode[4187]     arch already exists in fat dylib
1/22/11 10:56:20 PM     [0x0-0x4d04d].com.apple.Xcode[4187]     arch already exists in fat dylib
1/22/11 10:56:21 PM     [0x0-0x4d04d].com.apple.Xcode[4187]     arch already exists in fat dylib
1/22/11 10:56:21 PM     [0x0-0x4d04d].com.apple.Xcode[4187]     arch already exists in fat dylib
1/22/11 10:56:22 PM     [0x0-0x4d04d].com.apple.Xcode[4187]     arch already exists in fat dylib
1/22/11 10:56:22 PM     [0x0-0x4d04d].com.apple.Xcode[4187]     arch already exists in fat dylib
1/22/11 10:56:22 PM     [0x0-0x4d04d].com.apple.Xcode[4187]     arch already exists in fat dylib
1/22/11 10:56:23 PM     [0x0-0x4d04d].com.apple.Xcode[4187]     arch already exists in fat dylib
1/22/11 10:56:23 PM     [0x0-0x4d04d].com.apple.Xcode[4187]     arch already exists in fat dylib
1/22/11 10:56:23 PM     [0x0-0x4d04d].com.apple.Xcode[4187]     arch already exists in fat dylib

This error message is then repeated constantly.


问:
How to create regression lines for a subset of a graphed data in ggplot2?
I have a dataset of measurements from different genera. Some of these genera have multiple datapoints, others have only one. I've written the following code to produce a scatterplot of my measurements table containing Measurement_A and Measurement_B.

```<code># Load ggplot2 and ggpmisc
library(ggplot2)
library(ggpmisc)
measurements <- read.csv("measurements.csv")
# Define colours and shapes for each genus (which I've called A, B, C and D)
colour_specifications <- c("A"="green", "B"="red", "C"="yellow",  "D"="blue")
shape_specifications <- c("A"=15, "B"=16, "C"=17, "D"=18)

# Create scatterplot of data from each genus
# and plot a regression line for each genus and show the R^2 value for each line
scatterplot <- ggplot(measurements, aes(x=Measurement_A, y=Measurement_B,
colour=Genus, shape=Genus))+
+   geom_point()+theme_classic()+
+   scale_color_manual(values = colour_specifications)+
+   scale_shape_manual(values= shape_specifications)+
+   geom_smooth(method=lm, se=FALSE)+
+   stat_poly_eq(formula = y ~ x, eq.with.lhs=FALSE, parse = TRUE)
> scatterplot
</code>```

Despite genera C and D only having one datapoint the legends show the regression line as well as the symbol. I would like to find a way to plot regression lines for just those subset of genera that have multiple datapoints (genera A and B). I have tried the subset function as follows,

```<code>scatterplot <- ggplot(measurements, aes(x=Measurement_A, y=Measurement_B,
    colour=Genus, shape=Genus))+
  geom_point()+theme_classic()+
  scale_color_manual(values = colour_specifications)+
  scale_shape_manual(values= shape_specifications)+
  geom_smooth(data=subset(measurements, Genus="A"),
          method='lm', se=FALSE)+
  geom_smooth(method=lm, se=FALSE)+
  stat_poly_eq(formula = y ~ x, eq.with.lhs=FALSE, parse = TRUE)
</code>```

but it hasn't made any difference to the legend which makes me think I've done something wrong.

Is there a way to plot the regression lines for just genera A and B and not C and D?

ETA:

This is the data I'm using for this:

```<code>Genus <- c("A", "A", "A", "A", "A", "A", "A", "A", "B", "B", "B", "B", "C",     "D")
Specimen <- c("Aa","Ab","Ac","Ad","Ae","Af","Ag","Ah","Ba", "Bb", "Bc", "Bd", "Ca", "Da")
Measurement_A <- c(60, 80, 100, 105, 120, 130, 140, 95, 70, 80, 90, 100, 170, 55)
Measurement_B <- c(10, 15, 30, 30, 35, 40, 40, 27, 10, 17, 20, 27, 15, 5)
measurements <- data.frame(Genus, Specimen, Measurement_A, Measurement_B)
</code>```

All I want to do is create a single plot of my data with a single legend but with genera A and B showing regression lines and the R^2 values. Both sets of code above give me a legend with regression lines through all the symbols, not just A and B. As I explained above, I have tried the subset function but it does not change the legend. When I tried

```<code>scatterplot <- ggplot(measurements, aes(x=Measurement_A, y=Measurement_B,
                                        colour=Genus, shape=Genus))+
geom_point()+theme_classic()+
scale_color_manual(values = colour_specifications)+
scale_shape_manual(values= shape_specifications)+
geom_smooth(method=lm, se=FALSE)+
scale_color_manual(values = c("green","red"),limits = c("A","B"))+
stat_poly_eq(formula = y ~ x, eq.with.lhs=FALSE, parse = TRUE)
scatterplot
</code>```

I get an error message saying "Scale for 'colour' is already present. Adding another scale for 'colour', which will replace the existing scale" and then I get two legends, one with the preset symbols but all in black for all genera, and one with the colours but just circular symbols for genera A and B.

ETA:
I have found the answer, I just needed to add show.legend=FALSE in the geom_smooth bracket.

答:
Why don't you just specify both of your factor levels via subset?

```<code>scatterplot <- ggplot(measurements, aes(x=Measurement_A, y=Measurement_B,
colour=Genus, shape=Genus))
+ geom_point()
+ geom_smooth(data=subset(measurements, Genus== "A" | Genus == "B"), method='lm', se=FALSE)
</code>```

Body:
I have a dataset of measurements from different genera. Some of these genera have multiple datapoints, others have only one. I've written the following code to produce a scatterplot of my measurements table containing Measurement_A and Measurement_B.

# Load ggplot2 and ggpmisc
library(ggplot2)
library(ggpmisc)
measurements <- read.csv("measurements.csv")
# Define colours and shapes for each genus (which I've called A, B, C and D)
colour_specifications <- c("A"="green", "B"="red", "C"="yellow",  "D"="blue")
shape_specifications <- c("A"=15, "B"=16, "C"=17, "D"=18)

# Create scatterplot of data from each genus
# and plot a regression line for each genus and show the R^2 value for each line
scatterplot <- ggplot(measurements, aes(x=Measurement_A, y=Measurement_B,
colour=Genus, shape=Genus))+
+   geom_point()+theme_classic()+
+   scale_color_manual(values = colour_specifications)+
+   scale_shape_manual(values= shape_specifications)+
+   geom_smooth(method=lm, se=FALSE)+
+   stat_poly_eq(formula = y ~ x, eq.with.lhs=FALSE, parse = TRUE)
> scatterplot

Despite genera C and D only having one datapoint the legends show the regression line as well as the symbol. I would like to find a way to plot regression lines for just those subset of genera that have multiple datapoints (genera A and B). I have tried the subset function as follows,

scatterplot <- ggplot(measurements, aes(x=Measurement_A, y=Measurement_B,
    colour=Genus, shape=Genus))+
  geom_point()+theme_classic()+
  scale_color_manual(values = colour_specifications)+
  scale_shape_manual(values= shape_specifications)+
  geom_smooth(data=subset(measurements, Genus="A"),
          method='lm', se=FALSE)+
  geom_smooth(method=lm, se=FALSE)+
  stat_poly_eq(formula = y ~ x, eq.with.lhs=FALSE, parse = TRUE)

but it hasn't made any difference to the legend which makes me think I've done something wrong.

Is there a way to plot the regression lines for just genera A and B and not C and D?

ETA:

This is the data I'm using for this:

Genus <- c("A", "A", "A", "A", "A", "A", "A", "A", "B", "B", "B", "B", "C",     "D")
Specimen <- c("Aa","Ab","Ac","Ad","Ae","Af","Ag","Ah","Ba", "Bb", "Bc", "Bd", "Ca", "Da")
Measurement_A <- c(60, 80, 100, 105, 120, 130, 140, 95, 70, 80, 90, 100, 170, 55)
Measurement_B <- c(10, 15, 30, 30, 35, 40, 40, 27, 10, 17, 20, 27, 15, 5)
measurements <- data.frame(Genus, Specimen, Measurement_A, Measurement_B)

All I want to do is create a single plot of my data with a single legend but with genera A and B showing regression lines and the R^2 values. Both sets of code above give me a legend with regression lines through all the symbols, not just A and B. As I explained above, I have tried the subset function but it does not change the legend. When I tried

scatterplot <- ggplot(measurements, aes(x=Measurement_A, y=Measurement_B,
                                        colour=Genus, shape=Genus))+
geom_point()+theme_classic()+
scale_color_manual(values = colour_specifications)+
scale_shape_manual(values= shape_specifications)+
geom_smooth(method=lm, se=FALSE)+
scale_color_manual(values = c("green","red"),limits = c("A","B"))+
stat_poly_eq(formula = y ~ x, eq.with.lhs=FALSE, parse = TRUE)
scatterplot

I get an error message saying "Scale for 'colour' is already present. Adding another scale for 'colour', which will replace the existing scale" and then I get two legends, one with the preset symbols but all in black for all genera, and one with the colours but just circular symbols for genera A and B.

ETA:
I have found the answer, I just needed to add show.legend=FALSE in the geom_smooth bracket.

Body:
Why don't you just specify both of your factor levels via subset?

scatterplot <- ggplot(measurements, aes(x=Measurement_A, y=Measurement_B,
colour=Genus, shape=Genus))
+ geom_point()
+ geom_smooth(data=subset(measurements, Genus== "A" | Genus == "B"), method='lm', se=FALSE)


问:
Knockout where clause in foreach
I would like to replicate this logic in knockout foreach.. any suggestions please? The current code is in razor and I am converting this to use knockoutJS

Where ItemStatus.Active is 0 in an enum in c# (backend)

```<code>    @foreach (var employee in Employees.Where(x => x.Status == ItemStatus.Active))
{
      <div class="someclass”>
      <span class="label">Name:</span>
      <span class="value">@employee.Name</span>
    </div>
    }
</code>```

How do I replicate this logic in knockout foreach, ie I only want to show employees who are currently active or employed

thank you

答:
knockout's computed or pureComputed would do the trick.

Try with VM like this

```<code>function VM(data) {
    var self = this;
    //.............
    self.filter = ko.observable(null);
    self.data = ko.observableArray(data)

    self.filteredData = ko.pureComputed(function(){
        return self.data().filter(function(x){
            return !self.filter() || x.status == self.filter();
        })
    });
    self.setFilter = function(filter) {
        self.filter(filter || null);
    }
    //.........................
}
</code>```

and markup like this

```<code><ul data-bind="foreach:filteredData">
    <li data-bind="text:$data.value">
    </li>
</ul>
<a href="#" data-bind="click:setFilter(null)">all</a>
<a href="#" data-bind="click:setFilter('active')">active</a>
<a href="#" data-bind="click:setFilter('archived')">archived</a>
</code>```

This little test application could be initialized like this

```<code>var someData = [
    {status:  'active', value:  'some active'},
    {status:  'active', value:  'another active'},
    {status:  'archived', value:  'some archived'},
    {status:  'archived', value:  'another archived'},
];
var vm = new VM(someData);
ko.applyBindings(vm);
vm.setFilter(null);
</code>```

Note that if your data array is static (no changes during the page lifecycle is expected) you may omit self.data observable array from the VM and just use data instead

Title: Knockout where clause in foreach

Body:
I would like to replicate this logic in knockout foreach.. any suggestions please? The current code is in razor and I am converting this to use knockoutJS

Where ItemStatus.Active is 0 in an enum in c# (backend)

    @foreach (var employee in Employees.Where(x => x.Status == ItemStatus.Active))
{

      Name:
      @employee.Name

    }

How do I replicate this logic in knockout foreach, ie I only want to show employees who are currently active or employed

thank you

Body:
knockout's computed or pureComputed would do the trick.

Try with VM like this

function VM(data) {
    var self = this;
    //.............
    self.filter = ko.observable(null);
    self.data = ko.observableArray(data)

    self.filteredData = ko.pureComputed(function(){
        return self.data().filter(function(x){
            return !self.filter() || x.status == self.filter();
        })
    });
    self.setFilter = function(filter) {
        self.filter(filter || null);
    }
    //.........................
}

and markup like this

<ul data-bind="foreach:filteredData">
    <li data-bind="text:$data.value">
    </li>
</ul>
<a href="#" data-bind="click:setFilter(null)">all</a>
<a href="#" data-bind="click:setFilter('active')">active</a>
<a href="#" data-bind="click:setFilter('archived')">archived</a>

This little test application could be initialized like this

var someData = [
    {status:  'active', value:  'some active'},
    {status:  'active', value:  'another active'},
    {status:  'archived', value:  'some archived'},
    {status:  'archived', value:  'another archived'},
];
var vm = new VM(someData);
ko.applyBindings(vm);
vm.setFilter(null);

Note that if your data array is static (no changes during the page lifecycle is expected) you may omit self.data observable array from the VM and just use data instead


问:
gist.run QuotaExceededError for any gists
I'm using the gist.run online service, and I'm getting QuotaExceededError on Chrome for any gists. The cache.put call is the culprit, but even with primed cache (deleting everything under Application -> Cache Storage, then "Clear site data", followed by "Empty Cache and Hard Reload") the problem persists.

答: In my case, the problem was that I was running low on space. I had less than 500MB free space in my home and it seems like Chrome rejects new cache puts in this case.</p>


问:
Input text color change is not proper with addEventListener
From the input element Id 'email', I am performing an addEventListener operation for dynamic email validation. The color of text will be 'black' if it is valid or 'maroon' if it's not.

```<code><!-- HTML -->
<input type="text" id="email" name="email">

//Javascript
document.getElementById('email').addEventListener('keydown', function(e) {
            var value = this.value;
            ValidateEmail(value);

            function ValidateEmail(mail)   {
                if (/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(mail))
                {
                    console.log("ok");
                    var red = document.getElementById('email');
                    red.style.color = 'black';
                    return (true);
                } else {
                    console.log("You have entered an invalid email address!");
                    var red = document.getElementById('email');
                    red.style.color = '#9e1e1e';
                    return (false);
                }
            }
        });
</code>```

The above program is working but with one issue, ie. the function validates the text only on the next 'keydown' event.

Ex. 'smith@email.co' is a valid email string, but the color changes only on the next event operation (which is 'smith@email.com' or 'smith@email.c').

答:
Use keyup instead of keydown.

Why?

Because when you use keydown, the event is fired and your function is run before the new character is inserted into the <input> field. So that the function gets the old value and validate incorrectly.

When you use keyup, the event is fired and your function is run after the new character is inserted into the <input> field so that your function and get the value correctly and validate it correctly.

document.getElementById('email').addEventListener('keyup', function(e) {
            var value = this.value;
            ValidateEmail(value);

            function ValidateEmail(mail)   {
                if (/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(mail))
                {
                    console.log("ok");
                    var red = document.getElementById('email');
                    red.style.color = 'black';
                    return (true);
                } else {
                    console.log("You have entered an invalid email address!");
                    var red = document.getElementById('email');
                    red.style.color = '#9e1e1e';
                    return (false);
                }
            }
        });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" id="email" name="email"></code>```

Body:
From the input element Id 'email', I am performing an addEventListener operation for dynamic email validation. The color of text will be 'black' if it is valid or 'maroon' if it's not.

<input type="text" id="email" name="email">

//Javascript
document.getElementById('email').addEventListener('keydown', function(e) {
            var value = this.value;
            ValidateEmail(value);

            function ValidateEmail(mail)   {
                if (/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(mail))
                {
                    console.log("ok");
                    var red = document.getElementById('email');
                    red.style.color = 'black';
                    return (true);
                } else {
                    console.log("You have entered an invalid email address!");
                    var red = document.getElementById('email');
                    red.style.color = '#9e1e1e';
                    return (false);
                }
            }
        });

The above program is working but with one issue, ie. the function validates the text only on the next 'keydown' event.

Ex. 'smith@email.co' is a valid email string, but the color changes only on the next event operation (which is 'smith@email.com' or 'smith@email.c').

Body:
Use keyup instead of keydown.

Why?

Because when you use keydown, the event is fired and your function is run before the new character is inserted into the <input> field. So that the function gets the old value and validate incorrectly.

When you use keyup, the event is fired and your function is run after the new character is inserted into the <input> field so that your function and get the value correctly and validate it correctly.

document.getElementById('email').addEventListener('keyup', function(e) {
            var value = this.value;
            ValidateEmail(value);

            function ValidateEmail(mail)   {
                if (/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(mail))
                {
                    console.log("ok");
                    var red = document.getElementById('email');
                    red.style.color = 'black';
                    return (true);
                } else {
                    console.log("You have entered an invalid email address!");
                    var red = document.getElementById('email');
                    red.style.color = '#9e1e1e';
                    return (false);
                }
            }
        });

<input type="text" id="email" name="email">


问:
header(location:) always shows up 403 forbidden
I have some problems. My index.php at www.quso.epizy.com always return a 403 forbidden but if I type the redirect path on my own it works. I redirect it to www.quso.epizy.com/home

Every redirect in my application is not working and all shows up forbidden why is that?

It works fine in localhost but not in the hosting. I tried asking in the forum but no answers.

I tried using header("location: www.quso.epizy.com/home/index.php"); but the redirect still shows 403 forbidden.

Here is my index.php

```<code><?php

require_once 'config.php';
require_once 'vendor/libs/functions.php';

redirect(URL . 'home'); // redirect to authenticate page
</code>```

here is the redirect function

```<code>function redirect($url, $permanent = false) {
    if($permanent) {
        header('HTTP/1.1 301 Moved Permanently');
    }
    header('Location: '.$url);
    exit();
}
</code>```

and config.php for the URL

```<code>define('URL', 'http://www.quso.epizy.com/');
</code>```

答:
Ok I've found the problem !!!

If you're looking at the network you'll find :

for the first page but then :

So if you look at Request URL (URL de la requête in french), you can see that you just concatenate the url you wrote for redirection after your domain name. It would probably work if you replace your header function by :

```<code>header('Location: ./home/index.php');
header("HTTP/1.1 301 Moved Permanently");
exit;
</code>```

Don't forget that the browser is also your friend and when a request does'nt work, you can look at it ! Hope it helps

Body:
I have some problems. My index.php at www.quso.epizy.com always return a 403 forbidden but if I type the redirect path on my own it works. I redirect it to www.quso.epizy.com/home

Every redirect in my application is not working and all shows up forbidden why is that?

It works fine in localhost but not in the hosting. I tried asking in the forum but no answers.

I tried using header("location: www.quso.epizy.com/home/index.php"); but the redirect still shows 403 forbidden.

Here is my index.php

<?php

require_once 'config.php';
require_once 'vendor/libs/functions.php';

redirect(URL . 'home'); // redirect to authenticate page

here is the redirect function

function redirect($url, $permanent = false) {
    if($permanent) {
        header('HTTP/1.1 301 Moved Permanently');
    }
    header('Location: '.$url);
    exit();
}

and config.php for the URL

define('URL', 'http://www.quso.epizy.com/');

Body:
Ok I've found the problem !!!

If you're looking at the network you'll find :

for the first page but then :

So if you look at Request URL (URL de la requête in french), you can see that you just concatenate the url you wrote for redirection after your domain name. It would probably work if you replace your header function by :

header('Location: ./home/index.php');
header("HTTP/1.1 301 Moved Permanently");
exit;

Don't forget that the browser is also your friend and when a request does'nt work, you can look at it ! Hope it helps


问:
Which SDLC methodology to use?
I'm moving to a new company where I will be the project manager/developer/tester/release management etc... for the projects I work on. Basically I'm everything. The programming manager doesn't care what you do as long as you deliver a product. So, I need to develop how I'm going to go about managing my projects. I also need to follow some methodology so that I'm not learning bad habits.

So, basically what kind of methodology should I use? Is there some resources out there I might look at for the situation I'm going to be in? Should I adopt agile or scrum? These projects will be fairly small.

As of right now, here is how I plan on doing things. Please comment on any of the following.

gather requirements

analyze requirements

fix/change requirements...start over at 1

design

development

unit testing

load testing

user acceptance testing/ fix bugs

move to production

答:
If your Projects are small stick on to Agile method. Since you'l be developing it will be useful for you to have continuous interaction with client. Display your work ,get the outcome from him.Most of the times they would suggest small changes which could be given in next sprint.

Major benefits with Agile when its ONE MAN show  are

Continuous interaction with client.

Knowing what he wants clearly.

Fixed timeline, no delays as sprints would be small.

No ambiguity in requirements as you would be interacting. You can come with better ways to convince why it can't be done depending on situations too.

No hectic deadlines.

Title: Which SDLC methodology to use?


问:
How to set 4 RelativeLayout Horizontally and Adjust automatically according to screen size

Please Refer to screen shot.
Now my Problem is
i have make a xml design that is like in screenshot.
i have 4 relative layout contains imageview and textview.
now i want to set these 4 relative layout horizontally with equal space from right,left,start,end.
In my layout when it go on big screen the start and end showing extra space,i know i have set it like that.
But Is there any solution to set these RLs automatic adjust there size according to screen size.

```<code> <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/one"
    android:id="@+id/RL_MainCat"
    android:background="@color/white"
    android:layout_marginTop="10dp">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true">
<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/RL_UploadPres"
    android:layout_marginLeft="10dp"
    >
<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/upload_pres_icon"
    android:id="@+id/icon_uploadpres"
    android:layout_centerHorizontal="true"
    />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Upload\nPrescription"
        android:textAlignment="center"
        android:textColor="#1f222d"
        android:textSize="11sp"
        android:layout_below="@+id/icon_uploadpres"
        android:layout_marginTop="10dp"
        />
</RelativeLayout>

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/RL_UploadPres"
        android:id="@+id/RL_FindPharmacy"
        android:layout_marginLeft="20dp">
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/find_pharma_icon"
            android:id="@+id/icon_findphar"
            android:layout_centerHorizontal="true"
            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=" Find \n  Pharmacy  "
            android:textAlignment="center"
            android:textColor="#1f222d"
            android:textSize="11sp"
            android:layout_below="@+id/icon_findphar"
            android:layout_marginTop="10dp"
            android:layout_centerHorizontal="true"
            />
    </RelativeLayout>

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/RL_FindPharmacy"
        android:id="@+id/RL_BuyOTC"
        android:layout_marginLeft="20dp"
        >
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/otc_icon"
            android:id="@+id/icon_findotc"
            android:layout_centerHorizontal="true"

            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="  Buy \n      OTC     "
            android:textAlignment="center"
            android:textColor="#1f222d"
            android:textSize="11sp"
            android:layout_below="@+id/icon_findotc"
            android:layout_marginTop="10dp"
            android:layout_centerHorizontal="true"/>

    </RelativeLayout>

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/RL_BuyMedicine"
        android:layout_toRightOf="@+id/RL_BuyOTC"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="10dp"
        >
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/medicine_icon"
            android:id="@+id/icon_findmedi"
            android:layout_centerHorizontal="true"
            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="  Buy \n Medicines  "
            android:textColor="#1f222d"
            android:textSize="11sp"
            android:textAlignment="center"
            android:layout_marginTop="10dp"
            android:layout_centerHorizontal="true"
            android:layout_below="@+id/icon_findmedi"
            />

    </RelativeLayout>
</RelativeLayout>
</code>```

答:
Try this

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/RL_MainCat"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/one"
    android:layout_marginTop="10dp"
    android:background="#ffffff">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:weightSum="4"
        android:orientation="horizontal">

        <RelativeLayout
            android:id="@+id/RL_UploadPres"
            android:layout_width="match_parent"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp">

            <ImageView
                android:id="@+id/icon_uploadpres"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:src="@mipmap/ic_launcher" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/icon_uploadpres"
                android:layout_marginTop="10dp"
                android:text="Upload\nPrescription"
                android:textAlignment="center"
                android:textColor="#1f222d"
                android:textSize="11sp" />
        </RelativeLayout>

        <RelativeLayout
            android:id="@+id/RL_FindPharmacy"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:layout_weight="1"
            android:layout_toRightOf="@+id/RL_UploadPres">

            <ImageView
                android:id="@+id/icon_findphar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:src="@mipmap/ic_launcher" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/icon_findphar"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="10dp"
                android:text=" Find \n  Pharmacy  "
                android:textAlignment="center"
                android:textColor="#1f222d"
                android:textSize="11sp" />
        </RelativeLayout>

        <RelativeLayout
            android:id="@+id/RL_BuyOTC"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_marginLeft="20dp"
            android:layout_toRightOf="@+id/RL_FindPharmacy">

            <ImageView
                android:id="@+id/icon_findotc"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:src="@mipmap/ic_launcher"

                />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/icon_findotc"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="10dp"
                android:text="  Buy \n      OTC     "
                android:textAlignment="center"
                android:textColor="#1f222d"
                android:textSize="11sp" />

        </RelativeLayout>

        <RelativeLayout
            android:id="@+id/RL_BuyMedicine"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:layout_weight="1"
            android:layout_marginRight="10dp"
            android:layout_toRightOf="@+id/RL_BuyOTC">

            <ImageView
                android:id="@+id/icon_findmedi"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:src="@mipmap/ic_launcher" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/icon_findmedi"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="10dp"
                android:text="  Buy \n Medicines  "
                android:textAlignment="center"
                android:textColor="#1f222d"
                android:textSize="11sp" />

        </RelativeLayout>

    </LinearLayout>
</RelativeLayout>
</code>```

Below Output

Body:
Please Refer to screen shot.
Now my Problem is
i have make a xml design that is like in screenshot.
i have 4 relative layout contains imageview and textview.
now i want to set these 4 relative layout horizontally with equal space from right,left,start,end.
In my layout when it go on big screen the start and end showing extra space,i know i have set it like that.
But Is there any solution to set these RLs automatic adjust there size according to screen size.

 <RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/one"
    android:id="@+id/RL_MainCat"
    android:background="@color/white"
    android:layout_marginTop="10dp">

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_marginBottom="10dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true">
<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/RL_UploadPres"
    android:layout_marginLeft="10dp"
    >
<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/upload_pres_icon"
    android:id="@+id/icon_uploadpres"
    android:layout_centerHorizontal="true"
    />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Upload\nPrescription"
        android:textAlignment="center"
        android:textColor="#1f222d"
        android:textSize="11sp"
        android:layout_below="@+id/icon_uploadpres"
        android:layout_marginTop="10dp"
        />
</RelativeLayout>

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/RL_UploadPres"
        android:id="@+id/RL_FindPharmacy"
        android:layout_marginLeft="20dp">
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/find_pharma_icon"
            android:id="@+id/icon_findphar"
            android:layout_centerHorizontal="true"
            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text=" Find \n  Pharmacy  "
            android:textAlignment="center"
            android:textColor="#1f222d"
            android:textSize="11sp"
            android:layout_below="@+id/icon_findphar"
            android:layout_marginTop="10dp"
            android:layout_centerHorizontal="true"
            />
    </RelativeLayout>

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/RL_FindPharmacy"
        android:id="@+id/RL_BuyOTC"
        android:layout_marginLeft="20dp"
        >
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/otc_icon"
            android:id="@+id/icon_findotc"
            android:layout_centerHorizontal="true"

            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="  Buy \n      OTC     "
            android:textAlignment="center"
            android:textColor="#1f222d"
            android:textSize="11sp"
            android:layout_below="@+id/icon_findotc"
            android:layout_marginTop="10dp"
            android:layout_centerHorizontal="true"/>

    </RelativeLayout>

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/RL_BuyMedicine"
        android:layout_toRightOf="@+id/RL_BuyOTC"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="10dp"
        >
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/medicine_icon"
            android:id="@+id/icon_findmedi"
            android:layout_centerHorizontal="true"
            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="  Buy \n Medicines  "
            android:textColor="#1f222d"
            android:textSize="11sp"
            android:textAlignment="center"
            android:layout_marginTop="10dp"
            android:layout_centerHorizontal="true"
            android:layout_below="@+id/icon_findmedi"
            />

    </RelativeLayout>
</RelativeLayout>

Body:
Try this

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/RL_MainCat"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/one"
    android:layout_marginTop="10dp"
    android:background="#ffffff">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:weightSum="4"
        android:orientation="horizontal">

        <RelativeLayout
            android:id="@+id/RL_UploadPres"
            android:layout_width="match_parent"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp">

            <ImageView
                android:id="@+id/icon_uploadpres"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:src="@mipmap/ic_launcher" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/icon_uploadpres"
                android:layout_marginTop="10dp"
                android:text="Upload\nPrescription"
                android:textAlignment="center"
                android:textColor="#1f222d"
                android:textSize="11sp" />
        </RelativeLayout>

        <RelativeLayout
            android:id="@+id/RL_FindPharmacy"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:layout_weight="1"
            android:layout_toRightOf="@+id/RL_UploadPres">

            <ImageView
                android:id="@+id/icon_findphar"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:src="@mipmap/ic_launcher" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/icon_findphar"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="10dp"
                android:text=" Find \n  Pharmacy  "
                android:textAlignment="center"
                android:textColor="#1f222d"
                android:textSize="11sp" />
        </RelativeLayout>

        <RelativeLayout
            android:id="@+id/RL_BuyOTC"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_marginLeft="20dp"
            android:layout_toRightOf="@+id/RL_FindPharmacy">

            <ImageView
                android:id="@+id/icon_findotc"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:src="@mipmap/ic_launcher"

                />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/icon_findotc"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="10dp"
                android:text="  Buy \n      OTC     "
                android:textAlignment="center"
                android:textColor="#1f222d"
                android:textSize="11sp" />

        </RelativeLayout>

        <RelativeLayout
            android:id="@+id/RL_BuyMedicine"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="20dp"
            android:layout_weight="1"
            android:layout_marginRight="10dp"
            android:layout_toRightOf="@+id/RL_BuyOTC">

            <ImageView
                android:id="@+id/icon_findmedi"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:src="@mipmap/ic_launcher" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_below="@+id/icon_findmedi"
                android:layout_centerHorizontal="true"
                android:layout_marginTop="10dp"
                android:text="  Buy \n Medicines  "
                android:textAlignment="center"
                android:textColor="#1f222d"
                android:textSize="11sp" />

        </RelativeLayout>

    </LinearLayout>
</RelativeLayout>

Below Output


问:
SQL - how to update a column with each row value incremented by 1?
For the selected rows in a column, how to update each row sequentially from the beginning to the end, with each row value incremented by 1 (or certain number). I know this can be done in excel in few seconds but I could figure out how to achieve in SQL server. For instance:

customer id is NULL now
update customer id with every row incremented by 1 (i.e. first row = 1, second row = 2, .....nth row = n)

```<code>ship-to party   customer id
0002018092      NULL
0002008127      NULL
0002000129      NULL
0002031592      NULL
0002034232      NULL
</code>```

desired output

```<code>ship-to party   customer id
0002018092      1
0002008127      2
0002000129      3
0002031592      4
0002034232      5
</code>```

Also, for the selected rows in a column, how to update each row with the row number? I know there is a row_number() function but didn't succeed in producing the desired result. for instance

column A is NULL now
update Column A with every row incremented by 1 (i.e. first row = row number 1, second row = row number 2, .....nth row = row number n)

Any demonstration would be very helpful.thkans

答:
Rather than using a self referencing variable, use a CTE:

```<code>WITH CTE AS (
    SELECT [Your Incrementing Column],
           ROW_NUMBER() OVER (ORDER BY [Columns to Order By]) AS RN
    FROM YourTable)
UPDATE CTE
SET [Your Incrementing Column] = RN;
</code>```

Edit: To prove a point that ALL rows will be updated:

```<code>CREATE TABLE #Sample (String varchar(50),
                      IncrementingInt int);

INSERT INTO #Sample (String)
VALUES ('sdkfjasdf'),
       ('dfydsfdfg'),
       ('sdfgsdfg45yfg'),
       ('dfgf54d'),
       ('dsft43tdc'),
       ('f6gytrntrfu7m45'),
       ('5d6f45wgby54'),
       ('g34h636j'),
       ('jw'),
       ('h6nw54m'),
       ('g54j747jm5e5f4w5gsft'),
       ('ns67mw54mk8o7hr'),
       ('h45j4w5h4');

SELECT *
FROM #Sample;

WITH CTE AS(
    SELECT IncrementingInt,
           ROW_NUMBER() OVER (ORDER BY String) AS RN
    FROM #Sample)
UPDATE CTE
SET IncrementingInt = RN;

SELECT *
FROM #Sample;

DROP TABLE #Sample;
GO
</code>```

Body:
For the selected rows in a column, how to update each row sequentially from the beginning to the end, with each row value incremented by 1 (or certain number). I know this can be done in excel in few seconds but I could figure out how to achieve in SQL server. For instance:

customer id is NULL now
update customer id with every row incremented by 1 (i.e. first row = 1, second row = 2, .....nth row = n)

ship-to party   customer id
0002018092      NULL
0002008127      NULL
0002000129      NULL
0002031592      NULL
0002034232      NULL

desired output

ship-to party   customer id
0002018092      1
0002008127      2
0002000129      3
0002031592      4
0002034232      5

Also, for the selected rows in a column, how to update each row with the row number? I know there is a row_number() function but didn't succeed in producing the desired result. for instance

column A is NULL now
update Column A with every row incremented by 1 (i.e. first row = row number 1, second row = row number 2, .....nth row = row number n)

Any demonstration would be very helpful.thkans

Body:
Rather than using a self referencing variable, use a CTE:

WITH CTE AS (
    SELECT [Your Incrementing Column],
           ROW_NUMBER() OVER (ORDER BY [Columns to Order By]) AS RN
    FROM YourTable)
UPDATE CTE
SET [Your Incrementing Column] = RN;

Edit: To prove a point that ALL rows will be updated:

CREATE TABLE #Sample (String varchar(50),
                      IncrementingInt int);

INSERT INTO #Sample (String)
VALUES ('sdkfjasdf'),
       ('dfydsfdfg'),
       ('sdfgsdfg45yfg'),
       ('dfgf54d'),
       ('dsft43tdc'),
       ('f6gytrntrfu7m45'),
       ('5d6f45wgby54'),
       ('g34h636j'),
       ('jw'),
       ('h6nw54m'),
       ('g54j747jm5e5f4w5gsft'),
       ('ns67mw54mk8o7hr'),
       ('h45j4w5h4');

SELECT *
FROM #Sample;

WITH CTE AS(
    SELECT IncrementingInt,
           ROW_NUMBER() OVER (ORDER BY String) AS RN
    FROM #Sample)
UPDATE CTE
SET IncrementingInt = RN;

SELECT *
FROM #Sample;

DROP TABLE #Sample;
GO


问:
How to add safeStringify() to JSON in Typescript?
I want to have safeStringify for json objects.
for this purpose, I want to add it to interface JSON in Typescript (lib.d.ts)

```<code>interface JSON {
    safeStringify(value: any): string; // Right way ? - How to write the body ?
}
</code>```

Is this a right way for extending JSON interface or not? (browser and node)

If yes, How can I add the functionality (method body)? the interfaces do not accept a body.

I want to work the code globally without any effort just as JSON member.

UPDATE:

so the final result/answer is:

答:
You've defined the interface, but not the implementation:

```<code>interface JSON {
    safeStringify(value: any): string;
}

JSON.safeStringify = function(value: any): string {
    ... your implementation
}
</code>```

You also need to ensure you include safeStringify.ts in your build.

Unless of course safeStringify comes from some lib, in which case, just ensure you import the lib correctly.

Body:
I want to have safeStringify for json objects.
for this purpose, I want to add it to interface JSON in Typescript (lib.d.ts)

interface JSON {
    safeStringify(value: any): string; // Right way ? - How to write the body ?
}

Is this a right way for extending JSON interface or not? (browser and node)

If yes, How can I add the functionality (method body)? the interfaces do not accept a body.

I want to work the code globally without any effort just as JSON member.

UPDATE:

so the final result/answer is:

Body:
You've defined the interface, but not the implementation:

interface JSON {
    safeStringify(value: any): string;
}

JSON.safeStringify = function(value: any): string {
    ... your implementation
}

You also need to ensure you include safeStringify.ts in your build.

Unless of course safeStringify comes from some lib, in which case, just ensure you import the lib correctly.


问:
Qt C++ - displaying the links in QText Browser
Right now I am displaying the result in QTextBrowser. Results will be something like /home/User/, /media/Arena/ etc i.e path to different folders. Now I want to open the folder in a window by clicking on this result which is displayed in QTextBrowser. But I have no ideas how to do that. So can anyone let me know how to do it.

Thanx in advance.

P.S. I am using QtCreator & see the image http://i53.tinypic.com/qyxp1s.png.

答: can you insert html rather than plain text into the QTextBrowser widget?  then you can use a URL to describe the paths.  </p>

OwnerDisplayName: Winbros

OwnerDisplayName: BasementCat


问:
HDFS BLOCK SIZE
What is default block size 128MB or 64MB for hdfs?In hadoop definite guide it is mentioned as "HDFS, too, has the concept of a block, but it is a much larger unit—128 MB by default".Anyone can tell which is the default size?</p>

答: This document states that it is 128M (search for dfs.blocksize)

Title: HDFS BLOCK SIZE


问:
Add footer layout in navigation drawer
The Logout layout overlap on the menu items in navigation drawer below 5.5 inch screen devices

This looks perfect in 5.5 inch screen devices

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="@drawable/drawer_bg"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:itemTextColor="@color/grey_text"
        app:menu="@menu/activity_main_drawer">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:background="#50000000"
            android:clickable="true"
            android:orientation="vertical">

            <TextView
                android:id="@+id/nav_logout"
                android:layout_width="match_parent"
                android:layout_height="44dp"
                android:gravity="center"
                android:text="Logout"
                android:textColor="@color/colorAccent"
                android:textSize="16sp" />

        </LinearLayout>

    </android.support.design.widget.NavigationView>

</android.support.v4.widget.DrawerLayout>
</code>```

This is my xml codes. My question is how to let the logout layout become a part of navigation drawer in screen below 5.5 inch so that the user can scroll through the menu to reach to bottom to get the logout button.

Thank you.

答:
For Click or handling footer:</p>

```<code>NavigationView navigationView = (NavigationView) findViewById(R.id.navi);
    ListView footerLV = (ListView) navigationView.findViewById(R.id.expnavimenu);
    footerLV.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(MainActivity.this, "Footer is clicked", Toast.LENGTH_SHORT).show();
        }
    });
</code>```

Title: Add footer layout in navigation drawer

Body:
The Logout layout overlap on the menu items in navigation drawer below 5.5 inch screen devices

This looks perfect in 5.5 inch screen devices

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="@drawable/drawer_bg"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:itemTextColor="@color/grey_text"
        app:menu="@menu/activity_main_drawer">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            android:background="#50000000"
            android:clickable="true"
            android:orientation="vertical">

            <TextView
                android:id="@+id/nav_logout"
                android:layout_width="match_parent"
                android:layout_height="44dp"
                android:gravity="center"
                android:text="Logout"
                android:textColor="@color/colorAccent"
                android:textSize="16sp" />

        </LinearLayout>

    </android.support.design.widget.NavigationView>

</android.support.v4.widget.DrawerLayout>

This is my xml codes. My question is how to let the logout layout become a part of navigation drawer in screen below 5.5 inch so that the user can scroll through the menu to reach to bottom to get the logout button.

Thank you.

Body:
For Click or handling footer:

NavigationView navigationView = (NavigationView) findViewById(R.id.navi);
    ListView footerLV = (ListView) navigationView.findViewById(R.id.expnavimenu);
    footerLV.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(MainActivity.this, "Footer is clicked", Toast.LENGTH_SHORT).show();
        }
    });


问:
Numpy Matrix: Malformed String
I get the following error ValueError: malformed string when using the following code:

```<code>import numpy
l=[]
for x in [0.0,1.0]:
    for y in [0.0,1.0]:
        for z in [0.0,1.0]:
            if x+y+z ==1:
                print x
                pr_matrix = numpy.matrix('x ; y ; z')
                l.append(pr_matrix)
</code>```

It seems to me that the numpy.matrix function is unable to understand that x,y,z are of type float and not of type string.
I say so because the following works fine.

```<code>matrix = np.matrix('1 2 2;2 3 1')
</code>```

答:
Do not use numpy.matrix. It's deprecated and will be removed in the future NumPy releases. Instead you can use a simple comprehension

```<code>import itertools, numpy as np
arr=np.array([[[x],[y],[z]] for x,y,z in itertools.product(*[[1,0]]*3) if x+y+z==1])[:,:,0]
</code>```

Here, itertools.product is creating the cartesian product [0, 1]x[0, 1]x[0, 1] which is what you do with 3 nested loops. To give this argument to the itertools.product we basically first create three copies of [0,1] in an iterable.

Then with a star argument (*) before this iterable, we instruct to interpret the elements of this iterable as separate arguments so we get three distinct arguments. This produces the cartesian product

```<code>[(1, 1, 1),
 (1, 1, 0),
 (1, 0, 1),
 (1, 0, 0),
 (0, 1, 1),
 (0, 1, 0),
 (0, 0, 1),
 (0, 0, 0)]
</code>```

let's call this A. Then we do a list comprehension over A. For each element in A which is a 3-tuple x,y,z we form a column and add it to the list created by the list comprehension if their sum is 1.

The result is then

```<code>[[[1], [0], [0]], [[0], [1], [0]], [[0], [0], [1]]]
</code>```

and then an NumPy array is created but notice it is 3D. so we take the relevant part with a slice. You can also use np.squeeze for this.

Title: Numpy Matrix: Malformed String

Body:
I get the following error ValueError: malformed string when using the following code:

import numpy
l=[]
for x in [0.0,1.0]:
    for y in [0.0,1.0]:
        for z in [0.0,1.0]:
            if x+y+z ==1:
                print x
                pr_matrix = numpy.matrix('x ; y ; z')
                l.append(pr_matrix)

It seems to me that the numpy.matrix function is unable to understand that x,y,z are of type float and not of type string.
I say so because the following works fine.

matrix = np.matrix('1 2 2;2 3 1')

Body:
Do not use numpy.matrix. It's deprecated and will be removed in the future NumPy releases. Instead you can use a simple comprehension

import itertools, numpy as np
arr=np.array([[[x],[y],[z]] for x,y,z in itertools.product(*[[1,0]]*3) if x+y+z==1])[:,:,0]

Here, itertools.product is creating the cartesian product [0, 1]x[0, 1]x[0, 1] which is what you do with 3 nested loops. To give this argument to the itertools.product we basically first create three copies of [0,1] in an iterable.

Then with a star argument (*) before this iterable, we instruct to interpret the elements of this iterable as separate arguments so we get three distinct arguments. This produces the cartesian product

[(1, 1, 1),
 (1, 1, 0),
 (1, 0, 1),
 (1, 0, 0),
 (0, 1, 1),
 (0, 1, 0),
 (0, 0, 1),
 (0, 0, 0)]

let's call this A. Then we do a list comprehension over A. For each element in A which is a 3-tuple x,y,z we form a column and add it to the list created by the list comprehension if their sum is 1.

The result is then

[[[1], [0], [0]], [[0], [1], [0]], [[0], [0], [1]]]

and then an NumPy array is created but notice it is 3D. so we take the relevant part with a slice. You can also use np.squeeze for this.


问:
SQL Server displays char(1) as 4 characters wide, padded by spaces
I've been constructing a simple query to return fixed width records for export to an older application. I've used

```<code>Select Cast([myColumn1] as char(1)), Cast([myColumn2] as char(1)) from myTable
</code>```

for single character columns, but the displayed result in SQL Server Management Studio always pads it out to 4 characters. For example, for a couple of single-character columns, it displays:

```<code>---- ----
P    A
</code>```

I would expect to see:

```<code>- -
P A
</code>```

I have a couple of questions:

Will this still occur if I use the query in code or will it format as expected with single character width? What I'm wondering is if it is a feature of the output pane in SSMS (although it exhibits the same behaviour when output to a file).

If it does occur, is there a workaround?

I hope that's not a dumb question, but can't seem to find any documentation...

答:
I just wanted to summarise what it was I was actually trying to find. See copied comments below.

There is a known feature of the SSMS results pane that it will not return less than 4 characters for any column. This is not documented, but is a consistent and verifiable feature. This means that the results pane is not suitable for testing queries that rely on specific formatting or the width of the returned column.

```<code>Is this documented anywhere that you know of, or is it just known through
trial-and-error? – underscore_d 17 hours ago

Viewing query results in SSMS is a bit inconsistent. I wouldn't use SSMS
results window for anything mission critical. – digital.aaron 17 hours ago

@underscore_d, not anywhere that I know of. It was, however, brought up in a
side conversation in a Kimberley Tripp SQL Server training course I attended
many years ago. – digital.aaron 17 hours ago
</code>```

Body:
I've been constructing a simple query to return fixed width records for export to an older application. I've used

Select Cast([myColumn1] as char(1)), Cast([myColumn2] as char(1)) from myTable

for single character columns, but the displayed result in SQL Server Management Studio always pads it out to 4 characters. For example, for a couple of single-character columns, it displays:

---- ----
P    A

I would expect to see:

- -
P A

I have a couple of questions:

Will this still occur if I use the query in code or will it format as expected with single character width? What I'm wondering is if it is a feature of the output pane in SSMS (although it exhibits the same behaviour when output to a file).

If it does occur, is there a workaround?

I hope that's not a dumb question, but can't seem to find any documentation...

Body:
I just wanted to summarise what it was I was actually trying to find. See copied comments below.

There is a known feature of the SSMS results pane that it will not return less than 4 characters for any column. This is not documented, but is a consistent and verifiable feature. This means that the results pane is not suitable for testing queries that rely on specific formatting or the width of the returned column.

Is this documented anywhere that you know of, or is it just known through
trial-and-error? – underscore_d 17 hours ago

Viewing query results in SSMS is a bit inconsistent. I wouldn't use SSMS
results window for anything mission critical. – digital.aaron 17 hours ago

@underscore_d, not anywhere that I know of. It was, however, brought up in a
side conversation in a Kimberley Tripp SQL Server training course I attended
many years ago. – digital.aaron 17 hours ago


问:
Is there are way to get rowIDs of first occurrences of value from codechunks?
Is there a way to get that realized?

example:(distribution is random)

```<code>ID    size
1      x
2      x
3      x
4      x
5      x
0      2
0      x
0      x
0      x
4      x
5      x
0      4
0      x
0      x
0      x
4      x
5      x
0      3
0      x
0      x
0      x
4      x
5      x
</code>```

This is just an example but very hard to code for me.

The x's are random numeric and not relevant. The values I need are the shown integers in the size column, so everytime a ID==0 occurrs, I need the first size value.

答:
Here is an idea using rleid from data.table,

```<code>library(data.table)

setDT(dt)[, grp := rleid(ID == 0)][ID == 0, .(size = first(size)), by = grp]
</code>```

which gives,

```<code>   grp size
1:   2    2
2:   4    4
3:   6    3
</code>```

In the tidyverse, one idea can be,

```<code>library(tidyverse)

df %>%
 mutate(grp = cumsum(ID != 0)) %>%
 filter(ID == 0) %>%
 group_by(grp) %>%
 summarise(size = first(size))
</code>```

ehich gives,

```<code># A tibble: 3 x 2
    grp   size
  <int> <fctr>
1     5      2
2     7      4
3     9      3
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Is there a way to get that realized?

example:(distribution is random)

ID    size
1      x
2      x
3      x
4      x
5      x
0      2
0      x
0      x
0      x
4      x
5      x
0      4
0      x
0      x
0      x
4      x
5      x
0      3
0      x
0      x
0      x
4      x
5      x

This is just an example but very hard to code for me.

The x's are random numeric and not relevant. The values I need are the shown integers in the size column, so everytime a ID==0 occurrs, I need the first size value.

Body:
Here is an idea using rleid from data.table,

library(data.table)

setDT(dt)[, grp := rleid(ID == 0)][ID == 0, .(size = first(size)), by = grp]

which gives,

   grp size
1:   2    2
2:   4    4
3:   6    3

In the tidyverse, one idea can be,

library(tidyverse)

df %>%
 mutate(grp = cumsum(ID != 0)) %>%
 filter(ID == 0) %>%
 group_by(grp) %>%
 summarise(size = first(size))

ehich gives,

# A tibble: 3 x 2
    grp   size
  <int> <fctr>
1     5      2
2     7      4
3     9      3