问:
Testing a custom Django template filter
I have a custom template filter I created under project/app/templatetags.

I want to add some regression tests for some bugs I just found. How would I go about doing so?

答:
Here's how I do it (extracted from my django-multiforloop):

```<code>from django.test import TestCase
from django.template import Context, Template

class TagTests(TestCase):
    def tag_test(self, template, context, output):
        t = Template('{% load multifor %}'+template)
        c = Context(context)
        self.assertEqual(t.render(c), output)
    def test_for_tag_multi(self):
        template = "{% for x in x_list; y in y_list %}{{ x }}:{{ y }}/{% endfor %}"
        context = {"x_list": ('one', 1, 'carrot'), "y_list": ('two', 2, 'orange')}
        output = u"one:two/1:2/carrot:orange/"
        self.tag_test(template, context, output)
</code>```

This is fairly similar to how tests are laid out in Django's own test suite, but without relying on django's somewhat complicated testing machinery.

Title: Testing a custom Django template filter

Body:
Here's how I do it (extracted from my django-multiforloop):

from django.test import TestCase
from django.template import Context, Template

class TagTests(TestCase):
    def tag_test(self, template, context, output):
        t = Template('{% load multifor %}'+template)
        c = Context(context)
        self.assertEqual(t.render(c), output)
    def test_for_tag_multi(self):
        template = "{% for x in x_list; y in y_list %}{{ x }}:{{ y }}/{% endfor %}"
        context = {"x_list": ('one', 1, 'carrot'), "y_list": ('two', 2, 'orange')}
        output = u"one:two/1:2/carrot:orange/"
        self.tag_test(template, context, output)

This is fairly similar to how tests are laid out in Django's own test suite, but without relying on django's somewhat complicated testing machinery.


来源: stackexchange

问:
What is the point of void operator in JavaScript?
I've seen some people using void operator in their code. I have also seen this in href attributes: javascript:void(0) which doesn't seem any better than javascript:;

So, what is the justification of using the void operator?

答:
The undefined value was not directly accessible in JavaScript until ES1.3.

An operator void <expression> was therefore included to permit access to this value.

It is sometimes useful, particularly when working with the Web API (e.g. event handlers), to ensure that the result of an expression is consistently undefined.

When the undefined property was added to the global object in ES1.3 the utility of void became non-obvious.

Hence your question.

OwnerDisplayName: mkoryak

ContentLicense: CC BY-SA 3.0


问:
EventBus in vue not working
I have a Laravel (5.4) application with some Vue components in it. I would need to make some of those components communicate, so I decided to add an EventBus. The code is the following:

app.js:

```<code>import VueResource from "vue-resource";
import Vue from "vue";
import Menu from "components/src/core/Menu.vue";

import MapWrapper from "./components/MapWrapper.vue";
import PaymentModal from "./components/PaymentModal.vue";

require("../sass/app.scss");

Vue.use(VueResource);

Vue.component("map-wrapper", MapWrapper);
Vue.component("my-menu", Menu);
Vue.component("payment-modal", PaymentModal);

// eslint-disable-next-line
new Vue({
    el: "#app",
});
</code>```

event.js:

```<code>import Vue from "vue";

const EventBus = new Vue();

export default EventBus;
</code>```

component that should trigger the event:

```<code><template>
    <div style="height: 100%; width: 100%;">
        <button @click="emitEvent">Click me</button>
    </div>
</template>

<script>
import Vue from "vue";
import EventBus from "../event";

export default {
    methods: {
        emitEvent() {
            console.log(EventBus);
            EventBus.$emit("testEvent", "test");
        },
    },
};
</script>
<style>
</style>
</code>```

component that should receive the event:

```<code><template>
    <div>
    </div>
</template>

<script>
import EventBus from "../event";

export default {
    computed: {
        test() {
            EventBus.$on("testEvent", ($event) => {
                console.log("event triggered", $event);
            });
        },
    },
};
</script>

<style>
</style>
</code>```

The problem is that when I click the button I can see the EventBus logged by the console, but nothing else happen, the receiving components does not catch the event.

What am I missing?

答:
You should create EventBus on app.js before defining Vue components.

```<code>Vue.use(VueResource);

window.EventBus = new Vue();

Vue.component("map-wrapper", MapWrapper);
</code>```

Isn't necessary to import EventBus later if using this approach.
Just use EventBus.$emit and EventBus.$on everywhere you want!

Hope it helps!

Title: EventBus in vue not working

Body:
I have a Laravel (5.4) application with some Vue components in it. I would need to make some of those components communicate, so I decided to add an EventBus. The code is the following:

app.js:

import VueResource from "vue-resource";
import Vue from "vue";
import Menu from "components/src/core/Menu.vue";

import MapWrapper from "./components/MapWrapper.vue";
import PaymentModal from "./components/PaymentModal.vue";

require("../sass/app.scss");

Vue.use(VueResource);

Vue.component("map-wrapper", MapWrapper);
Vue.component("my-menu", Menu);
Vue.component("payment-modal", PaymentModal);

// eslint-disable-next-line
new Vue({
    el: "#app",
});

event.js:

import Vue from "vue";

const EventBus = new Vue();

export default EventBus;

component that should trigger the event:

<template>

        <button @click="emitEvent">Click me</button>

</template>

component that should receive the event:

<template>

</template>

The problem is that when I click the button I can see the EventBus logged by the console, but nothing else happen, the receiving components does not catch the event.

What am I missing?

Body:
You should create EventBus on app.js before defining Vue components.

Vue.use(VueResource);

window.EventBus = new Vue();

Vue.component("map-wrapper", MapWrapper);

Isn't necessary to import EventBus later if using this approach.
Just use EventBus.$emit and EventBus.$on everywhere you want!

Hope it helps!


问:
How to remove gap before the first column of wpf ListView?
I noticed that there is gap between the first column header and the left edge of the control. How can I remove it? </p>

答:
You could decrease the Padding of theListView and the Margin of the GridViewHeaderRowPresenter:

```<code><ListView ... Loaded="lv_Loaded">
</code>```

```<code>private void lv_Loaded(object sender, RoutedEventArgs e)
{
    ListView lv = sender as ListView;
    lv.Padding = new Thickness(-2, -1, -2, -1);
    GridViewHeaderRowPresenter presenter = FindChild<GridViewHeaderRowPresenter>(lv);
    if (presenter != null)
        presenter.Margin = new Thickness(1, 0, 2, 0);
}

private static T FindChild<T>(DependencyObject dependencyObject) where T : DependencyObject
{
    if (dependencyObject == null) return null;

    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(dependencyObject); i++)
    {
        var child = VisualTreeHelper.GetChild(dependencyObject, i);

        var result = (child as T) ?? FindChild<T>(child);
        if (result != null) return result;
    }
    return null;
}
</code>```

Body:
You could decrease the Padding of theListView and the Margin of the GridViewHeaderRowPresenter:

<ListView ... Loaded="lv_Loaded">

private void lv_Loaded(object sender, RoutedEventArgs e)
{
    ListView lv = sender as ListView;
    lv.Padding = new Thickness(-2, -1, -2, -1);
    GridViewHeaderRowPresenter presenter = FindChild<GridViewHeaderRowPresenter>(lv);
    if (presenter != null)
        presenter.Margin = new Thickness(1, 0, 2, 0);
}

private static T FindChild<T>(DependencyObject dependencyObject) where T : DependencyObject
{
    if (dependencyObject == null) return null;

    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(dependencyObject); i++)
    {
        var child = VisualTreeHelper.GetChild(dependencyObject, i);

        var result = (child as T) ?? FindChild<T>(child);
        if (result != null) return result;
    }
    return null;
}


问:
Select Data where the diffence between to different date field are less then 2 hours Oracle SQL
I want to know how many customers have placed an order within 2 hours compared to their registration date.

both date types have ddmmyyyy hh:mi

答:
Try This</p>

```<code> Select Count(*) from WhateverYourTable where (24)*(Orderdate-RegisteredDate)>2
</code>```

Body:
Try This

 Select Count(*) from WhateverYourTable where (24)*(Orderdate-RegisteredDate)>2


问:
WordPress custom post type archive widget to display only CPT
I currently have a CPT changelog, and on my custom sidebar I want to display the archives of only this CPT and not all the other posts.

For example :

January 2017 -> should display only CPT changelog post
And so on.

Here's what I have tried so far :

```<code>function custom_changelog_getarchives_where($where)
{
   $where = str_replace("post_type = 'post'", "post_type IN ( 'post',
  'changelog' )", $where);

  return $where;
}

add_filter('getarchives_where', 'custom_changelog_getarchives_where');
</code>```

The above snippet now returns archives of my CPT but it also include the normal posts as well

How do I display only the CPT?

答:
You're adding your CPT to the list and using an IN clause, if you just want to display your CPT, replace the WHERE clause with only your CPT, like this:

```<code>$where = str_replace("post_type = 'post'", "post_type = 'changelog'", $where);
</code>```

Body:
I currently have a CPT changelog, and on my custom sidebar I want to display the archives of only this CPT and not all the other posts.

For example :

January 2017 -> should display only CPT changelog post
And so on.

Here's what I have tried so far :

function custom_changelog_getarchives_where($where)
{
   $where = str_replace("post_type = 'post'", "post_type IN ( 'post',
  'changelog' )", $where);

  return $where;
}

add_filter('getarchives_where', 'custom_changelog_getarchives_where');

The above snippet now returns archives of my CPT but it also include the normal posts as well

How do I display only the CPT?

Body:
You're adding your CPT to the list and using an IN clause, if you just want to display your CPT, replace the WHERE clause with only your CPT, like this:

$where = str_replace("post_type = 'post'", "post_type = 'changelog'", $where);


问:
CSS text layout issue
I am using alertify to display notification on my application, The text in success notification is wrap and in multiple lines but I want it on one single line?

How do I do it?

I am not able to add link to CodePen in question hence added it in comment,
Please check live demo.

Click on "Success notification" button you will get the popup and in that popup the text is is in multiline but I want it in single line.

答:
```<code>.alertify-logs {
position: fixed;
z-index: 5000;
bottom: 10px;
right: 10px;
width: auto;
}
</code>```

I changed width: 300px;to width: auto;. It's on single line.
Is that what you wanted, correct? It also auto adjusts to whatever lenght of your text is/will be.

Title: CSS text layout issue

Body:
.alertify-logs {
position: fixed;
z-index: 5000;
bottom: 10px;
right: 10px;
width: auto;
}

I changed width: 300px;to width: auto;. It's on single line.
Is that what you wanted, correct? It also auto adjusts to whatever lenght of your text is/will be.


问:
Environment variables in LFTP script
I am trying to run lftp with a script like so:

$ lftp -f deploy.scp

However I would like to use environment variables for l/p inside deploy.scp like so:

open -u $FTP_USER,$FTP_PASSWORD $FTP_HOST;

Is that possible in any way? I have struck out finding any help in the man-pages.

答:
You can do

```<code><deploy.scp xargs -l sh -c 'eval echo $0 $*' | lftp
</code>```

or, to save some typing, make an alias, let's say

```<code>alias xv=$'xargs -l sh -c \'eval echo $0 $*\''
</code>```

and then

```<code>xv <deploy.scp | lftp
</code>```

Title: Environment variables in LFTP script

Body:
You can do

<deploy.scp xargs -l sh -c 'eval echo $0 $*' | lftp

or, to save some typing, make an alias, let's say

alias xv=$'xargs -l sh -c \'eval echo $0 $*\''

and then

xv <deploy.scp | lftp


问:
How to Clear the localStorage of a Cordova app for iOS Platform
I have a cordova app running on ios platform . The login ID and Password are being passed from the cordova side to the native side and the urls are  being called . They are stored in the local storage .whenever Im logging out how do i delete the app data containing the login id and password .</p>

答:
you can use removeItem() for removing the credentials whenever users log out.

In your case it could be -

```<code>localStorage.removeItem("loginID");
localStorage.removeItem("password"); //Its not preferred to store passwords in localStorage. Not directly atleast.
</code>```

UPDATE -

you can do clear() to remove the localStorage completely.
just do -

```<code>localStorage.clear();
</code>```

This is simple and efficient. You don't need any other native code to access and remove them explicitly.

If you want to remove items specifically (e.g. password) then you can use a loop to run through all elements and remove them like this -

```<code>function cleanLocalStorage() {
  for(key in localStorage) {
      if(key=="password" || key=="something") //optional condition..
         delete localStorage[key];
  }
}
</code>```

See this answer for the path of LocalStorage Storage locations in the system -
https://stackoverflow.com/a/27612275/5213405

Body:
you can use removeItem() for removing the credentials whenever users log out.

In your case it could be -

localStorage.removeItem("loginID");
localStorage.removeItem("password"); //Its not preferred to store passwords in localStorage. Not directly atleast.

UPDATE -

you can do clear() to remove the localStorage completely.
just do -

localStorage.clear();

This is simple and efficient. You don't need any other native code to access and remove them explicitly.

If you want to remove items specifically (e.g. password) then you can use a loop to run through all elements and remove them like this -

function cleanLocalStorage() {
  for(key in localStorage) {
      if(key=="password" || key=="something") //optional condition..
         delete localStorage[key];
  }
}

See this answer for the path of LocalStorage Storage locations in the system -
https://stackoverflow.com/a/27612275/5213405


问:
unique constraint check not enforced
```<code>create table A (id, field1, field2, field3, field4)
</code>```

I have a unique constraint on field1, field2, field3 and the following records are stored in the table

e.g.

```<code>insert into A (1, "f1", null, "f3", "f4");
insert into A (2, "f1", null, "f3", "f4");
insert into A (3, "f1", null, "f3", "f4");
</code>```

I would expect this to throw an unique constraint violation since all records are in violation, but it doesn't. What am I missing here, did check the database and the unique constraint index has been created.

答:
Null value is never equal to any other value, even null too. null != null

That is why record a + null + b will be never duplicate record a + null + b

ContentLicense: CC BY-SA 2.5

Title: unique constraint check not enforced

Body:
create table A (id, field1, field2, field3, field4)

I have a unique constraint on field1, field2, field3 and the following records are stored in the table

e.g.

insert into A (1, "f1", null, "f3", "f4");
insert into A (2, "f1", null, "f3", "f4");
insert into A (3, "f1", null, "f3", "f4");

I would expect this to throw an unique constraint violation since all records are in violation, but it doesn't. What am I missing here, did check the database and the unique constraint index has been created.


问:
How to install both .net framework 4.6.1 and 4.6.2 on a server?
Ho do i install both the versions 4.6.1 and 4.6.2 on a server and target applications specifically to a specific version of .net framework?

答:
.NET 4.x installs are cumulative. Installing 4.6.2 will include 4.6.1, 4.6, 4.5.2, ….

To specify which version a specific web app uses, use the <httpRuntime> element in your web.config.

Eg. to target 4.6.1:

```<code><system.web>
  …
  <httpRuntime targetFramework="4.6.1"  />
  …
</code>```

(This will cause the web app to fail to run with an unsupported framework exception if designated version is not available.)

For GUI and console executables the target version is in the manifest or app.config file.

Body:
.NET 4.x installs are cumulative. Installing 4.6.2 will include 4.6.1, 4.6, 4.5.2, ….

To specify which version a specific web app uses, use the <httpRuntime> element in your web.config.

Eg. to target 4.6.1:

<system.web>
  …
  <httpRuntime targetFramework="4.6.1"  />
  …

(This will cause the web app to fail to run with an unsupported framework exception if designated version is not available.)

For GUI and console executables the target version is in the manifest or app.config file.


问:
sizeof(text) not equal to : fp_len + 1
if

```<code>fp_len = ftell(fp);
</code>```

prints 470

shouldn't this be printing "471" ?  ( it prints 8. probably first line only )

```<code>char *text = malloc(sizeof(*text) * fp_len + 1);
int text_len;
text_len = sizeof(text);

printf("text-len: %d --- ",text_len);
</code>```

full:

```<code>FILE *fp;
fp = fopen(path, "r");

fseek(fp, 0, SEEK_END);

int fp_len;
fp_len = ftell(fp);
printf("%d---", fp_len);

fseek(fp, 0, SEEK_SET);

char *text = malloc(sizeof(*text) * fp_len + 1);

int text_len;
text_len = sizeof(text);
printf("text-len: %d --- ",text_len);

fread(text, fp_len, 1, fp);

printf("%s",text);

free(text);
</code>```

答:
sizeof gives the size of the type, not a string length.
In case of char *text, the type is a pointer value, and the size of a pointer value on a 64 bit machine is probably 8.

Title: sizeof(text) not equal to : fp_len + 1

Body:
if

fp_len = ftell(fp);

prints 470

shouldn't this be printing "471" ?  ( it prints 8. probably first line only )

char *text = malloc(sizeof(*text) * fp_len + 1);
int text_len;
text_len = sizeof(text);

printf("text-len: %d --- ",text_len);

full:

FILE *fp;
fp = fopen(path, "r");

fseek(fp, 0, SEEK_END);

int fp_len;
fp_len = ftell(fp);
printf("%d---", fp_len);

fseek(fp, 0, SEEK_SET);

char *text = malloc(sizeof(*text) * fp_len + 1);

int text_len;
text_len = sizeof(text);
printf("text-len: %d --- ",text_len);

fread(text, fp_len, 1, fp);

printf("%s",text);

free(text);


问:
Mass find and replace with a Bass Script in PHP Application
In a Zend Framework 2 application, there are 8/9 modules. In these modules, the View has over 15 odd phtml pages with hard coded links like

```<code>href='/controller/action'
</code>```

What I need to do is build a bash script which will go through the modules look for places in which the view has the href above and change it to look like this

```<code>href="<?php $this->url('controller'), action->'action' ?>"
</code>```

答:
Some text editors can do the job otherwise for command, I would use

```<code>find . -name '*.php' -exec perl -i.bak -pe \
   'BEGIN{$str=shift;$rep=shift}s/\Q$str\E/$rep/g' \
   'href='\''/controller/action'\' \
   'href="<?php $this->url('\''controller'\''), action->'\''action'\'' ?>"' \
   {} +
</code>```

This command should be adapted: see man find for options

Body:
In a Zend Framework 2 application, there are 8/9 modules. In these modules, the View has over 15 odd phtml pages with hard coded links like

href='/controller/action'

What I need to do is build a bash script which will go through the modules look for places in which the view has the href above and change it to look like this

href="<?php $this->url('controller'), action->'action' ?>"

Body:
Some text editors can do the job otherwise for command, I would use

find . -name '*.php' -exec perl -i.bak -pe \
   'BEGIN{$str=shift;$rep=shift}s/\Q$str\E/$rep/g' \
   'href='\''/controller/action'\' \
   'href="<?php $this->url('\''controller'\''), action->'\''action'\'' ?>"' \
   {} +

This command should be adapted: see man find for options


问:
accessing nested container members
I am trying to create a 2d array using nested containers. I want to print its members. Can anyone help me please.I am new to stl.
Thanx in advance.</p>

```<code>typedef vector<int> v;
 vector<v>v1;
 v1.push_back(v(45,67));
 v1.push_back(v(36,89));
 v1.push_back(v(27,81));
 v1.push_back(v(18,78));
</code>```

答:
You print the elements like this:

```<code>for(size_t i = 0, mi = v1.size(); i < mi; i++)
{
    for(size_t j = 0, mj = v1[i].size(); j < mj; j++)
        cout << v1[i][j] << ' ';
    cout << '\n';
}
</code>```

Then you'll see that you actually created an array that contains:

```<code>{67,67,67,...,67}, // 45 times
{89,89,89,...,89}, // 36 times
{81,81,81,...,81}, // 27 times
{78,78,78,...,78}, // 18 times
</code>```

Probably not what you expected.

Title: accessing nested container members

Body:
I am trying to create a 2d array using nested containers. I want to print its members. Can anyone help me please.I am new to stl.
Thanx in advance.

typedef vector<int> v;
 vector<v>v1;
 v1.push_back(v(45,67));
 v1.push_back(v(36,89));
 v1.push_back(v(27,81));
 v1.push_back(v(18,78));

Body:
You print the elements like this:

for(size_t i = 0, mi = v1.size(); i < mi; i++)
{
    for(size_t j = 0, mj = v1[i].size(); j < mj; j++)
        cout << v1[i][j] << ' ';
    cout << '\n';
}

Then you'll see that you actually created an array that contains:

{67,67,67,...,67}, // 45 times
{89,89,89,...,89}, // 36 times
{81,81,81,...,81}, // 27 times
{78,78,78,...,78}, // 18 times

Probably not what you expected.


问:
Regarding understanding Android resource folder
I make a research, and I delve deep into Android resources files. According to this link, it says that Android externalize and separate users' resources from the code to allow using
these resources by Ids that will be generated in R.class, here is the text:</p>

```<code>Once you externalize your application resources, you can access them using resource IDs that are generated in your project's R class.
</code>```

<p>(1): Does being the 'res' folder exists means generating the R.java class? In other words, is R.java a representation to "ids" assigned to any values inside 'res' folder? </p>

<p>(2): Is it possible to place my 'layout' or 'string' files in any other folders aside from 'res'? </p>

答:
R.java file is an auto-generated file by aapt (Android Asset Packaging
  Tool) that contains resource IDs for all the resources of res/
  directory. when you create any component in the xml file, id for the
  corresponding component is automatically created in this file.

when creating an layout file using android studio it will automatically put it under layout folder, but when you create it manually it will be classified as the parent folder, eg : create layout file under drawable will be called like R.drawable.mLayout, android studio will show it as warning but it will work fine, so yes you can put any type of xml under any folder and it will work fine, put it's easier to classify as default for more readability and clearer architecture

Body:
I make a research, and I delve deep into Android resources files. According to this link, it says that Android externalize and separate users' resources from the code to allow using
these resources by Ids that will be generated in R.class, here is the text:

Once you externalize your application resources, you can access them using resource IDs that are generated in your project's R class.

(1): Does being the 'res' folder exists means generating the R.java class? In other words, is R.java a representation to "ids" assigned to any values inside 'res' folder?

(2): Is it possible to place my 'layout' or 'string' files in any other folders aside from 'res'?


问:
Custom inherited button in items control, content not being set
(I'm using WPF and the MVVM pattern)

Firstly, I have inherited from the Button control to create my own custom button. This is because I want this button to have some added properties:

```<code>public class RangeButton : Button
{
    public Rank CardARank { get; set; }
    public Rank CardBRank { get; set; }
    public bool IsSuited { get; set; }
    public string ButtonContent { get; set; }

    public RangeButton(int i, int j, bool suited)
    {
        CardARank = GetRankFromInt(i);
        CardBRank = GetRankFromInt(j);
        IsSuited = suited;
        SetButtonContent();
    }

    public RangeButton()
    {
    }

    private Rank GetRankFromInt(int x)
    {
        return (Rank) x;
    }

    private void SetButtonContent()
    {
        ButtonContent = StaticGameHelpers.GetRangeSegmentString(CardARank, CardBRank, IsSuited);
    }
}
</code>```

I initialise a list of RangeButton's in my view model, each of it's properties are being properly set - I end up with a list of 169 RangeButtons:

```<code>public List<RangeButton> RangeButtons
    {
        get { return _rangeButtons; }
        set
        {
            _rangeButtons = value;
            OnPropertyChanged("RangeButtons");
        }
    }
</code>```

Here is my XAML:

```<code><ItemsControl x:Name="itemsControl" ItemsSource="{Binding RangeButtons}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <inheritedControls:RangeButton  Width="70" Height="50" Margin="3">
                    <ContentPresenter Content="{Binding ButtonContent, RelativeSource={RelativeSource Self}}"/>
                </inheritedControls:RangeButton>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <UniformGrid Columns="13" Rows="13"/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
    </ItemsControl>
</code>```

All 169 buttons are being displayed but each button is completely blank, with no content. Also, the width, height and margin properites are being ignored which leads me to believe there is a problem with my xaml but i can't quite figure it out.

I realise there are some similar questions asked like this, but none are using a custom inherited button. Any help much appreciated :)

答: Thanks to some advice from @dymanoid I took a different approach. I scrapped the whole inheritting from the button control idea and simply created a custom object 'RangeSegment' which would replace my RangeButton failure. In my VM I stored a list of RangeSegments and used these as the ItemsSource for my ItemsControl. Then inside the Datatemplate for each item, I added a Button, with the content property bound the properties in each RangeSegment</p>

Body:
(I'm using WPF and the MVVM pattern)

Firstly, I have inherited from the Button control to create my own custom button. This is because I want this button to have some added properties:

public class RangeButton : Button
{
    public Rank CardARank { get; set; }
    public Rank CardBRank { get; set; }
    public bool IsSuited { get; set; }
    public string ButtonContent { get; set; }

    public RangeButton(int i, int j, bool suited)
    {
        CardARank = GetRankFromInt(i);
        CardBRank = GetRankFromInt(j);
        IsSuited = suited;
        SetButtonContent();
    }

    public RangeButton()
    {
    }

    private Rank GetRankFromInt(int x)
    {
        return (Rank) x;
    }

    private void SetButtonContent()
    {
        ButtonContent = StaticGameHelpers.GetRangeSegmentString(CardARank, CardBRank, IsSuited);
    }
}

I initialise a list of RangeButton's in my view model, each of it's properties are being properly set - I end up with a list of 169 RangeButtons:

public List<RangeButton> RangeButtons
    {
        get { return _rangeButtons; }
        set
        {
            _rangeButtons = value;
            OnPropertyChanged("RangeButtons");
        }
    }

Here is my XAML:

<ItemsControl x:Name="itemsControl" ItemsSource="{Binding RangeButtons}">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <inheritedControls:RangeButton  Width="70" Height="50" Margin="3">
                    <ContentPresenter Content="{Binding ButtonContent, RelativeSource={RelativeSource Self}}"/>
                </inheritedControls:RangeButton>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <UniformGrid Columns="13" Rows="13"/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
    </ItemsControl>

All 169 buttons are being displayed but each button is completely blank, with no content. Also, the width, height and margin properites are being ignored which leads me to believe there is a problem with my xaml but i can't quite figure it out.

I realise there are some similar questions asked like this, but none are using a custom inherited button. Any help much appreciated :)


问:
Format a Google Sheets cell in plaintext via Apps Script
Using Google Apps Script, I want to set the format for a Google Sheets cell to plain text.

The reason I want to do this is because I want to show a date in the U.S. date format (MM/DD/YYYY). [We can assume the locale in the OP's Google account is set to use DD/MM/YYYY, a more common date format. –Ed.]

I create the string like this:

```<code>var thisDate = Utilities.formatDate (new Date (), SpreadsheetApp.getActiveSpreadsheet (). getSpreadsheetTimeZone (), "MM / d / yyyy");
</code>```

... which returns the date in the U.S. format, 06/13/2012, which is what I want. However, when I set the value of a cell to that string:

```<code>sheet.getRange (1, n). setValue (thisDate);
</code>```

... the date is formatted into the cell according to my locale, 13/06/2012, not the U.S. format.

The following operation also fails, because the date is returned in the standard format, not the U.S. format:

```<code>sheet.getRange (1, n). getValue () == "06/13/2012"
</code>```

When the cell is formatted as plain text, and not a date, everything works fine.

So, my question is, how to format a cell using JavaScript.

答:
Another way to force the value to be saved as plain text:

Prepend a quotation mark: '. This has no effect on displayed value and also by reading the value
 back the quatation mark is not included.

```<code>let dateStr = '07-07-20017';
sheet.getRange(x, y).setValue("'" + dateStr);

let backStr = sheet.getRange(x, y).getValue();
assert(dateStr === backStr);
</code>```

Body:
Using Google Apps Script, I want to set the format for a Google Sheets cell to plain text.

The reason I want to do this is because I want to show a date in the U.S. date format (MM/DD/YYYY). [We can assume the locale in the OP's Google account is set to use DD/MM/YYYY, a more common date format. –Ed.]

I create the string like this:

var thisDate = Utilities.formatDate (new Date (), SpreadsheetApp.getActiveSpreadsheet (). getSpreadsheetTimeZone (), "MM / d / yyyy");

... which returns the date in the U.S. format, 06/13/2012, which is what I want. However, when I set the value of a cell to that string:

sheet.getRange (1, n). setValue (thisDate);

... the date is formatted into the cell according to my locale, 13/06/2012, not the U.S. format.

The following operation also fails, because the date is returned in the standard format, not the U.S. format:

sheet.getRange (1, n). getValue () == "06/13/2012"

When the cell is formatted as plain text, and not a date, everything works fine.

So, my question is, how to format a cell using JavaScript.

Body:
Another way to force the value to be saved as plain text:

Prepend a quotation mark: '. This has no effect on displayed value and also by reading the value
 back the quatation mark is not included.

let dateStr = '07-07-20017';
sheet.getRange(x, y).setValue("'" + dateStr);

let backStr = sheet.getRange(x, y).getValue();
assert(dateStr === backStr);


问:
copy data from one sheet to another in google app script and append a row, one small issue
sure I had this down but just can't get it right. Had a script set up to get data from one sheet and put it into another one, which I have done but it leaves gaps when copying and I can't figure out how to solve it. I'm sure in the code, its where I have put a question mark, is where the problem lies.

I have tried put i, last, last+1, 10, 12 but none of these work, feel like i'm missing something small to get this right. Below is the code a link to view the sheet if needed (the sheet is just for me to learn from, a basic example if you will).

Thanks in advance and also if the code could be better written, please just let me know as still learning this :)

```<code>function copyInfo() {
  var app = SpreadsheetApp;
  var copySheet = app.getActiveSpreadsheet().getSheetByName("Copy");
  for (var i = 2; i <12; i++) {
  var getInfo = copySheet.getRange(2,2,i,2).getValues();
  //  get the info from range above - start at row 2 on column 2 (b), get number of rows i , number of columns = 2, b,c
  var last = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Paste").getLastRow();
  var pasteSheet = app.getActiveSpreadsheet().getSheetByName("Paste");
//  Tell it where you want the info to go to

  pasteSheet.getRange(last+1,1,?,2).setValues(getInfo);
  var clearIt = copySheet.getRange(2,2,i,2).clearContent();
// this clears the copy range aka getInfo
  }}
</code>```

link to sheet

答:
You can copy whole range at once using copyTo, so your function could be rewritten as:

```<code>function copyInfo() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var copySheet = ss.getSheetByName("Copy");
  var pasteSheet = ss.getSheetByName("Paste");

  // get source range
  var source = copySheet.getRange(2,2,12,2);
  // get destination range
  var destination = pasteSheet.getRange(pasteSheet.getLastRow()+1,2,12,2);

  // copy values to destination range
  source.copyTo(destination);

  // clear source values
  source.clearContent();
}
</code>```

Body:
sure I had this down but just can't get it right. Had a script set up to get data from one sheet and put it into another one, which I have done but it leaves gaps when copying and I can't figure out how to solve it. I'm sure in the code, its where I have put a question mark, is where the problem lies.

I have tried put i, last, last+1, 10, 12 but none of these work, feel like i'm missing something small to get this right. Below is the code a link to view the sheet if needed (the sheet is just for me to learn from, a basic example if you will).

Thanks in advance and also if the code could be better written, please just let me know as still learning this :)

function copyInfo() {
  var app = SpreadsheetApp;
  var copySheet = app.getActiveSpreadsheet().getSheetByName("Copy");
  for (var i = 2; i <12; i++) {
  var getInfo = copySheet.getRange(2,2,i,2).getValues();
  //  get the info from range above - start at row 2 on column 2 (b), get number of rows i , number of columns = 2, b,c
  var last = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Paste").getLastRow();
  var pasteSheet = app.getActiveSpreadsheet().getSheetByName("Paste");
//  Tell it where you want the info to go to

  pasteSheet.getRange(last+1,1,?,2).setValues(getInfo);
  var clearIt = copySheet.getRange(2,2,i,2).clearContent();
// this clears the copy range aka getInfo
  }}

link to sheet

Body:
You can copy whole range at once using copyTo, so your function could be rewritten as:

function copyInfo() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var copySheet = ss.getSheetByName("Copy");
  var pasteSheet = ss.getSheetByName("Paste");

  // get source range
  var source = copySheet.getRange(2,2,12,2);
  // get destination range
  var destination = pasteSheet.getRange(pasteSheet.getLastRow()+1,2,12,2);

  // copy values to destination range
  source.copyTo(destination);

  // clear source values
  source.clearContent();
}


问:
Stop Raspberry Pi from running program at boot
I was trying to figure out how to run a program at boot, but after realizing this program is an infinite loop, I have no way of getting out, or back to the terminal. Right when I give the Pi power it just goes right to the program on a black background. I don't remember exactly what I did to make it run at boot, I believe I just added some code in a place right above something that said "exit 0" and below something that says "esac". I don't remember the command that even got me there. (I am new to the Pi and Python and have just been playing around..unsucessfully.)

If anyone could help me either delete this program or get me to be able to edit it so I can fix the infinite loop that would be great. I'd rather not have to completely over-write the sd card with a fresh raspbian. But like I said I can't do anything at boot, and Ctrl + C doesn't do anything nor Ctrl + Alt + Delete.

EDIT: When I put the SD card in my computer, I see a list of 11 files:
bootcode
cmdline
config
fixup
fixup_cd
issue
kernel
kernel_cutdown
kernel_emergency
start.elf
start_cd.elf

None of these mean anything to me...

答:
I got myself stuck in exactly the same problem. Luckily I had the ssh enabled, apparently this is disabled by default on Raspbian Jessie, so this may not work for all.

The exit 0 is the line in /etc/rc.local where you would have added in the script that is now running in a continuous mode. If you can ssh into the Pi using Putty and the Pi's IP address then

```<code>sudo nano /etc/rc.local
</code>```

Scroll down to the bottom of the file and remove the offending program, then sudo reboot

They way to prevent this issue from happening is to add an & (ampersand) to the end of the line to fork the process and run it as a separate process like so

```<code>python /home/pi/myscript.py &
</code>```

as specified in https://www.raspberrypi.org/documentation/linux/usage/rc-local.md

The ampersand allows the command to run in a separate process and continue booting with the process running.

Body:
I got myself stuck in exactly the same problem. Luckily I had the ssh enabled, apparently this is disabled by default on Raspbian Jessie, so this may not work for all.

The exit 0 is the line in /etc/rc.local where you would have added in the script that is now running in a continuous mode. If you can ssh into the Pi using Putty and the Pi's IP address then

sudo nano /etc/rc.local

Scroll down to the bottom of the file and remove the offending program, then sudo reboot

They way to prevent this issue from happening is to add an & (ampersand) to the end of the line to fork the process and run it as a separate process like so

python /home/pi/myscript.py &

as specified in https://www.raspberrypi.org/documentation/linux/usage/rc-local.md

The ampersand allows the command to run in a separate process and continue booting with the process running.


问:
Why does this MOVSS instruction use RIP-relative addressing?
I found the following assembly code in disassembler (floating point logic c++).

```<code>  842: movss  0x21a(%rip),%xmm0
</code>```

I understand that when process rip will allways be 842 and this 0x21a(%rip) will be const. It seems a little odd to use this register.

I want to know is there any advantage of using rip relative address, instead other addressing.

答:
RIP is the instruction pointer register, which means that it contains the address of the instruction immediately following the current instruction.

For example, consider the following code:

```<code>mov  rax, [rip]
nop
</code>```

In the first line of code there, RIP points to the next instruction, so it points at the NOP. Thus, this code loads the address of the NOP instruction into the RAX register.

As such, it is not the case that RIP is simply a constant. Your understanding that RIP in this process "will always be 842" is not correct. The value of RIP will change, depending on where the code has been loaded into memory. 842 is just the line number, pulled from your debugging symbols; once code is compiled into a binary, it doesn't have line numbers anymore. :-)

In your disassembly, the constant is the offset (0x21A). That's the offset from the current value in RIP. Another way of writing this is: %rip + 0x21A.

RIP-relative addressing is a new form of effective addressing introduced with 64-bit long mode. The point is that it makes it easier to write position-independent code because you can make any memory reference RIP-relative. In fact, RIP-relative addressing is the default addressing mode in 64-bit applications. Virtually all instructions that address memory in 64-bit mode are RIP-relative. I'll quote from Ken Johnson (aka Skywing)'s blog because I couldn't say it any better myself:

One of the larger (but often overlooked) changes to x64 with respect to x86 is that most instructions that previously only referenced data via absolute addressing can now reference data via RIP-relative addressing.

RIP-relative addressing is a mode where an address reference is provided as a (signed) 32-bit displacement from the current instruction pointer. While this was typically only used on x86 for control transfer instructions (call, jmp, and soforth), x64 expands the use of instruction pointer relative addressing to cover a much larger set of instructions.

What’s the advantage of using RIP-relative addressing? Well, the main benefit is that it becomes much easier to generate position independent code, or code that does not depend on where it is loaded in memory. This is especially useful in today’s world of (relatively) self-contained modules (such as DLLs or EXEs) that contain both data (global variables) and the code that goes along with it. If one used flat addressing on x86, references to global variables typically required hardcoding the absolute address of the global in question, assuming the module loads at its preferred base address. If the module then could not be loaded at the preferred base address at runtime, the loader had to perform a set of base relocations that essentially rewrite all instructions that had an absolute address operand component to refer to take into account the new address of the module.

[ . . . ]

An instruction that uses RIP relative addressing, however, typically does not require any base relocations (otherwise known as “fixups”) at load time if the module containing it is relocated, however. This is because as long as portions of the module are not internally re-arranged in memory (something not supported by the PE format), any addresses reference that is both relative to the current instruction pointer and refers to a location within the confines of the current image will continue to refer to the correct location, no matter where the image is placed at load time.

As a result, many x64 images have a greatly reduced number of fixups, due to the fact that most operations can be performed in an RIP-relative fashion.

He's speaking in the context of Windows, but something conceptually similar applies on other operating systems as well.

The code you have is loading a constant value, stored somewhere in the binary image, into the XMM0 register, and it's doing so using RIP-relative addressing because of its many advantages.

Body:
I found the following assembly code in disassembler (floating point logic c++).

  842: movss  0x21a(%rip),%xmm0

I understand that when process rip will allways be 842 and this 0x21a(%rip) will be const. It seems a little odd to use this register.

I want to know is there any advantage of using rip relative address, instead other addressing.

Body:
RIP is the instruction pointer register, which means that it contains the address of the instruction immediately following the current instruction.

For example, consider the following code:

mov  rax, [rip]
nop

In the first line of code there, RIP points to the next instruction, so it points at the NOP. Thus, this code loads the address of the NOP instruction into the RAX register.

As such, it is not the case that RIP is simply a constant. Your understanding that RIP in this process "will always be 842" is not correct. The value of RIP will change, depending on where the code has been loaded into memory. 842 is just the line number, pulled from your debugging symbols; once code is compiled into a binary, it doesn't have line numbers anymore. :-)

In your disassembly, the constant is the offset (0x21A). That's the offset from the current value in RIP. Another way of writing this is: %rip + 0x21A.

RIP-relative addressing is a new form of effective addressing introduced with 64-bit long mode. The point is that it makes it easier to write position-independent code because you can make any memory reference RIP-relative. In fact, RIP-relative addressing is the default addressing mode in 64-bit applications. Virtually all instructions that address memory in 64-bit mode are RIP-relative. I'll quote from Ken Johnson (aka Skywing)'s blog because I couldn't say it any better myself:

One of the larger (but often overlooked) changes to x64 with respect to x86 is that most instructions that previously only referenced data via absolute addressing can now reference data via RIP-relative addressing.

RIP-relative addressing is a mode where an address reference is provided as a (signed) 32-bit displacement from the current instruction pointer. While this was typically only used on x86 for control transfer instructions (call, jmp, and soforth), x64 expands the use of instruction pointer relative addressing to cover a much larger set of instructions.

What’s the advantage of using RIP-relative addressing? Well, the main benefit is that it becomes much easier to generate position independent code, or code that does not depend on where it is loaded in memory. This is especially useful in today’s world of (relatively) self-contained modules (such as DLLs or EXEs) that contain both data (global variables) and the code that goes along with it. If one used flat addressing on x86, references to global variables typically required hardcoding the absolute address of the global in question, assuming the module loads at its preferred base address. If the module then could not be loaded at the preferred base address at runtime, the loader had to perform a set of base relocations that essentially rewrite all instructions that had an absolute address operand component to refer to take into account the new address of the module.

[ . . . ]

An instruction that uses RIP relative addressing, however, typically does not require any base relocations (otherwise known as “fixups”) at load time if the module containing it is relocated, however. This is because as long as portions of the module are not internally re-arranged in memory (something not supported by the PE format), any addresses reference that is both relative to the current instruction pointer and refers to a location within the confines of the current image will continue to refer to the correct location, no matter where the image is placed at load time.

As a result, many x64 images have a greatly reduced number of fixups, due to the fact that most operations can be performed in an RIP-relative fashion.

He's speaking in the context of Windows, but something conceptually similar applies on other operating systems as well.

The code you have is loading a constant value, stored somewhere in the binary image, into the XMM0 register, and it's doing so using RIP-relative addressing because of its many advantages.


问:
How to create custom java library and call its function inside Android App
I am new to java and android development and I want to create my own java library (JAR files) and I want to call this jar lib function inside android app code base.

Although there are numerous online tutorials available which demonstrate how to do this I couldnt find one for a newbee person like me.

The resources available on the internet, assume that a person should be hands on java and android platform. This is not the case with me.

I have just started learning it and I want to create a java library and call its function into an Android App.

So to achieve this, below are the steps I have performed.

Step 1 : Created a sample program "Addition of 2 numbers" so this is what I have written.

```<code> package MyPackage;
 import java.io.*;
 import java.net.*;

 public class MyAddition {
    public static int addition(int a, int b){
       return (a+b);
    }
 }
</code>```

Saved it as MyAddition.java .Compiled and created its  class file MyAddition.class inside folder [folder_path]..../mylib/MyPackage/

Steps 2 : Created its JAR files using following command

```<code>   jar -cf mylib.jar [folder_path]../mylib
</code>```

Steps 3 :

Now I have installed Android Studio in order to create my android app code base where I want to call this JAR lib function.

In Android Studio, I have created a new project using its predefined "bottom Navigation activity"  as "My Application" so the whole project is set up by the Android Studio. Here is a screenshot for the whole setup.

Step 4 : : I have my complete application set up which looks like this.

Step 5 : : Now I want to integrate my JAR file which I've created earlier into this app. So to achieve this I've added the jar lib "mylib.jar" inside apps/libs folder like this.

Step 6 : : After doing all this, I am adding following line into the build.gradle file
     compile files 'libs/mylib.jar'

and then sync.

After Adding the Jar, I am calling its function inside Android App Function
but in this case its showing me error "can not resolve the MyPackage", where as it shows me this inside the application scope

Now I could not proceed further in order to include and call jar files function.

Any help is appreciated .

答: Go to project structure-> modules->app->dependencies then check your jar is available or not. If your jar is not available then go to add icon on right top then add jar dependency.</p>

Body:
I am new to java and android development and I want to create my own java library (JAR files) and I want to call this jar lib function inside android app code base.

Although there are numerous online tutorials available which demonstrate how to do this I couldnt find one for a newbee person like me.

The resources available on the internet, assume that a person should be hands on java and android platform. This is not the case with me.

I have just started learning it and I want to create a java library and call its function into an Android App.

So to achieve this, below are the steps I have performed.

Step 1 : Created a sample program "Addition of 2 numbers" so this is what I have written.

 package MyPackage;
 import java.io.*;
 import java.net.*;

 public class MyAddition {
    public static int addition(int a, int b){
       return (a+b);
    }
 }

Saved it as MyAddition.java .Compiled and created its  class file MyAddition.class inside folder [folder_path]..../mylib/MyPackage/

Steps 2 : Created its JAR files using following command

   jar -cf mylib.jar [folder_path]../mylib

Steps 3 :

Now I have installed Android Studio in order to create my android app code base where I want to call this JAR lib function.

In Android Studio, I have created a new project using its predefined "bottom Navigation activity"  as "My Application" so the whole project is set up by the Android Studio. Here is a screenshot for the whole setup.

Step 4 : : I have my complete application set up which looks like this.

Step 5 : : Now I want to integrate my JAR file which I've created earlier into this app. So to achieve this I've added the jar lib "mylib.jar" inside apps/libs folder like this.

Step 6 : : After doing all this, I am adding following line into the build.gradle file
     compile files 'libs/mylib.jar'

and then sync.

After Adding the Jar, I am calling its function inside Android App Function
but in this case its showing me error "can not resolve the MyPackage", where as it shows me this inside the application scope

Now I could not proceed further in order to include and call jar files function.

Any help is appreciated .


问:
regex extract list of strings from file
I have an input file (input.txt) which contains some data that follows a standard format similar to the following lines:

```<code><descriptor/nnn> <http://www.nnn.org/2004/02/skos/core#prefLabel> "Politische Inklusion"@de .
<descriptor/nnn> <http://www.nnn.org/2004/02/skos/core#prefLabel> "Political inclusion"@en .
<descriptor/nnn> <http://www.nnn.org/2004/02/skos/core#prefLabel> "Radiologische Kampfmittel"@de .
</code>```

I want to extract a list of English strings which lies between the " "@en in outputfile-en.txt, and German strings which lies between the " "@de in outputfile-de.txt

In this example outputfile-en.txt should contain:

```<code>Political inclusion
</code>```

and outputfile-de.txt should contain:

```<code>Politische Inklusion
Radiologische Kampfmittel
</code>```

Which regex is suitable here?

答:
You could do something like this:

```<code>import re

str = """<descriptor/nnn> <http://www.nnn.org/2004/02/skos/core#prefLabel> "Politische Inklusion"@de .
<descriptor/nnn> <http://www.nnn.org/2004/02/skos/core#prefLabel> "Political inclusion"@en .
<descriptor/nnn> <http://www.nnn.org/2004/02/skos/core#prefLabel> "Radiologische Kampfmittel"@de . """

german = re.compile('"(.*)"@de')
english = re.compile('"(.*)"@en')

print german.findall(str)
print english.findall(str)
</code>```

This would give you
['Politische Inklusion', 'Radiologische Kampfmittel']
and
['Political inclusion'].
Now you only have to iterate over those results and write them to the appropriate file.

Title: regex extract list of strings from file

Body:
I have an input file (input.txt) which contains some data that follows a standard format similar to the following lines:

<descriptor/nnn> <http://www.nnn.org/2004/02/skos/core#prefLabel> "Politische Inklusion"@de .
<descriptor/nnn> <http://www.nnn.org/2004/02/skos/core#prefLabel> "Political inclusion"@en .
<descriptor/nnn> <http://www.nnn.org/2004/02/skos/core#prefLabel> "Radiologische Kampfmittel"@de .

I want to extract a list of English strings which lies between the " "@en in outputfile-en.txt, and German strings which lies between the " "@de in outputfile-de.txt

In this example outputfile-en.txt should contain:

Political inclusion

and outputfile-de.txt should contain:

Politische Inklusion
Radiologische Kampfmittel

Which regex is suitable here?

Body:
You could do something like this:

import re

str = """<descriptor/nnn> <http://www.nnn.org/2004/02/skos/core#prefLabel> "Politische Inklusion"@de .
<descriptor/nnn> <http://www.nnn.org/2004/02/skos/core#prefLabel> "Political inclusion"@en .
<descriptor/nnn> <http://www.nnn.org/2004/02/skos/core#prefLabel> "Radiologische Kampfmittel"@de . """

german = re.compile('"(.*)"@de')
english = re.compile('"(.*)"@en')

print german.findall(str)
print english.findall(str)

This would give you
['Politische Inklusion', 'Radiologische Kampfmittel']
and
['Political inclusion'].
Now you only have to iterate over those results and write them to the appropriate file.


问:
How to read/interpret html tags in Excel within a single cell?
So here's my problem, I got a metric ton of html code in an Excel colunm. Something like that:

HTML in Excel cell

```<code><p>Alerte suite à 1 vrt de EUR XXXXXX en provenance du YYYYY.</p>
<p> </p>
<p>Thing</p>
<p>bénéficiaire : Someone</p>
<p> </p>
<p>Flux inférieur à ZZZZZ EUR, ne nécessitant pas d'investigation.<br /> Décision du 5/7/2012</p>
</code>```

So i wanted to treat it, in way that the info will stay in one cell.
In my serch I saw this post Stack Question: Read html in Exel

But it was old, and the responce of @BornToCode from 2014, recommend to use a macro to automaticly copy/paste, however it turns the information into many cell.

On my side i use the following macro to "sorta" fix my issue

Code VBA

```<code>Sub suppHTML()
'Selection As Range For Each cell In Selection
cell.Select
Call supphtmlinCell
Next cell
End Sub

Sub supphtmlinCell()
Dim strPattern0 As String: strPattern0 = "</p>"
Dim strReplace0 As String: strReplace0 = vbNewLine
Dim regEx0 As New RegExp
Dim strInput0 As String

Dim strPattern As String: strPattern = "<.*?>"
Dim strReplace As String: strReplace = " "
Dim regEx As New RegExp
Dim strInput As String

Dim strPattern1 As String: strPattern1 = " "
Dim strReplace1 As String: strReplace1 = " "
Dim regEx1 As New RegExp
Dim strInput1 As String

Dim strPattern2 As String: strPattern2 = "é"
Dim strReplace2 As String: strReplace2 = "é"
Dim regEx2 As New RegExp
Dim strInput2 As String

Dim strPattern3 As String: strPattern3 = "è"
Dim strReplace3 As String: strReplace3 = "è"
Dim regEx3 As New RegExp
Dim strInput3 As String

Dim strPattern4 As String: strPattern4 = "ç"
Dim strReplace4 As String: strReplace4 = "ç"
Dim regEx4 As New RegExp
Dim strInput4 As String

Dim strPattern5 As String: strPattern5 = "ë"
Dim strReplace5 As String: strReplace5 = "ë"
Dim regEx5 As New RegExp
Dim strInput5 As String

Dim strPattern6 As String: strPattern6 = "à"
Dim strReplace6 As String: strReplace6 = "à"
Dim regEx6 As New RegExp
Dim strInput6 As String

Dim strPattern7 As String: strPattern7 = ">"
Dim strReplace7 As String: strReplace7 = ">"
Dim regEx7 As New RegExp
Dim strInput7 As String

Dim strPattern8 As String: strPattern8 = "<"
Dim strReplace8 As String: strReplace8 = "<"
Dim regEx8 As New RegExp
Dim strInput8 As String

Dim strPattern9 As String: strPattern9 = "&"
Dim strReplace9 As String: strReplace9 = "&"
Dim regEx9 As New RegExp
Dim strInput9 As String

    If strPattern0 <> "" Then
        strInput0 = ActiveCell.Offset(0, 0).Value

        With regEx0
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = strPattern0
        End With

        If regEx0.Test(strInput0) Then
            'MsgBox (regEx.Replace(strInput, strReplace))
            ActiveCell.Offset(0, 0).Value = regEx0.Replace(strInput0, strReplace0)
        Else
            'MsgBox ("Not matched")
        End If
    End If

'ActiveCell.Offset(0, 0).Value = 2
If strPattern <> "" Then
        strInput = ActiveCell.Offset(0, 0).Value
        strReplace = ""

        With regEx
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = strPattern
        End With

        If regEx.Test(strInput) Then
            'MsgBox (regEx.Replace(strInput, strReplace))
            ActiveCell.Offset(0, 0).Value = regEx.Replace(strInput, strReplace)
        Else
            'MsgBox ("Not matched")
        End If
    End If

    If strPattern1 <> "" Then
        strInput1 = ActiveCell.Offset(0, 0).Value

        With regEx1
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = strPattern1
        End With

        If regEx1.Test(strInput1) Then
            'MsgBox (regEx.Replace(strInput, strReplace))
            ActiveCell.Offset(0, 0).Value = regEx1.Replace(strInput1, strReplace1)
        Else
            'MsgBox ("Not matched")
        End If
    End If

    If strPattern2 <> "" Then
        strInput2 = ActiveCell.Offset(0, 0).Value

        With regEx2
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = strPattern2
        End With

        If regEx2.Test(strInput2) Then
            'MsgBox (regEx.Replace(strInput, strReplace))
            ActiveCell.Offset(0, 0).Value = regEx2.Replace(strInput2, strReplace2)
        Else
            'MsgBox ("Not matched")
        End If
    End If

    If strPattern3 <> "" Then
        strInput3 = ActiveCell.Offset(0, 0).Value

        With regEx3
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = strPattern3
        End With

        If regEx3.Test(strInput3) Then
            'MsgBox (regEx.Replace(strInput, strReplace))
            ActiveCell.Offset(0, 0).Value = regEx3.Replace(strInput3, strReplace3)
        Else
            'MsgBox ("Not matched")
        End If
    End If

    If strPattern4 <> "" Then
        strInput4 = ActiveCell.Offset(0, 0).Value

        With regEx4
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = strPattern4
        End With

        If regEx4.Test(strInput4) Then
            'MsgBox (regEx.Replace(strInput, strReplace))
            ActiveCell.Offset(0, 0).Value = regEx4.Replace(strInput4, strReplace4)
        Else
            'MsgBox ("Not matched")
        End If
    End If

    If strPattern5 <> "" Then
        strInput5 = ActiveCell.Offset(0, 0).Value

        With regEx5
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = strPattern5
        End With

        If regEx5.Test(strInput5) Then
            'MsgBox (regEx.Replace(strInput, strReplace))
            ActiveCell.Offset(0, 0).Value = regEx5.Replace(strInput5, strReplace5)
        Else
            'MsgBox ("Not matched")
        End If
    End If

    If strPattern6 <> "" Then
        strInput6 = ActiveCell.Offset(0, 0).Value

        With regEx6
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = strPattern6
        End With

        If regEx6.Test(strInput6) Then
            'MsgBox (regEx.Replace(strInput, strReplace))
            ActiveCell.Offset(0, 0).Value = regEx6.Replace(strInput6, strReplace6)
        Else
            'MsgBox ("Not matched")
        End If
    End If

    If strPattern7 <> "" Then
        strInput7 = ActiveCell.Offset(0, 0).Value

        With regEx7
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = strPattern7
        End With

        If regEx7.Test(strInput7) Then
            'MsgBox (regEx.Replace(strInput, strReplace))
            ActiveCell.Offset(0, 0).Value = regEx7.Replace(strInput7, strReplace7)
        Else
            'MsgBox ("Not matched")
        End If
    End If

    If strPattern8 <> "" Then
        strInput8 = ActiveCell.Offset(0, 0).Value

        With regEx8
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = strPattern8
        End With

        If regEx8.Test(strInput8) Then
            'MsgBox (regEx.Replace(strInput, strReplace))
            ActiveCell.Offset(0, 0).Value = regEx8.Replace(strInput8, strReplace8)
        Else
            'MsgBox ("Not matched")
        End If
    End If

    If strPattern9 <> "" Then
        strInput9 = ActiveCell.Offset(0, 0).Value

        With regEx9
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = strPattern9
        End With

        If regEx9.Test(strInput9) Then
            'MsgBox (regEx.Replace(strInput, strReplace))
            ActiveCell.Offset(0, 0).Value = regEx9.Replace(strInput9, strReplace9)
        Else
            'MsgBox ("Not matched")
        End If
    End If
End Sub
</code>```

So my solution is to find string i don't like and replace it by some other string that I prefer. But as you can all see, this solution is less than optimal.
For instance now I'm still missing the way to interpret "à", "â" or "ô".
And I'll need to edit the macro for every new string that I want to deal with.

So here I am looking for a better solution than mine, and I'm fairly confident a cleaner solution exist since Excel can interpret HTML through copy/paste.

答:
Here the ajustement of Rik Sportel code, in case someone arrive on that page with the same issue as mine:

```<code>Sub supphtml()

u = Selection.Address
For Each cel In Range(u)

    With CreateObject("htmlfile")
        .Open
        .write cel.Value
        .Close
        cel.Value = .body.outerText
    End With

Next cel
End Sub
</code>```

This will transform all cells that were selected before running the macro

Body:
So here's my problem, I got a metric ton of html code in an Excel colunm. Something like that:

HTML in Excel cell

Alerte suite à 1 vrt de EUR XXXXXX en provenance du YYYYY.

Thing

bénéficiaire : Someone

Flux inférieur à ZZZZZ EUR, ne nécessitant pas d'investigation.
 Décision du 5/7/2012

So i wanted to treat it, in way that the info will stay in one cell.
In my serch I saw this post Stack Question: Read html in Exel

But it was old, and the responce of @BornToCode from 2014, recommend to use a macro to automaticly copy/paste, however it turns the information into many cell.

On my side i use the following macro to "sorta" fix my issue

Code VBA

Sub suppHTML()
'Selection As Range For Each cell In Selection
cell.Select
Call supphtmlinCell
Next cell
End Sub

Sub supphtmlinCell()
Dim strPattern0 As String: strPattern0 = "
"
Dim strReplace0 As String: strReplace0 = vbNewLine
Dim regEx0 As New RegExp
Dim strInput0 As String

Dim strPattern As String: strPattern = "<.*?>"
Dim strReplace As String: strReplace = " "
Dim regEx As New RegExp
Dim strInput As String

Dim strPattern1 As String: strPattern1 = " "
Dim strReplace1 As String: strReplace1 = " "
Dim regEx1 As New RegExp
Dim strInput1 As String

Dim strPattern2 As String: strPattern2 = "é"
Dim strReplace2 As String: strReplace2 = "é"
Dim regEx2 As New RegExp
Dim strInput2 As String

Dim strPattern3 As String: strPattern3 = "è"
Dim strReplace3 As String: strReplace3 = "è"
Dim regEx3 As New RegExp
Dim strInput3 As String

Dim strPattern4 As String: strPattern4 = "ç"
Dim strReplace4 As String: strReplace4 = "ç"
Dim regEx4 As New RegExp
Dim strInput4 As String

Dim strPattern5 As String: strPattern5 = "ë"
Dim strReplace5 As String: strReplace5 = "ë"
Dim regEx5 As New RegExp
Dim strInput5 As String

Dim strPattern6 As String: strPattern6 = "à"
Dim strReplace6 As String: strReplace6 = "à"
Dim regEx6 As New RegExp
Dim strInput6 As String

Dim strPattern7 As String: strPattern7 = ">"
Dim strReplace7 As String: strReplace7 = ">"
Dim regEx7 As New RegExp
Dim strInput7 As String

Dim strPattern8 As String: strPattern8 = "<"
Dim strReplace8 As String: strReplace8 = "<"
Dim regEx8 As New RegExp
Dim strInput8 As String

Dim strPattern9 As String: strPattern9 = "&"
Dim strReplace9 As String: strReplace9 = "&"
Dim regEx9 As New RegExp
Dim strInput9 As String

    If strPattern0 <> "" Then
        strInput0 = ActiveCell.Offset(0, 0).Value

        With regEx0
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = strPattern0
        End With

        If regEx0.Test(strInput0) Then
            'MsgBox (regEx.Replace(strInput, strReplace))
            ActiveCell.Offset(0, 0).Value = regEx0.Replace(strInput0, strReplace0)
        Else
            'MsgBox ("Not matched")
        End If
    End If

'ActiveCell.Offset(0, 0).Value = 2
If strPattern <> "" Then
        strInput = ActiveCell.Offset(0, 0).Value
        strReplace = ""

        With regEx
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = strPattern
        End With

        If regEx.Test(strInput) Then
            'MsgBox (regEx.Replace(strInput, strReplace))
            ActiveCell.Offset(0, 0).Value = regEx.Replace(strInput, strReplace)
        Else
            'MsgBox ("Not matched")
        End If
    End If

    If strPattern1 <> "" Then
        strInput1 = ActiveCell.Offset(0, 0).Value

        With regEx1
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = strPattern1
        End With

        If regEx1.Test(strInput1) Then
            'MsgBox (regEx.Replace(strInput, strReplace))
            ActiveCell.Offset(0, 0).Value = regEx1.Replace(strInput1, strReplace1)
        Else
            'MsgBox ("Not matched")
        End If
    End If

    If strPattern2 <> "" Then
        strInput2 = ActiveCell.Offset(0, 0).Value

        With regEx2
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = strPattern2
        End With

        If regEx2.Test(strInput2) Then
            'MsgBox (regEx.Replace(strInput, strReplace))
            ActiveCell.Offset(0, 0).Value = regEx2.Replace(strInput2, strReplace2)
        Else
            'MsgBox ("Not matched")
        End If
    End If

    If strPattern3 <> "" Then
        strInput3 = ActiveCell.Offset(0, 0).Value

        With regEx3
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = strPattern3
        End With

        If regEx3.Test(strInput3) Then
            'MsgBox (regEx.Replace(strInput, strReplace))
            ActiveCell.Offset(0, 0).Value = regEx3.Replace(strInput3, strReplace3)
        Else
            'MsgBox ("Not matched")
        End If
    End If

    If strPattern4 <> "" Then
        strInput4 = ActiveCell.Offset(0, 0).Value

        With regEx4
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = strPattern4
        End With

        If regEx4.Test(strInput4) Then
            'MsgBox (regEx.Replace(strInput, strReplace))
            ActiveCell.Offset(0, 0).Value = regEx4.Replace(strInput4, strReplace4)
        Else
            'MsgBox ("Not matched")
        End If
    End If

    If strPattern5 <> "" Then
        strInput5 = ActiveCell.Offset(0, 0).Value

        With regEx5
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = strPattern5
        End With

        If regEx5.Test(strInput5) Then
            'MsgBox (regEx.Replace(strInput, strReplace))
            ActiveCell.Offset(0, 0).Value = regEx5.Replace(strInput5, strReplace5)
        Else
            'MsgBox ("Not matched")
        End If
    End If

    If strPattern6 <> "" Then
        strInput6 = ActiveCell.Offset(0, 0).Value

        With regEx6
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = strPattern6
        End With

        If regEx6.Test(strInput6) Then
            'MsgBox (regEx.Replace(strInput, strReplace))
            ActiveCell.Offset(0, 0).Value = regEx6.Replace(strInput6, strReplace6)
        Else
            'MsgBox ("Not matched")
        End If
    End If

    If strPattern7 <> "" Then
        strInput7 = ActiveCell.Offset(0, 0).Value

        With regEx7
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = strPattern7
        End With

        If regEx7.Test(strInput7) Then
            'MsgBox (regEx.Replace(strInput, strReplace))
            ActiveCell.Offset(0, 0).Value = regEx7.Replace(strInput7, strReplace7)
        Else
            'MsgBox ("Not matched")
        End If
    End If

    If strPattern8 <> "" Then
        strInput8 = ActiveCell.Offset(0, 0).Value

        With regEx8
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = strPattern8
        End With

        If regEx8.Test(strInput8) Then
            'MsgBox (regEx.Replace(strInput, strReplace))
            ActiveCell.Offset(0, 0).Value = regEx8.Replace(strInput8, strReplace8)
        Else
            'MsgBox ("Not matched")
        End If
    End If

    If strPattern9 <> "" Then
        strInput9 = ActiveCell.Offset(0, 0).Value

        With regEx9
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = strPattern9
        End With

        If regEx9.Test(strInput9) Then
            'MsgBox (regEx.Replace(strInput, strReplace))
            ActiveCell.Offset(0, 0).Value = regEx9.Replace(strInput9, strReplace9)
        Else
            'MsgBox ("Not matched")
        End If
    End If
End Sub

So my solution is to find string i don't like and replace it by some other string that I prefer. But as you can all see, this solution is less than optimal.
For instance now I'm still missing the way to interpret "à", "â" or "ô".
And I'll need to edit the macro for every new string that I want to deal with.

So here I am looking for a better solution than mine, and I'm fairly confident a cleaner solution exist since Excel can interpret HTML through copy/paste.

Body:
Here the ajustement of Rik Sportel code, in case someone arrive on that page with the same issue as mine:

Sub supphtml()

u = Selection.Address
For Each cel In Range(u)

    With CreateObject("htmlfile")
        .Open
        .write cel.Value
        .Close
        cel.Value = .body.outerText
    End With

Next cel
End Sub

This will transform all cells that were selected before running the macro


问:
to get Time in minutes
I want to get time in minutes.

I have shared the details in below format.

I want the running time in Minute.

kindly help me.

```<code>start_time               end_time                running time(end_time-start_time)
7/7/2017 2:52:05 PM      7/7/2017 2:52:54 PM     I want it in Minute
</code>```

答:
If this is Oracle (plsql tag says maybe):</p>

```<code>(end_time - start_time) * 24 /* days to hours */ * 60 /* hours to minutes */ as running_time
</code>```

Title: to get Time in minutes

Body:
I want to get time in minutes.

I have shared the details in below format.

I want the running time in Minute.

kindly help me.

start_time               end_time                running time(end_time-start_time)
7/7/2017 2:52:05 PM      7/7/2017 2:52:54 PM     I want it in Minute

Body:
If this is Oracle (plsql tag says maybe):

(end_time - start_time) * 24 /* days to hours */ * 60 /* hours to minutes */ as running_time


问:
AngularJS kendo treeview selected child node programmatically
Based on the following code I am able to select nodes in the tree view if the id I provide belongs to a parent node, example: 1. But when I provide the id of a child node, example: 2.1, it is not able to select the node from code level.
The following is the code I am currently using:</p>

```<code><div id="example" ng-app="KendoDemos">
    <div class="demo-section k-content" ng-controller="MyCtrl">
        <div class="box-col">
            <h4>TreeView</h4>
            <div kendo-tree-view="tree"
                k-data-source="treeData"
                k-on-change="selectedItem = dataItem">
                <span k-template>
                    {{dataItem.text}}
                </span>
            </div>
        </div>
    </div>
</div>

angular.module("KendoDemos", [ "kendo.directives" ])
.controller("MyCtrl", ["$scope", "$timeout", function($scope, $timeout) {
      $scope.treeData = new kendo.data.HierarchicalDataSource({
          data: [
              { text: "Item 1", id: 1 },
              { text: "Item 2", id: 2, items: [
              { text: "SubItem 2.1", id: 2.1 },
              { text: "SubItem 2.2", id: 2.2 }
          ] },
          { text: "Item 3", id: 3 }
      ]});

      $scope.click = function(dataItem) {
        alert(dataItem.text);
      };

      $scope.selectNode = function(id) {
          $scope.branchId = id;
          var item = $scope.treeData._data.find(findKendoBranchById);
          var node = $scope.tree.findByUid(item.uid);
          $scope.tree.select(node);
      }

      function findKendoBranchById(item, index, kendo) {
          var isThisBranch = false;

          if (item.id == null) {
              isThisBranch = item.text == $scope.branchId;
          } else {
              isThisBranch = item.id == $scope.branchId;
          }

          return isThisBranch;
      }

      $timeout(function() {
          $scope.selectNode(2);
          //when this runs, will show the error below
          $scope.selectNode(2.1);
      }, 2000);
  }]);

VM1703 angular.min.js:107 TypeError: Cannot read property 'uid' of undefined
at n.$scope.selectNode (<anonymous>:20:50)
at <anonymous>:38:18
at VM1703 angular.min.js:146
at e (VM1703 angular.min.js:43)
at VM1703 angular.min.js:45
</code>```

答:
In the end i chose to re-init the treeview when the selected node is changed.

```<code>$scope.rawData = [
   { text: "Item 1", id: 1 },
   { text: "Item 2", id: 2, items: [
      { text: "SubItem 2.1", id: 2.1 },
      { text: "SubItem 2.2", id: 2.2 }
      ]
   }];
$scope.selectNode = function(id){
   $scope.treeData = new kendo.data.ObservableArray(processSelectedNode($scope.rawData, id));
};

function processSelectedNode(array, id){
    var navigationData = [];

    for (var i = 0; i < array.length; i++) {
       var obj = array[i];
       obj.expanded = true;
       obj.selected = obj.id == id;

       if (array[i].items) {
           obj.items = prepareNavigationTreeDataSource(array[i].items, id);
        }

        navigationData.push(obj);
    }
}
</code>```

This works for me as the Kendo Treeview will select the node with selected = true

Body:
Based on the following code I am able to select nodes in the tree view if the id I provide belongs to a parent node, example: 1. But when I provide the id of a child node, example: 2.1, it is not able to select the node from code level.
The following is the code I am currently using:

TreeView

                    {{dataItem.text}}

angular.module("KendoDemos", [ "kendo.directives" ])
.controller("MyCtrl", ["$scope", "$timeout", function($scope, $timeout) {
      $scope.treeData = new kendo.data.HierarchicalDataSource({
          data: [
              { text: "Item 1", id: 1 },
              { text: "Item 2", id: 2, items: [
              { text: "SubItem 2.1", id: 2.1 },
              { text: "SubItem 2.2", id: 2.2 }
          ] },
          { text: "Item 3", id: 3 }
      ]});

      $scope.click = function(dataItem) {
        alert(dataItem.text);
      };

      $scope.selectNode = function(id) {
          $scope.branchId = id;
          var item = $scope.treeData._data.find(findKendoBranchById);
          var node = $scope.tree.findByUid(item.uid);
          $scope.tree.select(node);
      }

      function findKendoBranchById(item, index, kendo) {
          var isThisBranch = false;

          if (item.id == null) {
              isThisBranch = item.text == $scope.branchId;
          } else {
              isThisBranch = item.id == $scope.branchId;
          }

          return isThisBranch;
      }

      $timeout(function() {
          $scope.selectNode(2);
          //when this runs, will show the error below
          $scope.selectNode(2.1);
      }, 2000);
  }]);

VM1703 angular.min.js:107 TypeError: Cannot read property 'uid' of undefined
at n.$scope.selectNode (<anonymous>:20:50)
at <anonymous>:38:18
at VM1703 angular.min.js:146
at e (VM1703 angular.min.js:43)
at VM1703 angular.min.js:45

Body:
In the end i chose to re-init the treeview when the selected node is changed.

$scope.rawData = [
   { text: "Item 1", id: 1 },
   { text: "Item 2", id: 2, items: [
      { text: "SubItem 2.1", id: 2.1 },
      { text: "SubItem 2.2", id: 2.2 }
      ]
   }];
$scope.selectNode = function(id){
   $scope.treeData = new kendo.data.ObservableArray(processSelectedNode($scope.rawData, id));
};

function processSelectedNode(array, id){
    var navigationData = [];

    for (var i = 0; i < array.length; i++) {
       var obj = array[i];
       obj.expanded = true;
       obj.selected = obj.id == id;

       if (array[i].items) {
           obj.items = prepareNavigationTreeDataSource(array[i].items, id);
        }

        navigationData.push(obj);
    }
}

This works for me as the Kendo Treeview will select the node with selected = true


问:
What is the difference between DoS and Brute Force attacks?
I was reading about DoS attacks on Apache servers but the "Brute Force" word pops up sometimes I know DoS attacks but "Brute Force" seems to be similar, is there a difference or it is just another word of DoS?</p>

答:
Brute force refers to a solution to a problem that relies on computers being fast to get an answer. Generally, it works by trying all possibilities. For example, if you want to know the sum of all numbers 1 through 100, you could do something like:

```<code>sum = 0
for i from 1 to 100
  sum = sum + i
end
</code>```

That'd be brute force. You could also do notice that 1 through 100 contains 50 pairs totaling 101, and solve it like this:

```<code>sum = 50 * 101
</code>```

That's an intelligent approach. Note that brute force is generally easier to come up with.

The concept is extended to security in an obvious manner. For example, if you want to break into someone's account on a system that requires 8-character passwords, you could just start trying passwords — aaaaaaaa, aaaaaaab, ... — and eventually it'll work. That's brute force. You could try a list of common passwords (less brute force-ish). Or you could notice the site stores who you're logged in as in a cookie, and edit the cookie (not brute force).

Similar with breaking encryption. You could try all possible keys (brute force, not going to finish this lifetime on a reasonable cipher). Or you could analyze the cipher for weaknesses (very hard if its a good cipher, definitely not brute force).

And, to tie it all up, if you want to take down a site, you could just send a bunch of traffic/requests/whatever in its general direction. That's brute force. That's a DoS attack.

OwnerDisplayName: Sulaiman

LastEditorDisplayName: Jeremy Ruten

Body:
Brute force refers to a solution to a problem that relies on computers being fast to get an answer. Generally, it works by trying all possibilities. For example, if you want to know the sum of all numbers 1 through 100, you could do something like:

sum = 0
for i from 1 to 100
  sum = sum + i
end

That'd be brute force. You could also do notice that 1 through 100 contains 50 pairs totaling 101, and solve it like this:

sum = 50 * 101

That's an intelligent approach. Note that brute force is generally easier to come up with.

The concept is extended to security in an obvious manner. For example, if you want to break into someone's account on a system that requires 8-character passwords, you could just start trying passwords — aaaaaaaa, aaaaaaab, ... — and eventually it'll work. That's brute force. You could try a list of common passwords (less brute force-ish). Or you could notice the site stores who you're logged in as in a cookie, and edit the cookie (not brute force).

Similar with breaking encryption. You could try all possible keys (brute force, not going to finish this lifetime on a reasonable cipher). Or you could analyze the cipher for weaknesses (very hard if its a good cipher, definitely not brute force).

And, to tie it all up, if you want to take down a site, you could just send a bunch of traffic/requests/whatever in its general direction. That's brute force. That's a DoS attack.

OwnerDisplayName: derobert


问:
How do I parse a website in python once I know its url?
If I know the url of a wiki site , How do I use python to parse the contents of it ?</p>

答: This is a very broad question, but the first things to reach for are urllib, which will handle the downloading part, and Beautiful Soup, which will do the parsing.  Gluing them together and writing the code to actually extract information from the parse tree is up to you.</p>


问:
Why kafka throw Received -1 when reading from channel, socket has likely been closed, when spark streaming to secured kafka?
I'm getting this error when trying to stream from spark (using Java) to secured Kafka (with SASL PLAINTEXT mechanism).

more detailed error message:

```<code>17/07/07 14:38:43 INFO SimpleConsumer: Reconnect due to socket error: java.io.EOFException: Received -1 when reading from a channel, the socket has likely been closed.
Exception in thread "main" org.apache.spark.SparkException: java.io.EOFException: Received -1 when reading from channel, socket has likely been closed.
at org.apache.spark.streaming.kafka.KafkaCluster$$anonfun$checkErrors$1.apply(KafkaCluster.scala:366)
at org.apache.spark.streaming.kafka.KafkaCluster$$anonfun$checkErrors$1.apply(KafkaCluster.scala:366)
at scala.util.Either.fold(Either.scala:98)
at org.apache.spark.streaming.kafka.KafkaCluster$.checkErrors(KafkaCluster.scala:365)
at org.apache.spark.streaming.kafka.KafkaUtils$.getFromOffsets(KafkaUtils.scala:222)
at org.apache.spark.streaming.kafka.KafkaUtils$.createDirectStream(KafkaUtils.scala:484)
at org.apache.spark.streaming.kafka.KafkaUtils$.createDirectStream(KafkaUtils.scala:607)
at org.apache.spark.streaming.kafka.KafkaUtils.createDirectStream(KafkaUtils.scala)
at SparkStreaming.main(SparkStreaming.java:41)
</code>```

Are there a specified parameters or something from kafkaParams to get spark streaming authenticated to Kafka?

back then, I added the sasl plaintext security parameter in the Kafka broker server.properties.

```<code>authorizer.class.name=kafka.security.auth.SimpleAclAuthorizer
listeners=SASL_PLAINTEXT://:9092
security.inter.broker.protocol=SASL_PLAINTEXT
sasl.mechanism.inter.broker.protocol=PLAIN
sasl.enabled.mechanisms=PLAIN
super.users=User:admin
</code>```

here's also my kafka_jaas_server.conf

```<code>KafkaServer {
    org.apache.kafka.common.security.plain.PlainLoginModule required
    username="admin"
    password="admin1!"
    user_admin="admin1!"
    user_aldys="admin1!";
};
</code>```

and this is my kafka_jaas_client.conf

```<code>KafkaClient {
    org.apache.kafka.common.security.plain.PlainLoginModule required
    username="aldys"
    password="admin1!";
};
</code>```

i also include my jaas server config when start the kafka broker. via editing the kafka-server-start.sh in last line to:

```<code>exec $base_dir/kafka-run-class.sh $EXTRA_ARGS -Djava.security.auth.login.config=/etc/kafka/kafka_jaas_server.conf kafka.Kafka "$@"
</code>```

using this parameter, I can produce and consume to my topic that I set ACLs before.

this is my java code

```<code>import java.util.*;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.spark.SparkConf;
import org.apache.spark.streaming.Duration;
import org.apache.spark.streaming.api.java.JavaDStream;
import org.apache.spark.streaming.api.java.JavaPairInputDStream;
import org.apache.spark.streaming.api.java.JavaStreamingContext;
import org.apache.spark.streaming.kafka.KafkaUtils;

import kafka.serializer.StringDecoder;
import scala.Tuple2;

public class SparkStreaming {

    public static void main(String args[]) throws Exception {
        if (args.length < 2) {
            System.err.println("Usage: SparkStreaming <brokers> <topics>\n" +
                "  <brokers> is a list of one or more Kafka brokers\n" +
                "  <topics> is a list of one or more kafka topics to consume from\n\n");
            System.exit(1);
        }

        String brokers = args[0];
        String topics = args[1];

        Set<String> topicsSet = new HashSet<>(Arrays.asList(topics.split(",")));

        Map<String, String> kafkaParams = new HashMap<>();
        kafkaParams.put("bootstrap.servers", "localhost:9092");
        kafkaParams.put("group.id", "group1");
        kafkaParams.put("auto.offset.reset", "smallest");
        kafkaParams.put("security.protocol", "SASL_PLAINTEXT");

        SparkConf sparkConf = new SparkConf()
                            .setAppName("SparkStreaming")
                            .setMaster("local[2]");
        JavaStreamingContext jssc = new JavaStreamingContext(sparkConf, new Duration(2000));

        JavaPairInputDStream<String, String> messages = KafkaUtils.createDirectStream(
            jssc,
            String.class,
            String.class,
            StringDecoder.class,
            StringDecoder.class,
            kafkaParams,
            topicsSet
        );

        messages.print();

        jssc.start();
        jssc.awaitTermination();
    }
}
</code>```

also here's dependencies im using in my pom.xml

```<code><dependencies>
    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-core_2.11</artifactId>
        <version>2.1.1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-streaming_2.11</artifactId>
        <version>2.1.1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-streaming-kafka_2.11</artifactId>
        <version>1.6.3</version>
    </dependency>
    <dependency>
        <groupId>org.apache.kafka</groupId>
        <artifactId>kafka_2.10</artifactId>
        <version>0.10.2.1</version>
    </dependency>
</dependencies>
</code>```

答:
i've been resolved my problem with following guide from https://spark.apache.org/docs/latest/streaming-kafka-0-10-integration.html.

i replaced my spark-streaming-kafka_2.11 in my pom.xml to spark-streaming-kafka-0-10_2.11 and version 2.11.

based on error logs above in question. Im curious that the error throwed by SimpleConsumer, which SimpleConsumer is determined as an old consumer. Then i replace my pom dependencies as i said above, and change my code into following spark streaming integration guide above. Now i can stream into secured sasl plain kafka.

Body:
I'm getting this error when trying to stream from spark (using Java) to secured Kafka (with SASL PLAINTEXT mechanism).

more detailed error message:

17/07/07 14:38:43 INFO SimpleConsumer: Reconnect due to socket error: java.io.EOFException: Received -1 when reading from a channel, the socket has likely been closed.
Exception in thread "main" org.apache.spark.SparkException: java.io.EOFException: Received -1 when reading from channel, socket has likely been closed.
at org.apache.spark.streaming.kafka.KafkaCluster$$anonfun$checkErrors$1.apply(KafkaCluster.scala:366)
at org.apache.spark.streaming.kafka.KafkaCluster$$anonfun$checkErrors$1.apply(KafkaCluster.scala:366)
at scala.util.Either.fold(Either.scala:98)
at org.apache.spark.streaming.kafka.KafkaCluster$.checkErrors(KafkaCluster.scala:365)
at org.apache.spark.streaming.kafka.KafkaUtils$.getFromOffsets(KafkaUtils.scala:222)
at org.apache.spark.streaming.kafka.KafkaUtils$.createDirectStream(KafkaUtils.scala:484)
at org.apache.spark.streaming.kafka.KafkaUtils$.createDirectStream(KafkaUtils.scala:607)
at org.apache.spark.streaming.kafka.KafkaUtils.createDirectStream(KafkaUtils.scala)
at SparkStreaming.main(SparkStreaming.java:41)

Are there a specified parameters or something from kafkaParams to get spark streaming authenticated to Kafka?

back then, I added the sasl plaintext security parameter in the Kafka broker server.properties.

authorizer.class.name=kafka.security.auth.SimpleAclAuthorizer
listeners=SASL_PLAINTEXT://:9092
security.inter.broker.protocol=SASL_PLAINTEXT
sasl.mechanism.inter.broker.protocol=PLAIN
sasl.enabled.mechanisms=PLAIN
super.users=User:admin

here's also my kafka_jaas_server.conf

KafkaServer {
    org.apache.kafka.common.security.plain.PlainLoginModule required
    username="admin"
    password="admin1!"
    user_admin="admin1!"
    user_aldys="admin1!";
};

and this is my kafka_jaas_client.conf

KafkaClient {
    org.apache.kafka.common.security.plain.PlainLoginModule required
    username="aldys"
    password="admin1!";
};

i also include my jaas server config when start the kafka broker. via editing the kafka-server-start.sh in last line to:

exec $base_dir/kafka-run-class.sh $EXTRA_ARGS -Djava.security.auth.login.config=/etc/kafka/kafka_jaas_server.conf kafka.Kafka "$@"

using this parameter, I can produce and consume to my topic that I set ACLs before.

this is my java code

import java.util.*;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.apache.spark.SparkConf;
import org.apache.spark.streaming.Duration;
import org.apache.spark.streaming.api.java.JavaDStream;
import org.apache.spark.streaming.api.java.JavaPairInputDStream;
import org.apache.spark.streaming.api.java.JavaStreamingContext;
import org.apache.spark.streaming.kafka.KafkaUtils;

import kafka.serializer.StringDecoder;
import scala.Tuple2;

public class SparkStreaming {

    public static void main(String args[]) throws Exception {
        if (args.length < 2) {
            System.err.println("Usage: SparkStreaming <brokers> <topics>\n" +
                "  <brokers> is a list of one or more Kafka brokers\n" +
                "  <topics> is a list of one or more kafka topics to consume from\n\n");
            System.exit(1);
        }

        String brokers = args[0];
        String topics = args[1];

        Set<String> topicsSet = new HashSet<>(Arrays.asList(topics.split(",")));

        Map<String, String> kafkaParams = new HashMap<>();
        kafkaParams.put("bootstrap.servers", "localhost:9092");
        kafkaParams.put("group.id", "group1");
        kafkaParams.put("auto.offset.reset", "smallest");
        kafkaParams.put("security.protocol", "SASL_PLAINTEXT");

        SparkConf sparkConf = new SparkConf()
                            .setAppName("SparkStreaming")
                            .setMaster("local[2]");
        JavaStreamingContext jssc = new JavaStreamingContext(sparkConf, new Duration(2000));

        JavaPairInputDStream<String, String> messages = KafkaUtils.createDirectStream(
            jssc,
            String.class,
            String.class,
            StringDecoder.class,
            StringDecoder.class,
            kafkaParams,
            topicsSet
        );

        messages.print();

        jssc.start();
        jssc.awaitTermination();
    }
}

also here's dependencies im using in my pom.xml

<dependencies>
    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-core_2.11</artifactId>
        <version>2.1.1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-streaming_2.11</artifactId>
        <version>2.1.1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-streaming-kafka_2.11</artifactId>
        <version>1.6.3</version>
    </dependency>
    <dependency>
        <groupId>org.apache.kafka</groupId>
        <artifactId>kafka_2.10</artifactId>
        <version>0.10.2.1</version>
    </dependency>
</dependencies>


问:
How to sum items in updatecursor with None data types
Working in python with ESRI's arcpy, I'm trying to sum values across multiple fields with an arcpy updateCursor . I'm trying to convert the None items to an 0. However, I can't figure out a way to convert the None items.  I'm open to anything.

```<code>with arcpy.da.UpdateCursor(feature_class, score_fields) as cursor:
    for row in cursor:
        [0 if x==None else x+4 for x in row]
        print row
        row[len(score_fields)-1] = sum(row[i] for i in range(len(score_fields)))
        cursor.updateRow(row)
</code>```

Returns:

```<code>[-4, -4, None, None, -4, None, -4, -4]
</code>```

with error:

```<code>TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'
</code>```

Thanks!

答:
You can use an if statement to filter the None values in your list:

```<code>sum(row[i] for i in range(len(score_fields)) if row[i] is not None)
</code>```

Body:
Working in python with ESRI's arcpy, I'm trying to sum values across multiple fields with an arcpy updateCursor . I'm trying to convert the None items to an 0. However, I can't figure out a way to convert the None items.  I'm open to anything.

with arcpy.da.UpdateCursor(feature_class, score_fields) as cursor:
    for row in cursor:
        [0 if x==None else x+4 for x in row]
        print row
        row[len(score_fields)-1] = sum(row[i] for i in range(len(score_fields)))
        cursor.updateRow(row)

Returns:

[-4, -4, None, None, -4, None, -4, -4]

with error:

TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'

Thanks!

Body:
You can use an if statement to filter the None values in your list:

sum(row[i] for i in range(len(score_fields)) if row[i] is not None)


答:
You should update row by assigning the result of the list comprehension to row:

```<code>for row in cursor:
    row = [0 if x is None else x+4 for x in row]
</code>```

Also, note that since there is only one None object, better to test with is than use ==; more Pythonic, more performant.

Title: How to sum items in updatecursor with None data types

Body:
You should update row by assigning the result of the list comprehension to row:

for row in cursor:
    row = [0 if x is None else x+4 for x in row]

Also, note that since there is only one None object, better to test with is than use ==; more Pythonic, more performant.


问:
Atom build from source
I'm trying to achieve the same effect used here and modify my files in Atom.

What does the below mean and how do I implement this?

```<code>So you'll have to build from source.
</code>```

答: You have to download Atom source files from Github and follow the instructions here according to your OS.</p>

Title: Atom build from source

Body:
I'm trying to achieve the same effect used here and modify my files in Atom.

What does the below mean and how do I implement this?

So you'll have to build from source.


问:
How to get JobParameter and JobExecutionContext in the ItemWriter?
I want to retrieve JobParameter and JobExecutionContext object in my ItemWriter class.
How to  proceed?

I tried implementing StepExecutionListener through which I am just calling the parent class methods.  But it is not succeeding.

Thanks in advance.

答:
If you are using Spring Configuration file, you can access the StepExecution object with:

```<code><bean id="aaaReader" class="com.AAAReader" scope="step">
    <property name="stepExecution" value="#{stepExecution}" />
</bean>
</code>```

In AAAReader class you need to create the proper field and a setter:

```<code>private StepExecution stepExecution;

public void setStepExecution(final StepExecution stepExecution) {
    this.stepExecution = stepExecution;
}
</code>```

Same for Processor and Writer classes.

Body:
If you are using Spring Configuration file, you can access the StepExecution object with:

<bean id="aaaReader" class="com.AAAReader" scope="step">
    <property name="stepExecution" value="#{stepExecution}" />
</bean>

In AAAReader class you need to create the proper field and a setter:

private StepExecution stepExecution;

public void setStepExecution(final StepExecution stepExecution) {
    this.stepExecution = stepExecution;
}

Same for Processor and Writer classes.