问:
How to deduce contiguous memory from iterator
Somehow, the native stl::copy() algorithm on VC++ (Dinkumware) figures out that it can use memcpy() on data that is trivially copy-able. Is it possible for a mere mortal to do that? - assuming each element is_trivially_copyable.

Does random_access_iterator imply contiguous memory? The standard is not clear to me.

So, if all you have in a template is an iterator or two, is it possible to deduce at compile-time that the underlying array can be copied with memcpy(), and if so how?

EDIT - Here's my motivation. I have a routine that moves a block of data rather than copying it. To get speed when the data are memmove-able, I've made it call stl::copy sometimes. I was wondering if that is the only way. (As a kid, I would always try this at home.)

```<code>// Move a range of values
template<class Ptr, class Ptr2>
inline Ptr2 move(Ptr src, Ptr end, Ptr2 dest) {
    using value_type = std::iterator_traits<Ptr>::value_type;
    if constexpr (std::is_trivially_copyable_v<value_type>) {
        return std::copy(src, end, dest);
    } else {
        while (src != end) {
            *dest = std::move(*src);
            ++src; ++dest;
        }
    }
    return dest;
}
</code>```

EDIT: Kudos to zett42 for finding this related question: Contiguous iterator detection I can't explain how I missed it.

EDIT More: After going down many twisty little passages all the same, I discovered that Dinkum uses secret tags for iterators that are in with the in-crowd, e.g. _Really_trivial_ptr_iterator_tag. So prospects look dim.

My $0.02 worth: It was a beginner's mistake to make iterator_category an ad-hoc type rather than busting out the various traits, like "points_into_contiguous_memory," etc... Since random_access_iterator is an ad-hoc type denoted only with a tag, it cannot be subtyped without breaking legacy applications.  So the committee is now kind of stuck. Time to start over, I say.

Oh well.

答:
A) No. It just means that a valid mapping of the kind F(iterator +/- n) = iterator.next/prev.....n exists. This does not imply contiguous allocation at all.  ( bounds do apply)

B) No. It depends on the implementation. For instance, you might not know what kind of data structure might be received if there is a 2 level of indirection.

The good news?, you need not bother at all. Between the cache and the branch prediction that happens, you would not need to optimize it at all. During run time, The cache line will be filled with the block of contiguous memory you intend to copy, thus it is going to be very fast, and memmove or memcpy will not help much.

You do not guarantee much with modern processors that are going to pipeline your instructions at run time, and they would know if it is contiguous or not.

Body:
Somehow, the native stl::copy() algorithm on VC++ (Dinkumware) figures out that it can use memcpy() on data that is trivially copy-able. Is it possible for a mere mortal to do that? - assuming each element is_trivially_copyable.

Does random_access_iterator imply contiguous memory? The standard is not clear to me.

So, if all you have in a template is an iterator or two, is it possible to deduce at compile-time that the underlying array can be copied with memcpy(), and if so how?

EDIT - Here's my motivation. I have a routine that moves a block of data rather than copying it. To get speed when the data are memmove-able, I've made it call stl::copy sometimes. I was wondering if that is the only way. (As a kid, I would always try this at home.)

// Move a range of values
template<class Ptr, class Ptr2>
inline Ptr2 move(Ptr src, Ptr end, Ptr2 dest) {
    using value_type = std::iterator_traits<Ptr>::value_type;
    if constexpr (std::is_trivially_copyable_v<value_type>) {
        return std::copy(src, end, dest);
    } else {
        while (src != end) {
            *dest = std::move(*src);
            ++src; ++dest;
        }
    }
    return dest;
}

EDIT: Kudos to zett42 for finding this related question: Contiguous iterator detection I can't explain how I missed it.

EDIT More: After going down many twisty little passages all the same, I discovered that Dinkum uses secret tags for iterators that are in with the in-crowd, e.g. _Really_trivial_ptr_iterator_tag. So prospects look dim.

My $0.02 worth: It was a beginner's mistake to make iterator_category an ad-hoc type rather than busting out the various traits, like "points_into_contiguous_memory," etc... Since random_access_iterator is an ad-hoc type denoted only with a tag, it cannot be subtyped without breaking legacy applications.  So the committee is now kind of stuck. Time to start over, I say.

Oh well.


来源: stackexchange

问:
Search Form Styling CSS
So I have styled my search form on the top banner of my blog, but when I leave the home page to another page the background image search icon disappears!  Any suggestions as to why this is happening? Thanks ;-) http://demo.boxofficeboxing.co.uk</p>

```<code>#s {
   padding:8px 6px;
   background:rgba(0, 0, 0, 0);
   border-style: solid;
   border-color: #fff;
   border-width: 1px 0px 1px 1px;
   font-family:open sans;
   font-size:14px;
   color: #fff;
   }
   #searchsubmit {
   cursor:pointer;
   position:relative;
   padding:8px 16px;
   left:-9px;
   border-style: solid;
   border-color: #fff;
   border-width: 1px 1px 1px 0px;
   background-color: #a88f4b;
   font-family:open sans;
   font-size:14px;
   background-image: url('wp-content/uploads/2017/12/search.png');
   background-position: center center;
   background-repeat:no-repeat;
   text-indent: -9999px;
   }
   ::-webkit-input-placeholder { /* Chrome/Opera/Safari */
   color: white;
   }
   ::-moz-placeholder { /* Firefox 19+ */
   color: white;
   }
   :-ms-input-placeholder { /* IE 10+ */
   color: white;
   }
   :-moz-placeholder { /* Firefox 18- */
   color: white;
   }
   input:focus {
   outline: none;
   }
</code>```

答: Your reference to the image is relative, so when you go to another page, it's reference is wrong.  Make your background-image URL value absolute.

ContentLicense: CC BY-SA 3.0

Title: Search Form Styling CSS

Body:
So I have styled my search form on the top banner of my blog, but when I leave the home page to another page the background image search icon disappears!  Any suggestions as to why this is happening? Thanks ;-) http://demo.boxofficeboxing.co.uk

#s {
   padding:8px 6px;
   background:rgba(0, 0, 0, 0);
   border-style: solid;
   border-color: #fff;
   border-width: 1px 0px 1px 1px;
   font-family:open sans;
   font-size:14px;
   color: #fff;
   }
   #searchsubmit {
   cursor:pointer;
   position:relative;
   padding:8px 16px;
   left:-9px;
   border-style: solid;
   border-color: #fff;
   border-width: 1px 1px 1px 0px;
   background-color: #a88f4b;
   font-family:open sans;
   font-size:14px;
   background-image: url('wp-content/uploads/2017/12/search.png');
   background-position: center center;
   background-repeat:no-repeat;
   text-indent: -9999px;
   }
   ::-webkit-input-placeholder { /* Chrome/Opera/Safari */
   color: white;
   }
   ::-moz-placeholder { /* Firefox 19+ */
   color: white;
   }
   :-ms-input-placeholder { /* IE 10+ */
   color: white;
   }
   :-moz-placeholder { /* Firefox 18- */
   color: white;
   }
   input:focus {
   outline: none;
   }


问:
Select the number of days a record is present within a certain year/month
In sql server I have a table with start and end dates for job postings. Given a month and a year by the user I need to find the amount of days between the start and end date that fall in the given year/month for that posting.

So if the posting Start Date is 2010/11/15 and End Date is 2010/12/05
Then output should be:

```<code>November  16 days
December  5 days
Total     21 days
</code>```

I've been beating my head against the wall with this one and am fresh out of ideas.

答:
You want to use DateDiff

DateDiff("d",[StartDate],[EndDate])

the d above will count days.

ContentLicense: CC BY-SA 2.5

Body:
In sql server I have a table with start and end dates for job postings. Given a month and a year by the user I need to find the amount of days between the start and end date that fall in the given year/month for that posting.

So if the posting Start Date is 2010/11/15 and End Date is 2010/12/05
Then output should be:

November  16 days
December  5 days
Total     21 days

I've been beating my head against the wall with this one and am fresh out of ideas.


问:
In Python, is there a method to print lists into a string using .format notation?
A simple Madlibs exercise:

```<code>STORY = "This morning I woke up and felt %s because %s was going to finally %s over the big %s %s."

WORD_types = ('an adjective','a pronoun','a verb','an adjective','a noun')

WORD_values = []

for s in WORD_types:
  print "Please give {}.".format(s)
  s = raw_input()
  WORD_values.append(s)

print STORY % tuple(WORD_values)
</code>```

It's there a way to accomplish that last line with .format notation?

```<code>STORY = "This morning I woke up and felt {} because {} was going to finally {} over the big {} {}."

WORD_types = ('an adjective','a pronoun','a verb','an adjective','a noun')

WORD_values = []

for s in WORD_types:
  print "Please give {}.".format(s)
  s = raw_input()
  WORD_values.append(s)

print STORY.format(WORD_values)
</code>```

This kicks back the following error:

```<code>Traceback (most recent call last):
  File "Madlibs.py", line 12, in <module>
    print STORY.format(WORD_values)
IndexError: tuple index out of range
</code>```

答:
You can use * to unpack the list:

```<code>print STORY.format(*WORD_values)
</code>```

Example Output:

```<code>Please give an adjective
 optimistic
Please give a pronoun
 I
Please give a verb
 drive
Please give an adjective
 scary
Please give a noun
 hill
This morning I woke up and felt optimistic because I was going to finally drive over the big scary hill.
</code>```

Here is the relevant documentation: Unpacking Argument Lists and Format examples.

Body:
A simple Madlibs exercise:

STORY = "This morning I woke up and felt %s because %s was going to finally %s over the big %s %s."

WORD_types = ('an adjective','a pronoun','a verb','an adjective','a noun')

WORD_values = []

for s in WORD_types:
  print "Please give {}.".format(s)
  s = raw_input()
  WORD_values.append(s)

print STORY % tuple(WORD_values)

It's there a way to accomplish that last line with .format notation?

STORY = "This morning I woke up and felt {} because {} was going to finally {} over the big {} {}."

WORD_types = ('an adjective','a pronoun','a verb','an adjective','a noun')

WORD_values = []

for s in WORD_types:
  print "Please give {}.".format(s)
  s = raw_input()
  WORD_values.append(s)

print STORY.format(WORD_values)

This kicks back the following error:

Traceback (most recent call last):
  File "Madlibs.py", line 12, in <module>
    print STORY.format(WORD_values)
IndexError: tuple index out of range

Body:
You can use * to unpack the list:

print STORY.format(*WORD_values)

Example Output:

Please give an adjective
 optimistic
Please give a pronoun
 I
Please give a verb
 drive
Please give an adjective
 scary
Please give a noun
 hill
This morning I woke up and felt optimistic because I was going to finally drive over the big scary hill.

Here is the relevant documentation: Unpacking Argument Lists and Format examples.


问:
How to fix IE rendering of border-radius combined with box-shadow?
Does anybody have an idea on how to "fix" the rendering in IE 9 and 10 of a combination of box-shadow and border-radius?

It's especially noticeable when using inset shadows. The radius of the shadow is very different in IE compared to webkit/gecko...

In this image you can see the problem. On the left is a button with an inset box-shadow, on the right without box-shadow. (don't mind the different font-rendering)

Here's the code used: http://dabblet.com/gist/5450815

答:
You can safely use inset box shadows to emulate borders in modern browsers, but IE mis-renders the radius. You can work around this by letting IE fall back to the default "outset" style.

```<code>.Button {
  color: #0ac;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: inset 0 0 0 2px #0ac;
}

/* IE media query hack */
@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {
  .Button {
    box-shadow: 0 0 0 2px #0ac;
  }
}
</code>```

Body:
You can safely use inset box shadows to emulate borders in modern browsers, but IE mis-renders the radius. You can work around this by letting IE fall back to the default "outset" style.

.Button {
  color: #0ac;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: inset 0 0 0 2px #0ac;
}

/* IE media query hack */
@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {
  .Button {
    box-shadow: 0 0 0 2px #0ac;
  }
}


答: The url wp-content/uploads/2017/12/search.png supplied to background-image is relative, so while it works on your homepage, if for example you navigate to the /news/ section, becomes http://demo.boxofficeboxing.co.uk/news/wp-content/uploads/2017/12/search.png instead of http://demo.boxofficeboxing.co.uk/wp-content/uploads/2017/12/search.png. Just give it an absolute url complete with http://... and it should be fine.

Title: Search Form Styling CSS


问:
mysql string compares - md5 faster?
Would an indexed compare of two string fields be faster if those fields were md5'd during the import, and the md5 field used in the compare instead of the source string field?</p>

答:
If the source string is larger than the md5sum (32 bytes if you hex encode it), yes, using the md5sum would be faster.

While a low probability, you rish hash collision uising the md5 sum for equality though. i.e. 2 fields might comapare as equal while they're not, so think twice about that.

Title: mysql string compares - md5 faster?


问:
How to align a Chunk Left and Right Side
i want to align the Chunk Left and Right side. Also the each Chunk have different format you can see in image.

i try the below code:

```<code>Chunk invoiceid = new Chunk("Invoice ID: ", font9BoldDARK_GRAY);
Chunk invoiceidvalue = new Chunk("value from database", font10NoramlBlack);
Chunk inoicdate = new Chunk("Invoice Date: ", font9BoldDARK_GRAY);
Chunk inoicedatevalue = new Chunk(new SimpleDateFormat("MMMM dd yyyy").format(new Date()), font10NoramlBlack);// get From database

    Paragraph invoiceParagraph = new Paragraph();
    invoiceParagraph.setTabSettings(new TabSettings(325f));
    invoiceParagraph.add(invoiceid);
    invoiceParagraph.add(invoiceidvalue);

    invoiceParagraph1.add(Chunk.TABBING);

    invoiceParagraph1.add(inoicdate1);
    invoiceParagraph1.add(inoicedatevalue1);
    invoiceParagraph1.setAlignment(Element.ALIGN_JUSTIFIED);
    pdfdocument.add(invoiceParagraph1);
</code>```

which gives me result  the Right side Chunk not in well format.

but i want align the like
can you please help me.

答:
The correct way to do this, is to use iText 7. Read chapter 3 of the building blocks tutorial to discover how to create a PDF that looks like this:

The code to achieve this, is amazingly simple:

```<code>public void createPdf(String dest) throws IOException {
    // create a low-level document
    PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
    // create a high-level document
    Document document = new Document(pdf);
    // create a TabStop array
    List<TabStop> tabstops = new ArrayList<TabStop>();
    // don't forget to make a tab stop that aligns to the right
    tabstops.add(new TabStop(325, TabAlignment.RIGHT));
    // add paragraphs with Tab objects to the high-level document
    document.add(new Paragraph().addTabStops(tabstops)
            .add("Text to the left").add(new Tab()).add("Text to the right"));
    document.add(new Paragraph().addTabStops(tabstops)
            .add("ABCD").add(new Tab()).add("EFGH"));
    document.add(new Paragraph().addTabStops(tabstops)
            .add("01234").add(new Tab()).add("56789"));
    document.add(new Paragraph().addTabStops(tabstops)
            .add("iText 5 is old").add(new Tab()).add("iText 7 is new"));
    // close the document
    document.close();
}
</code>```

Before you say I don't recognize that code, let me tell you that you are right: iText was completely rewritten. The code is now more intuitive to create, and easier to read.

Update: you are using the old iText 5 version that is no longer supported for free users (only for paying customers). As explained in the 2009 book "iText in Action - Second Edition", you created glue like this:

```<code>Chunk glue = new Chunk(new VerticalPositionMark())
</code>```

You then used this glue in a Paragraph like this:

```<code>Paragraph p = new Paragraph();
p.add("Text to the left");
p.add(glue);
p.add("Text to the right");
</code>```

This way, you can indeed avoid having to use tabs in iText 5.

Body:
i want to align the Chunk Left and Right side. Also the each Chunk have different format you can see in image.

i try the below code:

Chunk invoiceid = new Chunk("Invoice ID: ", font9BoldDARK_GRAY);
Chunk invoiceidvalue = new Chunk("value from database", font10NoramlBlack);
Chunk inoicdate = new Chunk("Invoice Date: ", font9BoldDARK_GRAY);
Chunk inoicedatevalue = new Chunk(new SimpleDateFormat("MMMM dd yyyy").format(new Date()), font10NoramlBlack);// get From database

    Paragraph invoiceParagraph = new Paragraph();
    invoiceParagraph.setTabSettings(new TabSettings(325f));
    invoiceParagraph.add(invoiceid);
    invoiceParagraph.add(invoiceidvalue);

    invoiceParagraph1.add(Chunk.TABBING);

    invoiceParagraph1.add(inoicdate1);
    invoiceParagraph1.add(inoicedatevalue1);
    invoiceParagraph1.setAlignment(Element.ALIGN_JUSTIFIED);
    pdfdocument.add(invoiceParagraph1);

which gives me result  the Right side Chunk not in well format.

but i want align the like
can you please help me.

Body:
The correct way to do this, is to use iText 7. Read chapter 3 of the building blocks tutorial to discover how to create a PDF that looks like this:

The code to achieve this, is amazingly simple:

public void createPdf(String dest) throws IOException {
    // create a low-level document
    PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
    // create a high-level document
    Document document = new Document(pdf);
    // create a TabStop array
    List<TabStop> tabstops = new ArrayList<TabStop>();
    // don't forget to make a tab stop that aligns to the right
    tabstops.add(new TabStop(325, TabAlignment.RIGHT));
    // add paragraphs with Tab objects to the high-level document
    document.add(new Paragraph().addTabStops(tabstops)
            .add("Text to the left").add(new Tab()).add("Text to the right"));
    document.add(new Paragraph().addTabStops(tabstops)
            .add("ABCD").add(new Tab()).add("EFGH"));
    document.add(new Paragraph().addTabStops(tabstops)
            .add("01234").add(new Tab()).add("56789"));
    document.add(new Paragraph().addTabStops(tabstops)
            .add("iText 5 is old").add(new Tab()).add("iText 7 is new"));
    // close the document
    document.close();
}

Before you say I don't recognize that code, let me tell you that you are right: iText was completely rewritten. The code is now more intuitive to create, and easier to read.

Update: you are using the old iText 5 version that is no longer supported for free users (only for paying customers). As explained in the 2009 book "iText in Action - Second Edition", you created glue like this:

Chunk glue = new Chunk(new VerticalPositionMark())

You then used this glue in a Paragraph like this:

Paragraph p = new Paragraph();
p.add("Text to the left");
p.add(glue);
p.add("Text to the right");

This way, you can indeed avoid having to use tabs in iText 5.


问:
Fill React app with WordPress REST API
I just finished to learn react.js basics, and now I'm building an app that could get datas from a WordPress installation, via wp-rest-api.

I succeed in getting datas with an ajax call in a non-react script, and now I'm trying to implement this into my react app.

I've got only one react component that is App.js, and I'd like fill the App state with datas from WordPress, but failed...

This is my app.js code :

```<code>import React from 'react';

class App extends React.Component {

    state = {
        posts : {}
    }

    render() {

        const xhr = new XMLHttpRequest();
        xhr.open('GET', 'http://localhost/overwatch/wp-json/wp/v2/posts');
        xhr.addEventListener('readystatechange', function(){
            if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
                console.log(JSON.parse(xhr.response));
            }
        });
        xhr.send(null);

        return(
            <h1>App root</h1>
        );
    }
}

export default App;
</code>```

The console do display expected datas, but all what I tried to push them in the app state failed.
Could someone help please ?
Thank you.

答:
You have to use setState method to store data in to the react state. And also it's advised to make Ajax calls on componentDidMount lifecycle method. Not inside render method.</p>

```<code>componentDidMount(){
  const xhr = new XMLHttpRequest();
  xhr.open('GET', 'http://localhost/overwatch/wp-json/wp/v2/posts');
  xhr.addEventListener('readystatechange', function(){
    if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
    let data = JSON.parse(xhr.response);
      this.setState({
        posts: data
        }, function(){
          console.log(this.state.posts)
      })
    }
  });
}
</code>```

Title: Fill React app with WordPress REST API

Body:
I just finished to learn react.js basics, and now I'm building an app that could get datas from a WordPress installation, via wp-rest-api.

I succeed in getting datas with an ajax call in a non-react script, and now I'm trying to implement this into my react app.

I've got only one react component that is App.js, and I'd like fill the App state with datas from WordPress, but failed...

This is my app.js code :

import React from 'react';

class App extends React.Component {

    state = {
        posts : {}
    }

    render() {

        const xhr = new XMLHttpRequest();
        xhr.open('GET', 'http://localhost/overwatch/wp-json/wp/v2/posts');
        xhr.addEventListener('readystatechange', function(){
            if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
                console.log(JSON.parse(xhr.response));
            }
        });
        xhr.send(null);

        return(

App root

        );
    }
}

export default App;

The console do display expected datas, but all what I tried to push them in the app state failed.
Could someone help please ?
Thank you.

Body:
You have to use setState method to store data in to the react state. And also it's advised to make Ajax calls on componentDidMount lifecycle method. Not inside render method.

componentDidMount(){
  const xhr = new XMLHttpRequest();
  xhr.open('GET', 'http://localhost/overwatch/wp-json/wp/v2/posts');
  xhr.addEventListener('readystatechange', function(){
    if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
    let data = JSON.parse(xhr.response);
      this.setState({
        posts: data
        }, function(){
          console.log(this.state.posts)
      })
    }
  });
}


问:
How to open an app with the iOS11 integrated qrcode reader
I want to use the new in-build qrcode reader in the iOS camera to open an app.

I cannot find the right documentation in the API.

Thanks for your help

Best Regards
Christian

答:
I'v just tested with various URLs. It seems if the URL is http the Camera app opens Mobile Safari. If you know the target app URL (which is declared in the Info.plist) you can open the app with QR codes.

(ex) youtube://user/Apple --> Opens Youtube app


问:
Get data of specific node element on click
I'm trying to get specific data depending on which node element the user is clicking. I have 4 elements that I have targeted using the querySelectorAll code. What I want to accomplish is that if I click the first element I will console.log that specific data, and if I select the third element I will get that data logged. I've tried a couple of things, but haven't got it to work yet.

function selectedSplit() {
 var macroSplits = document.querySelectorAll(".card");
  console.log(macroSplits[0].childNodes[3].childNodes[1].innerHTML);
}```

答:
event.target has the clicked element:

d.onclick = e => console.log(e.target)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id=d>
 <button><b>b</b></button>
 <button><i>i</i></button>
 <button><u>u</u></button>
 <button><s>s</s></button>
</div></code>```

Body:
event.target has the clicked element:

d.onclick = e => console.log(e.target)

<div id=d>
 <button><b>b</b></button>
 <button><i>i</i></button>
 <button><u>u</u></button>
 <button><s>s</s></button>
</div>


问:
final Util Class Static vs Singleton Class
Currently I'm trying to Implement a utility Class that generates an invoice in a PDF Format and I predict that I'll need spring beans to be injected in my Utility Class Afterwards.

But I don't need the class to be instanciated, I only need the methods. So for me it's a dilemma

So I did some research and I still haven't made my mind If I want a spring singleton bean or .

Spring Singleton : Source

```<code>@Service
public class Singleton {

private static AtomicReference<Singleton> INSTANCE = new AtomicReference<Singleton>();

public Singleton() {
    final Singleton previous = INSTANCE.getAndSet(this);
    if(previous != null)
        throw new IllegalStateException("Second singleton " + this + " created after " + previous);
}

public static Singleton getInstance() {
    return INSTANCE.get();
}
}
</code>```

Or A final Class :

```<code> public final InvoiceUtil {

  private InvoiceUtil() {}

  public static String convertToPDF (Template template) {
    //Do the work
  }

 }
</code>```

but with the second approach, my class isn't managed by Spring so I can not inject beans to it.

Make me undrestand !! :p

答:
If you use a Spring bean, do not implement Spring Service as a Singleton with getInstance(). Just add @Service and Spring will only instantiate it once.

You can use static methods, and later pass any dependency also to these methods (if those are few dependencies):

```<code>public static String convertToPDF (Template template, NeededHelper helper) {
     ...
}
</code>```

Body:
Currently I'm trying to Implement a utility Class that generates an invoice in a PDF Format and I predict that I'll need spring beans to be injected in my Utility Class Afterwards.

But I don't need the class to be instanciated, I only need the methods. So for me it's a dilemma

So I did some research and I still haven't made my mind If I want a spring singleton bean or .

Spring Singleton : Source

@Service
public class Singleton {

private static AtomicReference<Singleton> INSTANCE = new AtomicReference<Singleton>();

public Singleton() {
    final Singleton previous = INSTANCE.getAndSet(this);
    if(previous != null)
        throw new IllegalStateException("Second singleton " + this + " created after " + previous);
}

public static Singleton getInstance() {
    return INSTANCE.get();
}
}

Or A final Class :

 public final InvoiceUtil {

  private InvoiceUtil() {}

  public static String convertToPDF (Template template) {
    //Do the work
  }

 }

but with the second approach, my class isn't managed by Spring so I can not inject beans to it.

Make me undrestand !! :p

Body:
If you use a Spring bean, do not implement Spring Service as a Singleton with getInstance(). Just add @Service and Spring will only instantiate it once.

You can use static methods, and later pass any dependency also to these methods (if those are few dependencies):

public static String convertToPDF (Template template, NeededHelper helper) {
     ...
}


问:
How to use SVProgressHUD in both ios app and its extension
I have a project of an iOS app and its share extension using libraries like Alamofire and FileKit. Everything was working perfectly with the following Podfile:

```<code>target 'myApp' do
  use_frameworks!
  pod 'BRYXBanner'
end
target 'myAppShareExtension' do
  use_frameworks!
  pod 'FileKit', '~> 4.0.1'
  pod 'Alamofire', '~> 4.4'
end
</code>```

Then, I wanted to use SVProgressHUD. First, I just added it to the main app and everything was okay. The problems began when I wanted to use it also in the extension. Since then, I changed the Podfile several times and none allowed me to have it in both the app and the extension. Worse, I cannot even use it again in the main app. As soon as I add it to the Podfile, my app fails to compile. Even Alamofire and FileKit cannot compile anymore.

Here is my new Podfile, the only one that does not generate any error during pod install.

```<code>platform :ios, '10.2'
use_frameworks!
target 'myApp' do
       target 'myAppShareExtension' do
                pod 'SVProgressHUD', :git => 'https://github.com/SVProgressHUD/SVProgressHUD.git'
                pod 'Alamofire', '~> 4.0'
                pod 'FileKit', '~> 4.0.1'
       end
end
</code>```

When I try to compile, I have the following errors, even without trying to import SVProgressHUD nor using it:

```<code>'sharedApplication' is unavailable: not available on iOS (App Extension) - Use view controller based solutions where appropriate instead.
</code>```

Note that when I use this latter Podfile, my extension target is named Pods-myApp-myAppShareExtension while it should be Pods-myAppShareExtension which makes me think the problem comes from the podfile

If you have any suggestion about the Podfile syntax, the build environment etc, please do not hesitate. I can provide additional information about

Edit: Note that I tried different build settings options and maybe I messed up with something there.

答:
After you see where the error is, you will understand what the problem is.

```<code>#if !defined(SV_APP_EXTENSIONS)
    UIInterfaceOrientation orientation = UIApplication.sharedApplication.statusBarOrientation;
#else
    UIInterfaceOrientation orientation = CGRectGetWidth(self.frame) > CGRectGetHeight(self.frame) ? UIInterfaceOrientationLandscapeLeft : UIInterfaceOrientationPortrait;
#endif
</code>```

Do you see the SV_APP_EXTENSIONS? That means if the target is not an App Extensions, it will compile the above code, if it is, it will compile the under code. So for now, you need it to work in your App Extension target, you need to add the preprocessor macro to your App Extension target.

Body:
I have a project of an iOS app and its share extension using libraries like Alamofire and FileKit. Everything was working perfectly with the following Podfile:

target 'myApp' do
  use_frameworks!
  pod 'BRYXBanner'
end
target 'myAppShareExtension' do
  use_frameworks!
  pod 'FileKit', '~> 4.0.1'
  pod 'Alamofire', '~> 4.4'
end

Then, I wanted to use SVProgressHUD. First, I just added it to the main app and everything was okay. The problems began when I wanted to use it also in the extension. Since then, I changed the Podfile several times and none allowed me to have it in both the app and the extension. Worse, I cannot even use it again in the main app. As soon as I add it to the Podfile, my app fails to compile. Even Alamofire and FileKit cannot compile anymore.

Here is my new Podfile, the only one that does not generate any error during pod install.

platform :ios, '10.2'
use_frameworks!
target 'myApp' do
       target 'myAppShareExtension' do
                pod 'SVProgressHUD', :git => 'https://github.com/SVProgressHUD/SVProgressHUD.git'
                pod 'Alamofire', '~> 4.0'
                pod 'FileKit', '~> 4.0.1'
       end
end

When I try to compile, I have the following errors, even without trying to import SVProgressHUD nor using it:

'sharedApplication' is unavailable: not available on iOS (App Extension) - Use view controller based solutions where appropriate instead.

Note that when I use this latter Podfile, my extension target is named Pods-myApp-myAppShareExtension while it should be Pods-myAppShareExtension which makes me think the problem comes from the podfile

If you have any suggestion about the Podfile syntax, the build environment etc, please do not hesitate. I can provide additional information about

Edit: Note that I tried different build settings options and maybe I messed up with something there.

Body:
After you see where the error is, you will understand what the problem is.

#if !defined(SV_APP_EXTENSIONS)
    UIInterfaceOrientation orientation = UIApplication.sharedApplication.statusBarOrientation;
#else
    UIInterfaceOrientation orientation = CGRectGetWidth(self.frame) > CGRectGetHeight(self.frame) ? UIInterfaceOrientationLandscapeLeft : UIInterfaceOrientationPortrait;
#endif

Do you see the SV_APP_EXTENSIONS? That means if the target is not an App Extensions, it will compile the above code, if it is, it will compile the under code. So for now, you need it to work in your App Extension target, you need to add the preprocessor macro to your App Extension target.


问:
Are there any classification algorithms which target data with a one to many (1:n) relationship?
Has there been any research in the field of data-mining regarding classifying data which has a one to many relationship?

For example of a problem like this, say I am trying to predict which students are going to drop out of university based on their class grades and personal information. Obviously there is a one to many relationship between the students personal information and the grades they achieved in their classes.

Obvious approaches include:

Aggregate - The multiple records could be aggregated together in some way reducing the problem to a basic classification problem. In the case of the student classification, the average of their grades could be combined with their personal data. While this solution is simple, often key information is lost. For example what if most students who take organic chemistry and get below a C- end up dropping out even if their average is above a B+ rating.

Voting - Create multiple classifiers (often weak ones) and have them cast votes to determine the overall class of the data in question. This would be like if two classifiers were built, one for the student's course data and one for their personal data. Each course record would be passed to the course classifier and based on the grade and the course name, the classifier would predict whether the student would drop out using that course record alone. The personal data record would be classified using the personal data classifier. Then all the class record predictions along with the personal information record prediction would be voted together. This voting could be done in a number of different ways, but most likely would take into account how accurate the classifiers are and how certain the classifier was of the vote. Clearly this scheme allows for more complicated classification patterns than aggregation, yet there is a lot of extra complexity involved. Also if the voting is not performed well, accuracy can easily suffer.

So I am looking for other possible solutions to the classification of data with a one to many relationship.

答:
Why wouldn't you treat each grade as a separate feature of the same model?

```<code>student['age'] = 23
student['gender'] = 'male'
 ...
student['grade_in_organic_chemistry'] = 'B+'
student['grade_in_classical_physics'] = 'A-'
</code>```

I guess I'm not seeing why you would want to "aggregate" or join together multiple classifiers when the grades can just be distinct features?

(Please excuse the lame psuedocode above, but just trying to demonstrate my point)

Body:
Why wouldn't you treat each grade as a separate feature of the same model?

student['age'] = 23
student['gender'] = 'male'
 ...
student['grade_in_organic_chemistry'] = 'B+'
student['grade_in_classical_physics'] = 'A-'

I guess I'm not seeing why you would want to "aggregate" or join together multiple classifiers when the grades can just be distinct features?

(Please excuse the lame psuedocode above, but just trying to demonstrate my point)


问:
How to get Pandoc from m Pandoc?
I started to write few programs using the pandoc api ,taking examples  from , https://johnmacfarlane.net/BayHac2014/#/the-pandoc-types , But I am unable to isolate Pandoc from m Pandoc.

```<code>module ImageAttr where
import Text.Pandoc.Builder
import Text.Pandoc.Generic
import Text.Pandoc.Definition
import Text.Pandoc.JSON
import qualified Data.Char as DataChar
import qualified Data.List as DataList
import Data.Either
import Text.Parsec as Parsec
import Text.Pandoc
import qualified Data.Text as T
import qualified Data.Text.IO as TIO

fromRight :: b -> Either a b -> b
fromRight _ (Right b) = b
fromRight b _         = b

fromLeft :: b -> Either b a -> b
fromLeft  _ (Left b)  = b
fromLeft  b _        = b

main :: IO ()
main = do
        result <- runIO $ do
            doc <- readMarkdown def (T.pack "[testing](url)")
            writeRST def doc
        x<-((handleError result))
        print x
</code>```

output is String but I need pandoc ast previously it was Either PandocError Pandoc type , instead I am getting "m Pandoc". How to get Pandoc out of "m Pandoc".

any Thought?
By the way , I am new and still learning haskell.

I am getting error message  as :

```<code>ImageSizeModifer.hs:28:12:
    Couldn't match expected type ‘PandocIO a0’ with actual type ‘IO ()’
    In a stmt of a 'do' block: print ""
    In the second argument of ‘($)’, namely
      ‘do { doc <- readMarkdown def (T.pack "[testing](url)");
            print "" }’
Failed, modules loaded: none.
Prelude T>
</code>```

My problem is I need Pandoc , but I have not much idea how to to get it ? There are new PandocIO and PandocPure , I believe these are new.

答: Have a look at http://pandoc.org/using-the-pandoc-api.html for a basic tutorial on using the pandoc 2.x API.</p>

Title: How to get Pandoc from m Pandoc?

Body:
I started to write few programs using the pandoc api ,taking examples  from , https://johnmacfarlane.net/BayHac2014/#/the-pandoc-types , But I am unable to isolate Pandoc from m Pandoc.

module ImageAttr where
import Text.Pandoc.Builder
import Text.Pandoc.Generic
import Text.Pandoc.Definition
import Text.Pandoc.JSON
import qualified Data.Char as DataChar
import qualified Data.List as DataList
import Data.Either
import Text.Parsec as Parsec
import Text.Pandoc
import qualified Data.Text as T
import qualified Data.Text.IO as TIO

fromRight :: b -> Either a b -> b
fromRight _ (Right b) = b
fromRight b _         = b

fromLeft :: b -> Either b a -> b
fromLeft  _ (Left b)  = b
fromLeft  b _        = b

main :: IO ()
main = do
        result <- runIO $ do
            doc <- readMarkdown def (T.pack "[testing](url)")
            writeRST def doc
        x<-((handleError result))
        print x

output is String but I need pandoc ast previously it was Either PandocError Pandoc type , instead I am getting "m Pandoc". How to get Pandoc out of "m Pandoc".

any Thought?
By the way , I am new and still learning haskell.

I am getting error message  as :

ImageSizeModifer.hs:28:12:
    Couldn't match expected type ‘PandocIO a0’ with actual type ‘IO ()’
    In a stmt of a 'do' block: print ""
    In the second argument of ‘($)’, namely
      ‘do { doc <- readMarkdown def (T.pack "[testing](url)");
            print "" }’
Failed, modules loaded: none.
Prelude T>

My problem is I need Pandoc , but I have not much idea how to to get it ? There are new PandocIO and PandocPure , I believe these are new.


问:
Single FLINK CEP Pattern exist at a Time
Is it possible to have single pattern for a key at a time. For e.g. I want to check if I get 5 events which matches a where condition within 1 min window and if I get 10 such events with in a min, I should get 2 alerts but i am getting 6 alerts. It is because every event triggers a new pattern. Can we have a single pattern instance at a time for a key.</p>

答: It sounds like you have similar problem I had: I do not want the same event to participate in more than one sliding window. I was able to achieve that by using AfterMatchSkipStrategy.skipPastLastEvent(). This is available in 1.4. Hope this helps!</p>


问:
How to create WinRAR, RAR file via command line with a certain profile
I'm referring to the profiles visible in the GUI version of the application. Can these be accessed via command line? I'm trying to create a RAR file via scheduled batch script. Thank you very much.

答:
As per documentation provided in WinRAR manual use -cp <name> switch to select compression profile.

Here is a cite from the documentation:

Using this switch you can load settings stored in WinRAR compression profile. You need to specify a profile name as switch parameter. If profile stores selected file names, WinRAR will compress both files specified in the command line and stored in profile. If profile contains an archive name, it will be used in archiving and you should not specify another archive name in command line.

Archive *.txt files using settings from "My Texts" compression profile by using:

```<code>WinRAR a "-cpMy Texts" texts *.txt
</code>```

Body:
As per documentation provided in WinRAR manual use -cp <name> switch to select compression profile.

Here is a cite from the documentation:

Using this switch you can load settings stored in WinRAR compression profile. You need to specify a profile name as switch parameter. If profile stores selected file names, WinRAR will compress both files specified in the command line and stored in profile. If profile contains an archive name, it will be used in archiving and you should not specify another archive name in command line.

Archive *.txt files using settings from "My Texts" compression profile by using:

WinRAR a "-cpMy Texts" texts *.txt


问:
How can I pass a variable to a URL?
I'm trying to send an email with a link in the body that contains a value retrieved from Firebase. I am successfully retrieving the value but I do not know how to append it to the link that is already listed.
Here is the code:

```<code>sendinvite() {
      var user = firebase.auth().currentUser;
      var uid = user.uid;

      firebase.database().ref('/userlist/' + uid + '/' + 'hashKey').once('value').then(function(snapshot) {
        var hashKey = (snapshot.val());
        console.log(hashKey)
      });

      var bcc = [];
      for(var e in this.emailinputs){
        if (this.emailinputs[e].email==null || this.emailinputs[e].email=="" || !this.emailinputs[e].email.includes("@") || !this.emailinputs[e].email.includes("."))
        {
          let alert = this.alerCtrl.create({
            title: 'Error!',
            message: 'There was an error with an email address you entered.',
            buttons: ['Ok']
          });
          alert.present()
        }else {
          bcc.push(this.emailinputs[e].email);
        }
      }
      if(bcc.length > 0) {
        let email = {
          bcc: bcc,
          subject: 'Nudget Invite',
          body: '<a href="https://nudget-72ee4.firebaseapp.com/?hashkey='+hashKey+'">Join my grocery list!</a>',
          isHtml: true
        };
        this.emailComposer.open(email);
      }
}
</code>```

I want the variable hashKey to be appended to the URL listed in the body but I'm not sure how to achieve this.

Edit 1

Updated the body to append the variable to the string. I'm not sure where I can place the hashkey from Firebase for it to be referenced properly.

答:
The main problem I see is that you are scoping the 'hashkey' variable to just the firebase...function(snapshot) block.  This should be defined at the top near the 'uid' variable, so that all of this code can reference it.

Then in you snapshot function, remove the 'var' in front of hashkey, so it just sets the existing variable.

Also, be sure to check if 'hashkey' has a non-blank value before sending the email.

HTH,
Jim

Title: How can I pass a variable to a URL?

Body:
I'm trying to send an email with a link in the body that contains a value retrieved from Firebase. I am successfully retrieving the value but I do not know how to append it to the link that is already listed.
Here is the code:

sendinvite() {
      var user = firebase.auth().currentUser;
      var uid = user.uid;

      firebase.database().ref('/userlist/' + uid + '/' + 'hashKey').once('value').then(function(snapshot) {
        var hashKey = (snapshot.val());
        console.log(hashKey)
      });

      var bcc = [];
      for(var e in this.emailinputs){
        if (this.emailinputs[e].email==null || this.emailinputs[e].email=="" || !this.emailinputs[e].email.includes("@") || !this.emailinputs[e].email.includes("."))
        {
          let alert = this.alerCtrl.create({
            title: 'Error!',
            message: 'There was an error with an email address you entered.',
            buttons: ['Ok']
          });
          alert.present()
        }else {
          bcc.push(this.emailinputs[e].email);
        }
      }
      if(bcc.length > 0) {
        let email = {
          bcc: bcc,
          subject: 'Nudget Invite',
          body: 'Join my grocery list!',
          isHtml: true
        };
        this.emailComposer.open(email);
      }
}

I want the variable hashKey to be appended to the URL listed in the body but I'm not sure how to achieve this.

Edit 1

Updated the body to append the variable to the string. I'm not sure where I can place the hashkey from Firebase for it to be referenced properly.


问:
Conduit streaming monad state
I have a conduit pipeline whose monad includes state. At one point I'd like to have a conduit that streams the state to the following ones (this is a simplified version of what I actually need).

But I have trouble making this. The following example only streams the state once, from the yield:

```<code>import Conduit (ConduitM, yield)
import Control.Monad.Except (Except)
import Control.Monad.State.Lazy (StateT, get)

type CondState = String
type CondMonad = StateT CondState (Except String)

passState :: ConduitM i CondState CondMonad ()
passState = do
  state <- get
  yield state
</code>```

If I run

```<code>runExcept $ (runStateT . runConduit $ yieldMany [(1::Int)..] .| passState .| sinkList) "state"
</code>```

I get

```<code>Right (["state"], "state")
</code>```

rather than the infinite list that I'm aiming for in the first tuple position.

In the actual application the state changes as the conduit streams.

Any ideas?

答:
Turns out a solution is something like</p>

```<code>passState = mapMC $ \_ -> do
  state <- get
  return state
</code>```

Title: Conduit streaming monad state

Body:
I have a conduit pipeline whose monad includes state. At one point I'd like to have a conduit that streams the state to the following ones (this is a simplified version of what I actually need).

But I have trouble making this. The following example only streams the state once, from the yield:

import Conduit (ConduitM, yield)
import Control.Monad.Except (Except)
import Control.Monad.State.Lazy (StateT, get)

type CondState = String
type CondMonad = StateT CondState (Except String)

passState :: ConduitM i CondState CondMonad ()
passState = do
  state <- get
  yield state

If I run

runExcept $ (runStateT . runConduit $ yieldMany [(1::Int)..] .| passState .| sinkList) "state"

I get

Right (["state"], "state")

rather than the infinite list that I'm aiming for in the first tuple position.

In the actual application the state changes as the conduit streams.

Any ideas?

Body:
Turns out a solution is something like

passState = mapMC $ \_ -> do
  state <- get
  return state


答:
The following example determines the
  difference in days between the current
  date and the order date for products
  in the AdventureWorks database.

```<code>USE AdventureWorks;
GO
SELECT DATEDIFF(day, OrderDate, GETDATE()) AS NumberOfDays
FROM Sales.SalesOrderHeader;
GO
</code>```

http://msdn.microsoft.com/en-us/library/ms189794%28v=sql.90%29.aspx

Title: Select the number of days a record is present within a certain year/month

Body:
In sql server I have a table with start and end dates for job postings. Given a month and a year by the user I need to find the amount of days between the start and end date that fall in the given year/month for that posting.

So if the posting Start Date is 2010/11/15 and End Date is 2010/12/05
Then output should be:

November  16 days
December  5 days
Total     21 days

I've been beating my head against the wall with this one and am fresh out of ideas.

Body:
The following example determines the
  difference in days between the current
  date and the order date for products
  in the AdventureWorks database.

USE AdventureWorks;
GO
SELECT DATEDIFF(day, OrderDate, GETDATE()) AS NumberOfDays
FROM Sales.SalesOrderHeader;
GO

http://msdn.microsoft.com/en-us/library/ms189794%28v=sql.90%29.aspx


问:
AWS Lambda SNS trigger Event Type?
I've been doing serverless dev for a while, mainly AWS, and just starting to get into SNS pub/sub design patters. I'm using typescript and the type support is fantastic, however I can't find the correct type for the event that comes in to a Lambda from SNS or an S3 trigger. These would make the seams between functions very safe indeed. For the moment I'm defining my own interfaces, this will get tiresome though. e.g.

interface IAWSSNSTriggerPayload {
  Records: [
    {
      EventSource: string,
      EventVersion: string,
      EventSubscriptionArn: string,
      Sns: {
        Type: string,
        MessageId: string,
        TopicArn: string,
        Subject: string,
        Message: string,
        Timestamp: string,
        SignatureVersion: string,
        Signature: string,
        SigningCertUrl: string,
        UnsubscribeUrl: string,
        MessageAttributes: {},
      }
    }
  ]
}

export const handler = (event: IAWSSNSTriggerPayload, context, cb) => {
  const response = {
    statusCode: 200,
    body: JSON.stringify({
      message: 'Go Serverless Webpack (Typescript) v1.0! Your function executed successfully! And from the SNS',
      input: event,
    }),
  };
  console.log('SNS Received from Lambda Publisher!!!')
  console.log(JSON.stringify(event.Records))
  cb(null, response);
}```

If anyone can point me in the right direction I'd be much obliged.

Cheers.

答:
You can use SNSEvent from @types/aws-lambda.

https://github.com/DefinitelyTyped/DefinitelyTyped/blob/56c1ea26b59ed0e4634b1ba27096ab3b90371875/types/aws-lambda/index.d.ts#L211

Please do remember that the typings are not maintained by AWS themselves so there may be some cases where it is not up to date.

Title: AWS Lambda SNS trigger Event Type?

Body:
I've been doing serverless dev for a while, mainly AWS, and just starting to get into SNS pub/sub design patters. I'm using typescript and the type support is fantastic, however I can't find the correct type for the event that comes in to a Lambda from SNS or an S3 trigger. These would make the seams between functions very safe indeed. For the moment I'm defining my own interfaces, this will get tiresome though. e.g.

interface IAWSSNSTriggerPayload {
  Records: [
    {
      EventSource: string,
      EventVersion: string,
      EventSubscriptionArn: string,
      Sns: {
        Type: string,
        MessageId: string,
        TopicArn: string,
        Subject: string,
        Message: string,
        Timestamp: string,
        SignatureVersion: string,
        Signature: string,
        SigningCertUrl: string,
        UnsubscribeUrl: string,
        MessageAttributes: {},
      }
    }
  ]
}

export const handler = (event: IAWSSNSTriggerPayload, context, cb) => {
  const response = {
    statusCode: 200,
    body: JSON.stringify({
      message: 'Go Serverless Webpack (Typescript) v1.0! Your function executed successfully! And from the SNS',
      input: event,
    }),
  };
  console.log('SNS Received from Lambda Publisher!!!')
  console.log(JSON.stringify(event.Records))
  cb(null, response);
}

If anyone can point me in the right direction I'd be much obliged.

Cheers.

ContentLicense: CC BY-SA 4.0


问:
UnicodeEncodeError with Python 2.7 csv.writer

I am trying to convert data from a json file to a csv file.

```<code>    with open('data.json') as data_file:
        x = json.load(data_file)

    g = csv.writer(open("output.csv", "wb+"))
    g.writerow(["name", "price", "1 star", "2 star", "3 star", "4 star", "5 star", "review_author", "review_comment_count", "review_header",
        "review_posted_date", "review_rating", "review_text", "url"].encode('utf-8'))

    for x in x:
        for i in range(len(x["reviews"])):
            g.writerow([x["name"],
                x["price"],
                x["ratings"]["1 star"],
                x["ratings"]["2 star"],
                x["ratings"]["3 star"],
                x["ratings"]["4 star"],
                x["ratings"]["5 star"],
                x["reviews"][i]["review_author"],
                x["reviews"][i]["review_comment_count"],
                x["reviews"][i]["review_header"],
                x["reviews"][i]["review_posted_date"],
                x["reviews"][i]["review_rating"],
                x["reviews"][i]["review_text"],
                x["url"]])
</code>```

I expect to get a CSV file with all the columns (price, 1 star, 2 star, etc) with rows as corresponding data.

Instead I get an error:

Traceback (most recent call last):
File "scraper5.py", line 162, in  ReadAsin()
File "scraper5.py", line 159, in ReadAsin x["url"].encode('utf8')])
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 377: ordinal not in range(128)

If I comment out line 159 I get the same error for the x["reviews"][i]["review_text"]. I've looked up previous questions on here but none of the solutions seem to work. Any suggestions for how to fix this?

答:
Your script is failing because the json file has contained some non-ascii chars.And the system default encoding char-set ascii cannot trans it , which is out of range(128).

Try to explicit encode the all the lines your want to output into the file , like

```<code>g.writerow([x["name"].encode('utf8'),
            x["reviews"][i]["review_author"].encode('utf8'),
            x["reviews"][i]["review_comment_count"].encode('utf8')
            x["url"].encode('utf8')])
</code>```

Body:
I am trying to convert data from a json file to a csv file.

    with open('data.json') as data_file:
        x = json.load(data_file)

    g = csv.writer(open("output.csv", "wb+"))
    g.writerow(["name", "price", "1 star", "2 star", "3 star", "4 star", "5 star", "review_author", "review_comment_count", "review_header",
        "review_posted_date", "review_rating", "review_text", "url"].encode('utf-8'))

    for x in x:
        for i in range(len(x["reviews"])):
            g.writerow([x["name"],
                x["price"],
                x["ratings"]["1 star"],
                x["ratings"]["2 star"],
                x["ratings"]["3 star"],
                x["ratings"]["4 star"],
                x["ratings"]["5 star"],
                x["reviews"][i]["review_author"],
                x["reviews"][i]["review_comment_count"],
                x["reviews"][i]["review_header"],
                x["reviews"][i]["review_posted_date"],
                x["reviews"][i]["review_rating"],
                x["reviews"][i]["review_text"],
                x["url"]])

I expect to get a CSV file with all the columns (price, 1 star, 2 star, etc) with rows as corresponding data.

Instead I get an error:

Traceback (most recent call last):
File "scraper5.py", line 162, in  ReadAsin()
File "scraper5.py", line 159, in ReadAsin x["url"].encode('utf8')])
UnicodeEncodeError: 'ascii' codec can't encode character u'\u2019' in position 377: ordinal not in range(128)

If I comment out line 159 I get the same error for the x["reviews"][i]["review_text"]. I've looked up previous questions on here but none of the solutions seem to work. Any suggestions for how to fix this?

Body:
Your script is failing because the json file has contained some non-ascii chars.And the system default encoding char-set ascii cannot trans it , which is out of range(128).

Try to explicit encode the all the lines your want to output into the file , like

g.writerow([x["name"].encode('utf8'),
            x["reviews"][i]["review_author"].encode('utf8'),
            x["reviews"][i]["review_comment_count"].encode('utf8')
            x["url"].encode('utf8')])


问:
Lenovo Ideapad 320 touchpad drag and drop does not work on Linux Mint
On my Lenovo Ideapad 320 touchpad drag and drop does not work. Touch click and scroll with fingers works.
Please help me troubleshoot
This is my configuration (please let me know if anything more is required )

Thankyou:-)

```<code>$ cat /etc/*-release
DISTRIB_ID=LinuxMint
DISTRIB_RELEASE=18.2
DISTRIB_CODENAME=sonya
DISTRIB_DESCRIPTION="Linux Mint 18.2 Sonya"
NAME="Linux Mint"
VERSION="18.2 (Sonya)"
ID=linuxmint
ID_LIKE=ubuntu
PRETTY_NAME="Linux Mint 18.2"
VERSION_ID="18.2"
HOME_URL="http://www.linuxmint.com/"
SUPPORT_URL="http://forums.linuxmint.com/"
BUG_REPORT_URL="http://bugs.launchpad.net/linuxmint/"
VERSION_CODENAME=sonya
UBUNTU_CODENAME=xenial

$ uname -a
Linux darling 4.8.0-53-generic #56~16.04.1-Ubuntu SMP Tue May 16 01:18:56 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux

$ lspci
00:00.0 Host bridge: Intel Corporation Sky Lake Host Bridge/DRAM Registers (rev 09)
00:02.0 VGA compatible controller: Intel Corporation Device 1921 (rev 0a)
00:14.0 USB controller: Intel Corporation Sunrise Point-LP USB 3.0 xHCI Controller (rev 21)
00:14.2 Signal processing controller: Intel Corporation Sunrise Point-LP Thermal subsystem (rev 21)
00:15.0 Signal processing controller: Intel Corporation Sunrise Point-LP Serial IO I2C Controller (rev 21)
00:16.0 Communication controller: Intel Corporation Sunrise Point-LP CSME HECI (rev 21)
00:17.0 SATA controller: Intel Corporation Sunrise Point-LP SATA Controller [AHCI mode] (rev 21)
00:1c.0 PCI bridge: Intel Corporation Sunrise Point-LP PCI Express Root Port (rev f1)
00:1c.5 PCI bridge: Intel Corporation Sunrise Point-LP PCI Express Root Port (rev f1)
00:1f.0 ISA bridge: Intel Corporation Sunrise Point-LP LPC Controller (rev 21)
00:1f.2 Memory controller: Intel Corporation Sunrise Point-LP PMC (rev 21)
00:1f.3 Audio device: Intel Corporation Sunrise Point-LP HD Audio (rev 21)
00:1f.4 SMBus: Intel Corporation Sunrise Point-LP SMBus (rev 21)
01:00.0 Ethernet controller: Realtek Semiconductor Co., Ltd. RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller (rev 10)
02:00.0 Network controller: Intel Corporation Intel Dual Band Wireless-AC 3165 Plus Bluetooth (rev 99)
</code>```

答:
I had a similar problem with my touchpad. If you have synclient, try

```<code>synclient ClickPad=1
</code>```

And see if that helps at all.

Body:
On my Lenovo Ideapad 320 touchpad drag and drop does not work. Touch click and scroll with fingers works.
Please help me troubleshoot
This is my configuration (please let me know if anything more is required )

Thankyou:-)

$ cat /etc/*-release
DISTRIB_ID=LinuxMint
DISTRIB_RELEASE=18.2
DISTRIB_CODENAME=sonya
DISTRIB_DESCRIPTION="Linux Mint 18.2 Sonya"
NAME="Linux Mint"
VERSION="18.2 (Sonya)"
ID=linuxmint
ID_LIKE=ubuntu
PRETTY_NAME="Linux Mint 18.2"
VERSION_ID="18.2"
HOME_URL="http://www.linuxmint.com/"
SUPPORT_URL="http://forums.linuxmint.com/"
BUG_REPORT_URL="http://bugs.launchpad.net/linuxmint/"
VERSION_CODENAME=sonya
UBUNTU_CODENAME=xenial

$ uname -a
Linux darling 4.8.0-53-generic #56~16.04.1-Ubuntu SMP Tue May 16 01:18:56 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux

$ lspci
00:00.0 Host bridge: Intel Corporation Sky Lake Host Bridge/DRAM Registers (rev 09)
00:02.0 VGA compatible controller: Intel Corporation Device 1921 (rev 0a)
00:14.0 USB controller: Intel Corporation Sunrise Point-LP USB 3.0 xHCI Controller (rev 21)
00:14.2 Signal processing controller: Intel Corporation Sunrise Point-LP Thermal subsystem (rev 21)
00:15.0 Signal processing controller: Intel Corporation Sunrise Point-LP Serial IO I2C Controller (rev 21)
00:16.0 Communication controller: Intel Corporation Sunrise Point-LP CSME HECI (rev 21)
00:17.0 SATA controller: Intel Corporation Sunrise Point-LP SATA Controller [AHCI mode] (rev 21)
00:1c.0 PCI bridge: Intel Corporation Sunrise Point-LP PCI Express Root Port (rev f1)
00:1c.5 PCI bridge: Intel Corporation Sunrise Point-LP PCI Express Root Port (rev f1)
00:1f.0 ISA bridge: Intel Corporation Sunrise Point-LP LPC Controller (rev 21)
00:1f.2 Memory controller: Intel Corporation Sunrise Point-LP PMC (rev 21)
00:1f.3 Audio device: Intel Corporation Sunrise Point-LP HD Audio (rev 21)
00:1f.4 SMBus: Intel Corporation Sunrise Point-LP SMBus (rev 21)
01:00.0 Ethernet controller: Realtek Semiconductor Co., Ltd. RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller (rev 10)
02:00.0 Network controller: Intel Corporation Intel Dual Band Wireless-AC 3165 Plus Bluetooth (rev 99)

Body:
I had a similar problem with my touchpad. If you have synclient, try

synclient ClickPad=1

And see if that helps at all.


问:
Detect html table cell value change
How am I able to detect change in html table on any cell? Currently I can only detect change in one cell, I could repeat the same code for all table cell ID but wondering if there is an efficient way.

Note that I have other inputs in my form and only wish to detect ones relevant to the table below:

Code:

html:

```<code><table id="myTable" border="1" data-mini="true" >
<tbody>
<tr>
<th>Drawing Number</th>
<th>Description</th>
<th>Sheet Number</th>
<th>Issue</th>
</tr>
<tr>
<td><input name="drawing-n-1" id="drawing-n-1" type="text" /></td>
<td><input name="drawing-d-1" type="text" /></td>
<td><input name="drawing-s-1" type="text" /></td>
<td><input name="drawing-i-1" type="text" /></td>
<td><input name="drawing-n-2" id="drawing-n-2" type="text" /></td>
<td><input name="drawing-d-2" type="text" /></td>
<td><input name="drawing-s-2" type="text" /></td>
<td><input name="drawing-i-2" type="text" /></td>
</tr>
</tbody>
</table>
</code>```

javascript:

```<code>var drawing_input = 'drawing-n-1';
$('#'+drawing_input).change(function(e) {
    alert("aha");
    var data = $('#'+drawing_input).val();
});
</code>```

答:
event delegation</p>

```<code>$("tbody").on("change", "input", function () {
    console.log(this.name, this.value)
});
</code>```

Title: Detect html table cell value change

Body:
How am I able to detect change in html table on any cell? Currently I can only detect change in one cell, I could repeat the same code for all table cell ID but wondering if there is an efficient way.

Note that I have other inputs in my form and only wish to detect ones relevant to the table below:

Code:

html:

Drawing Number
Description
Sheet Number
Issue

<input name="drawing-n-1" id="drawing-n-1" type="text" />
<input name="drawing-d-1" type="text" />
<input name="drawing-s-1" type="text" />
<input name="drawing-i-1" type="text" />
<input name="drawing-n-2" id="drawing-n-2" type="text" />
<input name="drawing-d-2" type="text" />
<input name="drawing-s-2" type="text" />
<input name="drawing-i-2" type="text" />

javascript:

var drawing_input = 'drawing-n-1';
$('#'+drawing_input).change(function(e) {
    alert("aha");
    var data = $('#'+drawing_input).val();
});

Body:
event delegation

$("tbody").on("change", "input", function () {
    console.log(this.name, this.value)
});


问:
How to hide navigation toolbar in firefox
I have opened a new window like this. I have to hide navigation toolbar in firefox and for that I provided location = no. It doesn't work in firefox. How can I hide the address bar (navigation toolbar)</p>

```<code>var features = 'height=420,width=320,top=10,left=25,status=no,toolbar=no,location=yes,menubar=no,titlebar=no,scrollbars=yes,modal=yes';

window.open ( path,title,features );
</code>```

答: If you wish to secure data which is passed as querystring - you can use POST method instead of GET method by  specifying method=post in the querystring .</p>

Body:
I have opened a new window like this. I have to hide navigation toolbar in firefox and for that I provided location = no. It doesn't work in firefox. How can I hide the address bar (navigation toolbar)

var features = 'height=420,width=320,top=10,left=25,status=no,toolbar=no,location=yes,menubar=no,titlebar=no,scrollbars=yes,modal=yes';

window.open ( path,title,features );


问:
error: invalid conversion from ‘int*’ to ‘int’ [-fpermissive]
Getting error:

error: invalid conversion from ‘int*’ to ‘int’ [-fpermissive]
  on g++

on the following code:

```<code>void* func(void *s)
{
    int i = 0;
    int self = (int *)s;
    printf("Thread Entered: %d\n", self);

    sm.lock(self);

    // Critical section (Only one thread
    // can enter here at a time)
    for (i=0; i<MAX; i++)
        ans++;

    sm.unlock(self);
}
</code>```

答:
You need to think of these as two different things.  One is a pointer to memory where the value is stored (int*) and the other is an actual value (int).

Looking at your function declaration void* func(void *s), your s parameter is of type void, this will need to be int if you wish to convert it.

Your data types seem a bit mixed, which just doesn't fly do well in C/C++.  Can you clean it?  If you are using this function with pthread_create(), as per the documentation with example for this function, try..

```<code>// your pthread_create call..
int SOME_INT = 123;
s = pthread_create(&thread_id, &attr, &thread_start, &SOME_INT);

//...and your function
void* func(void *s)
{
    int self = (int*) s;
</code>```

Pointers can be confusing.  See if that above code looks similar, in particular to passing the last parameter for pthread_create as a pointer reference.   And then try your original code.  It might just be that it wasn't passed as a reference.

See what that yields you, else try storing it as a pointer and then converting on use.

```<code>void* func(void *s)
{
    int *self = s;

    sm.lock(*self);  // but can give a potential race condition.
</code>```

Body:
Getting error:

error: invalid conversion from ‘int*’ to ‘int’ [-fpermissive]
  on g++

on the following code:

void* func(void *s)
{
    int i = 0;
    int self = (int *)s;
    printf("Thread Entered: %d\n", self);

    sm.lock(self);

    // Critical section (Only one thread
    // can enter here at a time)
    for (i=0; i<MAX; i++)
        ans++;

    sm.unlock(self);
}

Body:
You need to think of these as two different things.  One is a pointer to memory where the value is stored (int*) and the other is an actual value (int).

Looking at your function declaration void* func(void *s), your s parameter is of type void, this will need to be int if you wish to convert it.

Your data types seem a bit mixed, which just doesn't fly do well in C/C++.  Can you clean it?  If you are using this function with pthread_create(), as per the documentation with example for this function, try..

// your pthread_create call..
int SOME_INT = 123;
s = pthread_create(&thread_id, &attr, &thread_start, &SOME_INT);

//...and your function
void* func(void *s)
{
    int self = (int*) s;

Pointers can be confusing.  See if that above code looks similar, in particular to passing the last parameter for pthread_create as a pointer reference.   And then try your original code.  It might just be that it wasn't passed as a reference.

See what that yields you, else try storing it as a pointer and then converting on use.

void* func(void *s)
{
    int *self = s;

    sm.lock(*self);  // but can give a potential race condition.


问:
Extracting the variables names from a list of variables
Consider two series which are attributes of a class instance xyz, and a list containing them:

For the sake of reproducing the problem, imagine s1 and s2 are:

```<code>s1 = pd.Series(np.random.rand(10))
s2 = pd.Series(np.random.rand(10))

list= [xyz.s1, xyz.s2]
</code>```

Given the list, how can I extract the series' names 's1' and 's2'?

I tried something like:

```<code>series_names = [str(x) for x in list]
</code>```

But it did not work; it tried to convert the series' values into string, instead of the series' names.

Also,

```<code>series_names = [x.name for x in list]
</code>```

led to:

```<code>series_names = ['xyz', 'xyz']
</code>```

Desired output:

```<code>series_names = ['s1', 's2']
</code>```

答:
You could do something with the globals function:

```<code>>>> s1 = 'a'
>>> s2 = 'b'
>>> globals()
{..., 's1': 'a', 's2': 'b'}
</code>```

So you could do:

```<code>def extract_name(value):
    for k, v in globals().items():
        if v is value:
            yield k
</code>```

This makes a generator, so that if two variables refer to the same object, it captures all the possible names:

```<code>>>> class A: pass
>>> a = A()
>>> b = a
>>> list(extract_name(a))
['a', 'b']
</code>```

So, you could do:

```<code>>>> l = [s1, s2]
>>> [next(extract_name(v)) for v in l]
['s1', 's2']
</code>```

(The use of next is to get the name out of the generator.)

Body:
Consider two series which are attributes of a class instance xyz, and a list containing them:

For the sake of reproducing the problem, imagine s1 and s2 are:

s1 = pd.Series(np.random.rand(10))
s2 = pd.Series(np.random.rand(10))

list= [xyz.s1, xyz.s2]

Given the list, how can I extract the series' names 's1' and 's2'?

I tried something like:

series_names = [str(x) for x in list]

But it did not work; it tried to convert the series' values into string, instead of the series' names.

Also,

series_names = [x.name for x in list]

led to:

series_names = ['xyz', 'xyz']

Desired output:

series_names = ['s1', 's2']

Body:
You could do something with the globals function:

>>> s1 = 'a'
>>> s2 = 'b'
>>> globals()
{..., 's1': 'a', 's2': 'b'}

So you could do:

def extract_name(value):
    for k, v in globals().items():
        if v is value:
            yield k

This makes a generator, so that if two variables refer to the same object, it captures all the possible names:

>>> class A: pass
>>> a = A()
>>> b = a
>>> list(extract_name(a))
['a', 'b']

So, you could do:

>>> l = [s1, s2]
>>> [next(extract_name(v)) for v in l]
['s1', 's2']

(The use of next is to get the name out of the generator.)


问:
Correct way of making a singleton a Spring bean
I am converting a singleton to a Spring bean, so that if the singleton fails to initialize, then entire web application's spring context doesn't load properly.

The advantage of making the Spring context not load properly, is that people will take notice and fix the configuration during deployment itself. As opposed to using 'non-spring bean' singleton: when that throws exception during initialization, nobody notices.. until a actual user complains of missing functionality.

My changes are working as expected.. but I am not sure if I am doing the right thing.

Any thoughts?

The code looks like this:

```<code>public class MySingleton {

    private static MySingleton INSTANCE = null;
    private MySingleton(){}

public static MySingleton getInstance(){
    if(INSTANCE == null){
        synchronized(MySingleton.class){
            if(INSTANCE == null){
                try{
                    doWork()
                }catch(Exception e){
                    throw new IllegalStateException("xyz", e);
                }
                INSTANCE = new MySingleton();
            }
        }
    }

    return INSTANCE;
}

private static void doWork() {
    // do some work
    }

}
</code>```

And in the spring config xml, the bean will be defined as:

```<code><bean id="MySingletonBean"
    class="com.MySingleton"
    factory-method="getInstance" lazy-init="false" singleton="true">
</bean>
</code>```

Note:
Most of this is similar to the strategy discussed in this article:
http://springtips.blogspot.com/2007/06/configuration-hell-remedy-with.html

Edit 1:

The classes that use this singleton, are not spring beans themselves.. they are just non-spring pojos, that I can't convert to spring. They  must rely on getInstance() method get hold of the Singleton.

Edit 2: (copying a comment I made below into this description section)
 I am trying to target two things:

I want Spring to initialize the singleton. So that if the
initialization fails, then the application loading fails.

I want the other classes be able to use classes without having to rely on contextAwareObj.getBean("MySingleton")

EDIT 3 (FINAL):
I decided to make this class a singleton.. and am not making it a spring bean.  If it fails to initialize, it will log something in the Log file.. hopefully the person doing deployment takes notice....  I abandoned the approach I mentioned earlier because I feel it will create a maintenance nightmare in future, so I had to pick between - singleton - or - spring bean. I chose singleton.

答:
To run code at startup (and fail on error) use one of the many ways to register startup events, e.g. see http://www.baeldung.com/running-setup-logic-on-startup-in-spring

Example:

```<code>@Component
public class InitializingBeanExampleBean implements InitializingBean {

    private static final Logger LOG = Logger.getLogger(InitializingBeanExampleBean.class);

    @Autowired
    private Environment environment;

    @Override
    public void afterPropertiesSet() throws Exception {
        LOG.info(Arrays.asList(environment.getDefaultProfiles()));
    }
}
</code>```

Body:
I am converting a singleton to a Spring bean, so that if the singleton fails to initialize, then entire web application's spring context doesn't load properly.

The advantage of making the Spring context not load properly, is that people will take notice and fix the configuration during deployment itself. As opposed to using 'non-spring bean' singleton: when that throws exception during initialization, nobody notices.. until a actual user complains of missing functionality.

My changes are working as expected.. but I am not sure if I am doing the right thing.

Any thoughts?

The code looks like this:

public class MySingleton {

    private static MySingleton INSTANCE = null;
    private MySingleton(){}

public static MySingleton getInstance(){
    if(INSTANCE == null){
        synchronized(MySingleton.class){
            if(INSTANCE == null){
                try{
                    doWork()
                }catch(Exception e){
                    throw new IllegalStateException("xyz", e);
                }
                INSTANCE = new MySingleton();
            }
        }
    }

    return INSTANCE;
}

private static void doWork() {
    // do some work
    }

}

And in the spring config xml, the bean will be defined as:

<bean id="MySingletonBean"
    class="com.MySingleton"
    factory-method="getInstance" lazy-init="false" singleton="true">
</bean>

Note:
Most of this is similar to the strategy discussed in this article:
http://springtips.blogspot.com/2007/06/configuration-hell-remedy-with.html

Edit 1:

The classes that use this singleton, are not spring beans themselves.. they are just non-spring pojos, that I can't convert to spring. They  must rely on getInstance() method get hold of the Singleton.

Edit 2: (copying a comment I made below into this description section)
 I am trying to target two things:

I want Spring to initialize the singleton. So that if the
initialization fails, then the application loading fails.

I want the other classes be able to use classes without having to rely on contextAwareObj.getBean("MySingleton")

EDIT 3 (FINAL):
I decided to make this class a singleton.. and am not making it a spring bean.  If it fails to initialize, it will log something in the Log file.. hopefully the person doing deployment takes notice....  I abandoned the approach I mentioned earlier because I feel it will create a maintenance nightmare in future, so I had to pick between - singleton - or - spring bean. I chose singleton.

Body:
To run code at startup (and fail on error) use one of the many ways to register startup events, e.g. see http://www.baeldung.com/running-setup-logic-on-startup-in-spring

Example:

@Component
public class InitializingBeanExampleBean implements InitializingBean {

    private static final Logger LOG = Logger.getLogger(InitializingBeanExampleBean.class);

    @Autowired
    private Environment environment;

    @Override
    public void afterPropertiesSet() throws Exception {
        LOG.info(Arrays.asList(environment.getDefaultProfiles()));
    }
}


问:
Launching app in background in iPhone
Is there a way that I can use the url scheme approach to launch an application in the background or if it is already running in the background invoke it without it (the callee) coming to the foreground? I heard that this can be done in iOS 4.2 but don't see it when I use

[[UIApplication sharedApplication] openURL:url];

to open the application.
Thanks,
N.

答:
It does not look like it is possible.

If your application is not running when a URL request arrives, it is launched and moved to
  the foreground so that it can open the
  URL. The implementation of your
  application:didFinishLaunchingWithOptions:
  method should retrieve the URL from
  its options dictionary and determine
  whether the application can open it.
  If it can, return YES and let your
  application:openURL:sourceApplication:annotation:
  or application:handleOpenURL: method
  handle the actual opening of the URL.

If your application is running but is
  in the background or suspended, it is
  moved to the foreground to open the
  URL. Shortly thereafter, the system
  calls the delegate’s
  application:openURL:sourceApplication:annotation:
  to check the URL and open it. If your
  delegate does not implement this
  method (or the current system version
  is iOS 4.1 or earlier), the system
  calls your delegate’s
  application:handleOpenURL: method
  instead.

iOS Application Programming Guide

Title: Launching app in background in iPhone


问:
Error during VSTS Account creation Azure using Azure Arm templates
I am trying to create VSTS account on Azure using Arm Template.
I am using msrestazure python module for deploying the templates.
But i am getting the following error :

Azure Error: DeploymentFailed
          Message: At least one resource deployment operation failed. Please list deployment operations for details. Please see
  https://aka.ms/arm-debug for usage details.
          Exception Details:
                  Error Code: BadRequest
                  Message: {
            "code": "BadArgument",
            "message": "The string must have at least one character.\r\nParameter name: accountName",
            "target": "LegacyGetOrCreateBindPendingIdentity"
          }
                  Target: None

I am providing the value for parameter accountName but still it says that the string must have at least one character.Also i am able to create account using UI. Please help :)

答:
The message is not clear, but it could be that your user doesn't have enough permission; no guests are allowed to create Account.

You can validate that you are a member by going to the Users and groups section


问:
How to add value base on specific character ,also fix with certain digits in R
There is the basic width : xxxx.xxxxxx (4digits before "." 6 digits after".")

Have to add "0" when each side before and after "." is not enough digits.

Use regexr find "[.]" location with combination of str_pad can
fix the first 4 digits but

don't know how to add value after the specific character with fixed digits.
(cannot find a library can count the location from somewhere specified)

Data like this

```<code>> df
         Category
1       300.030340
2      3400.040290
3        700.07011
4        1700.0901
5       700.070114
6         700.0791
7       3600.05059
8        4400.0402
</code>```

Desired data

```<code>> df
         Category
1      0300.030340
2      3400.040290
3      0700.070110
4      1700.090100
5      0700.070114
6      0700.079100
7      3600.050590
8      4400.040200
</code>```

I am beginner of coding that sometime can't understand some regex like "["
e.t.c .With some explain of them would be super helpful.

Also i have a combination like this :

```<code>df$Category<-ifelse(regexpr("[.]",df$Category)==4,
             paste("0",df1$Category,sep = ""),df$Category)

df$Category<-str_pad(df$Category,11,side = c("right"),pad="0")
</code>```

Desire to know are there is any better way do this , especially count and
return the location from the END until specific character appear.

Body:
There is the basic width : xxxx.xxxxxx (4digits before "." 6 digits after".")

Have to add "0" when each side before and after "." is not enough digits.

Use regexr find "[.]" location with combination of str_pad can
fix the first 4 digits but

don't know how to add value after the specific character with fixed digits.
(cannot find a library can count the location from somewhere specified)

Data like this

> df
         Category
1       300.030340
2      3400.040290
3        700.07011
4        1700.0901
5       700.070114
6         700.0791
7       3600.05059
8        4400.0402

Desired data

> df
         Category
1      0300.030340
2      3400.040290
3      0700.070110
4      1700.090100
5      0700.070114
6      0700.079100
7      3600.050590
8      4400.040200

I am beginner of coding that sometime can't understand some regex like "["
e.t.c .With some explain of them would be super helpful.

Also i have a combination like this :

df$Category<-ifelse(regexpr("[.]",df$Category)==4,
             paste("0",df1$Category,sep = ""),df$Category)

df$Category<-str_pad(df$Category,11,side = c("right"),pad="0")

Desire to know are there is any better way do this , especially count and
return the location from the END until specific character appear.

Body:
We can use sprintf

df$Category <- sprintf("%011.6f", df$Category)
df
#    Category
#1 0300.030340
#2 3400.040290
#3 0700.070110
#4 1700.090100
#5 0700.070114
#6 0700.079100
#7 3600.050590
#8 4400.040200

data

df <- structure(list(Category = c(300.03034, 3400.04029, 700.07011,
1700.0901, 700.070114, 700.0791, 3600.05059, 4400.0402)),
.Names =   "Category", class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7", "8"))


问:
ThirdPersonController moving stuttering when the character collider colliding with a cube collider?
I'm trying to move the player 1.5 distance to the player direction he is facing.
The cubes scale are 1,1,1 so i guess in logic the player should be falling between the cubes and this is another problem to solve i can make the cubes scale on Y to be 0.1.

But the problem now is that the player is starting moving forward but then he is stuck in the air stuttering.

```<code>private void MovePlayer(float speed)
    {
        player.position += player.forward * Time.deltaTime * speed;
    }

    private void Update()
    {
        Vector3 newPos = new Vector3(player.position.x + 1.5f, player.position.y, player.position.z);
        MovePlayer(1f);
    }
</code>```

When the game is running the player keep stuttering all the time since he is trying to keep moving but getting stuck with the colliders.

Another problem related is in many case the player is in the air and looks like sitting instead standing on the cube. Only if i move the player a bit with the keys he is standing.

答:
There are two possible problems.

1.You did not disable ThirdPersonUserControl script. Note that the ThirdPersonUserControl script is attached to the ThirdPersonController GameObject. You must disable it, otherwise you will be moving the player from two scripts at the-same time.

2.ThirdPersonController uses Rigidbody. Do not move a Rigidbody object with the transform(player.position). You have to use one of the Rigidbody's functions such as MovePosition, AddForce, or velocity as described in this post.

Since this is a ThirdPersonController, you shouldn't modify the Rigidbody directly. Use the Move function declared there to move it. You can pass the new position to the first parameter, then crush and jump value to the second and third parameter respectively. This must be done in the FixedUpdate update.

Example of moving ThirdPersonCharacter object properly:

```<code>ThirdPersonCharacter tpsScript;

void Start()
{
    GameObject tpsObj = GameObject.Find("ThirdPersonController");
    tpsScript = tpsObj.GetComponent<ThirdPersonCharacter>();
}

void FixedUpdate()
{

    float h = CrossPlatformInputManager.GetAxis("Horizontal");
    float v = CrossPlatformInputManager.GetAxis("Vertical");

    Transform m_Cam = Camera.main.transform;
    Vector3 m_CamForward = Vector3.Scale(m_Cam.forward, new Vector3(1, 0, 1)).normalized;
    Vector3 m_Move = v * m_CamForward + h * m_Cam.right;

    tpsScript.Move(m_Move, false, false);
}
</code>```

Body:
I'm trying to move the player 1.5 distance to the player direction he is facing.
The cubes scale are 1,1,1 so i guess in logic the player should be falling between the cubes and this is another problem to solve i can make the cubes scale on Y to be 0.1.

But the problem now is that the player is starting moving forward but then he is stuck in the air stuttering.

private void MovePlayer(float speed)
    {
        player.position += player.forward * Time.deltaTime * speed;
    }

    private void Update()
    {
        Vector3 newPos = new Vector3(player.position.x + 1.5f, player.position.y, player.position.z);
        MovePlayer(1f);
    }

When the game is running the player keep stuttering all the time since he is trying to keep moving but getting stuck with the colliders.

Another problem related is in many case the player is in the air and looks like sitting instead standing on the cube. Only if i move the player a bit with the keys he is standing.

Body:
There are two possible problems.

1.You did not disable ThirdPersonUserControl script. Note that the ThirdPersonUserControl script is attached to the ThirdPersonController GameObject. You must disable it, otherwise you will be moving the player from two scripts at the-same time.

2.ThirdPersonController uses Rigidbody. Do not move a Rigidbody object with the transform(player.position). You have to use one of the Rigidbody's functions such as MovePosition, AddForce, or velocity as described in this post.

Since this is a ThirdPersonController, you shouldn't modify the Rigidbody directly. Use the Move function declared there to move it. You can pass the new position to the first parameter, then crush and jump value to the second and third parameter respectively. This must be done in the FixedUpdate update.

Example of moving ThirdPersonCharacter object properly:

ThirdPersonCharacter tpsScript;

void Start()
{
    GameObject tpsObj = GameObject.Find("ThirdPersonController");
    tpsScript = tpsObj.GetComponent<ThirdPersonCharacter>();
}

void FixedUpdate()
{

    float h = CrossPlatformInputManager.GetAxis("Horizontal");
    float v = CrossPlatformInputManager.GetAxis("Vertical");

    Transform m_Cam = Camera.main.transform;
    Vector3 m_CamForward = Vector3.Scale(m_Cam.forward, new Vector3(1, 0, 1)).normalized;
    Vector3 m_Move = v * m_CamForward + h * m_Cam.right;

    tpsScript.Move(m_Move, false, false);
}


答:
If you really want to keep the names for some reason, keep your data in a dictionary instead of a list.</p>

```<code>series = {
    's1': pd.Series(np.random.rand(10)),
    's2': pd.Series(np.random.rand(10))
}

series_names = [x for x in series] # ['s1', 's2']
</code>```

Title: Extracting the variables names from a list of variables

Body:
If you really want to keep the names for some reason, keep your data in a dictionary instead of a list.

series = {
    's1': pd.Series(np.random.rand(10)),
    's2': pd.Series(np.random.rand(10))
}

series_names = [x for x in series] # ['s1', 's2']


问:
latexmk - running bash command to stop Dropbox syncing
I am using latexmk to compile my LaTeX thesis.  I keep the thesis on my Dropbox, and as the dozens-to-hundreds of .aux and associated files are created, Dropbox indexing induces a significant overhead.

I thus want to insert the following bash script before compilation starts to stop Dropbox:

```<code>#!/usr/bin/env bash
dropbox_pid="$echo $(pgrep Dropbox)"
kill -STOP $dropbox_pid
</code>```

and correspondingly, to restart Dropbox at the end, I would like:

```<code>#!/usr/bin/env bash
dropbox_pid="$echo $(pgrep Dropbox)"
kill -CONT $dropbox_pid
</code>```

How do I do this by editing the local latexmkrc?

答:
Setting the working directories ($aux_dir and $out_dir) to somewhere outside the Dropbox repository, you can avoid excessive Dropbox syncing.

The following is from my $HOME/.latexmk.  It locates the working directory under ~/.tmp/tex/THE_NAME_OF_MY_WRITING_PROJECT and tries to create it if it is not present.

```<code>$aux_dir            = "$ENV{HOME}/.tmp/tex/" . basename(getcwd);
$out_dir            = $aux_dir;
mkpath($aux_dir);
</code>```

Body:
I am using latexmk to compile my LaTeX thesis.  I keep the thesis on my Dropbox, and as the dozens-to-hundreds of .aux and associated files are created, Dropbox indexing induces a significant overhead.

I thus want to insert the following bash script before compilation starts to stop Dropbox:

#!/usr/bin/env bash
dropbox_pid="$echo $(pgrep Dropbox)"
kill -STOP $dropbox_pid

and correspondingly, to restart Dropbox at the end, I would like:

#!/usr/bin/env bash
dropbox_pid="$echo $(pgrep Dropbox)"
kill -CONT $dropbox_pid

How do I do this by editing the local latexmkrc?

Body:
Setting the working directories ($aux_dir and $out_dir) to somewhere outside the Dropbox repository, you can avoid excessive Dropbox syncing.

The following is from my $HOME/.latexmk.  It locates the working directory under ~/.tmp/tex/THE_NAME_OF_MY_WRITING_PROJECT and tries to create it if it is not present.

$aux_dir            = "$ENV{HOME}/.tmp/tex/" . basename(getcwd);
$out_dir            = $aux_dir;
mkpath($aux_dir);