问:
How to implement the strategy pattern in Clojure?
I have three similar functions, they filter a collection of maps matching a key (column) against its value, case-insensitively.

Here is the original code I want to DRY up:

```<code>;; gets a collection filtered by a column, exact match
(defn get-collection-by-equals [collection-name column-name column-value]
 (filter #(= (string/lower-case (column-name %)) (string/lower-case column-value)) (cached-get-collection collection-name)))

;; gets a collection filtered by a column, with partial match, case-insensitive
(defn get-collection-by-like [collection-name column-name column-value]
 (filter #(string/includes? (string/lower-case (column-name %)) (string/lower-case column-value)) (cached-get-collection collection-name)))

;; gets a collection filtered by a column, which starts with given value, case-insensitive
(defn get-collection-by-starts-with [collection-name column-name column-value]
 (filter #(string/starts-with? (string/lower-case (column-name %)) (string/lower-case column-value)) (cached-get-collection collection-name)))
</code>```

You can see how similar the code is, I'm just using a different matching strategy in each case, =, includes? and starts-with?.

My first attempt was as follows:

```<code>;; returns a function which does a case-insensitive match between given column and value for the given map
(defn matching-fn [match-fn column-name column-value]
  (fn [map] (match-fn (string/lower-case (column-name map)) (string/lower-case column-value))))

;; gets a collection filtered by a column, exact match
(defn get-collection-by-equals [collection-name column-name column-value]
 (filter #((matching-fn = column-name column-value) %) (cached-get-collection collection-name)))

;; gets a collection filtered by a column, with partial match, case-insensitive
(defn get-collection-by-like [collection-name column-name column-value]
 (filter #((matching-fn string/includes? column-name column-value) %) (cached-get-collection collection-name)))

;; gets a collection filtered by a column, which starts with given value, case-insensitive
(defn get-collection-by-starts-with [collection-name column-name column-value]
 (filter #((matching-fn string/starts-with? column-name column-value) %) (cached-get-collection collection-name)))
</code>```

I didn't like the readability of this solution and it occurred to me that I could just pass the matching function, instead of having a function which returns a function, I came up with this:

```<code>;; gets a collection filtered by a column, using the given function, case-insensitive
(defn get-collection-by-filter [collection-name filter-fn column-name column-value]
 (filter #(filter-fn (string/lower-case (column-name %)) (string/lower-case column-value)) (cached-get-collection collection-name)))

;; gets a collection filtered by a column, exact match, case-insensitive
(defn get-collection-by-equals [collection-name column-name column-value]
  (get-collection-by collection-name = column-name column-value))

;; gets a collection filtered by a column, with partial match, case-insensitive
(defn get-collection-by-like [collection-name column-name column-value]
 (get-collection-by collection-name string/includes? column-name column-value))

;; gets a collection filtered by a column, which starts with given value, case-insensitive
(defn get-collection-by-starts-with [collection-name column-name column-value]
 (get-collection-by collection-name string/starts-with? column-name column-value))
</code>```

Is this idiomatic Clojure, are there other (better) solutions?

Using a macro seems overkill.

答:
I'd just use your get-collection-by-filter and not wrap it any more—why create a new function for every value the parameter might take?

Aside: just make the description a documentation string, and format it a bit:

```<code>(defn get-collection-by-filter
  "gets a collection filtered by a column, using the given function,
   case-insensitive"
  [collection-name filter-fn column-name column-value]
  (filter #(filter-fn (string/lower-case (column-name %))
                      (string/lower-case column-value))
          (cached-get-collection collection-name)))
</code>```

Body:
I have three similar functions, they filter a collection of maps matching a key (column) against its value, case-insensitively.

Here is the original code I want to DRY up:

;; gets a collection filtered by a column, exact match
(defn get-collection-by-equals [collection-name column-name column-value]
 (filter #(= (string/lower-case (column-name %)) (string/lower-case column-value)) (cached-get-collection collection-name)))

;; gets a collection filtered by a column, with partial match, case-insensitive
(defn get-collection-by-like [collection-name column-name column-value]
 (filter #(string/includes? (string/lower-case (column-name %)) (string/lower-case column-value)) (cached-get-collection collection-name)))

;; gets a collection filtered by a column, which starts with given value, case-insensitive
(defn get-collection-by-starts-with [collection-name column-name column-value]
 (filter #(string/starts-with? (string/lower-case (column-name %)) (string/lower-case column-value)) (cached-get-collection collection-name)))

You can see how similar the code is, I'm just using a different matching strategy in each case, =, includes? and starts-with?.

My first attempt was as follows:

;; returns a function which does a case-insensitive match between given column and value for the given map
(defn matching-fn [match-fn column-name column-value]
  (fn [map] (match-fn (string/lower-case (column-name map)) (string/lower-case column-value))))

;; gets a collection filtered by a column, exact match
(defn get-collection-by-equals [collection-name column-name column-value]
 (filter #((matching-fn = column-name column-value) %) (cached-get-collection collection-name)))

;; gets a collection filtered by a column, with partial match, case-insensitive
(defn get-collection-by-like [collection-name column-name column-value]
 (filter #((matching-fn string/includes? column-name column-value) %) (cached-get-collection collection-name)))

;; gets a collection filtered by a column, which starts with given value, case-insensitive
(defn get-collection-by-starts-with [collection-name column-name column-value]
 (filter #((matching-fn string/starts-with? column-name column-value) %) (cached-get-collection collection-name)))

I didn't like the readability of this solution and it occurred to me that I could just pass the matching function, instead of having a function which returns a function, I came up with this:

;; gets a collection filtered by a column, using the given function, case-insensitive
(defn get-collection-by-filter [collection-name filter-fn column-name column-value]
 (filter #(filter-fn (string/lower-case (column-name %)) (string/lower-case column-value)) (cached-get-collection collection-name)))

;; gets a collection filtered by a column, exact match, case-insensitive
(defn get-collection-by-equals [collection-name column-name column-value]
  (get-collection-by collection-name = column-name column-value))

;; gets a collection filtered by a column, with partial match, case-insensitive
(defn get-collection-by-like [collection-name column-name column-value]
 (get-collection-by collection-name string/includes? column-name column-value))

;; gets a collection filtered by a column, which starts with given value, case-insensitive
(defn get-collection-by-starts-with [collection-name column-name column-value]
 (get-collection-by collection-name string/starts-with? column-name column-value))

Is this idiomatic Clojure, are there other (better) solutions?

Using a macro seems overkill.

Body:
I'd just use your get-collection-by-filter and not wrap it any more—why create a new function for every value the parameter might take?

Aside: just make the description a documentation string, and format it a bit:

(defn get-collection-by-filter
  "gets a collection filtered by a column, using the given function,
   case-insensitive"
  [collection-name filter-fn column-name column-value]
  (filter #(filter-fn (string/lower-case (column-name %))
                      (string/lower-case column-value))
          (cached-get-collection collection-name)))


来源: stackexchange

问:
OpenSSL version in the SONOS Self-Test Suite
I am trying to run the latest SONOS Self-Test Suite against a revised version of our API. I'm running macOS Sierra Version 10.12.4. The built-in (and remarkably difficult-to-remove) version of OpenSSL is 0.9.8zh.

I have been able to install OpenSSL 1.0.2k and override the path to be the default OpenSSL version, as shown by:

```<code>> openssl version
OpenSSL 1.0.2k  26 Jan 2017

> which openssl
/usr/local/opt/openssl/bin/openssl
</code>```

Executing python suite_selftest.py returns the following:

```<code>Traceback (most recent call last):
  File "suite_selftest.py", line 36, in <module>
    import ssl_validation
  File "/XXX/sonostest/smapi/content_workflow/ssl_validation.py", line 17, in <module>
    from sslyze import sslyze
  File "../../sonos_sslyze-1.1.0.dev_r293552-py2.7.egg/sslyze/sslyze.py", line 29, in <module>
  File "../../sonos_sslyze-1.1.0.dev_r293552-py2.7.egg/sslyze/plugins/__init__.py", line 30, in <module>
  File "../../sonos_sslyze-1.1.0.dev_r293552-py2.7.egg/sslyze/plugins/PluginCertInfo.py", line 32, in <module>
  File "../../sonos_sslyze-1.1.0.dev_r293552-py2.7.egg/sslyze/utils/ctSSL/__init__.py", line 13, in <module>
  File "../../sonos_sslyze-1.1.0.dev_r293552-py2.7.egg/sslyze/utils/ctSSL/load_openssl.py", line 99, in <module>
</code>```

Is the Self-Test Suite directly using /usr/bin/openssl? Is there any way I can override or change the path it's using?

答:
The self-test uses the open source SSLyze tool, and SSLyze loads the OpenSSL libraries (crypto and ssl library). When loading the libraries on OS X, the code looks first into the current directory and then calls Python's find_library(). Here is another stackoverflow about where Python searches for libraries:

Which paths does python ctypes module search for libraries on Mac OS?

ContentLicense: CC BY-SA 3.0

Body:
I am trying to run the latest SONOS Self-Test Suite against a revised version of our API. I'm running macOS Sierra Version 10.12.4. The built-in (and remarkably difficult-to-remove) version of OpenSSL is 0.9.8zh.

I have been able to install OpenSSL 1.0.2k and override the path to be the default OpenSSL version, as shown by:

> openssl version
OpenSSL 1.0.2k  26 Jan 2017

> which openssl
/usr/local/opt/openssl/bin/openssl

Executing python suite_selftest.py returns the following:

Traceback (most recent call last):
  File "suite_selftest.py", line 36, in <module>
    import ssl_validation
  File "/XXX/sonostest/smapi/content_workflow/ssl_validation.py", line 17, in <module>
    from sslyze import sslyze
  File "../../sonos_sslyze-1.1.0.dev_r293552-py2.7.egg/sslyze/sslyze.py", line 29, in <module>
  File "../../sonos_sslyze-1.1.0.dev_r293552-py2.7.egg/sslyze/plugins/__init__.py", line 30, in <module>
  File "../../sonos_sslyze-1.1.0.dev_r293552-py2.7.egg/sslyze/plugins/PluginCertInfo.py", line 32, in <module>
  File "../../sonos_sslyze-1.1.0.dev_r293552-py2.7.egg/sslyze/utils/ctSSL/__init__.py", line 13, in <module>
  File "../../sonos_sslyze-1.1.0.dev_r293552-py2.7.egg/sslyze/utils/ctSSL/load_openssl.py", line 99, in <module>

Is the Self-Test Suite directly using /usr/bin/openssl? Is there any way I can override or change the path it's using?


问:
Set JSON values dynamically?
Can I do something like this:

```<code>var number = 0;
var values = ["my_component_state_0", "my_component_state_1"];

      this.setState({
          values[number]: evt.target.value
      });
</code>```

instead of writing out:

```<code>      this.setState({
        my_component_state_0: evt.target.value
      });
</code>```

?

I need to iterate through some things and something like this would be useful. But it seems too hacky, and it also doesn't seem to work - or does it? (or something like this)

答:
One way I thought of:</p>

```<code>var number = 0;
var values = ["my_component_state_0", "my_component_state_1"];
var state = {};

values.map(function(v, i) {
    state[v] = evt.target.value; // I've added 'test' for the test...
});

this.setState(state);

console.log(state); // { my_component_state_0: 'test', my_component_state_1: 'test' }
</code>```

Title: Set JSON values dynamically?

Body:
Can I do something like this:

var number = 0;
var values = ["my_component_state_0", "my_component_state_1"];

      this.setState({
          values[number]: evt.target.value
      });

instead of writing out:

      this.setState({
        my_component_state_0: evt.target.value
      });

?

I need to iterate through some things and something like this would be useful. But it seems too hacky, and it also doesn't seem to work - or does it? (or something like this)

Body:
One way I thought of:

var number = 0;
var values = ["my_component_state_0", "my_component_state_1"];
var state = {};

values.map(function(v, i) {
    state[v] = evt.target.value; // I've added 'test' for the test...
});

this.setState(state);

console.log(state); // { my_component_state_0: 'test', my_component_state_1: 'test' }


问:
Drupal module to control user post frequency?
We've been having a new type of spam-bot this week at PortableApps.com which posts at a rate of about 10 comments a minute and doesn't seem to stop - at least the first hour or so (we've always stopped it within that time so far). We've had them about a dozen times in the last week - sometimes stopping it at 50 or 60, sometimes up to 250 or 300. We're working to stop it and other spam bots as much as possible, but at the moment it's still a real pest.

I was wondering whether in the mean time whether there's any sort of module to control the frequency a user can post at to e.g. 50 an hour or something like 10 in an hour for new users. That at least would mean that instead of having to clear up 300 comments 50 at a time in admin/content/comment we'd have a smaller number to clear. (A module to add a page to delete all content by a user and block them would also be helpful!)

I believe that there's a plugin to do this available for WordPress, but can't find any such thing for Drupal.

答:
http://drupal.org/project/spam
http://drupal.org/project/antispam - with akismet support</p>

ContentLicense: CC BY-SA 2.5


问:
status bar is overlapping with navigation bar when showing uiviewcontroller with uipresentviewcontroller
I am presenting a uiviewcontroller in my app but the controller is overlapping with status bar. It only has navigation bar and because of this my barbutton is overlapping with battery icon in status bar. Any idea in showing navigation bar below status bar? I searched a lot but could not find a solution. My code to present viewcontroller:</p>

```<code>let timeVCObejct = self.storyboard?.instantiateViewControllerWithIdentifier("TimeConfigurationViewController") as? TimeConfigurationViewController
    timeVCObejct?.delegate = self
    self.presentViewController(timeVCObejct!, animated: true, completion: nil)
</code>```

答:
Use this property for your VC, in-order to avoid overlap of ur statusbar with your VC
Swift :

self.edgesForExtendedLayout = []

ObjectiveC C

self.edgesForExtendedLayout = UIRectEdgeNone;

Body:
I am presenting a uiviewcontroller in my app but the controller is overlapping with status bar. It only has navigation bar and because of this my barbutton is overlapping with battery icon in status bar. Any idea in showing navigation bar below status bar? I searched a lot but could not find a solution. My code to present viewcontroller:

let timeVCObejct = self.storyboard?.instantiateViewControllerWithIdentifier("TimeConfigurationViewController") as? TimeConfigurationViewController
    timeVCObejct?.delegate = self
    self.presentViewController(timeVCObejct!, animated: true, completion: nil)


问:
POSIXct objects showing as numeric
```<code>k <- file.Folder$LPRS.time[1] + lag*60
> k
[1] "2017-03-31 00:15:00 IST"
> file.Folder$start.time[1] <- file.Folder$LPRS.time[1] + lag*60
> file.Folder$start.time[1]
[1] 1490899500
</code>```

file.Folder$start.time is a new column created just at the last step.
Why is it showing properly as date in scenario 1 and as number in scenario 2??

答:
Option 1: You could use lubridate package since the arithmetic is easy.

```<code>library("lubridate")
x <- ymd_hms("2017-03-31 00:15:00 IST", tz = "Asia/Istanbul")
lag = hours(4)
x + lag * 60
</code>```

Results:

```<code>[1] "2017-04-10 00:15:00 EEST"
</code>```

Option 2: Convert the numeric result as.POSIXct:
as.POSIXct(1490899500, tz = "Asia/Istanbul", origin = "1970-01-01 00:00.00 UTC")

Title: POSIXct objects showing as numeric

Body:
k <- file.Folder$LPRS.time[1] + lag*60
> k
[1] "2017-03-31 00:15:00 IST"
> file.Folder$start.time[1] <- file.Folder$LPRS.time[1] + lag*60
> file.Folder$start.time[1]
[1] 1490899500

file.Folder$start.time is a new column created just at the last step.
Why is it showing properly as date in scenario 1 and as number in scenario 2??

Body:
Option 1: You could use lubridate package since the arithmetic is easy.

library("lubridate")
x <- ymd_hms("2017-03-31 00:15:00 IST", tz = "Asia/Istanbul")
lag = hours(4)
x + lag * 60

Results:

[1] "2017-04-10 00:15:00 EEST"

Option 2: Convert the numeric result as.POSIXct:
as.POSIXct(1490899500, tz = "Asia/Istanbul", origin = "1970-01-01 00:00.00 UTC")


问:
Creating a game board using struct
So I am making a game board for battle ship, but I am trying to use a struct to make it. Currently I am getting an error when trying to create the game board.  I'm trying to make it this way so that when the user inputs coordinates for the ships, or when they are making a move I can easily change symbols and get to the correct coordinate on the array. This is what I am working with right now. I am using 3 file format, so I put all the parts down below.

I could create the board without using a struct, but I'm pretty sure I need to create it this way so that I am able to manipulate the board later.

If this helps this is my current error: Run-Time Check Failure #3 - The variable 'person' is being used without being initialized.

This is in the header file

```<code>typedef struct game_board
{
    int board[10][10];
    int row;
    int col;
    char symbol;
    }Game_Board;

Game_Board initalize_game_board(Game_Board player);
</code>```

The function

```<code>Game_Board initalize_game_board(Game_Board player)
{
    int row_index = 0, col_index = 0;

    printf("  0 1 2 3 4 5 6 7 8 9\n");
    for (row_index = 0; row_index < player.row; row_index++)
    {
        printf("%d ", row_index);
        for (col_index = 0; col_index < player.col; col_index++)
        {
            player.board[row_index][col_index] = player.symbol;
            printf("%c ", player.board[row_index][col_index]);
        }
        printf("\n");
    }
}
</code>```

In the main function

```<code>int main(void)
{
    FILE *outfile = NULL;
    outfile = fopen("battleship.log", "w");

    Game_Board person, computer;
    int who_goes_first = 0;

    strcpy(person.symbol, '~');
    person.row = 10;
    person.col = 10;
    strcpy(computer.symbol, '~');
    computer.row = 10;
    computer.col = 10;

    welcome_screen(outfile);
    printf("Player 1\n");

   initalize_game_board(person);
</code>```

答:
You need return statements for both functions. Ending paren for main().

Highly recommend

```<code>computer.symbol = '~';
</code>```

Instead of

```<code>strcpy(computer.symbol, '~');
</code>```

Title: Creating a game board using struct

Body:
So I am making a game board for battle ship, but I am trying to use a struct to make it. Currently I am getting an error when trying to create the game board.  I'm trying to make it this way so that when the user inputs coordinates for the ships, or when they are making a move I can easily change symbols and get to the correct coordinate on the array. This is what I am working with right now. I am using 3 file format, so I put all the parts down below.

I could create the board without using a struct, but I'm pretty sure I need to create it this way so that I am able to manipulate the board later.

If this helps this is my current error: Run-Time Check Failure #3 - The variable 'person' is being used without being initialized.

This is in the header file

typedef struct game_board
{
    int board[10][10];
    int row;
    int col;
    char symbol;
    }Game_Board;

Game_Board initalize_game_board(Game_Board player);

The function

Game_Board initalize_game_board(Game_Board player)
{
    int row_index = 0, col_index = 0;

    printf("  0 1 2 3 4 5 6 7 8 9\n");
    for (row_index = 0; row_index < player.row; row_index++)
    {
        printf("%d ", row_index);
        for (col_index = 0; col_index < player.col; col_index++)
        {
            player.board[row_index][col_index] = player.symbol;
            printf("%c ", player.board[row_index][col_index]);
        }
        printf("\n");
    }
}

In the main function

int main(void)
{
    FILE *outfile = NULL;
    outfile = fopen("battleship.log", "w");

    Game_Board person, computer;
    int who_goes_first = 0;

    strcpy(person.symbol, '~');
    person.row = 10;
    person.col = 10;
    strcpy(computer.symbol, '~');
    computer.row = 10;
    computer.col = 10;

    welcome_screen(outfile);
    printf("Player 1\n");

   initalize_game_board(person);

Body:
You need return statements for both functions. Ending paren for main().

Highly recommend

computer.symbol = '~';

Instead of

strcpy(computer.symbol, '~');


问:
Broadcast Reveiver not being called from Alarm Manager
I've searched the archives and still can't resolve my issue.

I'm trying to take an user input in seconds that will call the broadcast receiver to create a toast message and vibrate the phone. However, the broadcast receiver is never called and I can't figure it out. My code is below.

Thanks!

```<code>package com.example.cs984x.alrm;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button btn1 = (Button) findViewById(R.id.button1);
    btn1.setOnClickListener(new View.OnClickListener() {
        @Override
         public void onClick(View v) {
            EditText inputSeconds = (EditText) findViewById(R.id.editText1);
            int inputTime = Integer.parseInt(inputSeconds.getText().toString());
            Toast.makeText(MainActivity.this, "The alarm will go off in " + inputTime + " seconds.", Toast.LENGTH_LONG).show();
            AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
            Intent myIntent = new Intent(MainActivity.this, MyReceiver.class);
            myIntent.setAction("com.example.cs984x.alrm.vibrate");
            PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent,0);
            alarmManager.set(AlarmManager.RTC_WAKEUP,   System.currentTimeMillis()+(inputTime*1000), pendingIntent);

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

Broadcast Receiver Class:

```<code>package com.example.cs984x.alrm;

import android.app.AlarmManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Vibrator;
import android.widget.EditText;
import android.widget.Toast;

import static android.content.Context.ALARM_SERVICE;

public class MyReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

    Toast.makeText(context, "Your time is up", Toast.LENGTH_LONG).show();
    Vibrator v;
    v= (Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE);
    v.vibrate(2000);

}

}
</code>```

Manifest:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.cs984x.alrm">
<uses-permission android:name="android.permission.VIBRATE" >
</uses-permission>

    <application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    </application>

    <receiver

    android:name=".MyReceiver" android:process=":remote"

    android:enabled="true">

  <intent-filter>

        <action android:name="com.example.cs984x.alrm.vibrate" />

    </intent-filter>

</receiver>

</manifest>
</code>```

答:
Add action to intent:

```<code>Intent myIntent = new Intent(MainActivity.this, MyReceiver.class);
myIntent.setAction("YourPackageName.YourAction");
            PendingIntent pendingIntent =PendingIntent.getBroadcast(MainActivity.this, 0, myIntent,0);
</code>```

in AndroidManifest:

```<code><intent-filter>
                <action android:name="YourPackageName.YourAction" />
            </intent-filter>
</code>```

Body:
I've searched the archives and still can't resolve my issue.

I'm trying to take an user input in seconds that will call the broadcast receiver to create a toast message and vibrate the phone. However, the broadcast receiver is never called and I can't figure it out. My code is below.

Thanks!

package com.example.cs984x.alrm;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button btn1 = (Button) findViewById(R.id.button1);
    btn1.setOnClickListener(new View.OnClickListener() {
        @Override
         public void onClick(View v) {
            EditText inputSeconds = (EditText) findViewById(R.id.editText1);
            int inputTime = Integer.parseInt(inputSeconds.getText().toString());
            Toast.makeText(MainActivity.this, "The alarm will go off in " + inputTime + " seconds.", Toast.LENGTH_LONG).show();
            AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
            Intent myIntent = new Intent(MainActivity.this, MyReceiver.class);
            myIntent.setAction("com.example.cs984x.alrm.vibrate");
            PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent,0);
            alarmManager.set(AlarmManager.RTC_WAKEUP,   System.currentTimeMillis()+(inputTime*1000), pendingIntent);

        }
    });
}
}

Broadcast Receiver Class:

package com.example.cs984x.alrm;

import android.app.AlarmManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Vibrator;
import android.widget.EditText;
import android.widget.Toast;

import static android.content.Context.ALARM_SERVICE;

public class MyReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

    Toast.makeText(context, "Your time is up", Toast.LENGTH_LONG).show();
    Vibrator v;
    v= (Vibrator)context.getSystemService(Context.VIBRATOR_SERVICE);
    v.vibrate(2000);

}

}

Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.cs984x.alrm">
<uses-permission android:name="android.permission.VIBRATE" >
</uses-permission>

    <application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    </application>

    <receiver

    android:name=".MyReceiver" android:process=":remote"

    android:enabled="true">

  <intent-filter>

        <action android:name="com.example.cs984x.alrm.vibrate" />

    </intent-filter>

</receiver>

</manifest>

Body:
Add action to intent:

Intent myIntent = new Intent(MainActivity.this, MyReceiver.class);
myIntent.setAction("YourPackageName.YourAction");
            PendingIntent pendingIntent =PendingIntent.getBroadcast(MainActivity.this, 0, myIntent,0);

in AndroidManifest:

<intent-filter>
                <action android:name="YourPackageName.YourAction" />
            </intent-filter>


问:
setting data context of silverlight user control leaves the control as always visible
I have a 'searchwin.xaml' user control in a Silverlight page called Mainpage.xaml. 'searchwin' has its own viewmodel 'searhwinVM'. I have set searchwin's datacontext to its viewmodel in the Mainpage xaml like this

```<code><UserControl.Resources>
<vm:SearchWin  x:Name="SearchWinVM" x:Key="SearchWinVM" /> </UserControl.Resources>

<part:SearchWin ..... {other properties here}
Visibility="{Binding Converter={StaticResource BooleanToVisibilityConverter}, Path=IsSearchVisible}"
DataContext="{StaticResource SearchWinVM}"/>
</code>```

This search control I want to set as invisible by default and visible only when I change to a particular value in my listbox which is on the mainpage.xaml. Setting the datacontext of the UC in the mainpage.xaml or programatically in the mainpage.xaml.cs causes the control to always be visble. I cant get it to hide now. If I remove the datacontext it works well as expected. Any ideas how to fix this?

Thanks for your time...

答: Have you verified that your converter is being called at all? I'd just put a breakpoint in and see what happens.</p>

Body:
I have a 'searchwin.xaml' user control in a Silverlight page called Mainpage.xaml. 'searchwin' has its own viewmodel 'searhwinVM'. I have set searchwin's datacontext to its viewmodel in the Mainpage xaml like this

<UserControl.Resources>
<vm:SearchWin  x:Name="SearchWinVM" x:Key="SearchWinVM" /> </UserControl.Resources>

<part:SearchWin ..... {other properties here}
Visibility="{Binding Converter={StaticResource BooleanToVisibilityConverter}, Path=IsSearchVisible}"
DataContext="{StaticResource SearchWinVM}"/>

This search control I want to set as invisible by default and visible only when I change to a particular value in my listbox which is on the mainpage.xaml. Setting the datacontext of the UC in the mainpage.xaml or programatically in the mainpage.xaml.cs causes the control to always be visble. I cant get it to hide now. If I remove the datacontext it works well as expected. Any ideas how to fix this?

Thanks for your time...


问:
ListView horizontal = {true} breaks application with app registry error
The error I get is: "Application PRSNT_prototype has not been registered"

The folder name of my project is PRSNT_demo and these are the codes that I think might be the issue:

```<code>AppRegistry.registerComponent('PRSNT_demo', () => Main);

<ListView
              horizontal={true}
              dataSource={this.state.dataSource}
              renderRow={(rowData) => <View>{rowData}</View>}
            />
</code>```

When ever i turn horizontal={true} on the app breaks. Ive tried turning the app on and off again, also tried:

```<code><ListView
                  style={Style.horList}
                  dataSource={this.state.dataSource}
                  renderRow={(rowData) => <View>{rowData}</View>}
                />
</code>```

With style.horlist being:

```<code>horList: {
  flexDirection: 'row',
</code>```

},

This álso broke the app.

If someone could help me out that would be absolutely amazing, thank you so much in advance

答:
I solved the problem by making the ListView a ScrollView, this worked fine:</p>

```<code><ScrollView showsHorizontalScrollIndicator={false} horizontal={true}>

    <Text>Item 1</Text>
    <Text>Item 2</Text>
    <Text>Item 3</Text>
    <Text>Item 4</Text>

</ScrollView>
</code>```

Body:
The error I get is: "Application PRSNT_prototype has not been registered"

The folder name of my project is PRSNT_demo and these are the codes that I think might be the issue:

AppRegistry.registerComponent('PRSNT_demo', () => Main);

<ListView
              horizontal={true}
              dataSource={this.state.dataSource}
              renderRow={(rowData) => <View>{rowData}</View>}
            />

When ever i turn horizontal={true} on the app breaks. Ive tried turning the app on and off again, also tried:

<ListView
                  style={Style.horList}
                  dataSource={this.state.dataSource}
                  renderRow={(rowData) => <View>{rowData}</View>}
                />

With style.horlist being:

horList: {
  flexDirection: 'row',

},

This álso broke the app.

If someone could help me out that would be absolutely amazing, thank you so much in advance

Body:
I solved the problem by making the ListView a ScrollView, this worked fine:

<ScrollView showsHorizontalScrollIndicator={false} horizontal={true}>

    <Text>Item 1</Text>
    <Text>Item 2</Text>
    <Text>Item 3</Text>
    <Text>Item 4</Text>

</ScrollView>


问:
View got hidden below UINavigationBar iOS 7
Earlier, I was using iOS 6.1 for my project. Recently I have switched to iOS 7. For, a lot of changes I knew, I updated my code.. But I have observed a strange behavior. My view on every screen gets hidden below navigation bar. Repositioning view solves the problem for iOS7, but creates problems for older iOS versions.

Can anyone explain me, what is the reason and why does it happen?? What has been changed in iOS 7 that's causing this problem??

Any help would be appreciated..

答:
Use this property for your VC, in-order to avoid overlap of ur statusbar with your VC Swift :

```<code>self.edgesForExtendedLayout = []
</code>```

Objective C

```<code>self.edgesForExtendedLayout = UIRectEdgeNone;
</code>```

Body:
Use this property for your VC, in-order to avoid overlap of ur statusbar with your VC Swift :

self.edgesForExtendedLayout = []

Objective C

self.edgesForExtendedLayout = UIRectEdgeNone;


问:
A flexbox grid of two flex items next to one
I am trying to have one div on the left and two on the right. The bottomright should always be below the topRight div. The topRight is the only div with a variable height.

I am currently trying to achieve this using flexbox als you can see in my code below.

I would like to have some directions.

.wrapper {
  display: flex;
  height: 100px;
}

.left {
  background-color: green
}

.topRight {
  background-color: yellow
}

.bottomright {
  background-color: red
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div class="left">Left</div>
  <div class="topRight">TopRight</div>
  <div class="bottomright">Bottom</div>
  </div</code>```

答:
With a fixed height on the container, as you have in your code, you can use flex-direction: column and flex-wrap: wrap. The fixed height serves as a break point, telling flex items where to wrap.

.wrapper {
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  height: 100px;
}

.left {
  flex: 0 0 100%; /* consumes full height of first column; forces siblings to wrap */
  background-color: lightgreen
}

/* variable height div */
.topRight {
  background-color: yellow
}

.bottomright {
  flex: 1; /* consumes remaining space in column */
  background-color: red
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div class="left">Left</div>
  <div class="topRight">TopRight<br>variable height</div>
  <div class="bottomright">Bottom</div>
  </div></code>```

Body:
I am trying to have one div on the left and two on the right. The bottomright should always be below the topRight div. The topRight is the only div with a variable height.

I am currently trying to achieve this using flexbox als you can see in my code below.

I would like to have some directions.

.wrapper {
  display: flex;
  height: 100px;
}

.left {
  background-color: green
}

.topRight {
  background-color: yellow
}

.bottomright {
  background-color: red
}

Left

TopRight

Bottom

  </div

Body:
With a fixed height on the container, as you have in your code, you can use flex-direction: column and flex-wrap: wrap. The fixed height serves as a break point, telling flex items where to wrap.

.wrapper {
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
  height: 100px;
}

.left {
  flex: 0 0 100%; /* consumes full height of first column; forces siblings to wrap */
  background-color: lightgreen
}

/* variable height div */
.topRight {
  background-color: yellow
}

.bottomright {
  flex: 1; /* consumes remaining space in column */
  background-color: red
}

<div class="wrapper">
  <div class="left">Left</div>
  <div class="topRight">TopRight<br>variable height</div>
  <div class="bottomright">Bottom</div>
  </div>


问:
SSIS - Export Master-Detail data to a single flat file that contains both master and detail row
I have DB with a master table with its detail table, let's say

```<code>Master (ID, MField1)
Det    (ID, IDMaster, DetField1)
</code>```

and I need to export a flat file with fixed column size, with both master rows and detail rows, here's below the records' structure:

Master Record:

```<code>Position    Desc        Length    Default
 1           RecordType  1         'M'
 2           ID          10
 3           MField1     10
</code>```

Detail Record:

```<code>Position    Desc        Length    Default
 1           RecordType  1         'D'
 2           ID          10
 3           MasterID    10
 4           MField1     10
</code>```

For example, if I had 2 row in Master (1,'MFieldVal1'),(2,'MFieldVal2') and 3 rows in Det (1,1,'DFieldVal1'),(2,1,'DFieldVal2'),(3,2,'DFieldVal3')

I'd export a file like this:

```<code>M         1MFieldVal1
D         1         1DFieldVal1
D         2         1DFieldVal2
M         2MFieldVal2
D         3         2DFieldVal3
</code>```

So far I built a view which joins Master and Det, and I used it as the source of my dataflow, but I don't know how to create the header row before its details in the exported file.

How can I achieve this??

答:
you can use an OLEDB Source with a similar SqlCommand to generate a column of type NVARCHAR that contains the whole row that you need to export to a flat file.

Note: Flat File must contains only one column in the flat file connection manager of type DT_WSTR and length equal to 4000 or higher if needed and map the column generated from the sqlCommand to it

```<code>SELECT  CAST(DataRow as NVARCHAR(4000))  as DataRow FROM (

SELECT ID ,'M' as RowType ,
       'M   ' + CAST(ID as VARCHAR(255)) + '    ' + MField1  AS DataRow
FROM Master

UNION ALL

SELECT IDMASTER ,'D' as RowType,
       'D   ' + CAST(ID as VARCHAR(255)) + '    ' + CAST(IDMASTER as VARCHAR(255)) + '  ' + DetField1  AS DataRow
FROM Det
        ) AS TBL
ORDER BY ID ASC, RowType DESC
</code>```

I made a little experiment in sql server

```<code>CREATE TABLE #Master (ID INT, MField1 VARCHAR(255))
CREATE TABLE #Det (ID INT, IDMaster INT , DetField1 VARCHAR(255))

INSERT INTO #Master(ID, MField1)
VALUES (1,'MFieldVal1'),(2,'MFieldVal2')

INSERT INTO #Det(ID, IDMASTER,DetField1)
VALUES (1,1,'DFieldVal1'),(2,1,'DFieldVal2'),(3,2,'DFieldVal3')

SELECT  CAST(DataRow as NVARCHAR(4000))  as DataRow FROM (

SELECT ID ,'M' as RowType ,  'M ' + CAST(ID as VARCHAR(255)) + '    ' + MField1  AS DataRow FROM #Master

UNION ALL

SELECT IDMASTER ,'D' as RowType,  'D    ' + CAST(ID as VARCHAR(255)) + '    ' + CAST(IDMASTER as VARCHAR(255)) + '  ' + DetField1  AS DataRow  FROM #Det) AS TBL
ORDER BY ID ASC, RowType DESC
</code>```

And the result was

Important Notes

In the SSIS the destination Flat File contains one column of type DT_WSTR but in real it contains Tab separated columns.

I used ine column, because it seems that you want to insert multiple structure into one flat file. So it is easier to do it this way

Body:
I have DB with a master table with its detail table, let's say

Master (ID, MField1)
Det    (ID, IDMaster, DetField1)

and I need to export a flat file with fixed column size, with both master rows and detail rows, here's below the records' structure:

Master Record:

Position    Desc        Length    Default
 1           RecordType  1         'M'
 2           ID          10
 3           MField1     10

Detail Record:

Position    Desc        Length    Default
 1           RecordType  1         'D'
 2           ID          10
 3           MasterID    10
 4           MField1     10

For example, if I had 2 row in Master (1,'MFieldVal1'),(2,'MFieldVal2') and 3 rows in Det (1,1,'DFieldVal1'),(2,1,'DFieldVal2'),(3,2,'DFieldVal3')

I'd export a file like this:

M         1MFieldVal1
D         1         1DFieldVal1
D         2         1DFieldVal2
M         2MFieldVal2
D         3         2DFieldVal3

So far I built a view which joins Master and Det, and I used it as the source of my dataflow, but I don't know how to create the header row before its details in the exported file.

How can I achieve this??

Body:
you can use an OLEDB Source with a similar SqlCommand to generate a column of type NVARCHAR that contains the whole row that you need to export to a flat file.

Note: Flat File must contains only one column in the flat file connection manager of type DT_WSTR and length equal to 4000 or higher if needed and map the column generated from the sqlCommand to it

SELECT  CAST(DataRow as NVARCHAR(4000))  as DataRow FROM (

SELECT ID ,'M' as RowType ,
       'M   ' + CAST(ID as VARCHAR(255)) + '    ' + MField1  AS DataRow
FROM Master

UNION ALL

SELECT IDMASTER ,'D' as RowType,
       'D   ' + CAST(ID as VARCHAR(255)) + '    ' + CAST(IDMASTER as VARCHAR(255)) + '  ' + DetField1  AS DataRow
FROM Det
        ) AS TBL
ORDER BY ID ASC, RowType DESC

I made a little experiment in sql server

CREATE TABLE #Master (ID INT, MField1 VARCHAR(255))
CREATE TABLE #Det (ID INT, IDMaster INT , DetField1 VARCHAR(255))

INSERT INTO #Master(ID, MField1)
VALUES (1,'MFieldVal1'),(2,'MFieldVal2')

INSERT INTO #Det(ID, IDMASTER,DetField1)
VALUES (1,1,'DFieldVal1'),(2,1,'DFieldVal2'),(3,2,'DFieldVal3')

SELECT  CAST(DataRow as NVARCHAR(4000))  as DataRow FROM (

SELECT ID ,'M' as RowType ,  'M ' + CAST(ID as VARCHAR(255)) + '    ' + MField1  AS DataRow FROM #Master

UNION ALL

SELECT IDMASTER ,'D' as RowType,  'D    ' + CAST(ID as VARCHAR(255)) + '    ' + CAST(IDMASTER as VARCHAR(255)) + '  ' + DetField1  AS DataRow  FROM #Det) AS TBL
ORDER BY ID ASC, RowType DESC

And the result was

Important Notes

In the SSIS the destination Flat File contains one column of type DT_WSTR but in real it contains Tab separated columns.

I used ine column, because it seems that you want to insert multiple structure into one flat file. So it is easier to do it this way


问:
Remove row dynamically from table in templates js
I have a page in which rows will be added dynamically using an add button (there is a java script function to add rows to the table on the page), these rows have to be deleted by clicking on a delete image which is a  value in one of the row
 that needs to be removed. I have done something like below, but 'onclick' is not working. The event is not getting triggered. What am I doing wrong here? Thanks.

```<code>function addRow(){
...
...
var deleteRow = "'deleteRowfun(\"rowNumber_"+(rowCount)+"\"); return false;'";

        var someName = "<tr id='rowNumber_" + (rowCount) + "' class = ' " + colorClass + " '><td valign='top' class='value'><label id='contactLastName_" +
            rowCount + "'>" + lastName + "</label></td>
            <td id='deleteContactAction_" + rowCount + "'>" +
            "<input type='image' src='/Projectname/plugins/folder/images/custom/delete-icon.jpg' id='contactDelete_" + rowCount + "'" +
            "title='Delete Contact' name='contactDelete' class='actionsIcon' " +
            "onclick="+ deleteRow + "/></td></tr>";

        $("#contactsTBL tbody").append(someName);
...
...

};

function deleteRowfun(itemId) {
        if (!confirm('Delete?')) {
            return false;
        }
        itemRowId = "#" + itemId
        $(itemRowId).remove();
    }
</code>```

答:
deleteRow doesn't exit as a function

when you call it it would be something like this: ...  "onclick='deleteRowfun("+itemId+")/>"; ...

Body:
I have a page in which rows will be added dynamically using an add button (there is a java script function to add rows to the table on the page), these rows have to be deleted by clicking on a delete image which is a  value in one of the row
 that needs to be removed. I have done something like below, but 'onclick' is not working. The event is not getting triggered. What am I doing wrong here? Thanks.

function addRow(){
...
...
var deleteRow = "'deleteRowfun(\"rowNumber_"+(rowCount)+"\"); return false;'";

        var someName = "
" + lastName + "
            " +
            "<input type='image' src='/Projectname/plugins/folder/images/custom/delete-icon.jpg' id='contactDelete_" + rowCount + "'" +
            "title='Delete Contact' name='contactDelete' class='actionsIcon' " +
            "onclick="+ deleteRow + "/>
";

        $("#contactsTBL tbody").append(someName);
...
...

};

function deleteRowfun(itemId) {
        if (!confirm('Delete?')) {
            return false;
        }
        itemRowId = "#" + itemId
        $(itemRowId).remove();
    }


问:
Load variable from a file & pass as arg value in ant build
What I want to do is load the contents of a file and sent it to an mxmlc compiler as an argument parameter.

I can load and read the contents of a file using loadfile and setting a property value say propery="filecontent". But the problem is I can pass it into the mxmlc (flex) compiler.

I'm not able to pass it (tried with ${filecontent}) to the arg line. Its gives an error: "value contains unknown token 'filecontent'"

How will I pass the contents of the file as a argument value to a compiler argument?

Edit:

The problem is with the include-resource-bundles arguments. When using command line it works. But using ant build doesn't. Do we need to manually provide the name of resource bundles by generating the resource file?

```<code><exec executable="${MXMLC}" dir="${APP_ROOT}/src" >
    <arg line="-locale 'en_US'"/>
  .. .. ..
    <arg line="-include-resource-bundles 'collections,components,containers,controls,core,effects,formatters,layout,modules,skins,states,styles'"/>
    .. ..
</code>```

I'm trying to replace the arguments via something like:

```<code>... ....
<loadfile property="resources" srcFile="${APP_ROOT}/src/resources.txt"/>
... ....
<exec executable="${MXMLC}" dir="${APP_ROOT}/src" >
  ...
    <arg line="-include-resource-bundles '${resources}'"/>
  ....
</exec>
</code>```

which doesn't work and gives and error -> command line: Error: configuration variable 'include-resource-bundles' value contains unknown token 'resources'

So how to automate this?

答:
There's nothing obviously wrong with the build file.  But the error message suggests that ${resources} is not set when you call the MXMLC compiler.  When an Ant property is not set, the property name (with dollar sign and enclosing curly brackets) is substituted instead anywhere that the property is used.

Can you insert something like

```<code><echo message="Resources: ${resources}" />
</code>```

after the 'loadfile' to check that that task is working?  Note, for example, that if the resources.txt is empty the property will not be set.

Body:
What I want to do is load the contents of a file and sent it to an mxmlc compiler as an argument parameter.

I can load and read the contents of a file using loadfile and setting a property value say propery="filecontent". But the problem is I can pass it into the mxmlc (flex) compiler.

I'm not able to pass it (tried with ${filecontent}) to the arg line. Its gives an error: "value contains unknown token 'filecontent'"

How will I pass the contents of the file as a argument value to a compiler argument?

Edit:

The problem is with the include-resource-bundles arguments. When using command line it works. But using ant build doesn't. Do we need to manually provide the name of resource bundles by generating the resource file?

<exec executable="${MXMLC}" dir="${APP_ROOT}/src" >
    <arg line="-locale 'en_US'"/>
  .. .. ..
    <arg line="-include-resource-bundles 'collections,components,containers,controls,core,effects,formatters,layout,modules,skins,states,styles'"/>
    .. ..

I'm trying to replace the arguments via something like:

... ....
<loadfile property="resources" srcFile="${APP_ROOT}/src/resources.txt"/>
... ....
<exec executable="${MXMLC}" dir="${APP_ROOT}/src" >
  ...
    <arg line="-include-resource-bundles '${resources}'"/>
  ....
</exec>

which doesn't work and gives and error -> command line: Error: configuration variable 'include-resource-bundles' value contains unknown token 'resources'

So how to automate this?

Body:
There's nothing obviously wrong with the build file.  But the error message suggests that ${resources} is not set when you call the MXMLC compiler.  When an Ant property is not set, the property name (with dollar sign and enclosing curly brackets) is substituted instead anywhere that the property is used.

Can you insert something like

<echo message="Resources: ${resources}" />

after the 'loadfile' to check that that task is working?  Note, for example, that if the resources.txt is empty the property will not be set.


问:
How to find records searched in all columns of table with multiple keyword in SQL Server?
I want to search the data in all fields by any keywords which is separated by space

For Example

Table Name:SampleTable

```<code>col1    |  col2  |   col3    |   col4 |  col5
-----------------------------------------------
my      |  name  |    is     | john   | Abraham
Abraham |   is   |   good    | person | null
Name    |  will  | Describe  |  a     | person
</code>```

If user search by word 'is'
select * from SampleTable where allColumn=is
It has to bring the result first two rows

```<code>my      |  name  |    is     | john   | Abraham
Abraham |   is   |   good    | person | null
</code>```

if search by is name. It has to bring first row

```<code>my      |  name  |    is     | john   | Abraham
</code>```

if search by Abraham is. It has to bring first and secend row

```<code>my      |  name  |    is     | john   | Abraham
Abraham |   is   |   good    | person | null
</code>```

It's almost like search engine. Do you have any idea?.

答:
You would seem to want full text search.  I would advise you to start with the documentation.

If you really want to use like and you want to pass in the words the way you are doing, then I would suggest splitting the string:

```<code>with terms as (
      select cast(left(@search, charindex(' ', @search + ' ') - 1) as varchar(max)) as term,
             cast(stuff(@search, 1, charindex(' ', @search + ' ') + 1, '') as varchar(max)) as rest
      union all
      select cast(left(rest, charindex(' ', rest + ' ') - 1) as varchar(max)),
             cast(stuff(rest, 1, charindex(' ', rest + ' ') + 1, '') as varchar(max))
      from terms
      where term <> ''
    )
select s.*
from sampleTable s cross apply
     (select count(*) as numterms,
             sum(case when t.term in (col1, col2, col3, col4, col5) then 1 else 0 end) as nummatches
      from terms t
     ) tt
where tt.numterms = tt.nummatches ;
</code>```

Body:
I want to search the data in all fields by any keywords which is separated by space

For Example

Table Name:SampleTable

col1    |  col2  |   col3    |   col4 |  col5
-----------------------------------------------
my      |  name  |    is     | john   | Abraham
Abraham |   is   |   good    | person | null
Name    |  will  | Describe  |  a     | person

If user search by word 'is'
select * from SampleTable where allColumn=is
It has to bring the result first two rows

my      |  name  |    is     | john   | Abraham
Abraham |   is   |   good    | person | null

if search by is name. It has to bring first row

my      |  name  |    is     | john   | Abraham

if search by Abraham is. It has to bring first and secend row

my      |  name  |    is     | john   | Abraham
Abraham |   is   |   good    | person | null

It's almost like search engine. Do you have any idea?.

Body:
You would seem to want full text search.  I would advise you to start with the documentation.

If you really want to use like and you want to pass in the words the way you are doing, then I would suggest splitting the string:

with terms as (
      select cast(left(@search, charindex(' ', @search + ' ') - 1) as varchar(max)) as term,
             cast(stuff(@search, 1, charindex(' ', @search + ' ') + 1, '') as varchar(max)) as rest
      union all
      select cast(left(rest, charindex(' ', rest + ' ') - 1) as varchar(max)),
             cast(stuff(rest, 1, charindex(' ', rest + ' ') + 1, '') as varchar(max))
      from terms
      where term <> ''
    )
select s.*
from sampleTable s cross apply
     (select count(*) as numterms,
             sum(case when t.term in (col1, col2, col3, col4, col5) then 1 else 0 end) as nummatches
      from terms t
     ) tt
where tt.numterms = tt.nummatches ;


问:
Only one toggle open at a time?
I am new to JS, so please bear with me.

I am trying to create a basic content toggle, however I am struggling to get my code to only show one toggle at a time.

The code I am using is:

```<code><div>
    <h3 class = "trigger"><a href="#box1"> Heading 1</a></h3>
    <h3 class = "trigger"><a href="#box2"> Heading 2</a></h3>

</div>
<div class ="toggle" id="box1">
        box one content
</div>

<div class ="toggle" id="box2">
    box two content
</div>

$("a").click(function(){
   var myelement = $(this).attr("href")
   $(myelement).slideToggle("slow");
   $(".toggle:visible").not(myelement).hide();
});
</code>```

答:
In order to have one toggle being shown at a time, you need to have a bit more control than the offered by slideToggle, since you are dealing with two opposite situations, the slideDown of the element you want to show, and the slideUp of the rest of them.

//By default they all will be hidden
$('.toggle').hide();
$("a").on('click', function(){
   //fetch the element wrapped with jQuery
   var $myelement = $($(this).attr("href"));
   //Hide all elements but the selected one
   //and shows it at the same time, since jQuery
   //returns the object right back to allow chaining
   $('.toggle').not($myelement.slideDown('slow')).slideUp("slow");
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <h3 class = "trigger"> Heading 1</h3>
  <h3 class = "trigger"> Heading 2</h3>
</div>
    <div class ="toggle" id="box1">
            box one content
    </div>

    <div class ="toggle" id="box2">
        box two content
    </div></code>```

Title: Only one toggle open at a time?

Body:
I am new to JS, so please bear with me.

I am trying to create a basic content toggle, however I am struggling to get my code to only show one toggle at a time.

The code I am using is:

 Heading 1

 Heading 2

        box one content

    box two content

$("a").click(function(){
   var myelement = $(this).attr("href")
   $(myelement).slideToggle("slow");
   $(".toggle:visible").not(myelement).hide();
});

Body:
In order to have one toggle being shown at a time, you need to have a bit more control than the offered by slideToggle, since you are dealing with two opposite situations, the slideDown of the element you want to show, and the slideUp of the rest of them.

//By default they all will be hidden
$('.toggle').hide();
$("a").on('click', function(){
   //fetch the element wrapped with jQuery
   var $myelement = $($(this).attr("href"));
   //Hide all elements but the selected one
   //and shows it at the same time, since jQuery
   //returns the object right back to allow chaining
   $('.toggle').not($myelement.slideDown('slow')).slideUp("slow");
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <h3 class = "trigger"><a href="#box1"> Heading 1</a></h3>
  <h3 class = "trigger"><a href="#box2"> Heading 2</a></h3>
</div>
    <div class ="toggle" id="box1">
            box one content
    </div>

    <div class ="toggle" id="box2">
        box two content
    </div>


问:
Version code error in exporting android apk
I have an app in the playstore. Its version code is 18.
Now made an update in the app and changed the version code to 19.
Cant upload the apk it shows the error.

This configuration cannot be published for the following reason(s):
Version 18 is not served to any device configuration: all devices that
might receive version 18 would receive version 28.

Some devices are
eligible to run multiple APKs. In such a scenario, the device will
receive the APK with the higher version code.

When i checked the AndroidManifest.xml file it shows error in the versioncode section

This versionCode value (18) is not used; it is always overridden by
the value specified in the Gradle build script (28) less... (Ctrl+F1)

The value of (for example) minSdkVersion is only used if it is not
specified in the build.gradle build scripts. When specified in the
Gradle build scripts, the manifest value is ignored and can be
misleading, so should be removed to avoid ambiguity.

答: Make sure you have the build.gradle(for the App) sync-ed

ContentLicense: CC BY-SA 4.0


问:
easiest way to generate base 3 numbers
I am trying to solve a mathematical problem programatically. Having a way to generate base 3 numbers would make it very easy to solve the problem. Do you know of any language that has in-built support for working with numbers of non-trivial base? It would be equally great if you could point me to some tool that can help me generate a sequence of base 3 numbers</p>

答: Just do a repeated divmod by 3 for the digits until you end up with 0. Multiply and add to restore the original.</p>

Title: easiest way to generate base 3 numbers


问:
Pin Button to Bottom Right Corner of TextField IOS
I would like to pin a button to the bottom right corner of a textfield. I completed this in Android using a relativelayout. I don't know how to do this in IOS. I attempted to set top and bottom constraints, but it didn't work.
Help?

Example

答:
Ok I have successfully pinned the button.
This is what I did.
I used control+click to set bottom and trailing constraints between the textfield and the button. Then I set equal height and equal width constraints between the button and the view and used a multiplier. </p>


问:
sed systemcall in python produces SOH character on macOS 10.12.4
I am trying to replace certain characters in a .h-file using a python script that does a sed-systemcall.

This is the line in the variables\ orig.h of which I want the '10' replaced with a value in an array:

```<code>#define PACKET_DELAY_TIME_A 10
</code>```

If I run a sed-command in bash, so e.g.

```<code>sed -E 's/(#define PACKET_DELAY_TIME_A).*/\1 2/' variables\ orig.h > variables.h
</code>```

this works completely fine and the output is as expected, namely the '10' is replaced with a '2'

However, when I use a python systemcall to do it, e.g.

```<code>import os

pckt_delay_A = ["1","2","5","10","20"]
command = "sed -E 's/(#define PACKET_DELAY_TIME_A).*/\1 " + pckt_delay_A[1] + "/' variables\ orig.h > variables.h"
os.system(command)
</code>```

this produces the SOH-character instead of the expected '#define PACKET_DELAY_TIME_A'

```<code>\u0001 2
</code>```

in my output file. Any idea on what causes this and how to get the expected output?
Thanks in advance!

答:
Use a raw string. With a normal string, \1 is interpreted by Python, which means to put a character with ASCII code 1 into the string, not being passed to the shell.

```<code>command = r"sed -E 's/(#define PACKET_DELAY_TIME_A).*/\1 " + pckt_delay_A[1] + r"/' variables\ orig.h > variables.h"
</code>```

Alternatively you could write the code that does this in Python, using its re module, rather than calling out to sed.

Body:
I am trying to replace certain characters in a .h-file using a python script that does a sed-systemcall.

This is the line in the variables\ orig.h of which I want the '10' replaced with a value in an array:

#define PACKET_DELAY_TIME_A 10

If I run a sed-command in bash, so e.g.

sed -E 's/(#define PACKET_DELAY_TIME_A).*/\1 2/' variables\ orig.h > variables.h

this works completely fine and the output is as expected, namely the '10' is replaced with a '2'

However, when I use a python systemcall to do it, e.g.

import os

pckt_delay_A = ["1","2","5","10","20"]
command = "sed -E 's/(#define PACKET_DELAY_TIME_A).*/\1 " + pckt_delay_A[1] + "/' variables\ orig.h > variables.h"
os.system(command)

this produces the SOH-character instead of the expected '#define PACKET_DELAY_TIME_A'

\u0001 2

in my output file. Any idea on what causes this and how to get the expected output?
Thanks in advance!

Body:
Use a raw string. With a normal string, \1 is interpreted by Python, which means to put a character with ASCII code 1 into the string, not being passed to the shell.

command = r"sed -E 's/(#define PACKET_DELAY_TIME_A).*/\1 " + pckt_delay_A[1] + r"/' variables\ orig.h > variables.h"

Alternatively you could write the code that does this in Python, using its re module, rather than calling out to sed.


问:
On change event doesn't work with dynamically created item
change event

```<code>$('.amount').on('change','input', function(){
        alert('hello!');
});
</code>```

dynamicly created item:

```<code><tr id="row{{$data['product_id']}}">
    <td><input type="checkbox" name="product[]" value="{{$data['product_id']}}"></td>
    <td>{{$data['product_id']}}</td>
    <td class="amount">{!! Form::input('number','qty',$data['qty'],['id'=>$data['product_id'],'min'=>'1','max'=>\App\Product::find($data['product_id'])->quantity,'required'=>'required'])!!}
    </td>
    <td>{{$data['stock']}}</td>
    <td id="rowprice{{$data['product_id']}}">{{$data['price']}} $</td>
    <td id="rowsum{{$data['product_id']}}">{{$data['qty']*$data['price']}} $</td>
</tr>
</code>```

adding this item:

```<code>$('#addProduct').click(function (e) {
        $('#qty').attr('required', 'required');
        $('#product_id').attr('required', 'required');
        e.preventDefault();

        var product_id = $('#product_id').val();
        var data = $("#editOrderContent").serializeArray();
        data.push(addProduct);

        $.ajax({
            type: 'POST',
            dataType: 'JSON',
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            url: $('#editOrderContent').attr('action'),
            data: data,
            success: function (html) {

               if (html.success) {
                    $('#summary').before(html.tdProduct);
                }
            }
        });

    });
</code>```

So when I try to change the value of qty input with freshly created item, event doesn't trigger, but when I reload page, it does.

答:
When you bind to a class, ID, etc., jQuery is only able to bind to elements currently on the page. It can't see into the future. The common fix for this is to bind to the document. It's kind of hard to see what you actually want to bind to, but here's an example.</p>

```<code>$(document).on('change','.amount input', function(){
        alert('hello!');
});
</code>```

Body:
change event

$('.amount').on('change','input', function(){
        alert('hello!');
});

dynamicly created item:

    <input type="checkbox" name="product[]" value="{{$data['product_id']}}">
    {{$data['product_id']}}
    {!! Form::input('number','qty',$data['qty'],['id'=>$data['product_id'],'min'=>'1','max'=>\App\Product::find($data['product_id'])->quantity,'required'=>'required'])!!}

    {{$data['stock']}}
    {{$data['price']}} $
    {{$data['qty']*$data['price']}} $

adding this item:

$('#addProduct').click(function (e) {
        $('#qty').attr('required', 'required');
        $('#product_id').attr('required', 'required');
        e.preventDefault();

        var product_id = $('#product_id').val();
        var data = $("#editOrderContent").serializeArray();
        data.push(addProduct);

        $.ajax({
            type: 'POST',
            dataType: 'JSON',
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            url: $('#editOrderContent').attr('action'),
            data: data,
            success: function (html) {

               if (html.success) {
                    $('#summary').before(html.tdProduct);
                }
            }
        });

    });

So when I try to change the value of qty input with freshly created item, event doesn't trigger, but when I reload page, it does.

Body:
When you bind to a class, ID, etc., jQuery is only able to bind to elements currently on the page. It can't see into the future. The common fix for this is to bind to the document. It's kind of hard to see what you actually want to bind to, but here's an example.

$(document).on('change','.amount input', function(){
        alert('hello!');
});


问:
sqlfilestream - getting blob data from SQL Server and saving the file locally to disk
I have the following scenario:

I have successfully saved my files(various extensions) into my sql server db using FILESTREAM.  These can be anything from an image, to a word doc, pdf etc.

now i want to retreive them and save them as a file to my local directory.

here is what i have so far

My function calling SQL and getting the the filestream information i want

```<code>    public static void SelectFile(string sourceId)
    {
        string serverPath;
        string filename;
        byte[] serverTxn;

        using (TransactionScope ts = new TransactionScope())
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["DBConn"].ToString()))
            {
                conn.Open();

                using (SqlCommand cmd = new SqlCommand("OPS.LoadFileBlobFromSQL", conn))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@AttachmentId", SqlDbType.VarChar).Value = sourceId;

                    using (SqlDataReader rdr = cmd.ExecuteReader())
                    {
                        rdr.Read();
                        filename = rdr.GetSqlString(0).Value;
                        serverPath = rdr.GetSqlString(1).Value;
                        serverTxn = rdr.GetSqlBinary(2).Value;
                        rdr.Close();
                    }
                }
               StreamObjectFromFilestream(serverPath, serverTxn, filename);
            }
            ts.Complete();
        }
    }

    private static void StreamObjectFromFilestream(string serverPath, byte[] serverTxn, string filename)
    {
        SqlFileStream sfs = new SqlFileStream(serverPath, serverTxn, FileAccess.Read);
        byte[] buffer = new byte[sfs.Length];
        sfs.Read(buffer, 0, buffer.Length);

        System.IO.File.WriteAllBytes(@"c:\test\hello.pdf", buffer);
        sfs.Close();
    }
</code>```

I am getting serverpath, filename and serverTxn .. but when i go into my StreamObjectFromFilestream function the buffer is empty.. i know i am missing something simple here  ... just dont know what.

Any pointers in the right direction would be appreciated.

Thanks,
Corey

答: You can skip using the SqlFilestream inside StreamObjectFromFilestram, your serverTxn is already a byte array that the Method WriteAllBytes is needing.</p>

Body:
I have the following scenario:

I have successfully saved my files(various extensions) into my sql server db using FILESTREAM.  These can be anything from an image, to a word doc, pdf etc.

now i want to retreive them and save them as a file to my local directory.

here is what i have so far

My function calling SQL and getting the the filestream information i want

    public static void SelectFile(string sourceId)
    {
        string serverPath;
        string filename;
        byte[] serverTxn;

        using (TransactionScope ts = new TransactionScope())
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["DBConn"].ToString()))
            {
                conn.Open();

                using (SqlCommand cmd = new SqlCommand("OPS.LoadFileBlobFromSQL", conn))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@AttachmentId", SqlDbType.VarChar).Value = sourceId;

                    using (SqlDataReader rdr = cmd.ExecuteReader())
                    {
                        rdr.Read();
                        filename = rdr.GetSqlString(0).Value;
                        serverPath = rdr.GetSqlString(1).Value;
                        serverTxn = rdr.GetSqlBinary(2).Value;
                        rdr.Close();
                    }
                }
               StreamObjectFromFilestream(serverPath, serverTxn, filename);
            }
            ts.Complete();
        }
    }

    private static void StreamObjectFromFilestream(string serverPath, byte[] serverTxn, string filename)
    {
        SqlFileStream sfs = new SqlFileStream(serverPath, serverTxn, FileAccess.Read);
        byte[] buffer = new byte[sfs.Length];
        sfs.Read(buffer, 0, buffer.Length);

        System.IO.File.WriteAllBytes(@"c:\test\hello.pdf", buffer);
        sfs.Close();
    }

I am getting serverpath, filename and serverTxn .. but when i go into my StreamObjectFromFilestream function the buffer is empty.. i know i am missing something simple here  ... just dont know what.

Any pointers in the right direction would be appreciated.

Thanks,
Corey


问:
How get coordinates from polygons inside a Layer
I have a LayerGroup

```<code>var mapLayer = new L.layerGroup();
</code>```

This is how I add several polygons to this LayerGroup:

```<code>var buffered = turf.buffer(polyline, path_alarmweight, 'meters');
bufferedPolygon = L.geoJson(buffered, bufferedOptions).addTo(mapLayer);`
</code>```

How can I get the coordinates from a single or several polygons which I added to the mapLayer?

答:
First of all you need to get all layers from LayerGroup, use getLayers() function, in documentation. You will get layers in LayerGroup:

```<code>var arrayOfLayers = mapLayer.getLayers();
</code>```

Then you can iterate over arrayOfLayers and for every layer you can get coordinates of polygon with getLatLngs() function. See the reference:

```<code>for(var i=0; i < arrayOfLayers.length; i++) {
// first get array of coordinates
var arrayOfPoints = arrayOfLayers[i].getLatLngs();

    //then iterate over coordinates
    for(var j=0; j < arrayOfPoints.length; j++) {
        console.log(arrayOfPoints[j]);
    }
}
</code>```

Body:
I have a LayerGroup

var mapLayer = new L.layerGroup();

This is how I add several polygons to this LayerGroup:

var buffered = turf.buffer(polyline, path_alarmweight, 'meters');
bufferedPolygon = L.geoJson(buffered, bufferedOptions).addTo(mapLayer);`

How can I get the coordinates from a single or several polygons which I added to the mapLayer?

Body:
First of all you need to get all layers from LayerGroup, use getLayers() function, in documentation. You will get layers in LayerGroup:

var arrayOfLayers = mapLayer.getLayers();

Then you can iterate over arrayOfLayers and for every layer you can get coordinates of polygon with getLatLngs() function. See the reference:

for(var i=0; i < arrayOfLayers.length; i++) {
// first get array of coordinates
var arrayOfPoints = arrayOfLayers[i].getLatLngs();

    //then iterate over coordinates
    for(var j=0; j < arrayOfPoints.length; j++) {
        console.log(arrayOfPoints[j]);
    }
}


问:
Setting order of accesibility labels in subviews of a group, read aloud by Voiceover?
I have a UITableView with cells based on an XIB with UIStackViews containing UILabels, in it. Labels have the texts A,B,C,D
 (look at screenshot).

When I enable VoiceOver or use the Accesibility Inspector, It automaticallly groups the labels in a cell, reading all the texts on the labels - that's fine.

But I want it to change the order that it reads the sub-labels, when the superview is focused, so it's read like A,B,C,D - currently it's A,C,B,D.

I've tried a lot of things with no luck, like overriding the accesibilityElements, shouldGroup... and isAccessiblityElement. Every time I change something, i get either:

No change

Empty accesiblity label for the cell

The single labels become selectable (which is not what I wanted)

Any tips on how to fix this one? I guess I can't be the only one in the world with this problem, but apparently it's hard to find any info on recent iOS versions. I use 10.3 and Swift 3...

答:
I gave up on the idea of profiting form iOS own concatenation of the subviews' accesibility labels and made a piece of code to handle it myself.

```<code>extension UIView {
    open func updateCombinedAccessibilityLabel (elements: [AnyObject]) {
        let accLabels: [String] = elements.map { $0.accessibilityLabel ?? "" }
        accessibilityLabel = accLabels.joined(separator: ", ")
    }
}
</code>```

Then, when I set the labels' text values, I tell the view how to arrange the subviews' accesiblity order:

```<code>view.updateCombinedAccessibilityLabel(elements: [view.titleLabel, view.subtitleLabel, view.detailsLabel])
</code>```

Body:
I gave up on the idea of profiting form iOS own concatenation of the subviews' accesibility labels and made a piece of code to handle it myself.

extension UIView {
    open func updateCombinedAccessibilityLabel (elements: [AnyObject]) {
        let accLabels: [String] = elements.map { $0.accessibilityLabel ?? "" }
        accessibilityLabel = accLabels.joined(separator: ", ")
    }
}

Then, when I set the labels' text values, I tell the view how to arrange the subviews' accesiblity order:

view.updateCombinedAccessibilityLabel(elements: [view.titleLabel, view.subtitleLabel, view.detailsLabel])


问:
Plotting a dendrogram using Plotly Python
I am trying to plot a dendrogram using Python, preferably using Plotly. I have a dataset containing a clustering of various objects. I can use this dataset to generate the required data or at least extrapolate. However, I don't understand what the input to the create_dendrogram actually is. The doc just says that it is a ndarray - Matrix of observations as array of arrays. I am familiar with Numpy ndarrays, but I would like to know what the array must contain.

More specifically, what is the significance of the value X[i][j]. It just seems to be a float between 0 and 1. I had looked at the Plotly API documentation for Python here - https://plot.ly/python/dendrogram/

```<code>import plotly.plotly as py
from plotly.tools import FigureFactory as FF

import numpy as np

X = np.random.rand(10, 10)
fig = FF.create_dendrogram(X, orientation='left', labels=names)
py.iplot(fig, filename='dendrogram_with_labels')
</code>```

If there was an alternative and more intuitive way to get a dendrogram in Python I would also like to know that. I am  new to this and any help would be appreciated. (Please let me know if I need to rephrase the question!)

答:
You can pass a linkage function to the create_dendrogram function.  For example:</p>

```<code>from scipy.cluster.hierarchy import linkage

...

figure = FF.create_dendrogram(
    data_array, orientation='bottom', labels=id_label_list,
    linkagefun=lambda x: linkage(data_array, 'ward', metric='euclidean')
)
</code>```

Body:
I am trying to plot a dendrogram using Python, preferably using Plotly. I have a dataset containing a clustering of various objects. I can use this dataset to generate the required data or at least extrapolate. However, I don't understand what the input to the create_dendrogram actually is. The doc just says that it is a ndarray - Matrix of observations as array of arrays. I am familiar with Numpy ndarrays, but I would like to know what the array must contain.

More specifically, what is the significance of the value X[i][j]. It just seems to be a float between 0 and 1. I had looked at the Plotly API documentation for Python here - https://plot.ly/python/dendrogram/

import plotly.plotly as py
from plotly.tools import FigureFactory as FF

import numpy as np

X = np.random.rand(10, 10)
fig = FF.create_dendrogram(X, orientation='left', labels=names)
py.iplot(fig, filename='dendrogram_with_labels')

If there was an alternative and more intuitive way to get a dendrogram in Python I would also like to know that. I am  new to this and any help would be appreciated. (Please let me know if I need to rephrase the question!)

Body:
You can pass a linkage function to the create_dendrogram function.  For example:

from scipy.cluster.hierarchy import linkage

...

figure = FF.create_dendrogram(
    data_array, orientation='bottom', labels=id_label_list,
    linkagefun=lambda x: linkage(data_array, 'ward', metric='euclidean')
)


问:
win32 resource file help
on this website, under the "Edit Control" title, there are a couple of lines of code like this..

```<code>case WM_CREATE:
    hwndEdit = CreateWindow(TEXT("Edit"), NULL, WS_CHILD | WS_VISIBLE | WS_BORDER,
                50, 50, 150, 20, hwnd, (HMENU) ID_EDIT,
                NULL, NULL);

    hwndButton = CreateWindow(
        TEXT("button"), TEXT("Set Title"),
        WS_VISIBLE | WS_CHILD,
        50, 100, 80, 25,
        hwnd, (HMENU) ID_BUTTON, NULL, NULL);

    break;
</code>```

I know that this method of creating buttons and such are done on the fly, But I was wondering how you would do it without doing it like this, instead using a resource file?.
In the Forgers Win32 tutorial it shows how to make a menu using a resource file, and how to describe a dialog box etc, But I cant seem to put any controls on the main(parent) window using a resource file??.

for example I have the following .rc file

```<code>#include "resource.h"
ID_MENU MENU
BEGIN
    POPUP "&File"
    BEGIN
        MENUITEM "E&xit", ID_FILE_EXIT
    END
    POPUP "&About"
    BEGIN
        MENUITEM "&Information", ID_ABOUT_INFO
    END
END

ID_ABOUT_INFO DIALOG DISCARDABLE  0,0,250,250
CAPTION "Information"
BEGIN
    CTEXT "some text",ID_BLA,15,15,144,33
END

//this is all fine but how do I decribe the main window?, instead of the menu and dialog boxes?.
</code>```

How do I describe the main window instead of creating things on the fly?. Is there some kind of keyword?

答: You can design a window like it was a dialog and put it in your resourcefile .Then use the FindResource and LoadResource functions to get a pointer to a DLGTEMPLATE ,which contains all the dialogs layout which you can use to size you own window and place controls at the positions you defined in the dialog (It's not easy though to interpret the DLGTEMPLATE). Don't forget to free the pointer to the DLGTEMPLATE.  </p>

Title: win32 resource file help

Body:
on this website, under the "Edit Control" title, there are a couple of lines of code like this..

case WM_CREATE:
    hwndEdit = CreateWindow(TEXT("Edit"), NULL, WS_CHILD | WS_VISIBLE | WS_BORDER,
                50, 50, 150, 20, hwnd, (HMENU) ID_EDIT,
                NULL, NULL);

    hwndButton = CreateWindow(
        TEXT("button"), TEXT("Set Title"),
        WS_VISIBLE | WS_CHILD,
        50, 100, 80, 25,
        hwnd, (HMENU) ID_BUTTON, NULL, NULL);

    break;

I know that this method of creating buttons and such are done on the fly, But I was wondering how you would do it without doing it like this, instead using a resource file?.
In the Forgers Win32 tutorial it shows how to make a menu using a resource file, and how to describe a dialog box etc, But I cant seem to put any controls on the main(parent) window using a resource file??.

for example I have the following .rc file

#include "resource.h"
ID_MENU MENU
BEGIN
    POPUP "&File"
    BEGIN
        MENUITEM "E&xit", ID_FILE_EXIT
    END
    POPUP "&About"
    BEGIN
        MENUITEM "&Information", ID_ABOUT_INFO
    END
END

ID_ABOUT_INFO DIALOG DISCARDABLE  0,0,250,250
CAPTION "Information"
BEGIN
    CTEXT "some text",ID_BLA,15,15,144,33
END

//this is all fine but how do I decribe the main window?, instead of the menu and dialog boxes?.

How do I describe the main window instead of creating things on the fly?. Is there some kind of keyword?


问:
How do I read a RAW RGB image in MATLAB?
I am trying to properly convert a RAW image so that I can view it in MATLAB. Image can be downloaded here. I am using the version of the code provided in How can I read in a RAW image in MATLAB?
However, it is not working properly for me. Here is my slightly modified version below:

```<code>clear;
row=966;  col=1296;
fin=fopen('C:\Users\user\Desktop\test2.raw','r');
I=fread(fin, col*row*3,'uint8=>uint8'); %// Read in as a single byte stream
I = reshape(I, [col row 3]); %// Reshape so that it's a 3D matrix - Note that this is column major
Ifinal = flipdim(imrotate(I, -90),2); % // The clever transpose
imshow(Ifinal);
fclose(fin); %// Close the file
</code>```

What I get:

What I should get:

I'm not sure why it's not working for me but if I use an imaging program (ImageJ) I can correctly convert the RAW file if I select Image type as '24-bit BGR'. The pixel format of the image is 8 Bit BAYRG.

答:
There you go:

```<code>function q43127920
row=966; col=1296;
fin=fopen('test.raw','r');
I = fread(fin, col*row*3,'ubit24=>uint32');
I = reshape(I, col, row, []);
B = uint8(bitand(bitshift(I,-00),uint32(255)));
G = uint8(bitand(bitshift(I,-08),uint32(255)));
R = uint8(bitand(bitshift(I,-16),uint32(255)));
I = cat(3,R,G,B);
Ifinal = flip(imrotate(I, -90),2);
imagesc(Ifinal);
fclose(fin);
</code>```

Result:

Body:
I am trying to properly convert a RAW image so that I can view it in MATLAB. Image can be downloaded here. I am using the version of the code provided in How can I read in a RAW image in MATLAB?
However, it is not working properly for me. Here is my slightly modified version below:

clear;
row=966;  col=1296;
fin=fopen('C:\Users\user\Desktop\test2.raw','r');
I=fread(fin, col*row*3,'uint8=>uint8'); %// Read in as a single byte stream
I = reshape(I, [col row 3]); %// Reshape so that it's a 3D matrix - Note that this is column major
Ifinal = flipdim(imrotate(I, -90),2); % // The clever transpose
imshow(Ifinal);
fclose(fin); %// Close the file

What I get:

What I should get:

I'm not sure why it's not working for me but if I use an imaging program (ImageJ) I can correctly convert the RAW file if I select Image type as '24-bit BGR'. The pixel format of the image is 8 Bit BAYRG.

Body:
There you go:

function q43127920
row=966; col=1296;
fin=fopen('test.raw','r');
I = fread(fin, col*row*3,'ubit24=>uint32');
I = reshape(I, col, row, []);
B = uint8(bitand(bitshift(I,-00),uint32(255)));
G = uint8(bitand(bitshift(I,-08),uint32(255)));
R = uint8(bitand(bitshift(I,-16),uint32(255)));
I = cat(3,R,G,B);
Ifinal = flip(imrotate(I, -90),2);
imagesc(Ifinal);
fclose(fin);

Result:


问:
The Decorator Design Pattern: What is meant by adding functionality?
I have just gone into studying the Decorator Design Pattern using C#.

I have made an example which kinda functions as I think it is intended except for one thing.

I kinda understood that the whole point of the pattern is to add functionality to an object dynamically.

So when I create an object like this:

```<code>Inventory a = new Ashbringer(new TravelersBagpack());
a.Execute();
</code>```

Then I kinda expected that the point was that the a object would now be able to call the Execute() method which only exists in the Ashbringer class. Thus adding functionality to the a object.

Though this I can't do without adding the Execute() method to the Inventory interface which would ultimately mean I would have to implement the Execute() method to all the classes implementing Inventory Interface or the abstract Decorator.

Perhaps there is a thing or two I don't know about interfaces or perhaps I misunderstand the point of the Decorator Design Pattern?

答:
The Decorator pattern is more about changing the behavior of existing methods of an object that you're decorating (wrapping) rather than adding new methods. While the decorator can certainly have its own methods, the intent is that the decorator can be treated as if it were the object it is wrapping.

Consider the Stream classes in .NET. Stream is a common abstract class that simply defines a basic interface for reading and writing to streams, but a concrete subclass like FileStream provides the implementation to read/write files. But if you want to add buffering or compression behavior to a FileStream class, you wouldn't want to subclass FileStream, because then your subclass wouldn't work with NetworkStream or MemoryStream unless you also made subclasses for them.

That's where the Decorator pattern comes in. A BufferedStream or CompressedStream class can "decorate" another instance of a Stream. You can read/write from BufferedStream or CompressedStream the same as you would read/write against any undecorated stream. It does this by overriding the methods of the Stream class, adding its functionality by doing whatever to the bytes coming into or out of the stream, then passing them onto the wrapped object, whether it's a FileStream, NetworkStream, or even another decorator.

But going back to your WoW example, maybe a better example would be an EnchantedWeapon class or a TransmogrifiedWeapon class that would act as decorators of a Weapon class. Then you could do something like:

```<code>Weapon w = new Ashbringer();
w = new TransmogrifiedWeapon(w, "Exodar Bastard Sword");
w = new EnchantedWeapon(w, "Scourgebane");
w.Render();
</code>```

Of course, that would obviously throw an exception, because everybody knows that Ashbringer can't be transmogged. :)

Body:
I have just gone into studying the Decorator Design Pattern using C#.

I have made an example which kinda functions as I think it is intended except for one thing.

I kinda understood that the whole point of the pattern is to add functionality to an object dynamically.

So when I create an object like this:

Inventory a = new Ashbringer(new TravelersBagpack());
a.Execute();

Then I kinda expected that the point was that the a object would now be able to call the Execute() method which only exists in the Ashbringer class. Thus adding functionality to the a object.

Though this I can't do without adding the Execute() method to the Inventory interface which would ultimately mean I would have to implement the Execute() method to all the classes implementing Inventory Interface or the abstract Decorator.

Perhaps there is a thing or two I don't know about interfaces or perhaps I misunderstand the point of the Decorator Design Pattern?

Body:
The Decorator pattern is more about changing the behavior of existing methods of an object that you're decorating (wrapping) rather than adding new methods. While the decorator can certainly have its own methods, the intent is that the decorator can be treated as if it were the object it is wrapping.

Consider the Stream classes in .NET. Stream is a common abstract class that simply defines a basic interface for reading and writing to streams, but a concrete subclass like FileStream provides the implementation to read/write files. But if you want to add buffering or compression behavior to a FileStream class, you wouldn't want to subclass FileStream, because then your subclass wouldn't work with NetworkStream or MemoryStream unless you also made subclasses for them.

That's where the Decorator pattern comes in. A BufferedStream or CompressedStream class can "decorate" another instance of a Stream. You can read/write from BufferedStream or CompressedStream the same as you would read/write against any undecorated stream. It does this by overriding the methods of the Stream class, adding its functionality by doing whatever to the bytes coming into or out of the stream, then passing them onto the wrapped object, whether it's a FileStream, NetworkStream, or even another decorator.

But going back to your WoW example, maybe a better example would be an EnchantedWeapon class or a TransmogrifiedWeapon class that would act as decorators of a Weapon class. Then you could do something like:

Weapon w = new Ashbringer();
w = new TransmogrifiedWeapon(w, "Exodar Bastard Sword");
w = new EnchantedWeapon(w, "Scourgebane");
w.Render();

Of course, that would obviously throw an exception, because everybody knows that Ashbringer can't be transmogged. :)


问:
Mocking Symfony Entities for Unit Testing using PHPUnit and Mockery
```<code>public function reportsToBeRun()
{
    $reports = $this->repository->getReportsToBeRun();

    foreach ($reports as $report) {
        $report->setUpdated(new \DateTime());
    }

    return $reports;
}
</code>```

I am learning test driven development in my new job and I am struggling with how I would test the above example. I make a call to a repository that uses getResults() and returns an array of entity objects. I can mock the repository fine, but I do not know what I am best to return here. I can mock the entities and return them, but then the setUpdated will not do anything. I can obviously mock setUpdated, but I do not know how to get it to update the mocked entity or entities.

My 2nd issue with this is the tests I am writing are not really testing anything. The repository call is being mocked and so is the setter. I am then just returning whatever I mocked. What would you recommend doing for a function like this.

答:
I wouldn't mock the entities, as they are plain old PHP objects that won't access external resources.

It's better to mock the repository and have it return a collection of entities:

```<code>class MyTest extends \PHPUnit_Framework_TestCase
{

    private $service;

    protected function setUp()
    {
        parent::setUp();
        $this->service = new ReportService($this->createRepositoryMock());
    }

    protected function tearDown()
    {
        $this->service = null;
        parent::tearDown();
    }

    public function testReportsToBeRun()
    {
        $reports = $this->service->reportsToBeRun();
        $now = new \DateTime();

        foreach ($reports as $report) {
            $this->assertInstanceOf(Report::class, $report);
            $this->assertTrue($report->getUpdated() <= $now);
        }
    }

    private function createRepositoryMock()
    {
        $mock = \Mockery::mock(ReportRepository::class);

        $reports = [
            $this->createReport(1),
            $this->createReport(2),
            $this->createReport(3),
        ];

        $mock->shouldReceive('getReportsToBeRun')->andReturn($reports);
    }

    private function createReport($id)
    {
        $report = new Report();
        $report->setId($id);

        return $report;
    }
}
</code>```

ReportService is your service that contains the reportsToBerun method.

Report is your entity class.

ReportRepository is the repository class that is mocked.

Body:
public function reportsToBeRun()
{
    $reports = $this->repository->getReportsToBeRun();

    foreach ($reports as $report) {
        $report->setUpdated(new \DateTime());
    }

    return $reports;
}

I am learning test driven development in my new job and I am struggling with how I would test the above example. I make a call to a repository that uses getResults() and returns an array of entity objects. I can mock the repository fine, but I do not know what I am best to return here. I can mock the entities and return them, but then the setUpdated will not do anything. I can obviously mock setUpdated, but I do not know how to get it to update the mocked entity or entities.

My 2nd issue with this is the tests I am writing are not really testing anything. The repository call is being mocked and so is the setter. I am then just returning whatever I mocked. What would you recommend doing for a function like this.

Body:
I wouldn't mock the entities, as they are plain old PHP objects that won't access external resources.

It's better to mock the repository and have it return a collection of entities:

class MyTest extends \PHPUnit_Framework_TestCase
{

    private $service;

    protected function setUp()
    {
        parent::setUp();
        $this->service = new ReportService($this->createRepositoryMock());
    }

    protected function tearDown()
    {
        $this->service = null;
        parent::tearDown();
    }

    public function testReportsToBeRun()
    {
        $reports = $this->service->reportsToBeRun();
        $now = new \DateTime();

        foreach ($reports as $report) {
            $this->assertInstanceOf(Report::class, $report);
            $this->assertTrue($report->getUpdated() <= $now);
        }
    }

    private function createRepositoryMock()
    {
        $mock = \Mockery::mock(ReportRepository::class);

        $reports = [
            $this->createReport(1),
            $this->createReport(2),
            $this->createReport(3),
        ];

        $mock->shouldReceive('getReportsToBeRun')->andReturn($reports);
    }

    private function createReport($id)
    {
        $report = new Report();
        $report->setId($id);

        return $report;
    }
}

ReportService is your service that contains the reportsToBerun method.

Report is your entity class.

ReportRepository is the repository class that is mocked.