问:
Is there an existing way to use arbitrary C# expressions in XAML?
I'd like to be able to use arbitrary C# expressions in XAML.  Usually this would be to compute a property for a UI element based on two bound values.

For example calculating the width of a UI element based on two other properties.

This is a contrived example of what I'd like the XAML to look like:

```<code><TextBox
   x:Name="textBox1"
   />

<TextBox
   x:Name="textBox2"
   />

<Rectangle
    Height={Double.Parse(textBox1.Text) + Double.Parse(textBox2.Text)}
    />
</code>```

Of course there is no built-in way of doing this in XAML.

I know that I could use a MultiBinding combined with a custom converter and this is usually the way I do this kind of thing.  However it seems to me that it would be so much simpler to just include some C# code in the XAML and I was wondering if anyone out there had already solved this problem with a XAML extension or something else.

答:
I have an answer to my question now.  It isn't the answer I was originally looking for, and it is a bit long winded but it does work.

I was reading this post by Josh Smith.  He recommends not using value converters but pushing   the calculations down into the view-model and exposing it as a property:

http://groups.google.com/group/wpf-disciples/browse_thread/thread/3fe270cd107f184f?pli=1

In my case the text for both 'textBox1' and 'textBox2' should be bound into the view-model, so when they change in the view-model I know its time to do the calculation and update the dependent property.  The dependent property then fires its property changed event and the UI updates from that.

If you have a case where you want to make the expression depend on read-only control properties, that you can't easily bind to the view-model, you can follow the advice presented here:

Pushing read-only GUI properties back into ViewModel

I still would like to have the ability to embed (non-business logic) expressions in the XAML.  But seeing as this is not built-in any way of doing it is likely to be a bit of a hack.  Going through the view-model seems to be the correct way of doing this, but maybe one-day I'll experiment with writing a markup extension that allows expression in XAML.

Body:
I'd like to be able to use arbitrary C# expressions in XAML.  Usually this would be to compute a property for a UI element based on two bound values.

For example calculating the width of a UI element based on two other properties.

This is a contrived example of what I'd like the XAML to look like:

<TextBox
   x:Name="textBox1"
   />

<TextBox
   x:Name="textBox2"
   />

<Rectangle
    Height={Double.Parse(textBox1.Text) + Double.Parse(textBox2.Text)}
    />

Of course there is no built-in way of doing this in XAML.

I know that I could use a MultiBinding combined with a custom converter and this is usually the way I do this kind of thing.  However it seems to me that it would be so much simpler to just include some C# code in the XAML and I was wondering if anyone out there had already solved this problem with a XAML extension or something else.


来源: stackexchange

问:
Scala: change value in list inside a map
I'm facing a problem:
I want to change one element inside but the code is changing all elements.
I must be doing something wrong.
Here's what I have:

```<code>var critics: Map[String, List[(String, Double)]] = Map(
  "First" -> List(("a", 1.0), ("b", 2.0)),
  "Second" -> List(("c", 3.0), ("d", 4.0))
  )

  def setNewRating(keyMap: String, param1: String, newRating: Double) = {
    val newList = critics(keyMap).map{case (param1, _) => (param1, newRating); case x => x}
    critics = critics + (keyMap -> newList)
    }

    println(critics)

    setNewRating("First", "b", 5.0)

    println(critics)
</code>```

so, I'm looking for the key "First" and getting the List I want to change the "b" from 2.0 to 5.0 but the result I'm getting is:

```<code>critics: Map[String,List[(String, Double)]] = Map(First -> List((a,1.0), (b,2.0)), Second -> List((c,3.0), (d,4.0)))
setNewRating: (keyMap: String, param1: String, newRating: Double)Unit
Map(First -> List((a,1.0), (b,2.0)), Second -> List((c,3.0), (d,4.0)))
Map(First -> List((a,5.0), (b,5.0)), Second -> List((c,3.0), (d,4.0)))
</code>```

The code changed all the values!

thanks in advance,

答:
This should work. the param1 you use in the case clause .map{case (param1, _) is not the same variable param1 defined in the argument. It is a new variable param1 which is assigned the value of the first element of the Tuple2 that shadows the method argument.

```<code>def setNewRating(keyMap: String, param1: String, newRating: Double) = {
  val newList = critics(keyMap) map {
    case (x, _) if x == param1 => (param1, newRating)
    case x => x
  }
  critics = critics + (keyMap -> newList)
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm facing a problem:
I want to change one element inside but the code is changing all elements.
I must be doing something wrong.
Here's what I have:

var critics: Map[String, List[(String, Double)]] = Map(
  "First" -> List(("a", 1.0), ("b", 2.0)),
  "Second" -> List(("c", 3.0), ("d", 4.0))
  )

  def setNewRating(keyMap: String, param1: String, newRating: Double) = {
    val newList = critics(keyMap).map{case (param1, _) => (param1, newRating); case x => x}
    critics = critics + (keyMap -> newList)
    }

    println(critics)

    setNewRating("First", "b", 5.0)

    println(critics)

so, I'm looking for the key "First" and getting the List I want to change the "b" from 2.0 to 5.0 but the result I'm getting is:

critics: Map[String,List[(String, Double)]] = Map(First -> List((a,1.0), (b,2.0)), Second -> List((c,3.0), (d,4.0)))
setNewRating: (keyMap: String, param1: String, newRating: Double)Unit
Map(First -> List((a,1.0), (b,2.0)), Second -> List((c,3.0), (d,4.0)))
Map(First -> List((a,5.0), (b,5.0)), Second -> List((c,3.0), (d,4.0)))

The code changed all the values!

thanks in advance,

Body:
This should work. the param1 you use in the case clause .map{case (param1, _) is not the same variable param1 defined in the argument. It is a new variable param1 which is assigned the value of the first element of the Tuple2 that shadows the method argument.

def setNewRating(keyMap: String, param1: String, newRating: Double) = {
  val newList = critics(keyMap) map {
    case (x, _) if x == param1 => (param1, newRating)
    case x => x
  }
  critics = critics + (keyMap -> newList)
}


问:
Spark - Exception in task
Using Spark, I am analysing a YouTube dataset to find the top five categories with the maximum number of videos uploaded.

Load the data:

```<code>val textRDD = sc.textFile("hdfs://quickstart.cloudera:8020/user/cloudera/spark/youtubedata.txt")
</code>```

First Line of the RDD

```<code>textRDD.first
res268: String = QuRYeRnAuXM    EvilSquirrelPictures    1135    Pets & Animals  252 1075    4.96    46  86  gFa1YMEJFag nRcovJn9xHg 3TYqkBJ9YRk rSJ8QZWBegU 0TZqX5MbXMA UEvVksP91kg ZTopArY7Nbg 0RViGi2Rne8 HT_QlOJbDpg YZev1imoxX8 8qQrrfUTmh0 zQ83d_D2MGs u6_DQQjLsAw 73Wz9CQFDtE
</code>```

Created a RDD by extracting the 4th column

```<code>val countRDD = textRDD.map( line => line.split("\t")(3))
</code>```

Created a pair

```<code>val pairRDD = countRDD.map(x => (x,1))
</code>```

Till here everything was working fine.
The final step is to retrieve the top 5 from the list

```<code>val result = pairRDD.reduceByKey(_ + _).sortByKey(false).take(5)
</code>```

The above step is returning the below error:

```<code>17/06/07 07:55:59 ERROR executor.Executor: Exception in task 0.0 in stage 262.0 (TID 245) java.lang.ArrayIndexOutOfBoundsException: 3
at $line486.$read$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$anonfun$1.apply(<console>:32)
at $line486.$read$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$anonfun$1.apply(<console>:32)
at scala.collection.Iterator$$anon$11.next(Iterator.scala:328)
.
.
.
</code>```

Where could I have gone wrong?

答:
change plain "\t" split to line.split("\s+");

The \s is equivalent to [ \t\n\x0B\f\r] and should resolve the issue.

Title: Spark - Exception in task

Body:
Using Spark, I am analysing a YouTube dataset to find the top five categories with the maximum number of videos uploaded.

Load the data:

val textRDD = sc.textFile("hdfs://quickstart.cloudera:8020/user/cloudera/spark/youtubedata.txt")

First Line of the RDD

textRDD.first
res268: String = QuRYeRnAuXM    EvilSquirrelPictures    1135    Pets & Animals  252 1075    4.96    46  86  gFa1YMEJFag nRcovJn9xHg 3TYqkBJ9YRk rSJ8QZWBegU 0TZqX5MbXMA UEvVksP91kg ZTopArY7Nbg 0RViGi2Rne8 HT_QlOJbDpg YZev1imoxX8 8qQrrfUTmh0 zQ83d_D2MGs u6_DQQjLsAw 73Wz9CQFDtE

Created a RDD by extracting the 4th column

val countRDD = textRDD.map( line => line.split("\t")(3))

Created a pair

val pairRDD = countRDD.map(x => (x,1))

Till here everything was working fine.
The final step is to retrieve the top 5 from the list

val result = pairRDD.reduceByKey(_ + _).sortByKey(false).take(5)

The above step is returning the below error:

17/06/07 07:55:59 ERROR executor.Executor: Exception in task 0.0 in stage 262.0 (TID 245) java.lang.ArrayIndexOutOfBoundsException: 3
at $line486.$read$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$anonfun$1.apply(<console>:32)
at $line486.$read$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$anonfun$1.apply(<console>:32)
at scala.collection.Iterator$$anon$11.next(Iterator.scala:328)
.
.
.

Where could I have gone wrong?


问:
Access .laccdb file not clean until last user logs out
I have an Access data base (.accdb) on the local network server that is used by multiple users, via the local network OR by using Remote Desktop via VPN to a terminal services computer connected to the www and the local network.

three issues:

1: The .laccdb file contains the users (local and remote) even after they log out until the file is deleted when the last user logs out.  Access doesn't seem to clean up after itself regardless of the mode of connection.  Are there any options, settings or anything I can add to the db to cleanup the .laccdb file?

The remote users are not listed by login id or computername or username in the .laccdb file, just by terminal-services-computer-name and "Admin".
I'd like to know which remote user(s) are actively logged in.

Rarely, the last user logs out but the .laccdb file is not deleted.  Restarting that user's computer seems to be the easiest fix but it can take some time to get that done.  Meanwhile there are some database operations that can't be done without exclusive access.

答:
Thanks.

1: normal behavior?  Okay.

2: I added the vba Environ$("username") function in the starting form load event to grab the username (and date/time) and write that to a file.  That does show the remote users login id, not the remote computer name.  Now I'll know which user to contact if there is a problem.

3: orphaned .laccdb file.  7 users, 2 years of daily use and that file got left behind just twice ever.  Good luck trying to track that problem down.

I make weekly updates (via vba modules) to the .accdb from other data sources and I run the compact action then. (after making a backup copy)


问:
How to recursively print the values of an object's properties using reflection
To aid in debugging some code I'm working on, I started to write a method to recursively print out the names and values of an object's properties. However, most of the objects contain nested types and I'd like to print their names and values too, but only on the types I have defined.

Here's an outline of what I have so far:

```<code>public void PrintProperties(object obj)
{
    if (obj == null)
        return;

    Propertyinfo[] properties = obj.GetType().GetProperties();

    foreach (PropertyInfo property in properties)
    {
        if ([property is a type I have defined])
        {
            PrintProperties([instance of property's type]);
        }
        else
        {
            Console.WriteLine("{0}: {1}", property.Name, property.GetValue(obj, null));
        }
    }
</code>```

The parts between the braces are where I'm unsure.

Any help will be greatly appreciated.

答:
Newtonsoft library provides very simple functions to serialize any object to JSON. This is a much simpler solution.

```<code>Newtonsoft.Json.JsonConvert.SerializeObject(objToSerialize);
</code>```

for example:

```<code>dynamic obj = new { x = 1, y = 2, z = "abc" };
string json = JsonConvert.SerializeObject(obj);
//'json' string value: {"x":1,"y":2,"z":"abc"}
</code>```

Body:
To aid in debugging some code I'm working on, I started to write a method to recursively print out the names and values of an object's properties. However, most of the objects contain nested types and I'd like to print their names and values too, but only on the types I have defined.

Here's an outline of what I have so far:

public void PrintProperties(object obj)
{
    if (obj == null)
        return;

    Propertyinfo[] properties = obj.GetType().GetProperties();

    foreach (PropertyInfo property in properties)
    {
        if ([property is a type I have defined])
        {
            PrintProperties([instance of property's type]);
        }
        else
        {
            Console.WriteLine("{0}: {1}", property.Name, property.GetValue(obj, null));
        }
    }

The parts between the braces are where I'm unsure.

Any help will be greatly appreciated.

Body:
Newtonsoft library provides very simple functions to serialize any object to JSON. This is a much simpler solution.

Newtonsoft.Json.JsonConvert.SerializeObject(objToSerialize);

for example:

dynamic obj = new { x = 1, y = 2, z = "abc" };
string json = JsonConvert.SerializeObject(obj);
//'json' string value: {"x":1,"y":2,"z":"abc"}


问:
Send a mail to Admin with a BO link to specific customer in Prestashop 1.6
In Prestashop 1.6, from a FrontController, I have to send a mail to the administrator of the Shop.

This part works well but I got problems to include a link to the administration page of a specific customer.

The only thing I miss is the name of the administration directory. I would be able to parse and concatenate the PS_ADMIN_DIR constant but it is not available from the FrontController.

I'm kinda stuck here.

Here is the code :

```<code>$admin_customer_link =
    _PS_BASE_URL_
    .__PS_BASE_URI__
    /* Missing the Administration directory name here */
    .$this->context->link->getAdminLink('AdminCustomers', false)
    ."&id_customer=".(int)$customer->id."&viewcustomer";
</code>```

The output I got :

```<code>http://127.0.0.1:8080/prestashop/index.php?controller=AdminCustomers&id_customer=2&viewcustomer
</code>```

The output I need :

```<code>http://127.0.0.1:8080/prestashop/administration/index.php?controller=AdminCustomers&id_customer=2&viewcustomer
</code>```

Any help will be appreciated.

答:
Since the use of the administration directory name from the Front End and sending a link to the administration in e-mail is not a good idea for security purpose, I choose to implement this another way.

Instead of send the administration customer's page link to the webmaster by e-mail, I create a new customer Thread and message. After that, I send an e-mail to the customer service. So, when they log in the Back Office, they see a new notification who leads them to the specific user.

Here is the code :

ModuleFrontController

```<code>// Create a new Customer Thread
$ct = new CustomerThread();
if (isset($customer->id)) {
     $ct->id_customer = (int)$customer->id;
}
$ct->id_shop = (int)$this->context->shop->id;
$ct->id_contact = $contact->id;
$ct->id_lang = (int)$this->context->language->id;
$ct->email = $customer->email;
$ct->status = 'open';
$ct->token = Tools::passwdGen(12);
$ct->add();

// Add a new message to the Customer Thread
if ($ct->id) {
    $cm = new CustomerMessage();
    $cm->id_customer_thread = $ct->id;
    $cm->message = $message;
    $cm->ip_address = (int)ip2long(Tools::getRemoteAddr());
    $cm->user_agent = $_SERVER['HTTP_USER_AGENT'];
    $cm->add();
}
</code>```

Hope it helps someone in the same situation.

Body:
In Prestashop 1.6, from a FrontController, I have to send a mail to the administrator of the Shop.

This part works well but I got problems to include a link to the administration page of a specific customer.

The only thing I miss is the name of the administration directory. I would be able to parse and concatenate the PS_ADMIN_DIR constant but it is not available from the FrontController.

I'm kinda stuck here.

Here is the code :

$admin_customer_link =
    _PS_BASE_URL_
    .__PS_BASE_URI__
    /* Missing the Administration directory name here */
    .$this->context->link->getAdminLink('AdminCustomers', false)
    ."&id_customer=".(int)$customer->id."&viewcustomer";

The output I got :

http://127.0.0.1:8080/prestashop/index.php?controller=AdminCustomers&id_customer=2&viewcustomer

The output I need :

http://127.0.0.1:8080/prestashop/administration/index.php?controller=AdminCustomers&id_customer=2&viewcustomer

Any help will be appreciated.

Body:
Since the use of the administration directory name from the Front End and sending a link to the administration in e-mail is not a good idea for security purpose, I choose to implement this another way.

Instead of send the administration customer's page link to the webmaster by e-mail, I create a new customer Thread and message. After that, I send an e-mail to the customer service. So, when they log in the Back Office, they see a new notification who leads them to the specific user.

Here is the code :

ModuleFrontController

// Create a new Customer Thread
$ct = new CustomerThread();
if (isset($customer->id)) {
     $ct->id_customer = (int)$customer->id;
}
$ct->id_shop = (int)$this->context->shop->id;
$ct->id_contact = $contact->id;
$ct->id_lang = (int)$this->context->language->id;
$ct->email = $customer->email;
$ct->status = 'open';
$ct->token = Tools::passwdGen(12);
$ct->add();

// Add a new message to the Customer Thread
if ($ct->id) {
    $cm = new CustomerMessage();
    $cm->id_customer_thread = $ct->id;
    $cm->message = $message;
    $cm->ip_address = (int)ip2long(Tools::getRemoteAddr());
    $cm->user_agent = $_SERVER['HTTP_USER_AGENT'];
    $cm->add();
}

Hope it helps someone in the same situation.


问:
Possible to get all Items from JList?
I know it is possible to get all selected Items from a JList with:
</p>

```<code>leftlist.getSelectedValues();
</code>```

<p>
But is it possible to get all Items and not only the selected ones? </p>

答:
You need to use getModel() and getSize() to catch the length of the JList. Also you need a loop to iterate through the indexes to get elements(getElementAt()).

Example:

```<code>for(int i = 0; i< jList.getModel().getSize();i++){
    System.out.println(jList.getModel().getElementAt(i));
}
</code>```

You are right, you can get selected values from jList.getSelectedValues(). Also it is possible to get multiple selected elements in JList by jList.getSelectedValuesList() or listen for events on the list's ListSelectionModel. Read the documentation for How to Use Lists.

Multiple selection demo from oracle.

Title: Possible to get all Items from JList?

Body:
I know it is possible to get all selected Items from a JList with:

leftlist.getSelectedValues();

But is it possible to get all Items and not only the selected ones?

Body:
You need to use getModel() and getSize() to catch the length of the JList. Also you need a loop to iterate through the indexes to get elements(getElementAt()).

Example:

for(int i = 0; i< jList.getModel().getSize();i++){
    System.out.println(jList.getModel().getElementAt(i));
}

You are right, you can get selected values from jList.getSelectedValues(). Also it is possible to get multiple selected elements in JList by jList.getSelectedValuesList() or listen for events on the list's ListSelectionModel. Read the documentation for How to Use Lists.

Multiple selection demo from oracle.


问:
Validate field and throw exception in JSF, but attach error message to another field?
I have some fields on my page which I want cross-validated. But I don't want error from this validation to be displayed in <h:message> for this fields.

If I add validator to any of the fields, and validator throws exception, error is displayed in <h:message> for this field. On the other hand I HAVE TO throw exception if I want to suppress page from submitting. Just displaying some error message is not enough.

So I created some hidden field on the form, and attached validator there. This validator has access to UIComponents of the fields I want to validate, so it can validate them. When validator throws exception, error shows in <h:message> for hidden field, which I can place anywhere I want.

Everything works, if I put hidden field after the fields I want to validate. (If I put it before, hidden field validation is triggered before even UIComponents of my fields are updated).

The problem is it's nasty hack :) Is there some better way to do it?

答:
The problem is it's nasty hack :) Is there some better way to do it?

Not for the particular functional requirement. It's very true that JSF allows very little fine grained control for cross-validation of multiple fields.

Everything works, if I put hidden field after the fields I want to validate. (If I put it before, hidden field validation is triggered before even UIComponents of my fields are updated).

Components are during validations phase processed in the order as they appear in the component tree. If you have at some point an UIInput at hands which is still to be processed yet, then you need to grab the submitted value by UIInput#getSubmittedValue(). If it is already been processed, then you need to grab the submitted (and converted and validated) value by UIInput#getValue() instead.

So, if you put the hidden field with the validator after the to-be-validated components, then you need UIInput#getValue() to grab the values. If the hidden field is put before the to-be-validated components, then you need UIInput#getSubmittedValue() to grab the values.

ContentLicense: CC BY-SA 2.5


问:
De-duplicating redux action logic with high order reducers
I'm refactoring a React/Redux app that has been built to a point where there is a need to de-duplicate a lot of reducer logic. I've looked into High Order Reducers but I'm having a hard time wrapping my head around how I can get them to work for me.

Here's an example:

reducers.js

```<code>import components from './entities/components';
import events from './entities/events';
import items from './entities/items';

const entities = combineReducers({
  components,
  items,
  events,
});
</code>```

I'm using normalizr. Here's an idea of what my state looks like. For this example, just know that events can belong to components or items, but the two are otherwise distinguishable.

```<code>{
  entities: {
    components: {
      component_1: {
        events: ['event_1'],
      },
    },
    items: {
      item_1: {
        events: ['event_2'],
      },
    },
    events: {
      event_1: {
        comment:  "foo"
      },
      event_2: {
        comment:  "bar"
      }
    }
  }
}
</code>```

I'm using the EVENT_ADD action type in all 3 reducers. The logic is identical for component.js and item.js (below), but the two also have independent actions that are specific to their type.

Here, I got around unnecessarily adding the event to the wrong place by using Immutable.js's .has() function to check if the target ID exists in that part of the state.

```<code>export default (state = getInitState('component'), action) => {
  switch (action.type) {
    case EVENT_ADD:
      return state.has(action.targetId) ?
        state.updateIn(
          [action.targetId, 'events'],
          arr => arr.push(action.event.id)
        ) :
        state;

    [...]
  }
}
</code>```

In event.js, I use EVENT_ADD here as well to add the contents of an event to that portion of the state.

```<code>export default (state = getInitState('events'), action) => {
  switch (action.type) {
    case EVENT_ADD:
      return state.set(action.event.id, fromJS(action.event));

    [...]
  }
}
</code>```

My understanding of high order reducers is that I need to do one or both of the following:

Use separate action types ADD_EVENT_${entity} (thus making me use both EVENT_ADD_COMPONENT and EVENT_ADD_ITEM in event.js to create an event regardless of its parent.)

Filter by name in my main reducer, as shown at the bottom of the docs, in which case, I'm not sure how to to differentiate my initialState and actions that are specific to a component and item if I'm just sharing a reducer for both.

It seems like I want some sharedReducer.js where I can share logic between components and items for actions like ADD_EVENT, DELETE_EVET, etc. And then also have two independent reducers for each entity. I'm unsure how I can accomplish this or what design pattern is best.

Any guidance would be appreciated. Thank you!

答:
I've had a similar problem wrapping my head around higher order reducers. Even with experience writing higher order functions and components, there's a lot of constraints with reducers that make it more difficult.

I came up with a solution like this:

```<code>export default function withSomething(reducer) {
    const initialState = {
        something: null,
        ...reducer(undefined, {}),
    };

    return function (state = initialState, action) {
        let newState = state;

        switch (action.type) {
            case actionTypes.SET_SOMETHING:
                newState = {
                    ...state,
                    something: action.something,
                };
                break;
            default:
        }

        return reducer(newState, action);
    };
}
</code>```

The main "tricks" are calling wrapper reducer with undefined state to get its initial state and add properties to it, and passing the new state that results from HOR's action handling to the wrapped reducer. You could optimize by not calling the wrapped reducer if newState != state after the switch construct, but I feel this way is more flexible because it potentially lets the wrapped reducer handle and action that has already been handled and do something with its own part of the state.

ContentLicense: CC BY-SA 4.0

Body:
I'm refactoring a React/Redux app that has been built to a point where there is a need to de-duplicate a lot of reducer logic. I've looked into High Order Reducers but I'm having a hard time wrapping my head around how I can get them to work for me.

Here's an example:

reducers.js

import components from './entities/components';
import events from './entities/events';
import items from './entities/items';

const entities = combineReducers({
  components,
  items,
  events,
});

I'm using normalizr. Here's an idea of what my state looks like. For this example, just know that events can belong to components or items, but the two are otherwise distinguishable.

{
  entities: {
    components: {
      component_1: {
        events: ['event_1'],
      },
    },
    items: {
      item_1: {
        events: ['event_2'],
      },
    },
    events: {
      event_1: {
        comment:  "foo"
      },
      event_2: {
        comment:  "bar"
      }
    }
  }
}

I'm using the EVENT_ADD action type in all 3 reducers. The logic is identical for component.js and item.js (below), but the two also have independent actions that are specific to their type.

Here, I got around unnecessarily adding the event to the wrong place by using Immutable.js's .has() function to check if the target ID exists in that part of the state.

export default (state = getInitState('component'), action) => {
  switch (action.type) {
    case EVENT_ADD:
      return state.has(action.targetId) ?
        state.updateIn(
          [action.targetId, 'events'],
          arr => arr.push(action.event.id)
        ) :
        state;

    [...]
  }
}

In event.js, I use EVENT_ADD here as well to add the contents of an event to that portion of the state.

export default (state = getInitState('events'), action) => {
  switch (action.type) {
    case EVENT_ADD:
      return state.set(action.event.id, fromJS(action.event));

    [...]
  }
}

My understanding of high order reducers is that I need to do one or both of the following:

Use separate action types ADD_EVENT_${entity} (thus making me use both EVENT_ADD_COMPONENT and EVENT_ADD_ITEM in event.js to create an event regardless of its parent.)

Filter by name in my main reducer, as shown at the bottom of the docs, in which case, I'm not sure how to to differentiate my initialState and actions that are specific to a component and item if I'm just sharing a reducer for both.

It seems like I want some sharedReducer.js where I can share logic between components and items for actions like ADD_EVENT, DELETE_EVET, etc. And then also have two independent reducers for each entity. I'm unsure how I can accomplish this or what design pattern is best.

Any guidance would be appreciated. Thank you!

Body:
I've had a similar problem wrapping my head around higher order reducers. Even with experience writing higher order functions and components, there's a lot of constraints with reducers that make it more difficult.

I came up with a solution like this:

export default function withSomething(reducer) {
    const initialState = {
        something: null,
        ...reducer(undefined, {}),
    };

    return function (state = initialState, action) {
        let newState = state;

        switch (action.type) {
            case actionTypes.SET_SOMETHING:
                newState = {
                    ...state,
                    something: action.something,
                };
                break;
            default:
        }

        return reducer(newState, action);
    };
}

The main "tricks" are calling wrapper reducer with undefined state to get its initial state and add properties to it, and passing the new state that results from HOR's action handling to the wrapped reducer. You could optimize by not calling the wrapped reducer if newState != state after the switch construct, but I feel this way is more flexible because it potentially lets the wrapped reducer handle and action that has already been handled and do something with its own part of the state.


问:
Delete until whitespace in Emacs
Is there an Emacs function to delete (forward or backwards) until the first whitespace?  For example, I have the following line, and the cursor is marked by the caret:

```<code>someword ?(&)!* morewords
               ^
</code>```

I want to delete the backwards the sequence of non-alphanumeric characters, but not the word someword.  Using backward-delete-word will wipe out the word as well.  The same is with the cursor before the weird characters and kill-word.

答:
I don't know of any function, but it's easy enough to make one:</p>

```<code>(defun my-delete-backward-to-ws ()
  (interactive)
  (delete-region (point) (save-excursion (skip-syntax-backward "^ ") (point))))
</code>```

Title: Delete until whitespace in Emacs

Body:
Is there an Emacs function to delete (forward or backwards) until the first whitespace?  For example, I have the following line, and the cursor is marked by the caret:

someword ?(&)!* morewords
               ^

I want to delete the backwards the sequence of non-alphanumeric characters, but not the word someword.  Using backward-delete-word will wipe out the word as well.  The same is with the cursor before the weird characters and kill-word.

Body:
I don't know of any function, but it's easy enough to make one:

(defun my-delete-backward-to-ws ()
  (interactive)
  (delete-region (point) (save-excursion (skip-syntax-backward "^ ") (point))))


问:
How do I assign values from Ajax to an array?
My code is supposed to pass 'seventythree' to php where it will be sent to a MYSQL database and a calculation will be made to calculate efficiency according to the values retrieved from the table seventythree. Afterwards, it's supposed to run again and get the values from seventy four. I used a for loop for this but the result just sends the same value for both the positions 0 and 1 in the array.

```<code>function calculateEfficiency(){
    for (x =0; x < 2; x++){
        var y = x+1;
        switch(y){
            case 1:
                mod = "seventythree";
                break;
            case 2:
                mod = "seventyfour";
                break;
        }
        $.ajax({
            type: 'post',
            url: 'efficiency.php',
            dataType: 'json',
            data: {'mod' : mod},
            error: function(){alert("fail");}
        }).done(function(data){
            efficiency = data.efficiency;
            refresh = data.refresh;
        });

        efficiencyArray[x] = efficiency;

        if (refresh){

        document.getElementById("efficiency1").innerHTML = efficiencyArray[0];
        document.getElementById("efficiency2").innerHTML = efficiencyArray[1];

        }
    }
}
</code>```

What do I do?

答:
What @barmar is saying is that you need to place this:

```<code>efficiencyArray[x] = efficiency;

    if (refresh){

    document.getElementById("efficiency1").innerHTML = efficiencyArray[0];
    document.getElementById("efficiency2").innerHTML = efficiencyArray[1];

    }
</code>```

Inside of this:

```<code>.done(function(data){
//inside here
});
</code>```

Body:
My code is supposed to pass 'seventythree' to php where it will be sent to a MYSQL database and a calculation will be made to calculate efficiency according to the values retrieved from the table seventythree. Afterwards, it's supposed to run again and get the values from seventy four. I used a for loop for this but the result just sends the same value for both the positions 0 and 1 in the array.

function calculateEfficiency(){
    for (x =0; x < 2; x++){
        var y = x+1;
        switch(y){
            case 1:
                mod = "seventythree";
                break;
            case 2:
                mod = "seventyfour";
                break;
        }
        $.ajax({
            type: 'post',
            url: 'efficiency.php',
            dataType: 'json',
            data: {'mod' : mod},
            error: function(){alert("fail");}
        }).done(function(data){
            efficiency = data.efficiency;
            refresh = data.refresh;
        });

        efficiencyArray[x] = efficiency;

        if (refresh){

        document.getElementById("efficiency1").innerHTML = efficiencyArray[0];
        document.getElementById("efficiency2").innerHTML = efficiencyArray[1];

        }
    }
}

What do I do?

Body:
What @barmar is saying is that you need to place this:

efficiencyArray[x] = efficiency;

    if (refresh){

    document.getElementById("efficiency1").innerHTML = efficiencyArray[0];
    document.getElementById("efficiency2").innerHTML = efficiencyArray[1];

    }

Inside of this:

.done(function(data){
//inside here
});


问:
ASP.net MVC: Creating a Simple Log-in Form in Visual Studio
I'm creating a simple ASP.net MVC login form using individual user accounts. I created the project following this tutorial: https://learn.microsoft.com/en-us/aspnet/mvc/overview/security/create-an-aspnet-mvc-5-app-with-facebook-and-google-oauth2-and-openid-sign-on

At what point do I connect it to my SQL Server database? In the tutorial, it seems as though the database tables are created automatically, though I've never seen an option to enter my database credentials.

Thanks!

答: The default template generates you a local database that is stored in the project directory. If I recall correctly, it does not require authentication. You can examine the Web.config file to see the connection string. It will not contain a username and password because it does not require them for that local database.</p>


问:
when a css ul li item extends past ul, how to match dynamic width of an ul
JSFiddle of the problem: https://jsfiddle.net/td6szj3o/

/
i have an ul li with standard text items per each li. the list is dynamic, so sometimes each content li is smaller than the set width:100% of the container it sits in, but sometimes a li item has text that expands past the width:100% of the container. instead of forcing the text to the next line, i am wanting to keep the long text extending past the ul. currently that works fine with little extra css styling to the ul.

using this method, i see a bottom scroller that pops up under the ul and allows me to scroll to the right to view the rest of the li content. that is fine for me and i want to keep this.

however i am introduced to a problem trying to keep the alternate li background color that is so popular and often standard with most data output in an unordered list. since the css of the li that sits in the ul is width:100%, and the ul itself stops at the width:100%, the li extends only as far as the ul width. but the problem is while the text is extending past the li, it technically is outside of the width:100% of the ul itself, and thus the background color on the li stops wherever the ul width ends.

i am trying to come to a solution that would work in all browsers, that will allow the ul to have the li item extend to the full width of the longest content of any li. the closest i have gotten is using display:table-header-group, but unfortunately it does not expand to width:100% when i have small text content inside the li.

i could simply add a min-width:300px or something to the ul, and this would fix my problem. but that isn't going to cut it when user is on a smaller device or monitor size unfortunately. when i use min-width:100% that does not solve the issue either. i have used every combination of display:XXX that i can come up with, and when i float:left anything in the ul or li, that breaks the view either for the smaller text ul output, or the longer text ul output, or both at the same time.

any help or guidance on this would be greatly appreciated. i am looking for a solution that works in all latest versions of Chrome, FF, Safari, etc; and sticks to a css solution.

please note i intentionally have left word-wrapping off of the css. i do not want the text to go to the next line, but instead keep being displayed horizontally across the ul.

below is the html/css i am using:

```<code><ul>
<li>dynamic li item would be here; nothing crazy</li>
</ul>

.sidebar ul {
    position:relative;
    max-height:55vh;
    min-height:10em;
    margin:0;
    width:100%;
}
.node-list{
    white-space:nowrap;
    padding-bottom: 2em;
}
.node-list li{
    padding: .15em .5em .15em .35em;
    margin:0;
    border-left: solid 2px transparent;
    max-width:100%;
    width:auto;
}
.node-list li a{
    color: rgb(73,73,73);
    font-weight: bold;
    text-decoration: none;
}
.node-list li:nth-of-type(2n){
    background-color: rgb(242,242,242)
}
.node-list li:nth-of-type(2n-1){
    background-color: rgb(255,255,255)
}
</code>```

答:
In your CSS file remove the no-wrap and add break-all to the li:

```<code>.node-list{
    padding-bottom: 2em;
}
.node-list li{
    padding: .15em .5em .15em .35em;
    margin:0;
    border-left: solid 2px transparent;
    word-break: break-all;
}
</code>```

JS Fiddle that I believe is the solution https://jsfiddle.net/td6szj3o/14/

Body:
JSFiddle of the problem: https://jsfiddle.net/td6szj3o/

/
i have an ul li with standard text items per each li. the list is dynamic, so sometimes each content li is smaller than the set width:100% of the container it sits in, but sometimes a li item has text that expands past the width:100% of the container. instead of forcing the text to the next line, i am wanting to keep the long text extending past the ul. currently that works fine with little extra css styling to the ul.

using this method, i see a bottom scroller that pops up under the ul and allows me to scroll to the right to view the rest of the li content. that is fine for me and i want to keep this.

however i am introduced to a problem trying to keep the alternate li background color that is so popular and often standard with most data output in an unordered list. since the css of the li that sits in the ul is width:100%, and the ul itself stops at the width:100%, the li extends only as far as the ul width. but the problem is while the text is extending past the li, it technically is outside of the width:100% of the ul itself, and thus the background color on the li stops wherever the ul width ends.

i am trying to come to a solution that would work in all browsers, that will allow the ul to have the li item extend to the full width of the longest content of any li. the closest i have gotten is using display:table-header-group, but unfortunately it does not expand to width:100% when i have small text content inside the li.

i could simply add a min-width:300px or something to the ul, and this would fix my problem. but that isn't going to cut it when user is on a smaller device or monitor size unfortunately. when i use min-width:100% that does not solve the issue either. i have used every combination of display:XXX that i can come up with, and when i float:left anything in the ul or li, that breaks the view either for the smaller text ul output, or the longer text ul output, or both at the same time.

any help or guidance on this would be greatly appreciated. i am looking for a solution that works in all latest versions of Chrome, FF, Safari, etc; and sticks to a css solution.

please note i intentionally have left word-wrapping off of the css. i do not want the text to go to the next line, but instead keep being displayed horizontally across the ul.

below is the html/css i am using:

dynamic li item would be here; nothing crazy

.sidebar ul {
    position:relative;
    max-height:55vh;
    min-height:10em;
    margin:0;
    width:100%;
}
.node-list{
    white-space:nowrap;
    padding-bottom: 2em;
}
.node-list li{
    padding: .15em .5em .15em .35em;
    margin:0;
    border-left: solid 2px transparent;
    max-width:100%;
    width:auto;
}
.node-list li a{
    color: rgb(73,73,73);
    font-weight: bold;
    text-decoration: none;
}
.node-list li:nth-of-type(2n){
    background-color: rgb(242,242,242)
}
.node-list li:nth-of-type(2n-1){
    background-color: rgb(255,255,255)
}

Body:
In your CSS file remove the no-wrap and add break-all to the li:

.node-list{
    padding-bottom: 2em;
}
.node-list li{
    padding: .15em .5em .15em .35em;
    margin:0;
    border-left: solid 2px transparent;
    word-break: break-all;
}

JS Fiddle that I believe is the solution https://jsfiddle.net/td6szj3o/14/


问:
How to call one controller's function from another controller
I was wondering if is it possible to call one controller's function from another controller. This way i tried but failed:

```<code><div ng-app="MyApp">
    <div ng-controller="Ctrl1">
        <button ng-click="func1()">func1</button>
    </div>
    <br>
    <div ng-controller="Ctrl2">
        <button ng-click="func2()">func2</button>
    </div>
</div>
</code>```

```<code>var app = angular.module('MyApp', []);

app.controller('Ctrl1', function($scope) {

  $scope.func1 = function() {
    alert('Ctrl1 and func1')
  }

    $scope.$on("MyFunction", function () {
        alert('Ctrl1 MyFunction')
    });
});

app.controller('Ctrl2', function($scope) {

  $scope.func2 = function() {
    alert('Ctrl2 and func2')
    $scope.$emit("MyFunction");
  }

});
</code>```

when func2 is calling then i used $scope.$emit("MyFunction"); to call Ctrl1 MyFunction but it does not worked. so is it not possible ?

please put some light here.

答:
Use $rootScope.$broadcast:

```<code>app.controller('Ctrl1', function($scope) {

  $scope.func1 = function() {
    alert('Ctrl1 and func1')
  }

    $scope.$on("MyFunction", function () {
        alert('Ctrl1 MyFunction')
    });
});

app.controller('Ctrl2', function($scope, $rootScope) {

  $scope.func2 = function() {
    alert('Ctrl2 and func2')
    //$scope.$emit("MyFunction");
    //USE rootScope
    $rootScope.$broadcast("MyFunction");
  }

});
</code>```

Best practice:  To avoid memory leaks, avoid using $on listeners on $rootScope. Listeners on $scope will be properly destroyed automatically when controllers are removed.

For more information on the AngularJS event bus, see

AngularJS Developer Guide - Scope Event Propagation

AngularJS rootScope/scope API Reference

Body:
I was wondering if is it possible to call one controller's function from another controller. This way i tried but failed:

        <button ng-click="func1()">func1</button>

        <button ng-click="func2()">func2</button>

var app = angular.module('MyApp', []);

app.controller('Ctrl1', function($scope) {

  $scope.func1 = function() {
    alert('Ctrl1 and func1')
  }

    $scope.$on("MyFunction", function () {
        alert('Ctrl1 MyFunction')
    });
});

app.controller('Ctrl2', function($scope) {

  $scope.func2 = function() {
    alert('Ctrl2 and func2')
    $scope.$emit("MyFunction");
  }

});

when func2 is calling then i used $scope.$emit("MyFunction"); to call Ctrl1 MyFunction but it does not worked. so is it not possible ?

please put some light here.

Body:
Use $rootScope.$broadcast:

app.controller('Ctrl1', function($scope) {

  $scope.func1 = function() {
    alert('Ctrl1 and func1')
  }

    $scope.$on("MyFunction", function () {
        alert('Ctrl1 MyFunction')
    });
});

app.controller('Ctrl2', function($scope, $rootScope) {

  $scope.func2 = function() {
    alert('Ctrl2 and func2')
    //$scope.$emit("MyFunction");
    //USE rootScope
    $rootScope.$broadcast("MyFunction");
  }

});

Best practice:  To avoid memory leaks, avoid using $on listeners on $rootScope. Listeners on $scope will be properly destroyed automatically when controllers are removed.

For more information on the AngularJS event bus, see

AngularJS Developer Guide - Scope Event Propagation

AngularJS rootScope/scope API Reference


问:
Ball to fixed ball collision
I am trying to implement balls that change their direction when they hit an obstacle(in this case a fixed ball). I can detect when a collision occurs but I don't know how to modify the direction of a ball once it hits an obstacle. Here's some code:</p>

```<code>struct Vec2
{
    float x, y;
};

struct Ball
{
     void onCollision(const Ball& fixedBall)
     {
         // This function will be called when a collision occurs
         // Speed will be constant, only direction needs to change
     }

     void update()
     {
         position += direction * speed;
     }

     Vec2 position, direction; // direction is a normalized vector
     float speed, radius;
};
</code>```

答:
You will need to invert the speed by negating it.</p>

```<code>if (collision)
  speed = speed * -1
</code>```

Title: Ball to fixed ball collision

Body:
I am trying to implement balls that change their direction when they hit an obstacle(in this case a fixed ball). I can detect when a collision occurs but I don't know how to modify the direction of a ball once it hits an obstacle. Here's some code:

struct Vec2
{
    float x, y;
};

struct Ball
{
     void onCollision(const Ball& fixedBall)
     {
         // This function will be called when a collision occurs
         // Speed will be constant, only direction needs to change
     }

     void update()
     {
         position += direction * speed;
     }

     Vec2 position, direction; // direction is a normalized vector
     float speed, radius;
};

Body:
You will need to invert the speed by negating it.

if (collision)
  speed = speed * -1


问:
Windows command for cutting columns from a text
The following content is stored in a file:

```<code>chrome.exe                   512 Console                 0     73,780 K
chrome.exe                   800 Console                 0     11,052 K
chrome.exe                  1488 Console                 0     92,720 K
chrome.exe                  1600 Console                 0     32,344 K
chrome.exe                  2240 Console                 0     35,132 K
chrome.exe                  2360 Console                 0     21,276 K
chrome.exe                  3524 Console                 0     66,732 K
chrome.exe                  3924 Console                 0     23,524 K
</code>```

Is there a way to extract the 5th column with the Windows command line?

Something like the UNIX cut command.

答:
If you're familiar with the GNU cut utility, you might be better off using the Win32 port:

http://gnuwin32.sourceforge.net/packages/coreutils.htm

Body:
The following content is stored in a file:

chrome.exe                   512 Console                 0     73,780 K
chrome.exe                   800 Console                 0     11,052 K
chrome.exe                  1488 Console                 0     92,720 K
chrome.exe                  1600 Console                 0     32,344 K
chrome.exe                  2240 Console                 0     35,132 K
chrome.exe                  2360 Console                 0     21,276 K
chrome.exe                  3524 Console                 0     66,732 K
chrome.exe                  3924 Console                 0     23,524 K

Is there a way to extract the 5th column with the Windows command line?

Something like the UNIX cut command.


问:
ngAnimate not adding ng-enter classes in Ionic V1 app
I have an ionic v1 app. I want to add a basic animation to an element when it gets added to the view via ng-repeat. Reading the docs, the element should have a ng-enter class I can use to add CSS animations but it doesn't.

ngAnimate is included with Ionic. I'm loading the module:

```<code>angular.module('app', [
    'ionic',
    'ngAnimate',
</code>```

Here's view code which uses ng-repeat:

```<code><div class="entry" ng-repeat="message in messages | orderBy:'-id'">{{message}}
</div>
</code>```

When I dynamically add a message to $scope.messages it gets added to the view as you would expect but it does not contain the ng-enter class which according to the docs it should.

I'm using ionic version 1.3.3, Angular 1.5.3 and ngAnimate 1.5.3.

Here's a codepen showing the issue: https://codepen.io/jamesjacobs/pen/YQyaZq

What am I missing? Thanks.

答:
Here is how to use ngAnimate with ionic

in view

```<code><ion-item class="chat-item item-remove-animate item-avatar item-icon-right" ...
</code>```

css

If you want to use it with chat-item class use it as below

```<code>.chat-item.ng-enter {
    -webkit-animation: fadeInLeft 1s;
    animation: fadeInLeft 1s;
}
</code>```

above code will animate whole list at a once. If you want to animate each item one by one use ng-enter-stagger with delay 200ms

```<code>.chat-item.ng-enter-stagger {
  -webkit-animation-delay:200ms;
  animation-delay:200ms;

  /* override to make sure it's not inherited from other styles */
  -webkit-animation-duration:0;
  animation-duration:0;
}
</code>```

Demo

Body:
I have an ionic v1 app. I want to add a basic animation to an element when it gets added to the view via ng-repeat. Reading the docs, the element should have a ng-enter class I can use to add CSS animations but it doesn't.

ngAnimate is included with Ionic. I'm loading the module:

angular.module('app', [
    'ionic',
    'ngAnimate',

Here's view code which uses ng-repeat:

{{message}}

When I dynamically add a message to $scope.messages it gets added to the view as you would expect but it does not contain the ng-enter class which according to the docs it should.

I'm using ionic version 1.3.3, Angular 1.5.3 and ngAnimate 1.5.3.

Here's a codepen showing the issue: https://codepen.io/jamesjacobs/pen/YQyaZq

What am I missing? Thanks.

Body:
Here is how to use ngAnimate with ionic

in view

<ion-item class="chat-item item-remove-animate item-avatar item-icon-right" ...

css

If you want to use it with chat-item class use it as below

.chat-item.ng-enter {
    -webkit-animation: fadeInLeft 1s;
    animation: fadeInLeft 1s;
}

above code will animate whole list at a once. If you want to animate each item one by one use ng-enter-stagger with delay 200ms

.chat-item.ng-enter-stagger {
  -webkit-animation-delay:200ms;
  animation-delay:200ms;

  /* override to make sure it's not inherited from other styles */
  -webkit-animation-duration:0;
  animation-duration:0;
}

Demo


问:
Child Process is failing using Popen
I'm trying to get a program named xselect to run using the Popen construct in python. If I run xselect from the terminal manually by typing in the commands by hand, It runs all the way through. However, when done from the python script, it freezes at a certain command and will not continue. When I check the log file, all of the output is captured, but none of the error messages are captured.

I'm thinking that Popen may not know what to do with the errors from the output of xselect, and its causing xselect to freeze. To counter this, I tried to add a timeout so that it kills xselect after 5 seconds, but this hasn't worked either.

Can anyone help me get this running?

```<code>with subprocess.Popen(args, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, universal_newlines=True) as proc:

    proc.wait(timeout=5)
    out = proc.stdout.read()
    if TimeoutExpired:
        proc.kill()
</code>```

答: See the warning for proc.wait() here: https://docs.python.org/2/library/subprocess.html#subprocess.Popen.wait. Basically, you should either be using proc.communicate(), or should be reading from proc.stdout instead of waiting.

Title: Child Process is failing using Popen

Body:
I'm trying to get a program named xselect to run using the Popen construct in python. If I run xselect from the terminal manually by typing in the commands by hand, It runs all the way through. However, when done from the python script, it freezes at a certain command and will not continue. When I check the log file, all of the output is captured, but none of the error messages are captured.

I'm thinking that Popen may not know what to do with the errors from the output of xselect, and its causing xselect to freeze. To counter this, I tried to add a timeout so that it kills xselect after 5 seconds, but this hasn't worked either.

Can anyone help me get this running?

with subprocess.Popen(args, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, universal_newlines=True) as proc:

    proc.wait(timeout=5)
    out = proc.stdout.read()
    if TimeoutExpired:
        proc.kill()


问:
Excel Macro freezes Outlook
I have this rather heavy Excel macro. When it runs Outlook freezes.

I know it is not using all the CPU power because

a) I have a powerful multiple-core machine

b) all my other programs (even heavy-duty ones) are running fine.

It seems like Outlook and Excel are sharing a process that Excel is hogging.

My macro does nothing Outlook-related, at least not knowingly. It pulls data from Bloomberg and does some calculation.

答:
I appreciate the horse has very much left the corral...however, I too have experienced this and with no references in my code to the Outlook model. I've also noticed my Excel locking up whilst macros in another Excel instance are running.

To resolve this you need add a

```<code>DOEVENTS
</code>```

line to your code, to quote the MSDN site

DoEvents passes control to the operating system. Control is returned
  after the operating system has finished processing the events in its
  queue

Where to put the DOEVENTS line very much depends on your code, but in a rather heavy macro of mine where I make a number of SQL calls, I've placed it just before each SQL call which appears to work well. Allowing me to work quite happily in one Excel instance whilst the background instance does a number of SQL fetches.

Title: Excel Macro freezes Outlook

Body:
I appreciate the horse has very much left the corral...however, I too have experienced this and with no references in my code to the Outlook model. I've also noticed my Excel locking up whilst macros in another Excel instance are running.

To resolve this you need add a

DOEVENTS

line to your code, to quote the MSDN site

DoEvents passes control to the operating system. Control is returned
  after the operating system has finished processing the events in its
  queue

Where to put the DOEVENTS line very much depends on your code, but in a rather heavy macro of mine where I make a number of SQL calls, I've placed it just before each SQL call which appears to work well. Allowing me to work quite happily in one Excel instance whilst the background instance does a number of SQL fetches.


问:
Oracle SQL match string with left zeros padding
I have to find strings which can or cannot starts with zeros.
For instance, if I have in my db the values '00563', '563', '43563', '0563', I have to find the rows '00563', '563', '0563'.

I've tryed this:

```<code>select distinct val
from table_one
where val = '00563' OR
      val = ltrim('00563', '0');
</code>```

but doesn't work.
val is a CHAR(5 BYTE) column.

Can you help me?

EDIT:
To be precise, if I execute the query:

```<code>select distinct val
from table_one;
</code>```

the result is:

```<code>5034
(null)
4dsfd
01005
03030
03075
05034
</code>```

To me, 05034 and 5034 are the same value.

答:
You need to make the column value and the literal value you're searching for match - explicitly making them the same data type (and length).

An earlier version of this answer gave various permutations based on unknowns and assumptions, but summarising comments: your val column is defined as char(5) (so the values are space-padded, which will have to be taken into account), may have values that can't be converted to numbers, and the value (literal or variable) you're comparing against is a number. Based on all of that most of the variations aren't relevant to you, and you can do:

```<code>select distinct val
from table_one
where lpad(trim(val), 5, '0') = lpad(to_char(563), 5, '0');
</code>```

The val from the table column is trimmed to remove whitespace (because it's char), then padded with zeros up to the maximum length instead. The number you're comparing against is converted to a string and also zero-padded to the same length. Those two strings can then be compared.

With some sample data:

```<code>create table table_one(val char(5));
insert into table_one
  select '00563' from dual
  union all select '563' from dual
  union all select '43563' from dual
  union all select '0563' from dual
  union all select '09999' from dual
  union all select '4dsfd' from dual;

select distinct val
from table_one
where lpad(trim(val), 5, '0') = lpad(to_char(563), 5, '0');

VAL
-----
00563
0563
563
</code>```

Applying a function to the table column value will prevent any index on that column being used, but that doesn't seem to be avoidable unless you can clean up the data in your table.

Body:
I have to find strings which can or cannot starts with zeros.
For instance, if I have in my db the values '00563', '563', '43563', '0563', I have to find the rows '00563', '563', '0563'.

I've tryed this:

select distinct val
from table_one
where val = '00563' OR
      val = ltrim('00563', '0');

but doesn't work.
val is a CHAR(5 BYTE) column.

Can you help me?

EDIT:
To be precise, if I execute the query:

select distinct val
from table_one;

the result is:

5034
(null)
4dsfd
01005
03030
03075
05034

To me, 05034 and 5034 are the same value.

Body:
You need to make the column value and the literal value you're searching for match - explicitly making them the same data type (and length).

An earlier version of this answer gave various permutations based on unknowns and assumptions, but summarising comments: your val column is defined as char(5) (so the values are space-padded, which will have to be taken into account), may have values that can't be converted to numbers, and the value (literal or variable) you're comparing against is a number. Based on all of that most of the variations aren't relevant to you, and you can do:

select distinct val
from table_one
where lpad(trim(val), 5, '0') = lpad(to_char(563), 5, '0');

The val from the table column is trimmed to remove whitespace (because it's char), then padded with zeros up to the maximum length instead. The number you're comparing against is converted to a string and also zero-padded to the same length. Those two strings can then be compared.

With some sample data:

create table table_one(val char(5));
insert into table_one
  select '00563' from dual
  union all select '563' from dual
  union all select '43563' from dual
  union all select '0563' from dual
  union all select '09999' from dual
  union all select '4dsfd' from dual;

select distinct val
from table_one
where lpad(trim(val), 5, '0') = lpad(to_char(563), 5, '0');

VAL
-----
00563
0563
563

Applying a function to the table column value will prevent any index on that column being used, but that doesn't seem to be avoidable unless you can clean up the data in your table.


问:
'NSInternalInconsistencyException' failure in RCTBridge delegation - React Native

Description

I've  successfully build a react-native project using XCode 8 but the app crashes after the build with the following error message. I've been trying everything but to no avail, and seems there are no similar issues out there. The issue, i think from trying to debug this, lies in RCTBridge.m:

```<code>- (Class)bridgeClass
{
  // In order to facilitate switching between bridges with only build
  // file changes, this uses reflection to check which bridges are
  // available.  This is a short-term hack until RCTBatchedBridge is
  // removed.

  Class batchedBridgeClass = objc_lookUpClass("RCTBatchedBridge");
  Class cxxBridgeClass = objc_lookUpClass("RCTCxxBridge");

  Class implClass = nil;

  if ([self.delegate respondsToSelector:@selector(shouldBridgeUseCxxBridge:)]) {
    if ([self.delegate shouldBridgeUseCxxBridge:self]) {
      implClass = cxxBridgeClass;
    } else {
      implClass = batchedBridgeClass;
    }
  } else if (batchedBridgeClass != nil) {
    implClass = batchedBridgeClass;
  } else if (cxxBridgeClass != nil) {
    implClass = cxxBridgeClass;
  }

  RCTAssert(implClass != nil, @"No bridge implementation is available, giving up.");
  return implClass;
}
</code>```

where the bridgeClass returns the assertion error due to the selection between the RCTBatchedBridge class and the RCTCxxBridge returning neither as explained in the comments below found in RCTBridgeDelegate.h

```<code>/**
 * Configure whether the legacy RCTBatchedBridge or new RCTCxxBridge
 * should be used.  If this method is implemented and the specified
 * bridge is not linked in, startup will fail.  If this method is not
 * implemented, the implementation will default to RCTBatchedBridge,
 * but if it is not linked in, will try RCTCxxBridge instead.  If
 * neither bridge is linked in, startup will fail.  This order will be
 * reversed in the near future, as the legacy bridge is closer to
 * being removed.
 *
 * @experimental
 */
- (BOOL)shouldBridgeUseCxxBridge:(RCTBridge *)bridge;
</code>```

Reproduction Steps and Sample Code

All the RN modules involved have been installed, linked etc with npm and CocoaPods. There are no prior build errors and the build is in debug mode. I've also been using the Ignite boilerplate but from the logs it hasn't yet gone to app specific codes.

The error after successful build:

```<code>2017-06-06 08:48:57.019 rn_irnext_demo[16376:122081] *** Assertion failure in -[RCTBridge bridgeClass](), myApp/node_modules/react-native/React/Base/RCTBridge.m:292
2017-06-06 08:48:57.031 rn_irnext_demo[16376:122081] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'No bridge implementation is available, giving up.'
*** First throw call stack:
(
    0   CoreFoundation                      0x0000000113344b0b __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x0000000112da9141 objc_exception_throw + 48
    2   CoreFoundation                      0x0000000113348cf2 +[NSException raise:format:arguments:] + 98
    3   Foundation                          0x000000011297869f -[NSAssertionHandler handleFailureInFunction:file:lineNumber:description:] + 165
    4   rn_irnext_demo                      0x000000010e578e27 -[RCTBridge bridgeClass] + 535
    5   rn_irnext_demo                      0x000000010e578f7d -[RCTBridge setUp] + 285
    6   rn_irnext_demo                      0x000000010e578387 -[RCTBridge initWithDelegate:bundleURL:moduleProvider:launchOptions:] + 375
    7   rn_irnext_demo                      0x000000010e5781a2 -[RCTBridge initWithBundleURL:moduleProvider:launchOptions:] + 146
    8   rn_irnext_demo                      0x000000010e54fee7 -[RCTRootView initWithBundleURL:moduleName:initialProperties:launchOptions:] + 183
    9   rn_irnext_demo                      0x000000010e540c58 -[AppDelegate application:didFinishLaunchingWithOptions:] + 280
    10  UIKit                               0x0000000111008957 -[UIApplication _handleDelegateCallbacksWithOptions:isSuspended:restoreState:] + 299
    11  UIKit                               0x000000011100a23c -[UIApplication _callInitializationDelegatesForMainScene:transitionContext:] + 4119
    12  UIKit                               0x0000000111010584 -[UIApplication _runWithMainScene:transitionContext:completion:] + 1709
    13  UIKit                               0x000000011100d793 -[UIApplication workspaceDidEndTransaction:] + 182
    14  FrontBoardServices                  0x000000011a3775f6 __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 24
    15  FrontBoardServices                  0x000000011a37746d -[FBSSerialQueue _performNext] + 186
    16  FrontBoardServices                  0x000000011a3777f6 -[FBSSerialQueue _performNextFromRunLoopSource] + 45
    17  CoreFoundation                      0x00000001132eac01 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    18  CoreFoundation                      0x00000001132d00cf __CFRunLoopDoSources0 + 527
    19  CoreFoundation                      0x00000001132cf5ff __CFRunLoopRun + 911
    20  CoreFoundation                      0x00000001132cf016 CFRunLoopRunSpecific + 406
    21  UIKit                               0x000000011100c02f -[UIApplication _run] + 468
    22  UIKit                               0x00000001110120d4 UIApplicationMain + 159
    23  rn_irnext_demo                      0x000000010e54103f main + 111
    24  libdyld.dylib                       0x00000001139cb65d start + 1
    25  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
</code>```

Additionally produces a Thread 1:signal SIGABRT error in the main.m file.

Additional info:

1) XCode 8
2) react-native: 0.44
3) macOSx

Need assistance in solving this. Thank you in advance for your help!

答:
I've finally manage to solve this issue and am posting this answer for those who might come across this issue as well.

The error is due to a separate fix, which having hindsight, is a temporary one:

Duplicate symbols for architecture x86_64 under Xcode

Removing the -ObjC from Other Linker Flags will cause the issue above as any linking done with native classes will not work and causes the App to crash. So what I did instead was the following:

1) Find the files which contain the duplicate symbols and removing any references to the duplicate files while maintaining the ones in the Libraries folder of the project.

2) Reinserting -ObjC in the Other Linker Flags for the main project target and the App will stop crashing.

Hope this helps.

Body:
Description

I've  successfully build a react-native project using XCode 8 but the app crashes after the build with the following error message. I've been trying everything but to no avail, and seems there are no similar issues out there. The issue, i think from trying to debug this, lies in RCTBridge.m:

- (Class)bridgeClass
{
  // In order to facilitate switching between bridges with only build
  // file changes, this uses reflection to check which bridges are
  // available.  This is a short-term hack until RCTBatchedBridge is
  // removed.

  Class batchedBridgeClass = objc_lookUpClass("RCTBatchedBridge");
  Class cxxBridgeClass = objc_lookUpClass("RCTCxxBridge");

  Class implClass = nil;

  if ([self.delegate respondsToSelector:@selector(shouldBridgeUseCxxBridge:)]) {
    if ([self.delegate shouldBridgeUseCxxBridge:self]) {
      implClass = cxxBridgeClass;
    } else {
      implClass = batchedBridgeClass;
    }
  } else if (batchedBridgeClass != nil) {
    implClass = batchedBridgeClass;
  } else if (cxxBridgeClass != nil) {
    implClass = cxxBridgeClass;
  }

  RCTAssert(implClass != nil, @"No bridge implementation is available, giving up.");
  return implClass;
}

where the bridgeClass returns the assertion error due to the selection between the RCTBatchedBridge class and the RCTCxxBridge returning neither as explained in the comments below found in RCTBridgeDelegate.h

/**
 * Configure whether the legacy RCTBatchedBridge or new RCTCxxBridge
 * should be used.  If this method is implemented and the specified
 * bridge is not linked in, startup will fail.  If this method is not
 * implemented, the implementation will default to RCTBatchedBridge,
 * but if it is not linked in, will try RCTCxxBridge instead.  If
 * neither bridge is linked in, startup will fail.  This order will be
 * reversed in the near future, as the legacy bridge is closer to
 * being removed.
 *
 * @experimental
 */
- (BOOL)shouldBridgeUseCxxBridge:(RCTBridge *)bridge;

Reproduction Steps and Sample Code

All the RN modules involved have been installed, linked etc with npm and CocoaPods. There are no prior build errors and the build is in debug mode. I've also been using the Ignite boilerplate but from the logs it hasn't yet gone to app specific codes.

The error after successful build:

2017-06-06 08:48:57.019 rn_irnext_demo[16376:122081] *** Assertion failure in -[RCTBridge bridgeClass](), myApp/node_modules/react-native/React/Base/RCTBridge.m:292
2017-06-06 08:48:57.031 rn_irnext_demo[16376:122081] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'No bridge implementation is available, giving up.'
*** First throw call stack:
(
    0   CoreFoundation                      0x0000000113344b0b __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x0000000112da9141 objc_exception_throw + 48
    2   CoreFoundation                      0x0000000113348cf2 +[NSException raise:format:arguments:] + 98
    3   Foundation                          0x000000011297869f -[NSAssertionHandler handleFailureInFunction:file:lineNumber:description:] + 165
    4   rn_irnext_demo                      0x000000010e578e27 -[RCTBridge bridgeClass] + 535
    5   rn_irnext_demo                      0x000000010e578f7d -[RCTBridge setUp] + 285
    6   rn_irnext_demo                      0x000000010e578387 -[RCTBridge initWithDelegate:bundleURL:moduleProvider:launchOptions:] + 375
    7   rn_irnext_demo                      0x000000010e5781a2 -[RCTBridge initWithBundleURL:moduleProvider:launchOptions:] + 146
    8   rn_irnext_demo                      0x000000010e54fee7 -[RCTRootView initWithBundleURL:moduleName:initialProperties:launchOptions:] + 183
    9   rn_irnext_demo                      0x000000010e540c58 -[AppDelegate application:didFinishLaunchingWithOptions:] + 280
    10  UIKit                               0x0000000111008957 -[UIApplication _handleDelegateCallbacksWithOptions:isSuspended:restoreState:] + 299
    11  UIKit                               0x000000011100a23c -[UIApplication _callInitializationDelegatesForMainScene:transitionContext:] + 4119
    12  UIKit                               0x0000000111010584 -[UIApplication _runWithMainScene:transitionContext:completion:] + 1709
    13  UIKit                               0x000000011100d793 -[UIApplication workspaceDidEndTransaction:] + 182
    14  FrontBoardServices                  0x000000011a3775f6 __FBSSERIALQUEUE_IS_CALLING_OUT_TO_A_BLOCK__ + 24
    15  FrontBoardServices                  0x000000011a37746d -[FBSSerialQueue _performNext] + 186
    16  FrontBoardServices                  0x000000011a3777f6 -[FBSSerialQueue _performNextFromRunLoopSource] + 45
    17  CoreFoundation                      0x00000001132eac01 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    18  CoreFoundation                      0x00000001132d00cf __CFRunLoopDoSources0 + 527
    19  CoreFoundation                      0x00000001132cf5ff __CFRunLoopRun + 911
    20  CoreFoundation                      0x00000001132cf016 CFRunLoopRunSpecific + 406
    21  UIKit                               0x000000011100c02f -[UIApplication _run] + 468
    22  UIKit                               0x00000001110120d4 UIApplicationMain + 159
    23  rn_irnext_demo                      0x000000010e54103f main + 111
    24  libdyld.dylib                       0x00000001139cb65d start + 1
    25  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

Additionally produces a Thread 1:signal SIGABRT error in the main.m file.

Additional info:

1) XCode 8
2) react-native: 0.44
3) macOSx

Need assistance in solving this. Thank you in advance for your help!


问:
Machine Learning Suggestions
I have data of a lot of students who got selected by some colleges based on their marks. Iam new to machine Learning. Can I have some suggestions how can I add Azure Machine Learning for predicting the colleges that they can get based on their marks</p>

答: The Least-square support vector machine (LSSVM) is a powerful algorithm for this application. Visit http://www.esat.kuleuven.be/sista/lssvmlab/ for more information.</p>

Title: Machine Learning Suggestions


问:
Getting duplicates on JOINs in SQL Server 2014
My Tables:

Account A

Plate P

FinTransMaster F

TollTrans T

Relationships:

```<code>A.AccountId = P.AccountId
A.AccountId = F.AccountId
A.AccountId = P.AccountId = F.AccountId
P.LicPlateNo = T.LicPlateNo

T.AccountId != A.AccountId
T.AccountId != P.AccountId
T.AccountId != F.AccountId
</code>```

I need all records where:

```<code>     T.AccountId = '123456'
 AND EXISTS F.TransCode = 'TOLL'
 AND NOT EXISTS F.TransCode = 'PYMT'
 AND A.CurrentBalance > 0
</code>```

My code so far:

```<code>SELECT A.*

FROM Account A
INNER JOIN Plate P ON P.AccountId = A.AccountId
INNER JOIN TollTrans T ON T.LicPlateNo = P.LicPlateNo

WHERE EXISTS     (SELECT 1
                  FROM FinTransMaster F
                  WHERE F.AcctID = A.AccountID AND F.TransCode = 'TOLL'
                  )
  AND NOT EXISTS (SELECT 1
                  FROM FinTransMaster F
                  WHERE F.AcctID = A.AccountID AND F.TransCode = 'PYMT'
                  )
  AND T.AccountId = '123456'
  AND A.CurrentBalance > 0

ORDER BY BalanceDT DESC
</code>```

Each Account has a Licence Plate. Some Accounts have multiple Licence Plates. Maybe, that's the reason I'm getting duplicates.

How can I refine this code?

答:
Use

```<code>select distinct a.col1,a.col2....
(rest of the query)
</code>```

Also see if you can replace join with exists as you are not selecting anything from other tables, so performance would be better.

Body:
My Tables:

Account A

Plate P

FinTransMaster F

TollTrans T

Relationships:

A.AccountId = P.AccountId
A.AccountId = F.AccountId
A.AccountId = P.AccountId = F.AccountId
P.LicPlateNo = T.LicPlateNo

T.AccountId != A.AccountId
T.AccountId != P.AccountId
T.AccountId != F.AccountId

I need all records where:

     T.AccountId = '123456'
 AND EXISTS F.TransCode = 'TOLL'
 AND NOT EXISTS F.TransCode = 'PYMT'
 AND A.CurrentBalance > 0

My code so far:

SELECT A.*

FROM Account A
INNER JOIN Plate P ON P.AccountId = A.AccountId
INNER JOIN TollTrans T ON T.LicPlateNo = P.LicPlateNo

WHERE EXISTS     (SELECT 1
                  FROM FinTransMaster F
                  WHERE F.AcctID = A.AccountID AND F.TransCode = 'TOLL'
                  )
  AND NOT EXISTS (SELECT 1
                  FROM FinTransMaster F
                  WHERE F.AcctID = A.AccountID AND F.TransCode = 'PYMT'
                  )
  AND T.AccountId = '123456'
  AND A.CurrentBalance > 0

ORDER BY BalanceDT DESC

Each Account has a Licence Plate. Some Accounts have multiple Licence Plates. Maybe, that's the reason I'm getting duplicates.

How can I refine this code?

Body:
Use

select distinct a.col1,a.col2....
(rest of the query)

Also see if you can replace join with exists as you are not selecting anything from other tables, so performance would be better.


问:
reading vm properties from a shell script XshowSettings
I am trying to capture the output of java -XshowSettings | grep file.encoding but it is not working. I am trying to read a property of java -XshowSettings from a Unix shell script. Normally, it is easy to ready a property by using e.g. printenv | grep JAVA_HOME but in case of java -XshowSetting, grep does not work.

So, I want something like this java -XshowSetting | grep file.encoding, but it does not work. Any idea?

答:
This will solve your problem

```<code>java -XshowSettings 2>&1 | grep file.encoding
</code>```

You need to combine the standard output and standard error to capture the results. Read more here.

Body:
This will solve your problem

java -XshowSettings 2>&1 | grep file.encoding

You need to combine the standard output and standard error to capture the results. Read more here.


问:
Get link of clicked image pure javascript
```<code><!DOCTYPE html>
<html>
<body>

<h2>Spectacular Mountain</h2>
<img src="pic_mountain.jpg" alt="Mountain View" style="width:304px;height:228px;">

</body>
</html>
</code>```

i want to get the image source in java script when any image is clicked and ovveride(ignore) the onclick attribute for any image (if available)

Note: i cant change anything in the HTML code

Note2: i can only use pure JavaScript (no jQuery or anything else)

Note3: the image does not have an ID

答:
If you have only one image, then

```<code>var img = document.getElementsByTagName("img");
console.log(img[0].src);
</code>```

To get all the src of images,

```<code>var img = document.getElementsByTagName("img");
    for(i = 0;i < img.length; i++)
    {
        console.log(img[i].src);
    }
</code>```

To get the clicked image src,

```<code>   document.addEventListener('click', function(e) {
     e = e || window.event;
     var target = e.target;
     if(target.tagName == 'IMG'){ console.log(target.src); }
    }, false);
</code>```

Body:
<!DOCTYPE html>

Spectacular Mountain

i want to get the image source in java script when any image is clicked and ovveride(ignore) the onclick attribute for any image (if available)

Note: i cant change anything in the HTML code

Note2: i can only use pure JavaScript (no jQuery or anything else)

Note3: the image does not have an ID

Body:
If you have only one image, then

var img = document.getElementsByTagName("img");
console.log(img[0].src);

To get all the src of images,

var img = document.getElementsByTagName("img");
    for(i = 0;i < img.length; i++)
    {
        console.log(img[i].src);
    }

To get the clicked image src,

   document.addEventListener('click', function(e) {
     e = e || window.event;
     var target = e.target;
     if(target.tagName == 'IMG'){ console.log(target.src); }
    }, false);


问:
Swift Use UnsafeMutablePointer of Struct to get value of String Error
I want to get the pointer of a struct, and get or set the value. the code is here

```<code>protocol TestProtocol {

}

struct TestStruct: TestProtocol {
    var username: String?
}

class TestViewModel {
    var testStruct: TestProtocol?

    func test() -> UnsafeMutablePointer<TestStruct?>? {
        guard let _ = self.testStruct as? TestStruct else {
            return nil
        }
        return withUnsafeMutablePointer(to: &(self.testStruct)) { (pointer) -> UnsafeMutablePointer<TestStruct?> in
            return pointer.withMemoryRebound(to: TestStruct?.self, capacity: MemoryLayout<TestStruct?>.size) { (point) -> UnsafeMutablePointer<TestStruct?> in
                return point
            }
        }
    }
}

func getvalue() {
     let testViewModel = TestViewModel()
     var testStruct = TestStruct()
     testStruct.username = "123"
     testViewModel.testStruct = testStruct
     print("\(testViewModel.test()?.pointee?.username)")
     // here print Optional("")， why not "123"?
}
</code>```

the get value function print result is wrong, but if the TestStruct only has a var of Int, the result is right. just like that:

```<code>struct TestStruct: TestProtocol {
        var number: Int?
    }

func getvalue() {
         let testViewModel = TestViewModel()
         var testStruct = TestStruct()
         testStruct. number = 123
         testViewModel.testStruct = testStruct
         print("\(testViewModel.test()?.pointee?.username)")
         // Optional(123)
    }
</code>```

why? how to fix it?

答:
here's the pattern for making/using/finishing with a pointer to an object:

```<code>// this allocates memory for the pointer
let somePointer = UnsafeMutablePointer<someType>.allocate(capacity: 1)
// this initializes the memory to the value
somePointer.initialize(to: someInstanceOfSomeTime)
// this allows me to access the object
somePointer.pointee.someMethod(/* ... */)
// this destroys the memory
somePointer.deinitialize(count: 1)
somePointer.deallocate(capacity: 1)
</code>```

Since your memory may contain a type that either directly or indirectly contains a reference counted type, it is vital that you understand that pointers have state and you need to manage the lifetime of all those states.

This is your typical lifetime
 - A pointer is allocated but its contents is not initialized and must not be used
 - A pointer is initialized and its contents may now be used
 - A pointer is deinitialized and now it's contents may no longer may be used but you can initialize it again
 - A pointer is deallocated and may no longer be initialized.

Knowing these steps is really important. When you're working with typical swift code you are doing all of these steps but they are implicit. Take this simple example:

```<code>public func printThingValue(t:Thing) {
    let aCopy = t.value
    print(aCopy)
}
</code>```

Let's consider the lifetime of aCopy. Before calling, aCopy is not allocated. When you enter the function, aCopy is allocated (on the stack) but not initialized. When the assignment happens, aCopy is initialized. When print is called, aCopy is used. Before printThingValue exits, aCopy is deinitialized. When it exits, aCopy gets deallocated (stack frame destroyed).

Knowing this lifetime is very important because this is exactly the model that is used by pointers but it is no longer automatic/implicit.

Related to this is the answer to the question: can I construct a value type that is not initialized? The answer is yes - there is a way and that's through UnsafeMutablePointer. If you call allocate you will get uninitialized memory that represents your value type, but this is extremely dangerous. If you assign to the pointee before it has been initialized, you require the swift compiler to inject code that will destroy the value that's there. And this will either crash or result in undefined behavior if the type pointed to contains a reference type.

Knowing and managing these steps is the way that Apple has tried to make it possible for you to use pointers, but it creates a new set of dangers:

```<code>- using an unallocated pointer (crash)
- using/assigning to an allocated but uninitialized pointer (crash)
- failing to deinitialize an initialized pointer (reference leak)
- failing to deallocate a deinitialized pointer (memory leak)
</code>```

Body:
I want to get the pointer of a struct, and get or set the value. the code is here

protocol TestProtocol {

}

struct TestStruct: TestProtocol {
    var username: String?
}

class TestViewModel {
    var testStruct: TestProtocol?

    func test() -> UnsafeMutablePointer<TestStruct?>? {
        guard let _ = self.testStruct as? TestStruct else {
            return nil
        }
        return withUnsafeMutablePointer(to: &(self.testStruct)) { (pointer) -> UnsafeMutablePointer<TestStruct?> in
            return pointer.withMemoryRebound(to: TestStruct?.self, capacity: MemoryLayout<TestStruct?>.size) { (point) -> UnsafeMutablePointer<TestStruct?> in
                return point
            }
        }
    }
}

func getvalue() {
     let testViewModel = TestViewModel()
     var testStruct = TestStruct()
     testStruct.username = "123"
     testViewModel.testStruct = testStruct
     print("\(testViewModel.test()?.pointee?.username)")
     // here print Optional("")， why not "123"?
}

the get value function print result is wrong, but if the TestStruct only has a var of Int, the result is right. just like that:

struct TestStruct: TestProtocol {
        var number: Int?
    }

func getvalue() {
         let testViewModel = TestViewModel()
         var testStruct = TestStruct()
         testStruct. number = 123
         testViewModel.testStruct = testStruct
         print("\(testViewModel.test()?.pointee?.username)")
         // Optional(123)
    }

why? how to fix it?

Body:
here's the pattern for making/using/finishing with a pointer to an object:

// this allocates memory for the pointer
let somePointer = UnsafeMutablePointer<someType>.allocate(capacity: 1)
// this initializes the memory to the value
somePointer.initialize(to: someInstanceOfSomeTime)
// this allows me to access the object
somePointer.pointee.someMethod(/* ... */)
// this destroys the memory
somePointer.deinitialize(count: 1)
somePointer.deallocate(capacity: 1)

Since your memory may contain a type that either directly or indirectly contains a reference counted type, it is vital that you understand that pointers have state and you need to manage the lifetime of all those states.

This is your typical lifetime
 - A pointer is allocated but its contents is not initialized and must not be used
 - A pointer is initialized and its contents may now be used
 - A pointer is deinitialized and now it's contents may no longer may be used but you can initialize it again
 - A pointer is deallocated and may no longer be initialized.

Knowing these steps is really important. When you're working with typical swift code you are doing all of these steps but they are implicit. Take this simple example:

public func printThingValue(t:Thing) {
    let aCopy = t.value
    print(aCopy)
}

Let's consider the lifetime of aCopy. Before calling, aCopy is not allocated. When you enter the function, aCopy is allocated (on the stack) but not initialized. When the assignment happens, aCopy is initialized. When print is called, aCopy is used. Before printThingValue exits, aCopy is deinitialized. When it exits, aCopy gets deallocated (stack frame destroyed).

Knowing this lifetime is very important because this is exactly the model that is used by pointers but it is no longer automatic/implicit.

Related to this is the answer to the question: can I construct a value type that is not initialized? The answer is yes - there is a way and that's through UnsafeMutablePointer. If you call allocate you will get uninitialized memory that represents your value type, but this is extremely dangerous. If you assign to the pointee before it has been initialized, you require the swift compiler to inject code that will destroy the value that's there. And this will either crash or result in undefined behavior if the type pointed to contains a reference type.

Knowing and managing these steps is the way that Apple has tried to make it possible for you to use pointers, but it creates a new set of dangers:

- using an unallocated pointer (crash)
- using/assigning to an allocated but uninitialized pointer (crash)
- failing to deinitialize an initialized pointer (reference leak)
- failing to deallocate a deinitialized pointer (memory leak)


问:
Display multiple plots with Plots.jl
I currently have two vectors, x and y which I plot separately as in

```<code>using Plots
pyplot() # chooses pyplot background
x = rand(100); y = rand(100)
plt1 = plot(x)
display(plt1)
plt2 = plot(y)
display(plt2)
</code>```

I have also tried the gui() and gui(plt1) functions, but these have a similar effect as the display(plt1) function.  Also note that I am running this in a file (hence the necessity of the display() function).  I have also tried similar code in the REPL, which has the same problem of only displaying the last plot I call.

My question is how do I display two different figures at the same time?  My current implementation has plt2 overwrite plt1, so I am not able to see them at the same time.  Note that I am not looking for making a subplot, but rather two distinct figures.  Is there a figure() function similar to Matplotlib which allows declaration of separate figures?

答: Yes, use the phrase plt2 = plot(y, reuse = false)

Title: Display multiple plots with Plots.jl

Body:
I currently have two vectors, x and y which I plot separately as in

using Plots
pyplot() # chooses pyplot background
x = rand(100); y = rand(100)
plt1 = plot(x)
display(plt1)
plt2 = plot(y)
display(plt2)

I have also tried the gui() and gui(plt1) functions, but these have a similar effect as the display(plt1) function.  Also note that I am running this in a file (hence the necessity of the display() function).  I have also tried similar code in the REPL, which has the same problem of only displaying the last plot I call.

My question is how do I display two different figures at the same time?  My current implementation has plt2 overwrite plt1, so I am not able to see them at the same time.  Note that I am not looking for making a subplot, but rather two distinct figures.  Is there a figure() function similar to Matplotlib which allows declaration of separate figures?


问:
Import UIkit Angular FullStack
I'm getting this error trying to import UIkit with Angular FullStack generator:

```<code>Module 'uikit' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
</code>```

This is what I've done:

webpack.make.js

```<code>    if(TEST) {
        config.entry = {};
    } else {
        config.entry = {
            app: './client/app/app.js',
            polyfills: './client/polyfills.js',
            vendor: [
                'angular',
                'angular-animate',
                'angular-aria',
                'angular-cookies',
                'angular-resource',

                'angular-sanitize',

                'angular-ui-router',
                'lodash',

                'uikit'
            ]
        };
    }
</code>```

app.js

```<code>...
import uikit from 'uikit';
...

angular.module('myApp', [ngCookies, ngResource, ngSanitize, uiRouter, uikit])
</code>```

However, I can use the style directives by adding the following to my app.scss:

```<code>@import'~uikit/dist/css/uikit.css';
</code>```

But, if I don't import the JS module, I get UIkit is not defined.

How can I properly import UIkit to my project??

Thanks in advance :)

答:
Following the docs, this is what worked for me:

Do not add uikit vendor to webpack.make.js

Insert import UIkit from 'uikit'; to my app.js

Title: Import UIkit Angular FullStack

Body:
I'm getting this error trying to import UIkit with Angular FullStack generator:

Module 'uikit' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

This is what I've done:

webpack.make.js

    if(TEST) {
        config.entry = {};
    } else {
        config.entry = {
            app: './client/app/app.js',
            polyfills: './client/polyfills.js',
            vendor: [
                'angular',
                'angular-animate',
                'angular-aria',
                'angular-cookies',
                'angular-resource',

                'angular-sanitize',

                'angular-ui-router',
                'lodash',

                'uikit'
            ]
        };
    }

app.js

...
import uikit from 'uikit';
...

angular.module('myApp', [ngCookies, ngResource, ngSanitize, uiRouter, uikit])

However, I can use the style directives by adding the following to my app.scss:

@import'~uikit/dist/css/uikit.css';

But, if I don't import the JS module, I get UIkit is not defined.

How can I properly import UIkit to my project??

Thanks in advance :)


问:
How to use a public method from a controller to another controller in codeigniter?
I have 2 controllers, Listes.php and Campagnes.php. I want to use a method from the Listes controller in a method from the campagnes, is it possible? And is it possible to pass some parameters to it?

I use Codeigniter 3.

I tried some answers I found here but none of them worked.

I also this in the campagnes.php controller :

```<code>    include_once (dirname(__FILE__) . "/Listes.php");

     class Campagnes extends Listes {

       public function listes_recap()
       {
         $result = parent::add($parameter1, $parameter2);
       }

      }
</code>```

and in the Listes.php controller :

```<code>    class Listes extends CI_Controller {

     public function add($parameter1, $parameter2)
     {
       code here...
     }

    }
</code>```

Thanks in advance for you're help.

答: calling one controller method from another controller is not a good programming  strategy</p>

Body:
I have 2 controllers, Listes.php and Campagnes.php. I want to use a method from the Listes controller in a method from the campagnes, is it possible? And is it possible to pass some parameters to it?

I use Codeigniter 3.

I tried some answers I found here but none of them worked.

I also this in the campagnes.php controller :

    include_once (dirname(__FILE__) . "/Listes.php");

     class Campagnes extends Listes {

       public function listes_recap()
       {
         $result = parent::add($parameter1, $parameter2);
       }

      }

and in the Listes.php controller :

    class Listes extends CI_Controller {

     public function add($parameter1, $parameter2)
     {
       code here...
     }

    }

Thanks in advance for you're help.


问:
How can I change a style via code that is stored in a resource dictionary in App.xaml on the fly?
I am trying to have the ability for several core colors throughout the app to be changeable on the fly by the user. My current idea is to have a single SolidColorBrush that is my "theme color" and then to reference that throughout my main styles.

```<code><SolidColorBrush x:Key="ReflectiveColor1" Color="#FF0E777B"></SolidColorBrush>
</code>```

This snippet is stored in a resourcedictionary that is reference in my App.xaml

```<code><Application.Resources>
    <ResourceDictionary Source="DictionaryAlienwareTheme.xaml">
    </ResourceDictionary>
</Application.Resources>
</code>```

When I try and access the color in my App.cs I get an error

```<code> Application.Current.Resources["ReflectiveColor1"] = Colors.Black;
</code>```

Error:

```<code>System.Runtime.InteropServices.COMException: 'No installed components were
detected.
Local values are not allowed in resource dictionary with Source set
</code>```

Is there anyway to make this work? I'm assuming this error is because it doesn't want us to modify styles stored there, but I don't know the workaround.

答:
Application will not be able to find the Resource ReflectiveColor1 until you merge all resource dictionaries together.

Change your App.xaml to Merge the dictionaries. Like below.

```<code><Application.Resources>
    <ResourceDictionary >
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="DictionaryAlienwareTheme.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>
</code>```

Then you should be able to access the Resource in the same way that you were doing before.

Body:
I am trying to have the ability for several core colors throughout the app to be changeable on the fly by the user. My current idea is to have a single SolidColorBrush that is my "theme color" and then to reference that throughout my main styles.

<SolidColorBrush x:Key="ReflectiveColor1" Color="#FF0E777B"></SolidColorBrush>

This snippet is stored in a resourcedictionary that is reference in my App.xaml

<Application.Resources>
    <ResourceDictionary Source="DictionaryAlienwareTheme.xaml">
    </ResourceDictionary>
</Application.Resources>

When I try and access the color in my App.cs I get an error

 Application.Current.Resources["ReflectiveColor1"] = Colors.Black;

Error:

System.Runtime.InteropServices.COMException: 'No installed components were
detected.
Local values are not allowed in resource dictionary with Source set

Is there anyway to make this work? I'm assuming this error is because it doesn't want us to modify styles stored there, but I don't know the workaround.

Body:
Application will not be able to find the Resource ReflectiveColor1 until you merge all resource dictionaries together.

Change your App.xaml to Merge the dictionaries. Like below.

<Application.Resources>
    <ResourceDictionary >
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="DictionaryAlienwareTheme.xaml" />
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

Then you should be able to access the Resource in the same way that you were doing before.


答:
you can remove with distinct</p>

```<code>SELECT distinct A.*
FROM Account A
INNER JOIN Plate P ON P.AccountId = A.AccountId
INNER JOIN TollTrans T ON T.LicPlateNo = P.LicPlateNo
INNER JOIN FinTransMaster F on F.AcctID = A.AccountID AND F.TransCode = 'TOLL'
WHERE NOT EXISTS (SELECT *
                  FROM FinTransMaster G
                  WHERE G.AcctID = A.AccountID AND G.TransCode = 'PYMT'
                  )
AND T.AccountId = '123456' AND A.CurrentBalance > 0
ORDER BY BalanceDT DESC
</code>```

Title: Getting duplicates on JOINs in SQL Server 2014

Body:
you can remove with distinct

SELECT distinct A.*
FROM Account A
INNER JOIN Plate P ON P.AccountId = A.AccountId
INNER JOIN TollTrans T ON T.LicPlateNo = P.LicPlateNo
INNER JOIN FinTransMaster F on F.AcctID = A.AccountID AND F.TransCode = 'TOLL'
WHERE NOT EXISTS (SELECT *
                  FROM FinTransMaster G
                  WHERE G.AcctID = A.AccountID AND G.TransCode = 'PYMT'
                  )
AND T.AccountId = '123456' AND A.CurrentBalance > 0
ORDER BY BalanceDT DESC