问:
Modifying Dijkstra to find path with max coloured node
I just saw a solution of a question that modifying Dijkstra to get the shortest path with a max of K coloured edge. I am wondering what if we want find the shortest path with coloured node instead of edge, how are we gonna modify Dijkstra to do the trick?

What I come up with is that on top of Dijkstra, I add an integer variable let say i. Then make a map to record how many coloured node it takes to get there, and if there is a way that passed through less coloured node, update it. And we will take the path with least coloured node. But this seems something is wrong, any suggestion?

```<code> Algorithm  Dijkstra ( G , s in V(G), c(v) in{black, white}, K )
 1.  for  each vertex u in V(G)  do  dist[u] <- +infinity
 2.  dist[s] <- 0 ;   p[s] <- null
 3. c(s)=black? r <- 1 : r <- 0
 4. Q <- ConstructMinHeap(V(G), dist)
 5. M <- Map(s, r)
 6.  while Q != null do
 7.     u <- DeleteMin(Q)
 8.     for  each v in Adj[u]  do
 9.         if M.value(u) is null then do
 10.                M <- Map(u, M.value(v) + c(u)=black? 1 : 0)
 11.            else
 12.                M.value(u) < (M.value(v) + c(u)=black? 1 : 0)? Update : do nothing
 13.            end-if
 14.             if   dist[v] >  dist[u] + w(u,v) and M.value < K then do
 15.                dist[v] <- dist[u] + w(u,v)
 16.                p[v] <- u
 17.                UpHeap(v,Q)
 18.            end-if
 19.        end-for
 20.     end-while
 end
</code>```

答: If you use a priority queue to rank your options, consider using both the distance so far and the number of coloured nodes passed through to determine the order of priority. In this manner, you can use the traditional Dijkstra and let the determination of a minimum path be determined by your priority ranking.</p>

Body:
I just saw a solution of a question that modifying Dijkstra to get the shortest path with a max of K coloured edge. I am wondering what if we want find the shortest path with coloured node instead of edge, how are we gonna modify Dijkstra to do the trick?

What I come up with is that on top of Dijkstra, I add an integer variable let say i. Then make a map to record how many coloured node it takes to get there, and if there is a way that passed through less coloured node, update it. And we will take the path with least coloured node. But this seems something is wrong, any suggestion?

 Algorithm  Dijkstra ( G , s in V(G), c(v) in{black, white}, K )
 1.  for  each vertex u in V(G)  do  dist[u] <- +infinity
 2.  dist[s] <- 0 ;   p[s] <- null
 3. c(s)=black? r <- 1 : r <- 0
 4. Q <- ConstructMinHeap(V(G), dist)
 5. M <- Map(s, r)
 6.  while Q != null do
 7.     u <- DeleteMin(Q)
 8.     for  each v in Adj[u]  do
 9.         if M.value(u) is null then do
 10.                M <- Map(u, M.value(v) + c(u)=black? 1 : 0)
 11.            else
 12.                M.value(u) < (M.value(v) + c(u)=black? 1 : 0)? Update : do nothing
 13.            end-if
 14.             if   dist[v] >  dist[u] + w(u,v) and M.value < K then do
 15.                dist[v] <- dist[u] + w(u,v)
 16.                p[v] <- u
 17.                UpHeap(v,Q)
 18.            end-if
 19.        end-for
 20.     end-while
 end


来源: stackexchange

问:
White blinking when changing background image
On my website I have a div with a blurred image, and I want this image to be unblurred on hover, progressively (with transition-property and transition-duration). I prepared two differents versions of my image, blurred and unblurred. The problem is that, online (even though I have optical fiber) and on my computer, there's a quick white blinking before the transition occurs.
Why is that, and how can I fix it ?

答:
If you don't want to use css to blur your image, you could use a pseudo element :after to stack your images.

You put the unblurred over the blurred one, with opacity: 0, on hover, you change to opacity:1

It won't blink this way.

ContentLicense: CC BY-SA 3.0


问:
Converting array of unicode byte to string
From some external module I receive array with unicode symbols and can not convert it to string.

```<code>   print(data)
   print(type(data))
   print(type(data[0]))
   print(len(data[0]))
</code>```

Output

```<code>   array('B', [99, 100, 99, 100, 99, 100, 99, 100, 99])
   <type 'unicode'>
   <type 'unicode'>
   1
</code>```

So I just need to get a string 'cdcdcdcdc', but type of data[0] is unicode, although 'B' (int) presented. All my tires finished with errors or I got same one array (not a string) when print.

upd:I tried

```<code>   rets=''
   for i in xrange(len(data)):
       rets += chr(int(ord( data[i] )))
   print( rets )
</code>```

答:
The outputs are an evidence that data is in fact this unicode string:

```<code>data = u"array('B', [99, 100, 99, 100, 99, 100, 99, 100, 99])"
</code>```

(weird to have got that, but it is the only possibility)

ast.litteral_eval cannot processes arrays, so you will have to use the evil eval to change this in a true array:

```<code>from array import array
arr = eval(str(data))
</code>```

Never do that if data could come from an external source, because eval-ing uncontrolled data can allow execution of arbitrary code: CAVEAT EMPTOR

But once this is done, arr is a nice array of unsigned chars. You can easily make it a string that way:

```<code>''.join([chr(i) for i in b])
</code>```

Anyway, above is just a workaround. The real solution would be to find how such a weird string was produced and fix that.

Body:
From some external module I receive array with unicode symbols and can not convert it to string.

   print(data)
   print(type(data))
   print(type(data[0]))
   print(len(data[0]))

Output

   array('B', [99, 100, 99, 100, 99, 100, 99, 100, 99])
   <type 'unicode'>
   <type 'unicode'>
   1

So I just need to get a string 'cdcdcdcdc', but type of data[0] is unicode, although 'B' (int) presented. All my tires finished with errors or I got same one array (not a string) when print.

upd:I tried

   rets=''
   for i in xrange(len(data)):
       rets += chr(int(ord( data[i] )))
   print( rets )

Body:
The outputs are an evidence that data is in fact this unicode string:

data = u"array('B', [99, 100, 99, 100, 99, 100, 99, 100, 99])"

(weird to have got that, but it is the only possibility)

ast.litteral_eval cannot processes arrays, so you will have to use the evil eval to change this in a true array:

from array import array
arr = eval(str(data))

Never do that if data could come from an external source, because eval-ing uncontrolled data can allow execution of arbitrary code: CAVEAT EMPTOR

But once this is done, arr is a nice array of unsigned chars. You can easily make it a string that way:

''.join([chr(i) for i in b])

Anyway, above is just a workaround. The real solution would be to find how such a weird string was produced and fix that.


问:
Is there an easy way to increase the value of a Map object value?
I currently have this code, where speciesMap is a map in which the keys have maps as values.

```<code>var speciesMap = new Map();
...
if(!speciesMap.get(species)) {
    let obj = new Map();
    obj.set('count', 0);
    obj.set('vol', 0);
    speciesMap.set(species, obj);
}
</code>```

I want to increase the count of a given specie by 1, but the only way I found to do it was like this.

```<code>speciesMap.get(species).set('count', speciesMap.get(species).get('count') + 1);
</code>```

Is there a cleaner and simpler way to increase the value instead of going down the whole map again to retrieve its value? Same goes for volume, I need to go down the object and add + vol to it.

Wanted something like

```<code>speciesMap.get(species).set('count', this+1);
</code>```

which obviously doesn't work.

答:
@Bergi's answer is fine, but it's Friday, so...

You can introduce a mutable number class and use instances of that class instead of bare numbers:

class Int {

    constructor(n) {
        this.n = n;
    }

    toString() {
        return String(this.n);
    }

    valueOf() {
        return this.n;
    }

    add(m) {
        this.n += m;
        return this;
    }
}

let speciesMap = new Map();
speciesMap.set('elefant', new Map([
    ['count', new Int(0)],
    ['vol', new Int(0)]
]));

speciesMap.get('elefant').get('count').add(1);

alert('count is now ' + speciesMap.get('elefant').get('count'));```

Body:
I currently have this code, where speciesMap is a map in which the keys have maps as values.

var speciesMap = new Map();
...
if(!speciesMap.get(species)) {
    let obj = new Map();
    obj.set('count', 0);
    obj.set('vol', 0);
    speciesMap.set(species, obj);
}

I want to increase the count of a given specie by 1, but the only way I found to do it was like this.

speciesMap.get(species).set('count', speciesMap.get(species).get('count') + 1);

Is there a cleaner and simpler way to increase the value instead of going down the whole map again to retrieve its value? Same goes for volume, I need to go down the object and add + vol to it.

Wanted something like

speciesMap.get(species).set('count', this+1);

which obviously doesn't work.


问:
Trigger c# Event from JavaScript Function
I'm trying to call c# event from javascript function. I tried this:

```<code><script type="text/javascript">
    function LikeClick() {
        document.getElementById('<%=Helper.ClientID %>').click();
    }
</script>

<asp:Button ID="Helper" runat="server" OnClick="Helper_Click" />
</code>```

But it doesn't trigger the c# event.

答:
I believe a <asp:Button> will natively post the form back without a client side event handler. You need a control that does not natively post back but instead uses a client side click handler to call the __doPostBack() function.

Change

<asp:Button ID="Helper" runat="server" OnClick="Helper_Click" />

to this

<asp:LinkButton ID="Helper" runat="server" OnClick="Helper_Click" />

Body:
I'm trying to call c# event from javascript function. I tried this:

<asp:Button ID="Helper" runat="server" OnClick="Helper_Click" />

But it doesn't trigger the c# event.


问:
Reduce Cordova apk's size
I am developing a hybrid app and now I am in a quandary over phonegap and cordova. Cordova is now in my PC and when I do a

cordova build android

I get an apk that's 3.7 mb, Nevertheless, if I use the build.phonegap.com route, the .apk is only 1.2 mb.

I tried deleting all the unnecessary plugins and even then the build size didnt change

How do I reduce the size of my cordova apk?

答:
Opening the apk archive, I noticed that no js file was minified, and .map files were big.
In my case (I am using TypeScript) map files are only for debug to map js source code to ts source code.

I've installed cordova-minify

```<code>npm install cordova-minify --save-dev
</code>```

I tweaked the hook a little bit to go into the correct folder, disabled the css minifier which messing all up, and delete any map file.

My hook path :

```<code>hooks/after_prepare/minify.js
</code>```

I've also used only one splash screen file (the one for xxxhdpi) not cropped (nor for portrait neither for landscape), following the ionic recommendation

The source image’s minimum dimensions should be 2208x2208 px, and its
  artwork should be centered within the square, knowing that each
  generated image will be center cropped into landscape and portrait
  images. The splash screen’s artwork should roughly fit within a center
  square (1200x1200 px).
  (http://ionicframework.com/docs/v1/cli/icon-splashscreen.html)

only one line in config.xml:

```<code><splash src="resources/splash.png" density="xxxhdpi"/>
</code>```

With all this, I've reduce the size of the apk from 4.8M to 2.5M without losing any features (splash screen).

Title: Reduce Cordova apk's size

Body:
Opening the apk archive, I noticed that no js file was minified, and .map files were big.
In my case (I am using TypeScript) map files are only for debug to map js source code to ts source code.

I've installed cordova-minify

npm install cordova-minify --save-dev

I tweaked the hook a little bit to go into the correct folder, disabled the css minifier which messing all up, and delete any map file.

My hook path :

hooks/after_prepare/minify.js

I've also used only one splash screen file (the one for xxxhdpi) not cropped (nor for portrait neither for landscape), following the ionic recommendation

The source image’s minimum dimensions should be 2208x2208 px, and its
  artwork should be centered within the square, knowing that each
  generated image will be center cropped into landscape and portrait
  images. The splash screen’s artwork should roughly fit within a center
  square (1200x1200 px).
  (http://ionicframework.com/docs/v1/cli/icon-splashscreen.html)

only one line in config.xml:

<splash src="resources/splash.png" density="xxxhdpi"/>

With all this, I've reduce the size of the apk from 4.8M to 2.5M without losing any features (splash screen).


问:
scroll header when scroll recyclerview items
I have a header with an image and a RecyclerView with some items

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:id="@+id/header"
        android:orientation="vertical" android:layout_width="match_parent"
        android:layout_height="100dp"
        android:background="#ffffff">

        <ImageView
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:padding="0dp"
            android:id="@+id/imageView"
            android:adjustViewBounds="true"
            android:cropToPadding="false" />

    </RelativeLayout>

    <ProgressBar
        android:id="@+id/progressBar1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentStart="true"
        android:scrollbars="vertical"
        android:layout_alignParentLeft="true" />

</LinearLayout>
</code>```

RelativeLayout is fixed on top of RecyclerView .
What I want is to scroll this header (RelativeLayout) up when scroll the RecyclerView .

Any ideas how to scroll header with RecyclerView?

答:
make your root layout a coordinator layout then make the RecyclerView Direct child of the coordinator layout. Wrap the scrollable content inside a AppBarLayout then apply the scroll behaviours. Try the following code this should help you.</p>

```<code><android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
>

<android.support.design.widget.AppBarLayout

        android:layout_height="wrap_content"
        android:layout_width="match_parent"
    >

    <RelativeLayout
        android:id="@+id/header"
        android:orientation="vertical" android:layout_width="match_parent"
        android:layout_height="100dp"
        app:layout_scrollFlags="scroll"
        android:background="#ffffff">

        <ImageView
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:padding="0dp"
            android:id="@+id/imageView"
            android:src="@mipmap/ic_launcher"
            android:adjustViewBounds="true"
            android:cropToPadding="false" />

    </RelativeLayout>

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

<android.support.v7.widget.RecyclerView
    android:id="@+id/recyclerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentStart="true"
    android:scrollbars="vertical"
    android:layout_alignParentLeft="true"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    />

 </android.support.design.widget.CoordinatorLayout>
</code>```

Body:
I have a header with an image and a RecyclerView with some items

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:id="@+id/header"
        android:orientation="vertical" android:layout_width="match_parent"
        android:layout_height="100dp"
        android:background="#ffffff">

        <ImageView
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:padding="0dp"
            android:id="@+id/imageView"
            android:adjustViewBounds="true"
            android:cropToPadding="false" />

    </RelativeLayout>

    <ProgressBar
        android:id="@+id/progressBar1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentStart="true"
        android:scrollbars="vertical"
        android:layout_alignParentLeft="true" />

</LinearLayout>

RelativeLayout is fixed on top of RecyclerView .
What I want is to scroll this header (RelativeLayout) up when scroll the RecyclerView .

Any ideas how to scroll header with RecyclerView?

Body:
make your root layout a coordinator layout then make the RecyclerView Direct child of the coordinator layout. Wrap the scrollable content inside a AppBarLayout then apply the scroll behaviours. Try the following code this should help you.

<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
>

<android.support.design.widget.AppBarLayout

        android:layout_height="wrap_content"
        android:layout_width="match_parent"
    >

    <RelativeLayout
        android:id="@+id/header"
        android:orientation="vertical" android:layout_width="match_parent"
        android:layout_height="100dp"
        app:layout_scrollFlags="scroll"
        android:background="#ffffff">

        <ImageView
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:padding="0dp"
            android:id="@+id/imageView"
            android:src="@mipmap/ic_launcher"
            android:adjustViewBounds="true"
            android:cropToPadding="false" />

    </RelativeLayout>

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

<android.support.v7.widget.RecyclerView
    android:id="@+id/recyclerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentStart="true"
    android:scrollbars="vertical"
    android:layout_alignParentLeft="true"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    />

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


问:
How to force a user to re-enter login password using PAPE extension with max_auth_age=0
I am using OpenID with GAE (Experimental - Federated Login). I don't
get prompted for user/password when I hit logout and then hit login
back again. Can someone please let me know what the problem is?

I use the following code to create my login url's:

```<code>UserService userService = UserServiceFactory.getUserService();
HashSet<String> attributeRequestSet = new HashSet<String>();
attributeRequestSet.add("openid.ns.pape=http://specs.openid.net/
extensions/pape/1.0");
attributeRequestSet.add("openid.pape.max_auth_age=0");
String loginUrl = userService.createLoginURL(destinationUrl,
"gmail.com", "gmail.com", attributeRequestSet);
</code>```

and code for my logout url's:

```<code>UserService userService = UserServiceFactory.getUserService();
User user = userService.getCurrentUser();
String logoutUrl = userService.createLogoutURL(destinationUrl,
user.getAuthDomain())
</code>```

答:
As long as you are logged in to your Google account it will not request you to input username/password.

If you logout of your app and then login again, you are redirected to Google auth page, but since you are still logged into Google it just immediately redirects you back to your app.

The OpenID feature you are requesting (openid.pape.max_auth_age=0) is not yet supported: see Unsupported Features

ContentLicense: CC BY-SA 2.5

Body:
I am using OpenID with GAE (Experimental - Federated Login). I don't
get prompted for user/password when I hit logout and then hit login
back again. Can someone please let me know what the problem is?

I use the following code to create my login url's:

UserService userService = UserServiceFactory.getUserService();
HashSet<String> attributeRequestSet = new HashSet<String>();
attributeRequestSet.add("openid.ns.pape=http://specs.openid.net/
extensions/pape/1.0");
attributeRequestSet.add("openid.pape.max_auth_age=0");
String loginUrl = userService.createLoginURL(destinationUrl,
"gmail.com", "gmail.com", attributeRequestSet);

and code for my logout url's:

UserService userService = UserServiceFactory.getUserService();
User user = userService.getCurrentUser();
String logoutUrl = userService.createLogoutURL(destinationUrl,
user.getAuthDomain())


问:
How to set the size of a column in angular material?
Is it possible to set the width of layout="column"? I found only flex applicable to layout="row", I want to make the following design:
 column that has pairs of rows where I can set the width of the entire parent column:

答:
Is this the kind of thing you mean? Plunker

When you say

set the width of layout="column"

I think you mean set the width of the layout="row". The row width defines the width of the column, which can be a bit confusing but it makes sense.

Markup

```<code><div ng-controller="AppCtrl" ng-cloak="" ng-app="MyApp" style="width:100%; height:100%; padding:50px" layout="row">
  <div style="border:red 5px solid; overflow:auto" flex="50">
    <div ng-repeat="item in items" layout="row" flex>
      <div style="background:darkred; height:50px; margin:10px" flex></div>
      <div style="background:blue; height:50px; margin:10px" flex></div>
    </div>
  </div>
  <div style="border:red 5px solid; overflow:auto; margin-left:50px" flex="20">
    <div ng-repeat="item in items" layout="row" flex>
      <div style="background:darkred; height:50px; margin:10px" flex></div>
      <div style="background:blue; height:50px; margin:10px" flex></div>
    </div>
  </div>
</div>
</code>```

JS

```<code>angular.module('MyApp',['ngMaterial'])
.controller('AppCtrl', function($scope) {
  $scope.items = [0, 1, 2, 3, 4 ,5 ,6, 7, 8, 9];
});
</code>```

Body:
Is this the kind of thing you mean? Plunker

When you say

set the width of layout="column"

I think you mean set the width of the layout="row". The row width defines the width of the column, which can be a bit confusing but it makes sense.

Markup

<div ng-controller="AppCtrl" ng-cloak="" ng-app="MyApp" style="width:100%; height:100%; padding:50px" layout="row">
  <div style="border:red 5px solid; overflow:auto" flex="50">
    <div ng-repeat="item in items" layout="row" flex>
      <div style="background:darkred; height:50px; margin:10px" flex></div>
      <div style="background:blue; height:50px; margin:10px" flex></div>
    </div>
  </div>
  <div style="border:red 5px solid; overflow:auto; margin-left:50px" flex="20">
    <div ng-repeat="item in items" layout="row" flex>
      <div style="background:darkred; height:50px; margin:10px" flex></div>
      <div style="background:blue; height:50px; margin:10px" flex></div>
    </div>
  </div>
</div>

JS

angular.module('MyApp',['ngMaterial'])
.controller('AppCtrl', function($scope) {
  $scope.items = [0, 1, 2, 3, 4 ,5 ,6, 7, 8, 9];
});


问:
Twitter Bootstrap alert (notification) dynamically change text
Simple question, but I didn't succeed finding a satisfactory answer on SO.

When I have a bootstrap alert:

```<code><div id='alert' class='alert alert-error hide'>Alert.</div>
</code>```

I want the text to be controlled using either Javascript of by jQuery, I just looked at this solution to this problem, but does it have to be so complicated? Really?

答: As simple as: $("#alert").text("My new Text");

Body:
Simple question, but I didn't succeed finding a satisfactory answer on SO.

When I have a bootstrap alert:

Alert.

I want the text to be controlled using either Javascript of by jQuery, I just looked at this solution to this problem, but does it have to be so complicated? Really?


问:
multiple queryset
How I can use querySet interface for two and more models?

for example:

```<code>assortments = get_list_or_404(Assortment, [some_list]) #this is content_types of each models
category = [ assortment.type.model_class() for assortment in assortments ]
all_goods = map(lambda cl: cl.objects.filter(has_shop=True, **kwargs).distinct(), category)
all_goods = reduce(lambda l,l1: l.extend(l1) or l, all_goods, [])
</code>```

but now i cant use querysets methods, like order_by, for example

how else can i get list of objects from different models?

答: You can't. A queryset is an ordered collection of instances of a single model type. There's no such thing as a queryset of multiple models.</p>

Title: multiple queryset

Body:
How I can use querySet interface for two and more models?

for example:

assortments = get_list_or_404(Assortment, [some_list]) #this is content_types of each models
category = [ assortment.type.model_class() for assortment in assortments ]
all_goods = map(lambda cl: cl.objects.filter(has_shop=True, **kwargs).distinct(), category)
all_goods = reduce(lambda l,l1: l.extend(l1) or l, all_goods, [])

but now i cant use querysets methods, like order_by, for example

how else can i get list of objects from different models?


问:
VBA code to clearcontents in excel
I just need  help to clear the contents of the cells (L,M) if the value in Column B is blank (i.e. customer is the same as the previous non-blank row) and if they are duplicates in column L for each customer.

For example:

```<code>       Customer (B)             Sales (L)    Description (M)
row1   James                     Laptop     Laptop sold
row2                             Laptop     Laptop sold
row3                            Iphone      Iphone sold
row4   Brian                    Iphone      Iphone sold
row5                             Mouse      Mouse sold
row6                             Iphone     Iphone sold
</code>```

Desired results:

```<code>       Customer (B)             Sales (L)    Description (M)
row1   James                     Laptop     Laptop sold
row2
row3                            Iphone      Iphone sold
row4   Brian                    Iphone      Iphone sold
row5                             Mouse      Mouse sold
row6
</code>```

答:
What it seems like you want is to clear the range(E:F) where B is blank and range(E:F) is the same as the row above? If this is the case you will need something like this:

```<code>Sub Testing2()
    Dim x
    For Each c In Range(Range("E1"), Range("E" & Rows.count).End(xlUp))
        If Range("B" & c.row).Value <> "" Then
            x = 1
            Do Until Range("B" & c.row + x).Value <> "" And c.row + x < Range("E" & Rows.count).End(xlUp).row
                Range("E" & c.row).Select
                If Range("E" & c.row).Value = Range("E" & c.row + x).Value And Range("F" & c.row).Value = Range("F" & c.row + x).Value Then
                    Range("E" & c.row + x & ":F" & c.row + x).ClearContents
                End If
                If c.row + x >= Range("E" & Rows.count).End(xlUp).row Then
                    Exit Do
                End If
                x = x + 1
            Loop
        End If
        If Range("B" & c.row).Value = "" Then
            x = 1
            Do Until Range("B" & c.row + x).Value <> "" And c.row + x < Range("E" & Rows.count).End(xlUp).row
                Range("E" & c.row).Select
                If Range("E" & c.row).Value = Range("E" & c.row + x).Value And Range("F" & c.row).Value = Range("F" & c.row + x).Value Then
                    Range("E" & c.row + x & ":F" & c.row + x).ClearContents
                End If
                If c.row + x >= Range("E" & Rows.count).End(xlUp).row Then
                    Exit Do
                End If
                x = x + 1
            Loop
        End If
    Next
End Sub
</code>```

This will start at the top and work it's way down looking for duplicates for each person.

Or you could delete the row with something like this:

```<code>Sub Testing2()
    Dim x
    For Each c In Range(Range("E1"), Range("E" & Rows.count).End(xlUp))
        If Range("B" & c.row).Value <> "" Then
            x = 1
            Do Until Range("B" & c.row + x).Value <> ""
                If Range("E" & c.row).Value = Range("E" & c.row + x).Value And Range("F" & c.row).Value = Range("F" & c.row + x).Value Then
                    Range("A" & c.row + x).Select
                    ActiveCell.Offset(0, 0).Rows("1:1").EntireRow.Select
                    Selection.Delete shift:=xlUp
                End If
                x = x + 1
            Loop
        End If
    Next
End Sub
</code>```

Title: VBA code to clearcontents in excel

Body:
I just need  help to clear the contents of the cells (L,M) if the value in Column B is blank (i.e. customer is the same as the previous non-blank row) and if they are duplicates in column L for each customer.

For example:

       Customer (B)             Sales (L)    Description (M)
row1   James                     Laptop     Laptop sold
row2                             Laptop     Laptop sold
row3                            Iphone      Iphone sold
row4   Brian                    Iphone      Iphone sold
row5                             Mouse      Mouse sold
row6                             Iphone     Iphone sold

Desired results:

       Customer (B)             Sales (L)    Description (M)
row1   James                     Laptop     Laptop sold
row2
row3                            Iphone      Iphone sold
row4   Brian                    Iphone      Iphone sold
row5                             Mouse      Mouse sold
row6

Body:
What it seems like you want is to clear the range(E:F) where B is blank and range(E:F) is the same as the row above? If this is the case you will need something like this:

Sub Testing2()
    Dim x
    For Each c In Range(Range("E1"), Range("E" & Rows.count).End(xlUp))
        If Range("B" & c.row).Value <> "" Then
            x = 1
            Do Until Range("B" & c.row + x).Value <> "" And c.row + x < Range("E" & Rows.count).End(xlUp).row
                Range("E" & c.row).Select
                If Range("E" & c.row).Value = Range("E" & c.row + x).Value And Range("F" & c.row).Value = Range("F" & c.row + x).Value Then
                    Range("E" & c.row + x & ":F" & c.row + x).ClearContents
                End If
                If c.row + x >= Range("E" & Rows.count).End(xlUp).row Then
                    Exit Do
                End If
                x = x + 1
            Loop
        End If
        If Range("B" & c.row).Value = "" Then
            x = 1
            Do Until Range("B" & c.row + x).Value <> "" And c.row + x < Range("E" & Rows.count).End(xlUp).row
                Range("E" & c.row).Select
                If Range("E" & c.row).Value = Range("E" & c.row + x).Value And Range("F" & c.row).Value = Range("F" & c.row + x).Value Then
                    Range("E" & c.row + x & ":F" & c.row + x).ClearContents
                End If
                If c.row + x >= Range("E" & Rows.count).End(xlUp).row Then
                    Exit Do
                End If
                x = x + 1
            Loop
        End If
    Next
End Sub

This will start at the top and work it's way down looking for duplicates for each person.

Or you could delete the row with something like this:

Sub Testing2()
    Dim x
    For Each c In Range(Range("E1"), Range("E" & Rows.count).End(xlUp))
        If Range("B" & c.row).Value <> "" Then
            x = 1
            Do Until Range("B" & c.row + x).Value <> ""
                If Range("E" & c.row).Value = Range("E" & c.row + x).Value And Range("F" & c.row).Value = Range("F" & c.row + x).Value Then
                    Range("A" & c.row + x).Select
                    ActiveCell.Offset(0, 0).Rows("1:1").EntireRow.Select
                    Selection.Delete shift:=xlUp
                End If
                x = x + 1
            Loop
        End If
    Next
End Sub


问:
matching occurrence of opposite number in a list python
I have a list such has

```<code>results = [100, 100, -100, 100, -100, -100]
</code>```

I would like to figure out the first occurrence of the opposite number. so first 100 would be match with the first -100, the second 100 would be match with the second -100.

I would like to have position as output such has:

```<code>[0, 2], [1, 4], [3, 5]
</code>```

i.e : [0,2] represent the results[0] and  results[2]  where first occurrence of 100 is match with the first occurrence of -100

edit : you can assume there will always be the same amount of positive / negative and that the list will only contain 1 number

any help would be appricated

答:
For your simple case where the list only contains 2 integers (x and -x), you could simply zip() together the indexes:

```<code>indexes = [[],[]]
for i,x in enumerate(results):
    indexes[0].append(i) if x > 0 else indexes[1].append(i)
list(zip(*indexes))
</code>```

Example:

```<code>>>> results = [100, 100, -100, 100, -100, -100]
>>> indexes = [[],[]]
>>> for i,x in enumerate(results): indexes[0].append(i) if x > 0 else indexes[1].append(i)
...
>>> list(zip(*indexes))
[(0, 2), (1, 4), (3, 5)]
</code>```

Note for small inputs 2 separate list comprehensions (e.g. [i for i,x in enumerate(results) if x > 0] may be faster than appending in a for loop.

Body:
I have a list such has

results = [100, 100, -100, 100, -100, -100]

I would like to figure out the first occurrence of the opposite number. so first 100 would be match with the first -100, the second 100 would be match with the second -100.

I would like to have position as output such has:

[0, 2], [1, 4], [3, 5]

i.e : [0,2] represent the results[0] and  results[2]  where first occurrence of 100 is match with the first occurrence of -100

edit : you can assume there will always be the same amount of positive / negative and that the list will only contain 1 number

any help would be appricated

Body:
For your simple case where the list only contains 2 integers (x and -x), you could simply zip() together the indexes:

indexes = [[],[]]
for i,x in enumerate(results):
    indexes[0].append(i) if x > 0 else indexes[1].append(i)
list(zip(*indexes))

Example:

>>> results = [100, 100, -100, 100, -100, -100]
>>> indexes = [[],[]]
>>> for i,x in enumerate(results): indexes[0].append(i) if x > 0 else indexes[1].append(i)
...
>>> list(zip(*indexes))
[(0, 2), (1, 4), (3, 5)]

Note for small inputs 2 separate list comprehensions (e.g. [i for i,x in enumerate(results) if x > 0] may be faster than appending in a for loop.


问:
How to get the valid part of a regex match
I want to test if a user string is "ok so far", in that it might not be valid as a whole but it is a subset of a valid one.

I have a regex say ^[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]$
such that "1234-1234-5678-5678" is valid

"1234-12" or even "1"  does not match pattern but its a valid subset of a valid format, in other words the input is ok so far.

is there a neat way of doing this without making many many regexes,    its friday.

答:
Not sure if I understood well your problem, but I think you want to have something like this:

```<code>^([0-9]{4}-){1,3}[0-9]{1,4}$
</code>```

Working demo

This will match set of 4 digits and can have the last set from 1 to 4 digits

You can also shorten your regex with:

```<code>^(\d{4}-){1,3}\d{1,4}$
</code>```

Body:
Not sure if I understood well your problem, but I think you want to have something like this:

^([0-9]{4}-){1,3}[0-9]{1,4}$

Working demo

This will match set of 4 digits and can have the last set from 1 to 4 digits

You can also shorten your regex with:

^(\d{4}-){1,3}\d{1,4}$


问:
Creating a password scrambler
I'm trying to copy a password scrambler from Javascript to C. What it does is take the ASCII character code of the letter, floor it, divide it, and grab a random character out of a given list.

Javascript version:

```<code>function getScrambledPassword(pwd) {
    var cipher = ['k', 's', 'z', 'h', 'x', 'b', 'p', 'j', 'v', 'c', 'g', 'f', 'q', 'n', 't', 'm'];
    var result="";
    if (pwd == null)
        pwd = "";
    pwd = encodeURIComponent(pwd);
    //alert("encoded password: " + pwd);
    for(var i=0;i<pwd.length;i++) {
            var cc = pwd.charCodeAt(i);
        result += cipher[Math.floor(cc/16)] + cipher[cc%16];
    }
    //alert("scrambled password: " + result);
    return result;
}
</code>```

Example of the scrambler being run: https://jsfiddle.net/w5db66va/

What I've done so far:

```<code>#include <stdio.h>
#include <math.h>
#include <string.h>

static char *scramblePassword(char *pwd)
{
    char *cipher[] = {
        "k", "s", "z", "h",
        "x", "b", "p", "j",
        "v", "c", "g", "f",
        "q", "n", "t", "m"
    };

    char *result = "";
    for(int i=0; i < strlen(pwd); i++)
    {
        int cc = (int) pwd[i];
        printf("%d", cc);
        result + cipher[floor(cc/16)] + cipher[cc%16];
    }
    return *result;
}

int main(void)
{
    char *test[] = {"test", "testtwo", "testthree"};
    for (int i=0;i < sizeof(test); i++)
    {
        printf("Original: %s", test[i]);
        printf("Scrambled: %s", scramblePassword(test[i]));
    }
}
</code>```

The issue I'm experiencing is that when I run the c file (after compilation) it will not output anything at all. What am I doing wrong to the point that I cannot get this to run as I'd expect it?

答:
C is not JS.

There are many subtle problems and your program doesn't even compile.

You probably want this:

```<code>#include <stdio.h>
#include <math.h>
#include <string.h>

static char *scramblePassword(char *pwd, char *result)
{
  char cipher[] = {    // you need an array of chars here, not an
                       // array of pointers to char
    'k', 's', 'z', 'h',
    'x', 'b', 'p', 'j',
    'v', 'c', 'g', 'f',
    'q', 'n', 't', 'm'
  };

  size_t i;
  for (i = 0; i < strlen(pwd); i++)
  {
    int cc = (int)pwd[i];
    //printf("%d", cc);
    result[i] = cipher[/*(int)floor*/(cc / 16)] + cipher[cc % 16];
                           // ^ actually you can drop the floor function,
                           // there is no floating point here, so integer
                           // division will do the job
  }

  result[i] = 0;  // this will NUL terminate the string
  return result;
}

int main(void)
{
  char *test[] = { "test", "testtwo", "testthree" };
  for (int i = 0; i < sizeof(test) / sizeof(test[0]); i++)
                    // ^ the number of elements is not sizeof(test)
                    // (that's the number of bytes the array takes in memory
                    // but sizeof(test) / sizeof(test[0])
  {
    char result[100];  // you cannot return arrays in C, you need to provide
                       // the array and pass the pointer to your function
    printf("Original: %s\n", test[i]);
    printf("Scrambled: %s\n", scramblePassword(test[i], result));
  }
}
</code>```

Title: Creating a password scrambler

Body:
I'm trying to copy a password scrambler from Javascript to C. What it does is take the ASCII character code of the letter, floor it, divide it, and grab a random character out of a given list.

Javascript version:

function getScrambledPassword(pwd) {
    var cipher = ['k', 's', 'z', 'h', 'x', 'b', 'p', 'j', 'v', 'c', 'g', 'f', 'q', 'n', 't', 'm'];
    var result="";
    if (pwd == null)
        pwd = "";
    pwd = encodeURIComponent(pwd);
    //alert("encoded password: " + pwd);
    for(var i=0;i<pwd.length;i++) {
            var cc = pwd.charCodeAt(i);
        result += cipher[Math.floor(cc/16)] + cipher[cc%16];
    }
    //alert("scrambled password: " + result);
    return result;
}

Example of the scrambler being run: https://jsfiddle.net/w5db66va/

What I've done so far:

#include <stdio.h>
#include <math.h>
#include <string.h>

static char *scramblePassword(char *pwd)
{
    char *cipher[] = {
        "k", "s", "z", "h",
        "x", "b", "p", "j",
        "v", "c", "g", "f",
        "q", "n", "t", "m"
    };

    char *result = "";
    for(int i=0; i < strlen(pwd); i++)
    {
        int cc = (int) pwd[i];
        printf("%d", cc);
        result + cipher[floor(cc/16)] + cipher[cc%16];
    }
    return *result;
}

int main(void)
{
    char *test[] = {"test", "testtwo", "testthree"};
    for (int i=0;i < sizeof(test); i++)
    {
        printf("Original: %s", test[i]);
        printf("Scrambled: %s", scramblePassword(test[i]));
    }
}

The issue I'm experiencing is that when I run the c file (after compilation) it will not output anything at all. What am I doing wrong to the point that I cannot get this to run as I'd expect it?

Body:
C is not JS.

There are many subtle problems and your program doesn't even compile.

You probably want this:

#include <stdio.h>
#include <math.h>
#include <string.h>

static char *scramblePassword(char *pwd, char *result)
{
  char cipher[] = {    // you need an array of chars here, not an
                       // array of pointers to char
    'k', 's', 'z', 'h',
    'x', 'b', 'p', 'j',
    'v', 'c', 'g', 'f',
    'q', 'n', 't', 'm'
  };

  size_t i;
  for (i = 0; i < strlen(pwd); i++)
  {
    int cc = (int)pwd[i];
    //printf("%d", cc);
    result[i] = cipher[/*(int)floor*/(cc / 16)] + cipher[cc % 16];
                           // ^ actually you can drop the floor function,
                           // there is no floating point here, so integer
                           // division will do the job
  }

  result[i] = 0;  // this will NUL terminate the string
  return result;
}

int main(void)
{
  char *test[] = { "test", "testtwo", "testthree" };
  for (int i = 0; i < sizeof(test) / sizeof(test[0]); i++)
                    // ^ the number of elements is not sizeof(test)
                    // (that's the number of bytes the array takes in memory
                    // but sizeof(test) / sizeof(test[0])
  {
    char result[100];  // you cannot return arrays in C, you need to provide
                       // the array and pass the pointer to your function
    printf("Original: %s\n", test[i]);
    printf("Scrambled: %s\n", scramblePassword(test[i], result));
  }
}


Title: How to get the valid part of a regex match

Body:
I want to test if a user string is "ok so far", in that it might not be valid as a whole but it is a subset of a valid one.

I have a regex say ^[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]$
such that "1234-1234-5678-5678" is valid

"1234-12" or even "1"  does not match pattern but its a valid subset of a valid format, in other words the input is ok so far.

is there a neat way of doing this without making many many regexes,    its friday.

Body:
For your case this will check as one types:

/^(\d(\d(\d(\d(-(\d(\d(\d(\d(-(\d(\d(\d(\d(-(\d)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?$/


问:
Django app: best place for a routine on enable app
I have a project in django 1.10 that has some apps. This project will be used by several organizations, and depends on each of them which apps will be enabled. Where is the best place in an app to include a function that has to be run only when the app is enabled? It needs to create some (main app) objects in the db, as a proper configuration for the app.
Reading the docs seems that AppConfig.ready() is the best place. Is it?</p>

答: Look at django-admin group permissions. You can use django-admin permissions ideas</p>


问:
How to change the files in my original commit
Background: I'm trying to remove all bin, obj, and packages folders, and all files with the pattern *.suo, *.user and _.ReSharper.* from my history.

I first checked out master and ran

```<code>git rebase -i --root $tip
</code>```

then in the edit window I changed the first commit from pick to edit and hit Esc + :wp.

Then I added a .gitignore files with

```<code>*.suo
*.user
_ReSharper.*
bin/
obj/
packages/
</code>```

Then, I did a git log to check that my first commit was the only one in the log. Good so far.

Then, I went to Amend Last Commit using Tortoise and it said "no files were changed or added since your last commit." I expected to see all the files that were in my first commit. Why don't I see them?

答: If the files were already committed on previous revisions, just adding the files to .gitignore won't change anything. That is telling git to ignore those files if they show up as "new" files. Files already committed, git will continue tracking them and reporting if they change. If you want to get rid of them on previous revisions, you will either have to amend those revisions or pull the big guns with git filter-branch. https://git-scm.com/docs/git-filter-branch

Body:
Background: I'm trying to remove all bin, obj, and packages folders, and all files with the pattern *.suo, *.user and _.ReSharper.* from my history.

I first checked out master and ran

git rebase -i --root $tip

then in the edit window I changed the first commit from pick to edit and hit Esc + :wp.

Then I added a .gitignore files with

*.suo
*.user
_ReSharper.*
bin/
obj/
packages/

Then, I did a git log to check that my first commit was the only one in the log. Good so far.

Then, I went to Amend Last Commit using Tortoise and it said "no files were changed or added since your last commit." I expected to see all the files that were in my first commit. Why don't I see them?


问:
Sraping with Beautifulsoup-Python
I am trying to scrape some data from the link: http://www.airlinequality.com/airline-reviews/vietjetair/?sortby=post_date%3ADesc&pagesize=100

For example I am trying with BeautifulSoup to extract the name of each reviewer but it doesn't work. I have tried before to use BeautifulSoup with other website and it worked perfectly! I don't know what is happening. Can you help me. The code is the following:

```<code>from bs4 import BeautifulSoup
import os
import urllib.request

file1 = open(os.path.expanduser(r"~/Desktop/Skytrax Reviews1.csv"), "wb")

file1.write(b"Reviewer" + b"\n")

WebSites = ["http://www.airlinequality.com/airline-reviews/vietjetair/?sortby=post_date%3ADesc&pagesize=100"]

# looping through each site until it hits a break. I will create a loop. It is not ready yet
for theurl in WebSites:
    thepage = urllib.request.urlopen(theurl)
    print(thepage)
    soup = BeautifulSoup(thepage,'lxml')
    print(soup)    #<-------This is the main problem

#Maybe it is not correct too but the main problem is at the above lines
    for Reviewer in soup.findAll(attrs={"class": "text_sub_header userStatusWrapper"}).text:
        print(Reviewer)

        Record1 = Reviewer
        file1.write(bytes(Record1, encoding="ascii", errors='ignore') + b"\n")

file1.close()
</code>```

答:
The site isn't returning what you see on the browser, try:

```<code>wget -qO- http://www.airlinequality.com/airline-reviews/vietjetair/?sortby=post_date%3ADesc&pagesize=100
</code>```

or try changing the user agent of the request.

ContentLicense: CC BY-SA 4.0

Title: Sraping with Beautifulsoup-Python

Body:
I am trying to scrape some data from the link: http://www.airlinequality.com/airline-reviews/vietjetair/?sortby=post_date%3ADesc&pagesize=100

For example I am trying with BeautifulSoup to extract the name of each reviewer but it doesn't work. I have tried before to use BeautifulSoup with other website and it worked perfectly! I don't know what is happening. Can you help me. The code is the following:

from bs4 import BeautifulSoup
import os
import urllib.request

file1 = open(os.path.expanduser(r"~/Desktop/Skytrax Reviews1.csv"), "wb")

file1.write(b"Reviewer" + b"\n")

WebSites = ["http://www.airlinequality.com/airline-reviews/vietjetair/?sortby=post_date%3ADesc&pagesize=100"]

# looping through each site until it hits a break. I will create a loop. It is not ready yet
for theurl in WebSites:
    thepage = urllib.request.urlopen(theurl)
    print(thepage)
    soup = BeautifulSoup(thepage,'lxml')
    print(soup)    #<-------This is the main problem

#Maybe it is not correct too but the main problem is at the above lines
    for Reviewer in soup.findAll(attrs={"class": "text_sub_header userStatusWrapper"}).text:
        print(Reviewer)

        Record1 = Reviewer
        file1.write(bytes(Record1, encoding="ascii", errors='ignore') + b"\n")

file1.close()

Body:
The site isn't returning what you see on the browser, try:

wget -qO- http://www.airlinequality.com/airline-reviews/vietjetair/?sortby=post_date%3ADesc&pagesize=100

or try changing the user agent of the request.


问:
SQL Case Statement - how to do it
I have the below statement which works nicely in Tableau.

However, I'd like to turn this into SQL and save all the results into a temporary column name.

Does anyone know how I might do this?

Essentially, the below removes the .com/.net etc... from the domain name.

I then have another script that removes the subdomain (everything from the first . to the left of the resulting value).

If anyone can help me with these, that would be incredible as I'm not sure how to do this in SQL

```<code>IF CONTAINS([domain], ".co.uk") then LEFT([domain],LEN([domain])-6)
elseif  CONTAINS([domain], ".com") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".net") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".org") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".biz") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".edu") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".ac") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".gov") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".biz") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".co") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".ca") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".io") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".in") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".it") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".uk") then LEFT([domain],LEN([domain])- 3)
elseif  CONTAINS([domain], ".ru") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".ie") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".tv") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".info") then LEFT([domain],LEN([domain])-5)
elseif  CONTAINS([domain], ".fr") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".es") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".pl") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".is") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".hu") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".xxx") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".nl") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".ro") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".xyz") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".no") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".eu") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".me") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".cz") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".fi") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".nl") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".al") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".am") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".af") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".st") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".cn") then LEFT([domain],LEN([domain])-3)
else [domain]
end
</code>```

答:
You can use Regular expression as below</p>

```<code>select case when v like '%.[a-z][a-z][a-z]' then left(v, len(v)-4)
            when v like '%.[a-z][a-z].[a-z][a-z]' then left(v, len(v)-6)
            when v like '%.[a-z][a-z]' then left(v, len(v)-3)  end from #yourTable
</code>```

Title: SQL Case Statement - how to do it

Body:
I have the below statement which works nicely in Tableau.

However, I'd like to turn this into SQL and save all the results into a temporary column name.

Does anyone know how I might do this?

Essentially, the below removes the .com/.net etc... from the domain name.

I then have another script that removes the subdomain (everything from the first . to the left of the resulting value).

If anyone can help me with these, that would be incredible as I'm not sure how to do this in SQL

IF CONTAINS([domain], ".co.uk") then LEFT([domain],LEN([domain])-6)
elseif  CONTAINS([domain], ".com") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".net") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".org") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".biz") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".edu") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".ac") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".gov") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".biz") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".co") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".ca") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".io") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".in") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".it") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".uk") then LEFT([domain],LEN([domain])- 3)
elseif  CONTAINS([domain], ".ru") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".ie") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".tv") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".info") then LEFT([domain],LEN([domain])-5)
elseif  CONTAINS([domain], ".fr") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".es") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".pl") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".is") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".hu") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".xxx") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".nl") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".ro") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".xyz") then LEFT([domain],LEN([domain])-4)
elseif  CONTAINS([domain], ".no") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".eu") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".me") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".cz") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".fi") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".nl") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".al") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".am") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".af") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".st") then LEFT([domain],LEN([domain])-3)
elseif  CONTAINS([domain], ".cn") then LEFT([domain],LEN([domain])-3)
else [domain]
end

Body:
You can use Regular expression as below

select case when v like '%.[a-z][a-z][a-z]' then left(v, len(v)-4)
            when v like '%.[a-z][a-z].[a-z][a-z]' then left(v, len(v)-6)
            when v like '%.[a-z][a-z]' then left(v, len(v)-3)  end from #yourTable


问:
Problem working with the NetworkInterface.Name
I am using following code to detect the name of the Network Interface Card on my PC. I am using a USB Modem.

```<code>public class DetectNIC
{
    public string ReturnNIC()
    {
        List<NetworkInterface> Interfaces = new List<NetworkInterface>();
        foreach (var nic in NetworkInterface.GetAllNetworkInterfaces())
        {
            if (nic.OperationalStatus == OperationalStatus.Up)
            {
                Interfaces.Add(nic);
            }
        }

        NetworkInterface result = null;
        foreach (NetworkInterface nic in Interfaces)
        {
            if (result == null)
            {
                result = nic;
            }
            else
            {
                if (nic.GetIPProperties().GetIPv4Properties() != null)
                {
                    if (nic.GetIPProperties().GetIPv4Properties().Index < result.GetIPProperties().GetIPv4Properties().Index)
                        result = nic;
                }
            }
        }
        return result.Name.ToString();
    }
}
</code>```

I am passing the result to the below given class to calculate the bytes consumption during internet traffic:

```<code>public class ByteCounter
{
    public double GetNetworkUtilization(string networkCard)
    {
        const int numberOfIterations = 10;

        PerformanceCounter bandwidthCounter =
            new PerformanceCounter("Network Interface", "Current Bandwidth", networkCard);

        float bandwidth = bandwidthCounter.NextValue();

        PerformanceCounter dataSentCounter =
            new PerformanceCounter("Network Interface", "Bytes Sent/sec", networkCard);

        PerformanceCounter dataReceivedCounter =
            new PerformanceCounter("Network Interface", "Bytes Received/sec", networkCard);

        float sendSum = 0;
        float receiveSum = 0;

        for (int index = 0; index < numberOfIterations; index++)
        {
            sendSum += dataSentCounter.NextValue();
            receiveSum += dataReceivedCounter.NextValue();
        }

        float dataSent = sendSum;
        float dataReceived = receiveSum;

        double utilization = (8 * (dataSent + dataReceived)) / (bandwidth * numberOfIterations) * 100;
        return utilization;
    }
}
</code>```

The first code works fine. It detects my modem as "MBlaze USB Modem", but when the control reaches to the second code with following line:

```<code>float bandwidth = bandwidthCounter.NextValue();
</code>```

it displays error:

```<code>System.InvalidOperationException was unhandled
  Message="Instance 'MBlaze USB Modem' does not exist in the specified Category."
  Source="System"
  StackTrace:
       at System.Diagnostics.CounterDefinitionSample.GetInstanceValue(String instanceName)
       at System.Diagnostics.PerformanceCounter.NextSample()
       at System.Diagnostics.PerformanceCounter.NextValue()
       at LogTraffic.ByteCounter.GetNetworkUtilization(String networkCard) in F:\Projects\LogTraffic\bytecounter.cs:line 15
       at LogTraffic.MainForm.MainForm_Load(Object sender, EventArgs e) in F:\Projects\LogTraffic\MainForm.cs:line 24
       at System.Windows.Forms.Form.OnLoad(EventArgs e)
       at System.Windows.Forms.Form.OnCreateControl()
       at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
       at System.Windows.Forms.Control.CreateControl()
       at System.Windows.Forms.Control.WmShowWindow(Message& m)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
       at System.Windows.Forms.ContainerControl.WndProc(Message& m)
       at System.Windows.Forms.Form.WmShowWindow(Message& m)
       at System.Windows.Forms.Form.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.SafeNativeMethods.ShowWindow(HandleRef hWnd, Int32 nCmdShow)
       at System.Windows.Forms.Control.SetVisibleCore(Boolean value)
       at System.Windows.Forms.Form.SetVisibleCore(Boolean value)
       at System.Windows.Forms.Control.set_Visible(Boolean value)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at LogTraffic.Program.Main() in F:\Projects\LogTraffic\Program.cs:line 18
       at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException:
</code>```

What is the problem?

I won't forget to give the credit to the authors of both the code.

First code credit: Keyvan Nayyeri

Second code credit: entens for his answer here.

答:
Your problem is that the instance name is a bit different from the name you get from the ReturnNIC and you are using netwrokCard in all places. I have modified the code a bit and now it works for me:

```<code>    public static double GetNetworkUtilization(string networkCard)
    {
        const int numberOfIterations = 10;
        PerformanceCounterCategory category = null;
        foreach (var performanceCounterCategory in PerformanceCounterCategory.GetCategories())
        {
            if (performanceCounterCategory.CategoryName == "Network Interface")
            {
                category = performanceCounterCategory;
                break;
            }
        }

        string instanceName = category.GetInstanceNames().Where(x=>x.Contains(networkCard)).FirstOrDefault();

        PerformanceCounter bandwidthCounter =
            new PerformanceCounter("Network Interface", "Current Bandwidth", instanceName);

        float bandwidth = bandwidthCounter.NextValue();

        PerformanceCounter dataSentCounter =
            new PerformanceCounter("Network Interface", "Bytes Sent/sec", instanceName);

        PerformanceCounter dataReceivedCounter =
            new PerformanceCounter("Network Interface", "Bytes Received/sec", instanceName);

        float sendSum = 0;
        float receiveSum = 0;

        for (int index = 0; index < numberOfIterations; index++)
        {
            sendSum += dataSentCounter.NextValue();
            receiveSum += dataReceivedCounter.NextValue();
        }

        float dataSent = sendSum;
        float dataReceived = receiveSum;

        double utilization = (8 * (dataSent + dataReceived)) / (bandwidth * numberOfIterations) * 100;
        return utilization;
    }
</code>```

Body:
I am using following code to detect the name of the Network Interface Card on my PC. I am using a USB Modem.

public class DetectNIC
{
    public string ReturnNIC()
    {
        List<NetworkInterface> Interfaces = new List<NetworkInterface>();
        foreach (var nic in NetworkInterface.GetAllNetworkInterfaces())
        {
            if (nic.OperationalStatus == OperationalStatus.Up)
            {
                Interfaces.Add(nic);
            }
        }

        NetworkInterface result = null;
        foreach (NetworkInterface nic in Interfaces)
        {
            if (result == null)
            {
                result = nic;
            }
            else
            {
                if (nic.GetIPProperties().GetIPv4Properties() != null)
                {
                    if (nic.GetIPProperties().GetIPv4Properties().Index < result.GetIPProperties().GetIPv4Properties().Index)
                        result = nic;
                }
            }
        }
        return result.Name.ToString();
    }
}

I am passing the result to the below given class to calculate the bytes consumption during internet traffic:

public class ByteCounter
{
    public double GetNetworkUtilization(string networkCard)
    {
        const int numberOfIterations = 10;

        PerformanceCounter bandwidthCounter =
            new PerformanceCounter("Network Interface", "Current Bandwidth", networkCard);

        float bandwidth = bandwidthCounter.NextValue();

        PerformanceCounter dataSentCounter =
            new PerformanceCounter("Network Interface", "Bytes Sent/sec", networkCard);

        PerformanceCounter dataReceivedCounter =
            new PerformanceCounter("Network Interface", "Bytes Received/sec", networkCard);

        float sendSum = 0;
        float receiveSum = 0;

        for (int index = 0; index < numberOfIterations; index++)
        {
            sendSum += dataSentCounter.NextValue();
            receiveSum += dataReceivedCounter.NextValue();
        }

        float dataSent = sendSum;
        float dataReceived = receiveSum;

        double utilization = (8 * (dataSent + dataReceived)) / (bandwidth * numberOfIterations) * 100;
        return utilization;
    }
}

The first code works fine. It detects my modem as "MBlaze USB Modem", but when the control reaches to the second code with following line:

float bandwidth = bandwidthCounter.NextValue();

it displays error:

System.InvalidOperationException was unhandled
  Message="Instance 'MBlaze USB Modem' does not exist in the specified Category."
  Source="System"
  StackTrace:
       at System.Diagnostics.CounterDefinitionSample.GetInstanceValue(String instanceName)
       at System.Diagnostics.PerformanceCounter.NextSample()
       at System.Diagnostics.PerformanceCounter.NextValue()
       at LogTraffic.ByteCounter.GetNetworkUtilization(String networkCard) in F:\Projects\LogTraffic\bytecounter.cs:line 15
       at LogTraffic.MainForm.MainForm_Load(Object sender, EventArgs e) in F:\Projects\LogTraffic\MainForm.cs:line 24
       at System.Windows.Forms.Form.OnLoad(EventArgs e)
       at System.Windows.Forms.Form.OnCreateControl()
       at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
       at System.Windows.Forms.Control.CreateControl()
       at System.Windows.Forms.Control.WmShowWindow(Message& m)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
       at System.Windows.Forms.ContainerControl.WndProc(Message& m)
       at System.Windows.Forms.Form.WmShowWindow(Message& m)
       at System.Windows.Forms.Form.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.SafeNativeMethods.ShowWindow(HandleRef hWnd, Int32 nCmdShow)
       at System.Windows.Forms.Control.SetVisibleCore(Boolean value)
       at System.Windows.Forms.Form.SetVisibleCore(Boolean value)
       at System.Windows.Forms.Control.set_Visible(Boolean value)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(Form mainForm)
       at LogTraffic.Program.Main() in F:\Projects\LogTraffic\Program.cs:line 18
       at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException:

What is the problem?

I won't forget to give the credit to the authors of both the code.

First code credit: Keyvan Nayyeri

Second code credit: entens for his answer here.

Body:
Your problem is that the instance name is a bit different from the name you get from the ReturnNIC and you are using netwrokCard in all places. I have modified the code a bit and now it works for me:

    public static double GetNetworkUtilization(string networkCard)
    {
        const int numberOfIterations = 10;
        PerformanceCounterCategory category = null;
        foreach (var performanceCounterCategory in PerformanceCounterCategory.GetCategories())
        {
            if (performanceCounterCategory.CategoryName == "Network Interface")
            {
                category = performanceCounterCategory;
                break;
            }
        }

        string instanceName = category.GetInstanceNames().Where(x=>x.Contains(networkCard)).FirstOrDefault();

        PerformanceCounter bandwidthCounter =
            new PerformanceCounter("Network Interface", "Current Bandwidth", instanceName);

        float bandwidth = bandwidthCounter.NextValue();

        PerformanceCounter dataSentCounter =
            new PerformanceCounter("Network Interface", "Bytes Sent/sec", instanceName);

        PerformanceCounter dataReceivedCounter =
            new PerformanceCounter("Network Interface", "Bytes Received/sec", instanceName);

        float sendSum = 0;
        float receiveSum = 0;

        for (int index = 0; index < numberOfIterations; index++)
        {
            sendSum += dataSentCounter.NextValue();
            receiveSum += dataReceivedCounter.NextValue();
        }

        float dataSent = sendSum;
        float dataReceived = receiveSum;

        double utilization = (8 * (dataSent + dataReceived)) / (bandwidth * numberOfIterations) * 100;
        return utilization;
    }


问:
Multiple `.sublime-settings` files for single syntax
For example, I want 2 separate preference files for Markdown syntax.

This will work:

```<code>Markdown.sublime-settings
</code>```

This will not:

```<code>Markdown_Additional_Settings.sublime-settings
</code>```

When I open some .md-file, I want settings from both these preference files to be applied. In other words, these settings should me merged.

Is there some trick to make it work?

答: You can just create the settings file Markdown.sublime-settings twice in different subfolders of Packages (Preferences > Browse Packages...). Usually you would create your main settings inside the User folder, because it has the highest precedence. So you create the files Packages/MyAdditionalSettings/Markdown-sublime-settings and Packages/User/Markdown.sublime-settings or Packages/MyMainSettings/Markdown.sublime-settings. If you use the same setting in both files the one in the User folder or in the folder, which is the last in the lexical order, will be used.

Body:
For example, I want 2 separate preference files for Markdown syntax.

This will work:

Markdown.sublime-settings

This will not:

Markdown_Additional_Settings.sublime-settings

When I open some .md-file, I want settings from both these preference files to be applied. In other words, these settings should me merged.

Is there some trick to make it work?


问:
Displaying local storage in page: Jquery
I am able to add to local storage and remove items but it wont display the added item in my html. Once something is added to local storage it should display on a favorites page, then when removed it should be removed from the favorites page. It is the viewing favorites section of the code that doesn't seem to be working.

//Add Favorites
$('.favoritesbtn').click(function() {
  var storedbar = JSON.parse(localStorage.getItem('storedBar'));
  var favArray = [];
  favArray.push(storedbar.id, storedbar.barname, storedbar.address, storedbar.description, storedbar.image);
  localStorage.setItem('favorites', JSON.stringify(favArray));
  console.log(localStorage.getItem('favorites'));

});

//viewing favorites

var favBar = JSON.parse(localStorage.getItem('favorites'));
console.log(favBar);

function displayPageContent(object) {
  if (object) {
    $('#bar-info h2').html(object.barname);
    $('#bar-info h5').html(object.address);
    $('#bar-info p').html(object.description);
    $('#bar-info img').html(object.image);
  }
}
displayPageContent(favBar);

//Removing favorites
$('.removebtn').click(function() {
  console.log('delete');
  localStorage.removeItem('favorites');
  console.log(localStorage.getItem('favorites'));
});```

答:
You need to call displayPageContent(localStorage.getItem('favorites')); every time you make change to 'favorites'.

I don't have your other code like html, if this does not work, post your other code. and make sure check your console log to make sure the data is correct.

//Add Favorites
$('.favoritesbtn').click(function() {
  var storedbar = JSON.parse(localStorage.getItem('storedBar'));
  var favArray = [];
  favArray.push(storedbar.id, storedbar.barname, storedbar.address, storedbar.description, storedbar.image);
  localStorage.setItem('favorites', JSON.stringify(favArray));
  console.log(localStorage.getItem('favorites'));
  //update view
  displayPageContent(localStorage.getItem('favorites'));
});

//viewing favorites

var favBar = JSON.parse(localStorage.getItem('favorites'));
console.log(favBar);

function displayPageContent(object) {
  if (object) {
    $('#bar-info h2').html(object.barname);
    $('#bar-info h5').html(object.address);
    $('#bar-info p').html(object.description);
    $('#bar-info img').html(object.image);
  }
}
displayPageContent(favBar);

//Removing favorites
$('.removebtn').click(function() {
  console.log('delete');
  localStorage.removeItem('favorites');
  console.log(localStorage.getItem('favorites'));
  //update view
  displayPageContent(localStorage.getItem('favorites'));
});```


问:
plot bar by x and y coordinates
I want to plot a hanging rootogram in python. I know there is already a question on this here: How to plot a hanging rootogram in python?
but my approach is a bit different.

In my pandas dataframe the data is organized like this:

x: is the x axis point, here 1,2,3,...

height : is the height of the bar

y: starting point for plot

line: the bordering line for each bar

What I want is a bar for each point x, that starts at y and is of height . The end of the bar is then at line

this is what I got so far:

```<code>fig, ax = plt.subplots()
rects = ax.bar(df['x'], df['height'] - df['y'], 1)
ax.plot(df['x'], df['line'], color='r')
ax.set_ylim([-10,15])
</code>```

what I want is something like this:

答:
The solution in this case is much easier than in the linked question. You just need to use the bottom argument of plt.bar.

```<code>import numpy as np; np.random.seed(0)
import matplotlib.pyplot as plt

x = np.arange(12)
line = np.sqrt(np.sinc(np.sqrt(x/2.))**2)*2+0.35
y = np.random.rand(12)-1
#height is redundant
height = line-y

plt.bar(x, height, bottom=y, edgecolor="k" )
plt.plot(x,line, color="#dd0000")
plt.plot(x,y, marker="o", ls="", color="k")
plt.ylim(-2,3)
plt.show()
</code>```

Title: plot bar by x and y coordinates

Body:
I want to plot a hanging rootogram in python. I know there is already a question on this here: How to plot a hanging rootogram in python?
but my approach is a bit different.

In my pandas dataframe the data is organized like this:

x: is the x axis point, here 1,2,3,...

height : is the height of the bar

y: starting point for plot

line: the bordering line for each bar

What I want is a bar for each point x, that starts at y and is of height . The end of the bar is then at line

this is what I got so far:

fig, ax = plt.subplots()
rects = ax.bar(df['x'], df['height'] - df['y'], 1)
ax.plot(df['x'], df['line'], color='r')
ax.set_ylim([-10,15])

what I want is something like this:

Body:
The solution in this case is much easier than in the linked question. You just need to use the bottom argument of plt.bar.

import numpy as np; np.random.seed(0)
import matplotlib.pyplot as plt

x = np.arange(12)
line = np.sqrt(np.sinc(np.sqrt(x/2.))**2)*2+0.35
y = np.random.rand(12)-1
#height is redundant
height = line-y

plt.bar(x, height, bottom=y, edgecolor="k" )
plt.plot(x,line, color="#dd0000")
plt.plot(x,y, marker="o", ls="", color="k")
plt.ylim(-2,3)
plt.show()


问:
library integration limit in IOS / Apple
I haeard from some android developer that there is a library limit in android provided by google so:

Is there such scenarios exist in apple or how any library integration limit in a single app ios/apple. ??

How many libraries can we integrate in single project?

答:
There is no actual numeric limit, but adding an embedded dynamic library will add to your launch time. There is a requirement for an app to launch within 20 seconds.

Here is a github discussion from 2015 of the problem with many dylibs and slow launch times:
https://github.com/artsy/eigen/issues/586

Apple did a WWDC 16 session about launch times and said the following:
https://developer.apple.com/videos/play/wwdc2016/406/

If you take longer than 20 seconds, the OS will kill your app, assuming it's going through an infinite loop, and we've all had that experience.

...

So dylib loading, the big thing to understand about dylib loading and the slowdown that you'll see from it, is that embedded dylibs can be expensive.

So Nick said an average app can be 100 to 400 dylibs. But OS dylibs are fast because when we build the OS, we have ways of pre-calculating a lot of that data.

...

So you absolutely can and should use some [dylibs], but it's good to try to target a limited number, we would, I would say off hand, a good target's about a half a dozen.


问:
Angular : When to use "[]" in modules and controllers
I'm starting in Angular and i don't understand when to use or not [] when declaring (if it's called like this) modules and controllers.

So far, i understood that :

angular.module('app.prof', []).config(config); means i declare the module prof

while angular.module('app.prof').config(config); means i call it.

But i always end up having the [] in the controller and not in the module, and when i have two controllers i don't know what to do anymore.

I just want to understand Angular :(

Edit : adding more details

In my Angular project, i use the Fuse theme with a thing called Yeoman (if i understood well) so i never write

答:
The second argument are the dependencies for the module. Since you don't have any dependencies at the moment you have an empty array [].

You add the brackets (dependencies) only when you create a new module. Every time when you simply want to use the same module you shouldn't have brackets. So in the end every module should be declared only once with the []. And every other time should be called without.

Also make sure that files and code is imported in the correct order. Otherwise the module is not yet defined when you try to add controllers to it.

Small example. App module with multiple controllers.

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

angular.module('app').controller('aCtrl', [ function () {} ]);
angular.module('app').controller('bCtrl', [ function () {} ]);

// ...
</code>```

Long story short. If you declare a module, you need the brackets. If you want to use the module you don't add them.

Edit: For your edit, once again, you need to make sure that you define and use everything in correct order.

Following depends on app.prof which means that app.prof declaration needs to be before this row:

```<code>angular.module('fuse', ['app.prof']);
</code>```

This already suggests that module app.prof is declared and you try to add config to it. When app.prof is not declared before you get a similar error as you displayed:

```<code>angular.module('app.prof')
    .config(config);
</code>```

This declares the module app.prof and adds a controller to that module:

```<code>angular.module('app.prof', [])
    .controller('ProfController', ProfController);
</code>```

This declares the app.prof module ands immediately adds some config to it:

```<code>angular.module('app.prof', [])
    .config(config);
</code>```

This adds a controller to an existing module called app.prof:

```<code>angular.module('app.prof')
    .controller('ProfController', ProfController);
</code>```

I think you get the idea...

As for a solution you need to declare these in an order similar to this... Doesn't matter if everything is in one file or you load them in file by file but the module declaration order is important.

```<code>angular.module('app.prof', [])
    .config(config);

angular.module('app.prof')
    .controller('ProfController', ProfController);

angular.module('fuse', ['app.prof']);
</code>```

Controller declaration can probably happen later but anyway you need to pay attention to the ordering. As you said that fuse is the main module you need to declare the app.prof before.

Body:
The second argument are the dependencies for the module. Since you don't have any dependencies at the moment you have an empty array [].

You add the brackets (dependencies) only when you create a new module. Every time when you simply want to use the same module you shouldn't have brackets. So in the end every module should be declared only once with the []. And every other time should be called without.

Also make sure that files and code is imported in the correct order. Otherwise the module is not yet defined when you try to add controllers to it.

Small example. App module with multiple controllers.

angular.module('app', []);

angular.module('app').controller('aCtrl', [ function () {} ]);
angular.module('app').controller('bCtrl', [ function () {} ]);

// ...

Long story short. If you declare a module, you need the brackets. If you want to use the module you don't add them.

Edit: For your edit, once again, you need to make sure that you define and use everything in correct order.

Following depends on app.prof which means that app.prof declaration needs to be before this row:

angular.module('fuse', ['app.prof']);

This already suggests that module app.prof is declared and you try to add config to it. When app.prof is not declared before you get a similar error as you displayed:

angular.module('app.prof')
    .config(config);

This declares the module app.prof and adds a controller to that module:

angular.module('app.prof', [])
    .controller('ProfController', ProfController);

This declares the app.prof module ands immediately adds some config to it:

angular.module('app.prof', [])
    .config(config);

This adds a controller to an existing module called app.prof:

angular.module('app.prof')
    .controller('ProfController', ProfController);

I think you get the idea...

As for a solution you need to declare these in an order similar to this... Doesn't matter if everything is in one file or you load them in file by file but the module declaration order is important.

angular.module('app.prof', [])
    .config(config);

angular.module('app.prof')
    .controller('ProfController', ProfController);

angular.module('fuse', ['app.prof']);

Controller declaration can probably happen later but anyway you need to pay attention to the ordering. As you said that fuse is the main module you need to declare the app.prof before.


问:
Sorting an array with multiple elements
I am making a to-do list in java for a class project. In the jList i display a date and a string that represent a date and what needs to be done on that day. I would also like to be able to sort these events by the dates on them, so the tasks that are due sooner appear first. I know how to sort a list of dates using bubble sort, but I do not know how to apply this to my list because each item contains a date AND a string. This is the code I have so far. Does anyone know how I will be able to sort the dates in order and keep the strings attached to their dates. Thanks. </p>

```<code>public class ToDoListManager {

    final int maxitems = 20;
    int items = 0;
    String[] toDoList = new String[20];
    Date[] Dates = new Date[20];

    String addItem(String toDo, Date date) {
        if (items == maxitems) {
            return ("No more Space");
        } else if (toDo.equalsIgnoreCase("") || (toDo == null) || (date == null)) {
            return ("All fields required");
        } else if (items < maxitems) {
            Dates[items] = date;
            SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-MM-dd");
            toDoList[items] = "On " + dt1.format(date) + " " + toDo;
            items = items + 1;
            return (toDo + " Was Added to the List");
        }
        return null;
    }

    void Order(Date[] dates) {
        Date temp;
        boolean fixed = false;
        while (fixed == false) {
            fixed = true;
            for (int i = 0; i < dates.length - 1; i++) {
                if (dates[i].before(dates[i + 1])) {
                    temp = dates[i + 1];
                    dates[i + 1] = dates[i];
                    dates[i] = temp;
                    fixed = false;
                }
            }

        }
        System.out.println(dates);

    }

    String[] getItems() {
        String[] displayList = new String[items];
        for (int i = 0; i < items; i++) {
            displayList[i] = toDoList[i];

        }

        return displayList;

    }
}
</code>```

答:
You mention JList in the question, thus I assume that is where you want to see the sorted TODOs. Here's one possible way to do that:

JList is backed by a ListModel<E> instance. That is a generic class that can contain a list of instances of E. So a possible way to wire it together is to:

Create a class that represents a an item in the todo list (class ToDo, that has the fields that contain e.g. the date and the toDo text).

Define one or more comparators of the ToDo instances - e.g. one based on date, other on text, whatever you need.

Populate a List (or another collection) with your ToDo instances and sort it using one of your comparators.

Create a ListModel implementation backed by your list and set that to the JList component. The ListModel implementation can be e.g. an extension of AbstractListModel. Also see an example of sorted ListModel implementation.

To display the ToDos in a meaningful way in the List, create a toString() implementation on your ToDo class (JList will call that to get a string representation of your object), or supply your own ListCellRenderer to the JList instance.

If you need to re-sort, make sure your ListModel implementation correctly notifies the JList each time it changes the order.

Title: Sorting an array with multiple elements

Body:
I am making a to-do list in java for a class project. In the jList i display a date and a string that represent a date and what needs to be done on that day. I would also like to be able to sort these events by the dates on them, so the tasks that are due sooner appear first. I know how to sort a list of dates using bubble sort, but I do not know how to apply this to my list because each item contains a date AND a string. This is the code I have so far. Does anyone know how I will be able to sort the dates in order and keep the strings attached to their dates. Thanks.

public class ToDoListManager {

    final int maxitems = 20;
    int items = 0;
    String[] toDoList = new String[20];
    Date[] Dates = new Date[20];

    String addItem(String toDo, Date date) {
        if (items == maxitems) {
            return ("No more Space");
        } else if (toDo.equalsIgnoreCase("") || (toDo == null) || (date == null)) {
            return ("All fields required");
        } else if (items < maxitems) {
            Dates[items] = date;
            SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-MM-dd");
            toDoList[items] = "On " + dt1.format(date) + " " + toDo;
            items = items + 1;
            return (toDo + " Was Added to the List");
        }
        return null;
    }

    void Order(Date[] dates) {
        Date temp;
        boolean fixed = false;
        while (fixed == false) {
            fixed = true;
            for (int i = 0; i < dates.length - 1; i++) {
                if (dates[i].before(dates[i + 1])) {
                    temp = dates[i + 1];
                    dates[i + 1] = dates[i];
                    dates[i] = temp;
                    fixed = false;
                }
            }

        }
        System.out.println(dates);

    }

    String[] getItems() {
        String[] displayList = new String[items];
        for (int i = 0; i < items; i++) {
            displayList[i] = toDoList[i];

        }

        return displayList;

    }
}


问:
Sort a column by clicking on a Button not on the ColumnHeader of a DataGrid c#
I have a DataGrid with HeadersVisibility="None".
I want to create a Button outside of the DataGrid that does exactly the same as if I clicked on the n column of the DataGrid(order the column).

I have tried the following code (myDataGrid is the name of my DataGrid):

```<code>private void button_Click(object sender, RoutedEventArgs e)
{
     DataGridColumn column = myDataGrid.Columns[0];
     DataGridColumnHeader columnHeader = GetColumnHeaderFromColumn(column);
     columnHeader.OnClick();
}
</code>```

but the function DataGridColumnHeader.OnClick() is inaccessible due to its protection level.

I have also looked at the class DataGrid that is in namespace System.Windows.Controls where I have found this :

```<code>public event DataGridSortingEventHandler Sorting;

/// <summary>
/// Protected method which raises the sorting event and does default sort
/// </summary>
/// <param name="eventArgs"></param>
protected virtual void OnSorting(DataGridSortingEventArgs eventArgs)
{
    eventArgs.Handled = false;
    if (Sorting != null)
    {
        Sorting(this, eventArgs);
    }

    if (!eventArgs.Handled)
    {
        DefaultSort(
                eventArgs.Column,
                /* clearExistinSortDescriptions */
                (Keyboard.Modifiers & ModifierKeys.Shift) != ModifierKeys.Shift);
    }
}

/// <summary>
/// Method to perform sorting on datagrid
/// </summary>
/// <param name="sortColumn"></param>
internal void PerformSort(DataGridColumn sortColumn)
{
    Debug.Assert(sortColumn != null, "column should not be null");

    if (!CanUserSortColumns || !sortColumn.CanUserSort)
    {
        return;
    }
    if (CommitAnyEdit())
    {
        PrepareForSort(sortColumn);

        DataGridSortingEventArgs eventArgs = new DataGridSortingEventArgs(sortColumn);
        OnSorting(eventArgs);

        if (Items.NeedsRefresh)
        {
            try
            {
                Items.Refresh();
            }
            catch (InvalidOperationException invalidOperationException)
            {
                Items.SortDescriptions.Clear();
                throw new InvalidOperationException(SR.Get(SRID.DataGrid_ProbableInvalidSortDescription), invalidOperationException);
            }
        }
    }
}
</code>```

But I wasn't able to use that.
Any idea about how can I do that ?

答:
You will have to apply sorting on 'dataView' and rebind it to dataGrid.

```<code>private void SortButton_Click(object sender, System.EventArgs e)
{
   if(order == SORT_ORDER.ASC)
   {
     //Ascending
     this.BindData(SORT_ORDER.DESC);
   }
   else
   {
     //Descending
     this.BindData(SORT_ORDER.ASC);
   }
}

private void BindData(SORT_ORDER order)
{
   //here read data from your datasource, by implementing that logic in 'GetDataSource()' function
    DataView dv = this.GetDataSource().DefaultView;

    if(order == SORT_ORDER.ASC)
    {
        dv.Sort = "Address ASC";
        this.SortLabel.Text = "Current sorting order is ascending";
    }
    else
    {
        dv.Sort = "Address DESC";
        this.SortLabel.Text = "Current sorting order is descending";
    }
    this.dgTest.DataSource = dv;
}
</code>```

Or

If you could use DataGridView it is much easier:

this.myDataGrid.Sort(this.dataGridViewTextBoxColumn1, ListSortDirection.Descending);

Body:
I have a DataGrid with HeadersVisibility="None".
I want to create a Button outside of the DataGrid that does exactly the same as if I clicked on the n column of the DataGrid(order the column).

I have tried the following code (myDataGrid is the name of my DataGrid):

private void button_Click(object sender, RoutedEventArgs e)
{
     DataGridColumn column = myDataGrid.Columns[0];
     DataGridColumnHeader columnHeader = GetColumnHeaderFromColumn(column);
     columnHeader.OnClick();
}

but the function DataGridColumnHeader.OnClick() is inaccessible due to its protection level.

I have also looked at the class DataGrid that is in namespace System.Windows.Controls where I have found this :

public event DataGridSortingEventHandler Sorting;

///
/// Protected method which raises the sorting event and does default sort
///
/// <param name="eventArgs"></param>
protected virtual void OnSorting(DataGridSortingEventArgs eventArgs)
{
    eventArgs.Handled = false;
    if (Sorting != null)
    {
        Sorting(this, eventArgs);
    }

    if (!eventArgs.Handled)
    {
        DefaultSort(
                eventArgs.Column,
                /* clearExistinSortDescriptions */
                (Keyboard.Modifiers & ModifierKeys.Shift) != ModifierKeys.Shift);
    }
}

///
/// Method to perform sorting on datagrid
///
/// <param name="sortColumn"></param>
internal void PerformSort(DataGridColumn sortColumn)
{
    Debug.Assert(sortColumn != null, "column should not be null");

    if (!CanUserSortColumns || !sortColumn.CanUserSort)
    {
        return;
    }
    if (CommitAnyEdit())
    {
        PrepareForSort(sortColumn);

        DataGridSortingEventArgs eventArgs = new DataGridSortingEventArgs(sortColumn);
        OnSorting(eventArgs);

        if (Items.NeedsRefresh)
        {
            try
            {
                Items.Refresh();
            }
            catch (InvalidOperationException invalidOperationException)
            {
                Items.SortDescriptions.Clear();
                throw new InvalidOperationException(SR.Get(SRID.DataGrid_ProbableInvalidSortDescription), invalidOperationException);
            }
        }
    }
}

But I wasn't able to use that.
Any idea about how can I do that ?

Body:
You will have to apply sorting on 'dataView' and rebind it to dataGrid.

private void SortButton_Click(object sender, System.EventArgs e)
{
   if(order == SORT_ORDER.ASC)
   {
     //Ascending
     this.BindData(SORT_ORDER.DESC);
   }
   else
   {
     //Descending
     this.BindData(SORT_ORDER.ASC);
   }
}

private void BindData(SORT_ORDER order)
{
   //here read data from your datasource, by implementing that logic in 'GetDataSource()' function
    DataView dv = this.GetDataSource().DefaultView;

    if(order == SORT_ORDER.ASC)
    {
        dv.Sort = "Address ASC";
        this.SortLabel.Text = "Current sorting order is ascending";
    }
    else
    {
        dv.Sort = "Address DESC";
        this.SortLabel.Text = "Current sorting order is descending";
    }
    this.dgTest.DataSource = dv;
}

Or

If you could use DataGridView it is much easier:

this.myDataGrid.Sort(this.dataGridViewTextBoxColumn1, ListSortDirection.Descending);