问:
How do I get the binding target in a guice provider?
Is there a way to get the class into which something is being injected in a provider (or some other way)? This is for logging -- When my SqlDatabase does something, I want it to show up in the logs with the name of the class in which it's being used. The best I can think of is to get the stack trace and go backwards through that to find out where it's used, but I would really rather do it at injection time.

A different way to put the question is: I need to find the injection site -- the exact class where the @Inject annotation was found -- to create the instance of the injected class.

答:
So I came up with a... thing... that seems to work:

```<code>import com.google.inject.Binder;
import com.google.inject.Binding;
import com.google.inject.Key;
import com.google.inject.matcher.AbstractMatcher;
import com.google.inject.matcher.Matcher;
import com.google.inject.spi.DependencyAndSource;
import com.google.inject.spi.InjectionPoint;
import com.google.inject.spi.ProvisionListener;
import java.util.List;
import java.util.function.Function;
import javax.inject.Provider;

/**
 * This is a dirty, dirty hack to allow some types to know what they're being injected into. There are other
 * (possibly cleaner) ways to do this, but this has the nice advantage of the injected class not needing
 * to know anything about this.
 */
public class ContextAwareInjection
{
    public static <T> void bindContextAwareProvider(Binder binder, Class<T> type, Function<InjectionPoint, T> provider)
    {
        bindContextAwareProvider(binder, Key.get(type), provider);
    }

    public static <T> void bindContextAwareProvider(Binder binder, Key<T> key, Function<InjectionPoint, T> provider)
    {
        Matcher<Binding<?>> matcher = new AbstractMatcher<Binding<?>>() {
            @Override public boolean matches(Binding<?> binding) { return binding.getKey().equals(key); } };
        ContextAwareImpl<T> impl = new ContextAwareImpl<>(provider, key);
        binder.bind(key).toProvider(impl);
        binder.bindListener(matcher, impl);
    }

    private static class ContextAwareImpl<T> implements ProvisionListener, Provider<T>
    {
        private final Key<T> key;
        private final Function<InjectionPoint, T> provider;
        private final ThreadLocal<T> current = new ThreadLocal<>();

        private ContextAwareImpl(Function<InjectionPoint, T> provider, Key<T> key)
        {
            this.provider = provider;
            this.key = key;
        }

        @Override
        public <T2> void onProvision(ProvisionInvocation<T2> pi)
        {
            if(!pi.getBinding().getKey().equals(key))
                throw new RuntimeException("Unexpected key -- got " + pi.getBinding().getKey() + ", expected " + key);
            try
            {
                List<DependencyAndSource> chain = pi.getDependencyChain();
                if(chain.isEmpty())
                    throw new RuntimeException("This should never be empty");
                DependencyAndSource das = chain.get(chain.size() - 1);
                InjectionPoint ip = das == null || das.getDependency() == null ? null : das.getDependency().getInjectionPoint();
                T value = provider.apply(ip);
                if(value == null)
                    throw new RuntimeException("Context aware providers should never return null");
                current.set(value);
                pi.provision();
            }
            finally
            {
                current.remove();
            }
        }

        @Override
        public T get()
        {
            T value = current.get();
            if(value == null)
                throw new RuntimeException("There is no current value -- this should never happen");
            return value;
        }
    }
}
</code>```

This may have some slight runtime performance implications, but for tests it works fine. More importantly, it requires no changes at all to the target classes. You can keep using @Inject as you always were.

Body:
So I came up with a... thing... that seems to work:

import com.google.inject.Binder;
import com.google.inject.Binding;
import com.google.inject.Key;
import com.google.inject.matcher.AbstractMatcher;
import com.google.inject.matcher.Matcher;
import com.google.inject.spi.DependencyAndSource;
import com.google.inject.spi.InjectionPoint;
import com.google.inject.spi.ProvisionListener;
import java.util.List;
import java.util.function.Function;
import javax.inject.Provider;

/**
 * This is a dirty, dirty hack to allow some types to know what they're being injected into. There are other
 * (possibly cleaner) ways to do this, but this has the nice advantage of the injected class not needing
 * to know anything about this.
 */
public class ContextAwareInjection
{
    public static <T> void bindContextAwareProvider(Binder binder, Class<T> type, Function<InjectionPoint, T> provider)
    {
        bindContextAwareProvider(binder, Key.get(type), provider);
    }

    public static <T> void bindContextAwareProvider(Binder binder, Key<T> key, Function<InjectionPoint, T> provider)
    {
        Matcher<Binding<?>> matcher = new AbstractMatcher<Binding<?>>() {
            @Override public boolean matches(Binding<?> binding) { return binding.getKey().equals(key); } };
        ContextAwareImpl<T> impl = new ContextAwareImpl<>(provider, key);
        binder.bind(key).toProvider(impl);
        binder.bindListener(matcher, impl);
    }

    private static class ContextAwareImpl<T> implements ProvisionListener, Provider<T>
    {
        private final Key<T> key;
        private final Function<InjectionPoint, T> provider;
        private final ThreadLocal<T> current = new ThreadLocal<>();

        private ContextAwareImpl(Function<InjectionPoint, T> provider, Key<T> key)
        {
            this.provider = provider;
            this.key = key;
        }

        @Override
        public <T2> void onProvision(ProvisionInvocation<T2> pi)
        {
            if(!pi.getBinding().getKey().equals(key))
                throw new RuntimeException("Unexpected key -- got " + pi.getBinding().getKey() + ", expected " + key);
            try
            {
                List<DependencyAndSource> chain = pi.getDependencyChain();
                if(chain.isEmpty())
                    throw new RuntimeException("This should never be empty");
                DependencyAndSource das = chain.get(chain.size() - 1);
                InjectionPoint ip = das == null || das.getDependency() == null ? null : das.getDependency().getInjectionPoint();
                T value = provider.apply(ip);
                if(value == null)
                    throw new RuntimeException("Context aware providers should never return null");
                current.set(value);
                pi.provision();
            }
            finally
            {
                current.remove();
            }
        }

        @Override
        public T get()
        {
            T value = current.get();
            if(value == null)
                throw new RuntimeException("There is no current value -- this should never happen");
            return value;
        }
    }
}

This may have some slight runtime performance implications, but for tests it works fine. More importantly, it requires no changes at all to the target classes. You can keep using @Inject as you always were.


来源: stackexchange

问:
Splitting up collection in order to convert to excel/csv
My collection is almost 2GB and i need to put it into mySQL. Its too big for any converters. So i was thinking of splitting collection. Make table with HotelInfo where HotelID is the key, and have a second table that has HotelID and ReviewID with the rest of the review questions. I am really new to using mongoDB and JSON files so i am beyond confused.
The format of JSON file :

```<code>{
"_id": string
"Reviews": [{
    "Ratings": {
    "Service"(optional): numeric,
    "Cleanliness"(optional): numeric,
    "Overall": numeric,
    "Value"(optional): numeric,
    "Sleep Quality"(optional): numeric,
    "Rooms"(optional): numeric,
    "Location"(optional): numeric
    },
    "AuthorLocation": string,
    "Title": string,
    "Author": string,
    "ReviewID": string,
    "Content": string,
    "Date": ISODate()
}],
"HotelInfo": {
    "Name": string,
    "HotelURL": string,
    "Price": string,
    "Address": string,
    "HotelID": string,
    "ImgURL": string
    }
}
</code>```

How can i "split" the collection and save it to a seperate JSON file and so then I can convert it to csv/excel?

答:
You could use $out to write the results of your aggregation into a new collection. Here is an example:
For your hotelInfo

```<code>db.yourCurrentCollection.aggregate([{
        $project: {
            // here you are just copying your fields to the new collection structure
            name: "$HotelInfo.Name",
            hotelUrl: "$HotelInfo.HotelURL",
            price: "$HotelInfo.Price",
            address: "$HotelInfo.Address",
            hotelId: "$HotelInfo.HotelID",
            imgUrl: "$HotelInfo.ImgURL"
        }
    },
    {
        $out: "hotelInfo" // The name of your new collection
    }
])
</code>```

For your Reviews it would be a little bit trickier but you would have to flatten your array with $unwind, copy your fields to the new structure (similarly to your hotelInfo) and write it to your new collection. Example:

```<code>db.yourCurrentCollection.aggregate([
{ $unwind: "$Reviews"},
{ $project:{
    service: "$Reviews.Ratings.Service",
    cleanliness:  "$Reviews.Ratings.Cleanliness",
    overall: "$Reviews.Ratings.Overall",
    value: "$Reviews.Ratings.Value",
    sleep_quality: "$Reviews.Ratings.Sleep Quality",
    rooms: "$Reviews.Ratings.Rooms",
    location: "$Reviews.Ratings.Location",
    authorLocation: "$Reviews.AuthorLocation",
    title: "$Reviews.Title",
    author: "$Reviews.Author",
    reviewId: "$Reviews.ReviewID",
    content: "$Reviews.Content",
    date: "$Reviews.Date",
}},
{ $out : "reviewInfo" }
])
</code>```

But have you thought of foreign keys? Would you need to connect the hotelInfo to a specific review? If so you would have to add a foreign key in your reviewInfo collection with a hotelId.

Regarding the connection between the documents, as you mentioned in the comment you can add the hotelId is your reviewInfo collection. Here an example:

```<code>db.yourCurrentCollection.aggregate([
{ $unwind: "$Reviews"},
{ $project:{
    service: "$Reviews.Ratings.Service",
    cleanliness:  "$Reviews.Ratings.Cleanliness",
    overall: "$Reviews.Ratings.Overall",
    value: "$Reviews.Ratings.Value",
    sleep_quality: "$Reviews.Ratings.Sleep Quality",
    rooms: "$Reviews.Ratings.Rooms",
    location: "$Reviews.Ratings.Location",
    authorLocation: "$Reviews.AuthorLocation",
    title: "$Reviews.Title",
    author: "$Reviews.Author",
    reviewId: "$Reviews.ReviewID",
    content: "$Reviews.Content",
    date: "$Reviews.Date",
    hotelId: "$HotelInfo.HotelID" // Here you add the connection of each document
                                 // to a hotelId
}}

{ $out : "reviewInfo" }
])
</code>```

ContentLicense: CC BY-SA 3.0

Body:
My collection is almost 2GB and i need to put it into mySQL. Its too big for any converters. So i was thinking of splitting collection. Make table with HotelInfo where HotelID is the key, and have a second table that has HotelID and ReviewID with the rest of the review questions. I am really new to using mongoDB and JSON files so i am beyond confused.
The format of JSON file :

{
"_id": string
"Reviews": [{
    "Ratings": {
    "Service"(optional): numeric,
    "Cleanliness"(optional): numeric,
    "Overall": numeric,
    "Value"(optional): numeric,
    "Sleep Quality"(optional): numeric,
    "Rooms"(optional): numeric,
    "Location"(optional): numeric
    },
    "AuthorLocation": string,
    "Title": string,
    "Author": string,
    "ReviewID": string,
    "Content": string,
    "Date": ISODate()
}],
"HotelInfo": {
    "Name": string,
    "HotelURL": string,
    "Price": string,
    "Address": string,
    "HotelID": string,
    "ImgURL": string
    }
}

How can i "split" the collection and save it to a seperate JSON file and so then I can convert it to csv/excel?

Body:
You could use $out to write the results of your aggregation into a new collection. Here is an example:
For your hotelInfo

db.yourCurrentCollection.aggregate([{
        $project: {
            // here you are just copying your fields to the new collection structure
            name: "$HotelInfo.Name",
            hotelUrl: "$HotelInfo.HotelURL",
            price: "$HotelInfo.Price",
            address: "$HotelInfo.Address",
            hotelId: "$HotelInfo.HotelID",
            imgUrl: "$HotelInfo.ImgURL"
        }
    },
    {
        $out: "hotelInfo" // The name of your new collection
    }
])

For your Reviews it would be a little bit trickier but you would have to flatten your array with $unwind, copy your fields to the new structure (similarly to your hotelInfo) and write it to your new collection. Example:

db.yourCurrentCollection.aggregate([
{ $unwind: "$Reviews"},
{ $project:{
    service: "$Reviews.Ratings.Service",
    cleanliness:  "$Reviews.Ratings.Cleanliness",
    overall: "$Reviews.Ratings.Overall",
    value: "$Reviews.Ratings.Value",
    sleep_quality: "$Reviews.Ratings.Sleep Quality",
    rooms: "$Reviews.Ratings.Rooms",
    location: "$Reviews.Ratings.Location",
    authorLocation: "$Reviews.AuthorLocation",
    title: "$Reviews.Title",
    author: "$Reviews.Author",
    reviewId: "$Reviews.ReviewID",
    content: "$Reviews.Content",
    date: "$Reviews.Date",
}},
{ $out : "reviewInfo" }
])

But have you thought of foreign keys? Would you need to connect the hotelInfo to a specific review? If so you would have to add a foreign key in your reviewInfo collection with a hotelId.

Regarding the connection between the documents, as you mentioned in the comment you can add the hotelId is your reviewInfo collection. Here an example:

db.yourCurrentCollection.aggregate([
{ $unwind: "$Reviews"},
{ $project:{
    service: "$Reviews.Ratings.Service",
    cleanliness:  "$Reviews.Ratings.Cleanliness",
    overall: "$Reviews.Ratings.Overall",
    value: "$Reviews.Ratings.Value",
    sleep_quality: "$Reviews.Ratings.Sleep Quality",
    rooms: "$Reviews.Ratings.Rooms",
    location: "$Reviews.Ratings.Location",
    authorLocation: "$Reviews.AuthorLocation",
    title: "$Reviews.Title",
    author: "$Reviews.Author",
    reviewId: "$Reviews.ReviewID",
    content: "$Reviews.Content",
    date: "$Reviews.Date",
    hotelId: "$HotelInfo.HotelID" // Here you add the connection of each document
                                 // to a hotelId
}}

{ $out : "reviewInfo" }
])


问:
Laravel 5.5 form confirmed by password
Im making form via LaravelCollective forms in my app.
I have email changing form with fields:
New e-mail
Confirm Email
Password

I need to validate user password on this form with user password in database. Can i do it via Validate?

My form:

```<code>{{ Form::model($user, ['route' => ['profile.email.update']]) }}
<div class="form-group row">
    <div class="col-md-12">
        <h2>Edytuj email</h2>
        <div class="form-group">
            <label for="edit-page-email">Nowy adres email</label>

            {{Form::text('email',null,['class' => 'form-control', 'id'=>'edit-page-email'])}}
        </div>
        <div class="form-group">
            <label for="edit-page-repemail">Nowy adres email (powtórz)</label>
            {{Form::text('email_confirmation',null,['class' => 'form-control', 'id'=>'edit-page-email'])}}
        </div>
        <div class="form-group">
            <label for="edit-page-pass">Twoje hasło</label>
                {{Form::password('password',['class' => 'form-control', 'id'=>'edit-page-npass'])}}
        </div>
        <div class="col-md-12 text-center">
                {{Form::submit('Zapisz zmiany',['class' => 'btn btn-primary btm-sm']) }}
            <a href="#" class="btn btn-link btn-sm font-red" title="Anuluj">Anuluj</a>
        </div>
    </div>
</div>
{{Form::close()}}
</code>```

And validation is:

```<code> $request->validate([
            'email' => 'required|confirmed',
            'email_confirmation' => 'required',
            'password' => 'required|confirmed',
        ]);
</code>```

Any ideas how can i do this?

答:
You can compare a string with the user's stored password using this</p>

```<code>$pwd = "secret";
$user = User::find(1);
Hash::check($pwd, $user->password); //returns a boolean
</code>```

Title: Laravel 5.5 form confirmed by password

Body:
Im making form via LaravelCollective forms in my app.
I have email changing form with fields:
New e-mail
Confirm Email
Password

I need to validate user password on this form with user password in database. Can i do it via Validate?

My form:

{{ Form::model($user, ['route' => ['profile.email.update']]) }}

Edytuj email

            Nowy adres email

            {{Form::text('email',null,['class' => 'form-control', 'id'=>'edit-page-email'])}}

            Nowy adres email (powtórz)
            {{Form::text('email_confirmation',null,['class' => 'form-control', 'id'=>'edit-page-email'])}}

            Twoje hasło
                {{Form::password('password',['class' => 'form-control', 'id'=>'edit-page-npass'])}}

                {{Form::submit('Zapisz zmiany',['class' => 'btn btn-primary btm-sm']) }}
            Anuluj

{{Form::close()}}

And validation is:

 $request->validate([
            'email' => 'required|confirmed',
            'email_confirmation' => 'required',
            'password' => 'required|confirmed',
        ]);

Any ideas how can i do this?

Body:
You can compare a string with the user's stored password using this

$pwd = "secret";
$user = User::find(1);
Hash::check($pwd, $user->password); //returns a boolean


问:
Is there a library for iPhone to work with HMAC-SHA-1 encoding
For all operation with Amazon services(S3, EC2, SimpleDB) You need to sign all resquest with HMAC-SHA-1 Signature(http://en.wikipedia.org/wiki/HMAC , http://docs.amazonwebservices.com/AWSFWS/latest/DeveloperGuide/index.html?SummaryOfAuthentication.html).

I'm working under asp.net backend and there is no problems. Problem is in the iPhone application. iPhone developer says that there is no way to use HMAC-SHA-1 encoding, and he have no rigths to implement his own algorithm. As programmer I cannot understand why there can be a problem.

So I want too know is iPhone developer right?

I've never coded for iPhone, so I don't even where to search such an information.

答:
CommonCrypto will do it. But if you want code, I have some here:

http://oauth.googlecode.com/svn/code/obj-c/OAuthConsumer/Crypto/

Which I wrote for use in the Cocoa OAuth implementation: http://code.google.com/p/oauthconsumer/wiki/UsingOAuthConsumer

OwnerDisplayName: AlfeG

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: schwa


问:
Scraping Woeidlookup.com for WOEID
I am attempting to make more or less a weather checker. I am scraping Yahoo for this, as I cannot figure out how to use their API plus it seems like more fun to me. I haven't been coding using Python3 for very long. All of this code is being done on a RPI the version of Python3 it uses is 3.4.2.

The issue I have ran across is getting the WOEID number. I figured scraping Woeidlookup.com would be an easy task to get the number. However, now after trying various ways to get the data from the site I am here. I do not have any code to show for scraping this website as if it didn't work I just deleted it.

I am sure that someone on here knows how to input the required text into the
 field of the website and then submit it. Once it is submitted I have to scrape the table that shows up below the  field to get the WOEID number.

I have already completed the scrape for Yahoo weather which is posted below. Any critiques on the code for learning purposes would be appreciated. I have found a ton of useful information on this site the past few weeks and all of that knowledge for the most part went into this project. The pandas import is if I decide to add in a table later on instead of the current print() setup.

```<code>import requests
from bs4 import BeautifulSoup
import pandas as pd
import datetime

baseurl = "https://www.yahoo.com/news/weather"
Country = input("Country : ").replace(" ", "-")
State = input("State : ").replace(" ", "-")
Town = input("Town : ").replace(" ", "-")
WOEID = "" # this is what I need to figure out

url = '%(U)s/%(C)s/%(S)s/%(T)s-%(W)s' % {'U': baseurl, "C": Country, "S": State, "T": Town, "W": WOEID}

now = datetime.datetime.now()
hour = 0
minute = now.minute
AMPM = ""
ToD = ""

page = requests.get(url)
code =  page.status_code
content = page.content
soup = BeautifulSoup(content, 'html.parser')
weather = soup.find(class_="weather")
temp = soup.find(class_="temperature Fz(14px) Tsh($temperature-text-shadow)")
wind = weather.find(id="weather-wind")
sunMoon = weather.find(id='weather-sun-moon')
details = weather.find(id="weather-detail")
detail = details.find(class_="detail")
start = detail.find_all(class_="Fl(start)")
end = detail.find_all(class_="Fl(end)")
desc = detail.find(class_="description Py(10px) Px(4px) Fz(1em)")
dayNight = desc.find_all(class_="day-description My(10px)")
windText = wind.find('span', {'data-reactid': '455'}).text
windSpeedDir = wind.find('p', {'data-reactid': '456'}).text
baro = wind.find('span', {'data-reactid': '461'}).text
pressure = wind.find('p', {'data-reactid': '462'}).text
phase = sunMoon.find('div', {'data-reactid': '504'}).text
dayDesc = temp.find(class_="description Va(m) Px(2px) Fz(1.3em)--sm Fz(1.6em)")
currentTemp = temp.find('span', {'data-reactid': '37'}).text
degreeSymbol = temp.find('span', {'data-reactid': '38'}).text
high = temp.find('span', {'data-reactid': '29'}).text
low = temp.find('span', {'data-reactid': '33'}).text
city = weather.find(class_="city Fz(2em)--sm Fz(3.7em)--lg Fz(3.3em) Fw(n) M(0) Trsdu(.3s) desktop_Lh(1) smartphone_Lh(1)")
country = weather.find(class_="Fz(1.2em)--sm Fz(2em)--lg Fz(1.5em) Fw(200) country Trsdu(.3s) Lh(2.5)")
dateTime = weather.find(class_="Lts(1px) Fz(14px) Fs(i) Lh(2.5) Fw(300) Tsh($temperature-text-shadow)")

try:
    sunrise = sunMoon.find('span', {'data-reactid': '510'}).text
except:
    sunrise = sunMoon.find('span', {'data-reactid': '515'}).text
try:
    sunset = sunMoon.find('span', {'data-reactid': '511'}).text
except:
    sunset = sunMoon.find('span', {'data-reactid': '516'}).text

sunrise1 = sunrise.split(" ")
sunrise2 = sunrise1[0].split(":")
srHour = int(sunrise2[0])
srMinute = int(sunrise2[1])
sunset1 = sunset.split(" ")
sunset2 = sunset1[0].split(":")
ssHour = int(sunset2[0])
ssMinute = int(sunset2[1])

if now.hour > 12:
    hour = now.hour - 12
    AMPM = "PM"
else:
    hour = now.hour
    AMPM = "AM"

if now.hour >= srHour and now.hour < 12:
    ToD = "morning"
if now.hour >= 12 and now.hour - 12 < ssHour:
    ToD = "afternoon"
if now.hour > 12 and now.hour - 12 >= ssHour:
    ToD = "night"

print('Weather data for the city of', city.get_text(), 'in the country of', country.get_text())
print('Today is', "%02d" % (now.month), '/', "%02d" % (now.day), '/', now.year)
print('The current time is', "%02d" % (hour), ":", "%02d" % (now.minute), ":", "%02d" % (now.second), AMPM)
print('Right now it is a', dayDesc.get_text().lower(), ToD, 'sky.')
print('It is currently', currentTemp, degreeSymbol, 'F.')
print('The high for today is', high, 'F.')
print('The low for today is', low, 'F.')
print(start[0].get_text(), ' : ', end[0].get_text())
print(start[1].get_text(), '   : ', end[1].get_text())
print(start[2].get_text(), ' : ', end[2].get_text())
print(start[3].get_text(), '   : ', end[3].get_text())
print(windText, "       : ", windSpeedDir)
print(baro, "  : ", pressure)
print("Moon Phase  : ", phase)
print("Sunrise     : ", sunrise)
print("Sunset      : ", sunset)
print(dayNight[0].get_text())
print(dayNight[1].get_text())
</code>```

答:
After much coding, searching etc.. I have fixed the problem I was having by using a different website to get the WOEID and data. Here below are the completed scripts I made for the base of the project I am working on for school. I split it into 3 files and it is undocumented throughout the code, but it should be fairly easy to follow. Hopefully this helps someone who is also doing something like this even if it is probably coded poorly.

Main Script

```<code>import requests
from bs4 import BeautifulSoup
import pandas as pd
import datetime
import WeatherAppBS4_Woeid as woeid

baseurl = "https://www.yahoo.com/news/weather"
Country = woeid.Country.replace(" ", "-")
State = woeid.State.replace(" ", "-")
Town = woeid.Town.replace(" ", "-")
WOEID = woeid.WOEID

url = '%(U)s/%(C)s/%(S)s/%(T)s-%(W)s' % {'U': baseurl, "C": Country, "S": State, "T": Town, "W": WOEID}

now = datetime.datetime.now()
hour = 0
minute = now.minute
AMPM = ""
ToD = ""

page = requests.get(url)
code =  page.status_code
content = page.content
soup = BeautifulSoup(content, 'html.parser')
weather = soup.find(class_="weather")
temp = soup.find(class_="temperature Fz(14px) Tsh($temperature-text-shadow)")
wind = weather.find(id="weather-wind")
sunMoon = weather.find(id='weather-sun-moon')
details = weather.find(id="weather-detail")
detail = details.find(class_="detail")
start = detail.find_all(class_="Fl(start)")
end = detail.find_all(class_="Fl(end)")
desc = detail.find(class_="description Py(10px) Px(4px) Fz(1em)")
dayNight = desc.find_all(class_="day-description My(10px)")
windText = wind.find('span', {'data-reactid': '455'}).text
windSpeedDir = wind.find('p', {'data-reactid': '456'}).text
baro = wind.find('span', {'data-reactid': '461'}).text
pressure = wind.find('p', {'data-reactid': '462'}).text
phase = sunMoon.find('div', {'data-reactid': '504'}).text
dayDesc = temp.find(class_="description Va(m) Px(2px) Fz(1.3em)--sm Fz(1.6em)")
currentTemp = temp.find('span', {'data-reactid': '37'}).text
degreeSymbol = temp.find('span', {'data-reactid': '38'}).text
high = temp.find('span', {'data-reactid': '29'}).text
low = temp.find('span', {'data-reactid': '33'}).text
city = weather.find(class_="city Fz(2em)--sm Fz(3.7em)--lg Fz(3.3em) Fw(n) M(0) Trsdu(.3s) desktop_Lh(1) smartphone_Lh(1)")
country = weather.find(class_="Fz(1.2em)--sm Fz(2em)--lg Fz(1.5em) Fw(200) country Trsdu(.3s) Lh(2.5)")
dateTime = weather.find(class_="Lts(1px) Fz(14px) Fs(i) Lh(2.5) Fw(300) Tsh($temperature-text-shadow)")

try:
    sunrise = sunMoon.find('span', {'data-reactid': '510'}).text
except:
    sunrise = sunMoon.find('span', {'data-reactid': '515'}).text
try:
    sunset = sunMoon.find('span', {'data-reactid': '511'}).text
except:
    sunset = sunMoon.find('span', {'data-reactid': '516'}).text

sunrise1 = sunrise.split(" ")
sunrise2 = sunrise1[0].split(":")
srHour = int(sunrise2[0])
srMinute = int(sunrise2[1])
sunset1 = sunset.split(" ")
sunset2 = sunset1[0].split(":")
ssHour = int(sunset2[0])
ssMinute = int(sunset2[1])

if now.hour > 12:
    hour = now.hour - 12
    AMPM = "PM"
else:
    hour = now.hour
    AMPM = "AM"

if now.hour >= srHour and now.hour < 12:
    ToD = "morning"
if now.hour >= 12 and now.hour < ssHour:
    ToD = "afternoon"
if now.hour > 12 and now.hour >= ssHour:
    ToD = "night"

print('Weather data for the city of', city.get_text(), 'in the country of', country.get_text())
print('Today is', "%02d" % (now.month), '/', "%02d" % (now.day), '/', now.year)
print('The current time is', "%02d" % (hour), ":", "%02d" % (now.minute), ":", "%02d" % (now.second), AMPM)
print('Right now it is a', dayDesc.get_text().lower(), ToD, 'sky.')
print('It is currently', currentTemp, degreeSymbol, 'F.')
print('The high for today is', high, 'F.')
print('The low for today is', low, 'F.')
print(start[0].get_text(), ' : ', end[0].get_text())
print(start[1].get_text(), '   : ', end[1].get_text())
print(start[2].get_text(), ' : ', end[2].get_text())
print(start[3].get_text(), '   : ', end[3].get_text())
print(windText, "       : ", windSpeedDir)
print(baro, "  : ", pressure)
print("Moon Phase  : ", phase)
print("Sunrise     : ", sunrise)
print("Sunset      : ", sunset)
print(dayNight[0].get_text())
print(dayNight[1].get_text())
</code>```

WOEID Script

```<code>import requests
import bs4 as BeautifulSoup
import pandas as pd
import WeatherAppMECH as mech

page = requests.get(mech.url)
code =  page.status_code
content = page.content
soup = BeautifulSoup.BeautifulSoup(content, 'html.parser')
search = soup.find(id="content")
results = search.find('div', {'id': 'lookup_result'})

rows=list()
for tr in results.find('table', {'id':'woeid_results_table'}):
    for td in tr:
        rows.append(td.string)
resultList=rows[1:]

Town = resultList[0]
State = resultList[1]
Country = resultList[2]
WOEID = resultList[3]
</code>```

MechanicalSoup Script

```<code>import requests
import mechanicalsoup
import bs4 as BeautifulSoup

browserurl = "http://woeid.rosselliot.co.nz"
userInput = input('Town, state, country, address, zipcode or landmark : ').replace(',','%20').replace(' ','%20')
browser = mechanicalsoup.StatefulBrowser()

browser.open(browserurl)
browser.select_form('form[action="http://woeid.rosselliot.co.nz/lookup"]')
browser["place"] = userInput

browser.close()

baseurl = "http://woeid.rosselliot.co.nz/lookup"
url = '%(U)s/%(I)s' % {'U': baseurl, "I": userInput}
</code>```

Title: Scraping Woeidlookup.com for WOEID

Body:
I am attempting to make more or less a weather checker. I am scraping Yahoo for this, as I cannot figure out how to use their API plus it seems like more fun to me. I haven't been coding using Python3 for very long. All of this code is being done on a RPI the version of Python3 it uses is 3.4.2.

The issue I have ran across is getting the WOEID number. I figured scraping Woeidlookup.com would be an easy task to get the number. However, now after trying various ways to get the data from the site I am here. I do not have any code to show for scraping this website as if it didn't work I just deleted it.

I am sure that someone on here knows how to input the required text into the
 field of the website and then submit it. Once it is submitted I have to scrape the table that shows up below the  field to get the WOEID number.

I have already completed the scrape for Yahoo weather which is posted below. Any critiques on the code for learning purposes would be appreciated. I have found a ton of useful information on this site the past few weeks and all of that knowledge for the most part went into this project. The pandas import is if I decide to add in a table later on instead of the current print() setup.

import requests
from bs4 import BeautifulSoup
import pandas as pd
import datetime

baseurl = "https://www.yahoo.com/news/weather"
Country = input("Country : ").replace(" ", "-")
State = input("State : ").replace(" ", "-")
Town = input("Town : ").replace(" ", "-")
WOEID = "" # this is what I need to figure out

url = '%(U)s/%(C)s/%(S)s/%(T)s-%(W)s' % {'U': baseurl, "C": Country, "S": State, "T": Town, "W": WOEID}

now = datetime.datetime.now()
hour = 0
minute = now.minute
AMPM = ""
ToD = ""

page = requests.get(url)
code =  page.status_code
content = page.content
soup = BeautifulSoup(content, 'html.parser')
weather = soup.find(class_="weather")
temp = soup.find(class_="temperature Fz(14px) Tsh($temperature-text-shadow)")
wind = weather.find(id="weather-wind")
sunMoon = weather.find(id='weather-sun-moon')
details = weather.find(id="weather-detail")
detail = details.find(class_="detail")
start = detail.find_all(class_="Fl(start)")
end = detail.find_all(class_="Fl(end)")
desc = detail.find(class_="description Py(10px) Px(4px) Fz(1em)")
dayNight = desc.find_all(class_="day-description My(10px)")
windText = wind.find('span', {'data-reactid': '455'}).text
windSpeedDir = wind.find('p', {'data-reactid': '456'}).text
baro = wind.find('span', {'data-reactid': '461'}).text
pressure = wind.find('p', {'data-reactid': '462'}).text
phase = sunMoon.find('div', {'data-reactid': '504'}).text
dayDesc = temp.find(class_="description Va(m) Px(2px) Fz(1.3em)--sm Fz(1.6em)")
currentTemp = temp.find('span', {'data-reactid': '37'}).text
degreeSymbol = temp.find('span', {'data-reactid': '38'}).text
high = temp.find('span', {'data-reactid': '29'}).text
low = temp.find('span', {'data-reactid': '33'}).text
city = weather.find(class_="city Fz(2em)--sm Fz(3.7em)--lg Fz(3.3em) Fw(n) M(0) Trsdu(.3s) desktop_Lh(1) smartphone_Lh(1)")
country = weather.find(class_="Fz(1.2em)--sm Fz(2em)--lg Fz(1.5em) Fw(200) country Trsdu(.3s) Lh(2.5)")
dateTime = weather.find(class_="Lts(1px) Fz(14px) Fs(i) Lh(2.5) Fw(300) Tsh($temperature-text-shadow)")

try:
    sunrise = sunMoon.find('span', {'data-reactid': '510'}).text
except:
    sunrise = sunMoon.find('span', {'data-reactid': '515'}).text
try:
    sunset = sunMoon.find('span', {'data-reactid': '511'}).text
except:
    sunset = sunMoon.find('span', {'data-reactid': '516'}).text

sunrise1 = sunrise.split(" ")
sunrise2 = sunrise1[0].split(":")
srHour = int(sunrise2[0])
srMinute = int(sunrise2[1])
sunset1 = sunset.split(" ")
sunset2 = sunset1[0].split(":")
ssHour = int(sunset2[0])
ssMinute = int(sunset2[1])

if now.hour > 12:
    hour = now.hour - 12
    AMPM = "PM"
else:
    hour = now.hour
    AMPM = "AM"

if now.hour >= srHour and now.hour < 12:
    ToD = "morning"
if now.hour >= 12 and now.hour - 12 < ssHour:
    ToD = "afternoon"
if now.hour > 12 and now.hour - 12 >= ssHour:
    ToD = "night"

print('Weather data for the city of', city.get_text(), 'in the country of', country.get_text())
print('Today is', "%02d" % (now.month), '/', "%02d" % (now.day), '/', now.year)
print('The current time is', "%02d" % (hour), ":", "%02d" % (now.minute), ":", "%02d" % (now.second), AMPM)
print('Right now it is a', dayDesc.get_text().lower(), ToD, 'sky.')
print('It is currently', currentTemp, degreeSymbol, 'F.')
print('The high for today is', high, 'F.')
print('The low for today is', low, 'F.')
print(start[0].get_text(), ' : ', end[0].get_text())
print(start[1].get_text(), '   : ', end[1].get_text())
print(start[2].get_text(), ' : ', end[2].get_text())
print(start[3].get_text(), '   : ', end[3].get_text())
print(windText, "       : ", windSpeedDir)
print(baro, "  : ", pressure)
print("Moon Phase  : ", phase)
print("Sunrise     : ", sunrise)
print("Sunset      : ", sunset)
print(dayNight[0].get_text())
print(dayNight[1].get_text())

Body:
After much coding, searching etc.. I have fixed the problem I was having by using a different website to get the WOEID and data. Here below are the completed scripts I made for the base of the project I am working on for school. I split it into 3 files and it is undocumented throughout the code, but it should be fairly easy to follow. Hopefully this helps someone who is also doing something like this even if it is probably coded poorly.

Main Script

import requests
from bs4 import BeautifulSoup
import pandas as pd
import datetime
import WeatherAppBS4_Woeid as woeid

baseurl = "https://www.yahoo.com/news/weather"
Country = woeid.Country.replace(" ", "-")
State = woeid.State.replace(" ", "-")
Town = woeid.Town.replace(" ", "-")
WOEID = woeid.WOEID

url = '%(U)s/%(C)s/%(S)s/%(T)s-%(W)s' % {'U': baseurl, "C": Country, "S": State, "T": Town, "W": WOEID}

now = datetime.datetime.now()
hour = 0
minute = now.minute
AMPM = ""
ToD = ""

page = requests.get(url)
code =  page.status_code
content = page.content
soup = BeautifulSoup(content, 'html.parser')
weather = soup.find(class_="weather")
temp = soup.find(class_="temperature Fz(14px) Tsh($temperature-text-shadow)")
wind = weather.find(id="weather-wind")
sunMoon = weather.find(id='weather-sun-moon')
details = weather.find(id="weather-detail")
detail = details.find(class_="detail")
start = detail.find_all(class_="Fl(start)")
end = detail.find_all(class_="Fl(end)")
desc = detail.find(class_="description Py(10px) Px(4px) Fz(1em)")
dayNight = desc.find_all(class_="day-description My(10px)")
windText = wind.find('span', {'data-reactid': '455'}).text
windSpeedDir = wind.find('p', {'data-reactid': '456'}).text
baro = wind.find('span', {'data-reactid': '461'}).text
pressure = wind.find('p', {'data-reactid': '462'}).text
phase = sunMoon.find('div', {'data-reactid': '504'}).text
dayDesc = temp.find(class_="description Va(m) Px(2px) Fz(1.3em)--sm Fz(1.6em)")
currentTemp = temp.find('span', {'data-reactid': '37'}).text
degreeSymbol = temp.find('span', {'data-reactid': '38'}).text
high = temp.find('span', {'data-reactid': '29'}).text
low = temp.find('span', {'data-reactid': '33'}).text
city = weather.find(class_="city Fz(2em)--sm Fz(3.7em)--lg Fz(3.3em) Fw(n) M(0) Trsdu(.3s) desktop_Lh(1) smartphone_Lh(1)")
country = weather.find(class_="Fz(1.2em)--sm Fz(2em)--lg Fz(1.5em) Fw(200) country Trsdu(.3s) Lh(2.5)")
dateTime = weather.find(class_="Lts(1px) Fz(14px) Fs(i) Lh(2.5) Fw(300) Tsh($temperature-text-shadow)")

try:
    sunrise = sunMoon.find('span', {'data-reactid': '510'}).text
except:
    sunrise = sunMoon.find('span', {'data-reactid': '515'}).text
try:
    sunset = sunMoon.find('span', {'data-reactid': '511'}).text
except:
    sunset = sunMoon.find('span', {'data-reactid': '516'}).text

sunrise1 = sunrise.split(" ")
sunrise2 = sunrise1[0].split(":")
srHour = int(sunrise2[0])
srMinute = int(sunrise2[1])
sunset1 = sunset.split(" ")
sunset2 = sunset1[0].split(":")
ssHour = int(sunset2[0])
ssMinute = int(sunset2[1])

if now.hour > 12:
    hour = now.hour - 12
    AMPM = "PM"
else:
    hour = now.hour
    AMPM = "AM"

if now.hour >= srHour and now.hour < 12:
    ToD = "morning"
if now.hour >= 12 and now.hour < ssHour:
    ToD = "afternoon"
if now.hour > 12 and now.hour >= ssHour:
    ToD = "night"

print('Weather data for the city of', city.get_text(), 'in the country of', country.get_text())
print('Today is', "%02d" % (now.month), '/', "%02d" % (now.day), '/', now.year)
print('The current time is', "%02d" % (hour), ":", "%02d" % (now.minute), ":", "%02d" % (now.second), AMPM)
print('Right now it is a', dayDesc.get_text().lower(), ToD, 'sky.')
print('It is currently', currentTemp, degreeSymbol, 'F.')
print('The high for today is', high, 'F.')
print('The low for today is', low, 'F.')
print(start[0].get_text(), ' : ', end[0].get_text())
print(start[1].get_text(), '   : ', end[1].get_text())
print(start[2].get_text(), ' : ', end[2].get_text())
print(start[3].get_text(), '   : ', end[3].get_text())
print(windText, "       : ", windSpeedDir)
print(baro, "  : ", pressure)
print("Moon Phase  : ", phase)
print("Sunrise     : ", sunrise)
print("Sunset      : ", sunset)
print(dayNight[0].get_text())
print(dayNight[1].get_text())

WOEID Script

import requests
import bs4 as BeautifulSoup
import pandas as pd
import WeatherAppMECH as mech

page = requests.get(mech.url)
code =  page.status_code
content = page.content
soup = BeautifulSoup.BeautifulSoup(content, 'html.parser')
search = soup.find(id="content")
results = search.find('div', {'id': 'lookup_result'})

rows=list()
for tr in results.find('table', {'id':'woeid_results_table'}):
    for td in tr:
        rows.append(td.string)
resultList=rows[1:]

Town = resultList[0]
State = resultList[1]
Country = resultList[2]
WOEID = resultList[3]

MechanicalSoup Script

import requests
import mechanicalsoup
import bs4 as BeautifulSoup

browserurl = "http://woeid.rosselliot.co.nz"
userInput = input('Town, state, country, address, zipcode or landmark : ').replace(',','%20').replace(' ','%20')
browser = mechanicalsoup.StatefulBrowser()

browser.open(browserurl)
browser.select_form('form[action="http://woeid.rosselliot.co.nz/lookup"]')
browser["place"] = userInput

browser.close()

baseurl = "http://woeid.rosselliot.co.nz/lookup"
url = '%(U)s/%(I)s' % {'U': baseurl, "I": userInput}


问:
Exclude property from WebApi OData (EF) response in c#
I'm working with a WebApi project in C# (EF code first) and I'm using OData.
I have a "User" model with Id, Name, LastName, Email, and Password.

In controller for example I have this code:

```<code>// GET: odata/Users
[EnableQuery]
public IQueryable<User> GetUsers()
{
    return db.Users;
}
</code>```

If I call /odata/Users I'll get all the data: Id, Name, LastName, Email, and Password.

How can I exclude Password from results but keep available in controller to make Linq queries?

答:
You should not query your Domain model directly in the controller.  Instead, create a QueryModel DTO that maps to the Domain model.

You can read more about these concepts in DDD and CQRS

Body:
I'm working with a WebApi project in C# (EF code first) and I'm using OData.
I have a "User" model with Id, Name, LastName, Email, and Password.

In controller for example I have this code:

// GET: odata/Users
[EnableQuery]
public IQueryable<User> GetUsers()
{
    return db.Users;
}

If I call /odata/Users I'll get all the data: Id, Name, LastName, Email, and Password.

How can I exclude Password from results but keep available in controller to make Linq queries?


问:
Why won't my Custom React Native Component Import Correctly
Currently, I have a simple React Native Expo app setup. I have two components App and QRreader.

I am trying to import the QRreader component into my main App component.

The Main App component code...

```<code>import React, { Component } from 'react';
import { Button, Text, View, StyleSheet } from 'react-native';
import { Constants, WebBrowser } from 'expo';
import QRreader from './qr';

export default class App extends Component {
  state = {
    result: null,
  };

  render() {
    return (
      <View style={styles.container}>
        <QRreader/>
      </View>
    );
  }

}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
  },
});
</code>```

The QR component code...

```<code>import React, { Component } from 'react';
import { Text, View, StyleSheet, Alert } from 'react-native';
import { Constants, BarCodeScanner, Permissions } from 'expo';

export default class QRreader extends Component {
  state = {
    hasCameraPermission: null
  };

  componentDidMount() {
    this._requestCameraPermission();
  }

  _requestCameraPermission = async () => {
    const { status } = await Permissions.askAsync(Permissions.CAMERA);
    this.setState({
      hasCameraPermission: status === 'granted',
    });
  };

  _handleBarCodeRead = data => {
    Alert.alert(
      'Scan successful!',
      JSON.stringify(data)
    );
  };

  render() {
    return (
      <View style={styles.container}>
        {this.state.hasCameraPermission === null ?
          <Text>Requesting for camera permission</Text> :
          this.state.hasCameraPermission === false ?
            <Text>Camera permission is not granted</Text> :
            <BarCodeScanner
              onBarCodeRead={this._handleBarCodeRead}
              style={{ height: 200, width: 200 }}
            />
        }
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
  }
});
</code>```

I tried different variations of the import using "./" "." "qr.js" "qr"

Im getting an error Unable to resolve module "qr.js" Module does not exist in the main module map.

My file structure is Here

答:
hmm...so it looked like I had to restart the Expo project for it to work without adding any additional code.

Just out of curiosity?
Where would I add AppRegistry.registerComponent('Main', () => App); exactly? and why would I have to do this?

Body:
Currently, I have a simple React Native Expo app setup. I have two components App and QRreader.

I am trying to import the QRreader component into my main App component.

The Main App component code...

import React, { Component } from 'react';
import { Button, Text, View, StyleSheet } from 'react-native';
import { Constants, WebBrowser } from 'expo';
import QRreader from './qr';

export default class App extends Component {
  state = {
    result: null,
  };

  render() {
    return (
      <View style={styles.container}>
        <QRreader/>
      </View>
    );
  }

}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
  },
});

The QR component code...

import React, { Component } from 'react';
import { Text, View, StyleSheet, Alert } from 'react-native';
import { Constants, BarCodeScanner, Permissions } from 'expo';

export default class QRreader extends Component {
  state = {
    hasCameraPermission: null
  };

  componentDidMount() {
    this._requestCameraPermission();
  }

  _requestCameraPermission = async () => {
    const { status } = await Permissions.askAsync(Permissions.CAMERA);
    this.setState({
      hasCameraPermission: status === 'granted',
    });
  };

  _handleBarCodeRead = data => {
    Alert.alert(
      'Scan successful!',
      JSON.stringify(data)
    );
  };

  render() {
    return (
      <View style={styles.container}>
        {this.state.hasCameraPermission === null ?
          <Text>Requesting for camera permission</Text> :
          this.state.hasCameraPermission === false ?
            <Text>Camera permission is not granted</Text> :
            <BarCodeScanner
              onBarCodeRead={this._handleBarCodeRead}
              style={{ height: 200, width: 200 }}
            />
        }
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
  }
});

I tried different variations of the import using "./" "." "qr.js" "qr"

Im getting an error Unable to resolve module "qr.js" Module does not exist in the main module map.

My file structure is Here


问:
Access nested Select query get the a row with a max value
I have two tables and need to create a query that lists all of the first table and a field from a second table where a second field in the second table is a maximum value.

```<code>Table1
MatID | MatCode | Name |
-----------------------
1     | A       | Ex1  |
2     | B       | Ex2  |
3     | C       | Ex3  |

Table 2
MatID | MatCode | OtherName | Count |
------------------------------------
1     | A       | Red       | 5     |
1     | A       | Blue      | 15    |
1     | A       | Green     | 2     |
2     | B       | Red       | 25    |
2     | B       | Blue      | 3     |
2     | B       | Green     | 1     |
3     | C       | Red       | 2     |
3     | C       | Blue      | 3     |
3     | C       | Green     | 11    |
</code>```

The Result would be

```<code>MatID | MatCode | Name | OtherName |
-----------------------------------
1     | A       | Ex1  | Blue
2     | B       | Ex2  | Red
3     | C       | Ex3  | Green
</code>```

Hope this is clear.

Thanks in Advance

答:
I would suggest a correlated subquery:</p>

```<code>select t1.*,
       (select top 1 t2.OtherName
        from table2 as t2
        where t2.MatId = t1.MatId
        order by count desc, matid  -- to prevent duplicates
       ) as OtherName
from table1 as t1;
</code>```

Body:
I have two tables and need to create a query that lists all of the first table and a field from a second table where a second field in the second table is a maximum value.

Table1
MatID | MatCode | Name |
-----------------------
1     | A       | Ex1  |
2     | B       | Ex2  |
3     | C       | Ex3  |

Table 2
MatID | MatCode | OtherName | Count |
------------------------------------
1     | A       | Red       | 5     |
1     | A       | Blue      | 15    |
1     | A       | Green     | 2     |
2     | B       | Red       | 25    |
2     | B       | Blue      | 3     |
2     | B       | Green     | 1     |
3     | C       | Red       | 2     |
3     | C       | Blue      | 3     |
3     | C       | Green     | 11    |

The Result would be

MatID | MatCode | Name | OtherName |
-----------------------------------
1     | A       | Ex1  | Blue
2     | B       | Ex2  | Red
3     | C       | Ex3  | Green

Hope this is clear.

Thanks in Advance

Body:
I would suggest a correlated subquery:

select t1.*,
       (select top 1 t2.OtherName
        from table2 as t2
        where t2.MatId = t1.MatId
        order by count desc, matid  -- to prevent duplicates
       ) as OtherName
from table1 as t1;


问:
isAvailableForServiceType(SLServiceTypeTwitter) always return true when installed Twitter client
```<code>SLComposeViewController.isAvailableForServiceType(SLServiceTypeTwitter)
</code>```

That's a method in the Social.framework.

The document say that the method returns a Boolean value indicating whether the service is accessible and at least one account is set up.

But when I installed Twitter client, the method always return true whether or not the account is added in the Settings.

I run a demo on real devices such as iPhone 6s with iOS 9.3, iPhone 6 Plus with iOS 9.0, iPhone 5s with iOS 8.2.

答:
I have the same  problem.and I use ACAccountStore to judge whether user has already set system twitter account</p>

```<code>    ACAccountStore *accountStore = [[ACAccountStore alloc] init];
    ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
    NSArray *twitterAccounts = [accountStore accountsWithAccountType:accountType];
</code>```

Body:
SLComposeViewController.isAvailableForServiceType(SLServiceTypeTwitter)

That's a method in the Social.framework.

The document say that the method returns a Boolean value indicating whether the service is accessible and at least one account is set up.

But when I installed Twitter client, the method always return true whether or not the account is added in the Settings.

I run a demo on real devices such as iPhone 6s with iOS 9.3, iPhone 6 Plus with iOS 9.0, iPhone 5s with iOS 8.2.

Body:
I have the same  problem.and I use ACAccountStore to judge whether user has already set system twitter account

    ACAccountStore *accountStore = [[ACAccountStore alloc] init];
    ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
    NSArray *twitterAccounts = [accountStore accountsWithAccountType:accountType];


问:
Java Implementing ActionListener methods in Constructor
Im trying to call my keyPressed method that I created (override) in my constructor for a game I am making to allow an object to move. I implemented ActionListener and KeyListener in the main class.

Is this even possible? I tried calling the method by this.keyPressed(KeyEvent e) but I don't know how to initialize e.

What would be the best way to do something like this?

```<code>Timer timer = new Timer(DELAY, this);
public Game(Main game) {

    this.game = game;
    gamePanel = new GamePanel();
    buttonPanel = new JPanel();
    buttonPanel.add(startButton);

    this.addKeyListener(this);
    this.setFocusable(true);
    this.setFocusTraversalKeysEnabled(false);
    this.getContentPane().add(gamePanel, BorderLayout.CENTER);
    this.getContentPane().add(buttonPanel, BorderLayout.PAGE_END);
    this.setSize(1000, 1000);
    this.setVisible(true);

    }

}

@Override
public void keyTyped(KeyEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void keyPressed(KeyEvent e) {

    switch (e.getKeyCode()) {
    case KeyEvent.VK_UP:
        game.move("u");
        break;

    case KeyEvent.VK_DOWN:
        game.move("d");
        break;

    case KeyEvent.VK_RIGHT:
        game.move("r");
        break;

    case KeyEvent.VK_LEFT:
        game.move("l");
        break;
    }
}
@Override
public void actionPerformed(ActionEvent e) {

    Object src = e.getSource();

    if (src == timer) {
        game.updateBoard();
        if (game.gameEnded()) {
            timer.stop();
            }
        repaint();

    } else if (src == startButton) {

        if (timer.isRunning()) {
            timer.stop();
        } else {
            timer.stop();
        }
    }
}
</code>```

答:
The problem is here:

```<code>while(!game.gameEnded()) {
    game.updateBoard();
    KeyEvent e = null;
    this.keyPressed(e);
}
</code>```

If your constructor is called with the Swing Event-Dispatching-Thread, it blocks it, and no event can therefore be dispatched.

The correct way should be using a javax.swing.Timer, which fires an ActionEvent periodically.

```<code>int period = 1000;//fire ActionEvent every second
Timer timer = new Timer(period,new ActionListener(){
    public void actionPerformed(ActionEvent e){
        //do your stuff, for example
        game.updateBoard();
    }
});
timer.start();
</code>```

You shouldn't invoke the methods in EventListener by yourself since they should all be handled by the Event-Dispatching-Thread.

Body:
Im trying to call my keyPressed method that I created (override) in my constructor for a game I am making to allow an object to move. I implemented ActionListener and KeyListener in the main class.

Is this even possible? I tried calling the method by this.keyPressed(KeyEvent e) but I don't know how to initialize e.

What would be the best way to do something like this?

Timer timer = new Timer(DELAY, this);
public Game(Main game) {

    this.game = game;
    gamePanel = new GamePanel();
    buttonPanel = new JPanel();
    buttonPanel.add(startButton);

    this.addKeyListener(this);
    this.setFocusable(true);
    this.setFocusTraversalKeysEnabled(false);
    this.getContentPane().add(gamePanel, BorderLayout.CENTER);
    this.getContentPane().add(buttonPanel, BorderLayout.PAGE_END);
    this.setSize(1000, 1000);
    this.setVisible(true);

    }

}

@Override
public void keyTyped(KeyEvent e) {
    // TODO Auto-generated method stub

}

@Override
public void keyPressed(KeyEvent e) {

    switch (e.getKeyCode()) {
    case KeyEvent.VK_UP:
        game.move("u");
        break;

    case KeyEvent.VK_DOWN:
        game.move("d");
        break;

    case KeyEvent.VK_RIGHT:
        game.move("r");
        break;

    case KeyEvent.VK_LEFT:
        game.move("l");
        break;
    }
}
@Override
public void actionPerformed(ActionEvent e) {

    Object src = e.getSource();

    if (src == timer) {
        game.updateBoard();
        if (game.gameEnded()) {
            timer.stop();
            }
        repaint();

    } else if (src == startButton) {

        if (timer.isRunning()) {
            timer.stop();
        } else {
            timer.stop();
        }
    }
}

Body:
The problem is here:

while(!game.gameEnded()) {
    game.updateBoard();
    KeyEvent e = null;
    this.keyPressed(e);
}

If your constructor is called with the Swing Event-Dispatching-Thread, it blocks it, and no event can therefore be dispatched.

The correct way should be using a javax.swing.Timer, which fires an ActionEvent periodically.

int period = 1000;//fire ActionEvent every second
Timer timer = new Timer(period,new ActionListener(){
    public void actionPerformed(ActionEvent e){
        //do your stuff, for example
        game.updateBoard();
    }
});
timer.start();

You shouldn't invoke the methods in EventListener by yourself since they should all be handled by the Event-Dispatching-Thread.


问:
how to select data on sql using group by
i have table

i would like to select like this

how to get data count_attendance?

答:
you can use subquery to do that:

select name, gol, count(attendance) as count_data,(Select count(attendance) from tablename n where n.attendance='yes' and n.name=tablename.name and n.gol=tablename.gol) as count_attendance from tablename group by name,gol

Just replace tablename with the name of your table.


问:
How to extract the substring between two markers?
Let's say I have a string 'gfgfdAAA1234ZZZuijjk' and I want to extract just the '1234' part.

I only know what will be the few characters directly before AAA, and after ZZZ the part I am interested in 1234.

With sed it is possible to do something like this with a string:

```<code>echo "$STRING" | sed -e "s|.*AAA\(.*\)ZZZ.*|\1|"
</code>```

And this will give me 1234 as a result.

How to do the same thing in Python?

答:
One liners that return other string if there was no match.
Edit: improved version uses next function, replace "not-found" with something else if needed:

```<code>import re
res = next( (m.group(1) for m in [re.search("AAA(.*?)ZZZ", "gfgfdAAA1234ZZZuijjk" ),] if m), "not-found" )
</code>```

My other method to do this, less optimal, uses regex 2nd time, still didn't found a shorter way:

```<code>import re
res = ( ( re.search("AAA(.*?)ZZZ", "gfgfdAAA1234ZZZuijjk") or re.search("()","") ).group(1) )
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Let's say I have a string 'gfgfdAAA1234ZZZuijjk' and I want to extract just the '1234' part.

I only know what will be the few characters directly before AAA, and after ZZZ the part I am interested in 1234.

With sed it is possible to do something like this with a string:

echo "$STRING" | sed -e "s|.*AAA\(.*\)ZZZ.*|\1|"

And this will give me 1234 as a result.

How to do the same thing in Python?

Body:
One liners that return other string if there was no match.
Edit: improved version uses next function, replace "not-found" with something else if needed:

import re
res = next( (m.group(1) for m in [re.search("AAA(.*?)ZZZ", "gfgfdAAA1234ZZZuijjk" ),] if m), "not-found" )

My other method to do this, less optimal, uses regex 2nd time, still didn't found a shorter way:

import re
res = ( ( re.search("AAA(.*?)ZZZ", "gfgfdAAA1234ZZZuijjk") or re.search("()","") ).group(1) )


问:
How to add series to an empty chart without breaking the plot border in highcharts
I'm trying to  add a series to an empty chart in high charts, this chart will sometimes have a plot border but when adding a series to a chart with a plot border, the plot border doesn't seem to adjust  to meet the new plot area.

Here is a jsfiddle with the problem
http://jsfiddle.net/Lzpztwf7/1/

```<code>var chart = Highcharts.chart('container', {
    chart: {
            renderTo: 'container',
            borderWidth: 1,
            borderColor: '#fff',
            plotBorderWidth: 1,
            plotBorderColor: '#777',
    },

    xAxis: {
        categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    },
});

chart.addSeries({"name":"series 1","data": [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]});
</code>```

And here is a jsfiddle of how it should look, with the series defined in the options:
http://jsfiddle.net/ebj9jn6w/

```<code>var chart = Highcharts.chart('container', {
    chart: {
            renderTo: 'container',
            borderWidth: 1,
            borderColor: '#fff',
            plotBorderWidth: 1,
            plotBorderColor: '#777',
    },
   xAxis: {
           categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
        },
        series: [{"name":"series 1","data": [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]}]
    });
</code>```

It's not possible for me to just add the series in at the start because the users add the data in, and can remove it and add new data, as well as change various options on the chart either before or after adding data.

答:
Try adding an empty series in the initial options and the use the series.update from the API to update

HIGHCHARTS DEMO

```<code>var chart = Highcharts.chart('container', {
    chart: {
            renderTo: 'container',
            borderWidth: 1,
            borderColor: '#fff',
            plotBorderWidth: 1,
            plotBorderColor: '#777',
    },

    xAxis: {
        categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    },
    series: [{}]
});

chart.series[0].update({name: "Your series", data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]})
</code>```

Body:
I'm trying to  add a series to an empty chart in high charts, this chart will sometimes have a plot border but when adding a series to a chart with a plot border, the plot border doesn't seem to adjust  to meet the new plot area.

Here is a jsfiddle with the problem
http://jsfiddle.net/Lzpztwf7/1/

var chart = Highcharts.chart('container', {
    chart: {
            renderTo: 'container',
            borderWidth: 1,
            borderColor: '#fff',
            plotBorderWidth: 1,
            plotBorderColor: '#777',
    },

    xAxis: {
        categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    },
});

chart.addSeries({"name":"series 1","data": [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]});

And here is a jsfiddle of how it should look, with the series defined in the options:
http://jsfiddle.net/ebj9jn6w/

var chart = Highcharts.chart('container', {
    chart: {
            renderTo: 'container',
            borderWidth: 1,
            borderColor: '#fff',
            plotBorderWidth: 1,
            plotBorderColor: '#777',
    },
   xAxis: {
           categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
        },
        series: [{"name":"series 1","data": [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]}]
    });

It's not possible for me to just add the series in at the start because the users add the data in, and can remove it and add new data, as well as change various options on the chart either before or after adding data.

Body:
Try adding an empty series in the initial options and the use the series.update from the API to update

HIGHCHARTS DEMO

var chart = Highcharts.chart('container', {
    chart: {
            renderTo: 'container',
            borderWidth: 1,
            borderColor: '#fff',
            plotBorderWidth: 1,
            plotBorderColor: '#777',
    },

    xAxis: {
        categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
    },
    series: [{}]
});

chart.series[0].update({name: "Your series", data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]})


问:
Google Sheets multiple search and replace from a list
I am looking for a solution to search for certain strings in a Google Sheet and, when found, replace them with another string from a list in another sheet.

For better understanding, I prepared a Sheet for you:

https://docs.google.com/a/vicampo.de/spreadsheets/d/1mETtAY72K6ST-hg1qOU9651265nGq0qvcgvzMRqHDO8/edit?usp=sharing

So here's the exact task I want to achieve:

In every single cell in column A of sheet "Text", look for the strings given in column A in sheet "List" and, when found, replace it with the corresponding string in column B of the sheet "List".

See my Example: Look in cell A1 for the string "Lorem" and replace it with "Xlorem", then look for the string "Ipsum" and replace it with "Xipsum", then look for the string "amet" and replace it with "Xamet" then move on to cell B1 and start again looking for the strings...

I have tried different functions and managed to do this with a function for one cell. But how to do it in a loop?

Thanks everyone who is interested in helping out with this problem!

答:
Probably the best for you, in this case, should be creating a new function to your Google Spreadsheet. It tends to be, in the general case, more simple, clear and powerfull than that kind of complex formulas that should do the same.

In this particular case, I have the same problem, so you can use the same function:

Click on "Tools" menu, then click on the "Script Editor" option. Into the script editor, erase the draft and paste this function:

function preg_quote( str ) {
  // http://kevin.vanzonneveld.net
  // +   original by: booeyOH
  // +   improved by: Ates Goral (http://magnetiq.com)
  // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // +   bugfixed by: Onno Marsman
  // *     example 1: preg_quote("$40");
  // *     returns 1: '\$40'
  // *     example 2: preg_quote("*RRRING* Hello?");
  // *     returns 2: '\*RRRING\* Hello\?'
  // *     example 3: preg_quote("\\.+*?[^]$(){}=!<>|:");
  // *     returns 3: '\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:'

  return (str+'').replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:])/g, "\\$1");
}

function ARRAYREPLACE(input,fromList,toList,caseSensitive){
  /* default behavior it is not case sensitive */
  if( caseSensitive === undefined ){
    caseSensitive = false;
  }
  /* if the from list it is not a list, become a list */
  if( typeof fromList != "object" ) {
    fromList = [ fromList ];
  }
  /* if the to list it is not a list, become a list */
  if( typeof toList != "object" ) {
    toList = [ toList ];
  }
  /* force the input be a string */
  var result = input.toString();

  /* iterates using the max size */
  var bigger  = Math.max( fromList.length, toList.length) ;

  /* defines the words separators */
  var arrWordSeparator = [ ".", ",", ";", " " ];

  /* interate into the lists */
  for(var i = 0; i < bigger; i++ ) {
    /* get the word that should be replaced */
    var fromValue = fromList[ ( i % ( fromList.length ) ) ]
    /* get the new word that should replace */
    var toValue = toList[ ( i % ( toList.length ) ) ]

    /* do not replace undefined */
    if ( fromValue === undefined ) {
      continue;
    }
    if ( toValue == undefined ) {
      toValue = "";
    }

    /* apply case sensitive rule */
    var caseRule = "g";
    if( !caseSensitive ) {
      /* make the regex case insensitive */
      caseRule = "gi";
    }

    /* for each end word char, make the replacement and update the result */
    for ( var j = 0; j < arrWordSeparator.length; j++ ) {

      /* from value being the first word of the string */
      result =  result.replace( new RegExp( "^(" + preg_quote( fromValue + arrWordSeparator[ j ] ) + ")" , caseRule ), toValue + arrWordSeparator[ j ] );

      /* from value being the last word of the string */
      result =  result.replace( new RegExp( "(" + preg_quote( arrWordSeparator[ j ] + fromValue ) + ")$" , caseRule ), arrWordSeparator[ j ] + toValue );

      /* from value in the middle of the string between two word separators */
      for ( var k = 0; k < arrWordSeparator.length; k++ ) {
        result =  result.replace(
          new RegExp(
            "(" + preg_quote( arrWordSeparator[ j ] + fromValue + arrWordSeparator[ k ] ) + ")" ,
            caseRule
          ),
          /* need to keep the same word separators */
          arrWordSeparator[ j ] + toValue + arrWordSeparator[ k ]
        );
      }
    }

    /* from value it is the only thing in the string */
    result =  result.replace( new RegExp( "^(" + preg_quote( fromValue ) + ")$" , caseRule ), toValue );
  }
  /* return the new result */
  return result;
}
```
<p>Just save your script and the new function it will be available to you. Now, you have the function that replaces all the first values list by the second value list.</p>
```=ARRAYREPLACE(C2;A1:A4;B1:B4)
```

for example, takes the C2 text and replaces all the elements found in the A1:A4 list by the equivalent into the B1:B4 list.

Body:
Probably the best for you, in this case, should be creating a new function to your Google Spreadsheet. It tends to be, in the general case, more simple, clear and powerfull than that kind of complex formulas that should do the same.

In this particular case, I have the same problem, so you can use the same function:

Click on "Tools" menu, then click on the "Script Editor" option. Into the script editor, erase the draft and paste this function:

function preg_quote( str ) {
  // http://kevin.vanzonneveld.net
  // +   original by: booeyOH
  // +   improved by: Ates Goral (http://magnetiq.com)
  // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
  // +   bugfixed by: Onno Marsman
  // *     example 1: preg_quote("$40");
  // *     returns 1: '\$40'
  // *     example 2: preg_quote("*RRRING* Hello?");
  // *     returns 2: '\*RRRING\* Hello\?'
  // *     example 3: preg_quote("\\.+*?[^]$(){}=!<>|:");
  // *     returns 3: '\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:'

  return (str+'').replace(/([\\\.\+\*\?\[\^\]\$\(\)\{\}\=\!\<\>\|\:])/g, "\\$1");
}

function ARRAYREPLACE(input,fromList,toList,caseSensitive){
  /* default behavior it is not case sensitive */
  if( caseSensitive === undefined ){
    caseSensitive = false;
  }
  /* if the from list it is not a list, become a list */
  if( typeof fromList != "object" ) {
    fromList = [ fromList ];
  }
  /* if the to list it is not a list, become a list */
  if( typeof toList != "object" ) {
    toList = [ toList ];
  }
  /* force the input be a string */
  var result = input.toString();

  /* iterates using the max size */
  var bigger  = Math.max( fromList.length, toList.length) ;

  /* defines the words separators */
  var arrWordSeparator = [ ".", ",", ";", " " ];

  /* interate into the lists */
  for(var i = 0; i < bigger; i++ ) {
    /* get the word that should be replaced */
    var fromValue = fromList[ ( i % ( fromList.length ) ) ]
    /* get the new word that should replace */
    var toValue = toList[ ( i % ( toList.length ) ) ]

    /* do not replace undefined */
    if ( fromValue === undefined ) {
      continue;
    }
    if ( toValue == undefined ) {
      toValue = "";
    }

    /* apply case sensitive rule */
    var caseRule = "g";
    if( !caseSensitive ) {
      /* make the regex case insensitive */
      caseRule = "gi";
    }

    /* for each end word char, make the replacement and update the result */
    for ( var j = 0; j < arrWordSeparator.length; j++ ) {

      /* from value being the first word of the string */
      result =  result.replace( new RegExp( "^(" + preg_quote( fromValue + arrWordSeparator[ j ] ) + ")" , caseRule ), toValue + arrWordSeparator[ j ] );

      /* from value being the last word of the string */
      result =  result.replace( new RegExp( "(" + preg_quote( arrWordSeparator[ j ] + fromValue ) + ")$" , caseRule ), arrWordSeparator[ j ] + toValue );

      /* from value in the middle of the string between two word separators */
      for ( var k = 0; k < arrWordSeparator.length; k++ ) {
        result =  result.replace(
          new RegExp(
            "(" + preg_quote( arrWordSeparator[ j ] + fromValue + arrWordSeparator[ k ] ) + ")" ,
            caseRule
          ),
          /* need to keep the same word separators */
          arrWordSeparator[ j ] + toValue + arrWordSeparator[ k ]
        );
      }
    }

    /* from value it is the only thing in the string */
    result =  result.replace( new RegExp( "^(" + preg_quote( fromValue ) + ")$" , caseRule ), toValue );
  }
  /* return the new result */
  return result;
}

Just save your script and the new function it will be available to you. Now, you have the function that replaces all the first values list by the second value list.

=ARRAYREPLACE(C2;A1:A4;B1:B4)

for example, takes the C2 text and replaces all the elements found in the A1:A4 list by the equivalent into the B1:B4 list.


问:
How to compile C++ files organized in a directory structure?
I've written a bunch of code now, and sorted it in a fashion similar to this outline:

```<code>project/
+ include/
| + bar/
| |   bar.hpp
|   foo.hpp
+ src/
| + bar/
| |   bar.cpp
|   foo.cpp
|   main.cpp
</code>```

My question is, how do I call g++ now, so that it links everything together nicely?

I've already figured out that I need to call it with the -I option pointing to the include/ directory. I'm guessing it would make most sense calling g++ from the project/ folder. Also, I'm considering writing a Makefile to automate this process, but I have to admit I haven't done very much research on that yet.

答: I think the easiest approach is to use an IDE - for example NetBeans will generate Makefiles for you (other IDEs are available).</p>

Body:
I've written a bunch of code now, and sorted it in a fashion similar to this outline:

project/
+ include/
| + bar/
| |   bar.hpp
|   foo.hpp
+ src/
| + bar/
| |   bar.cpp
|   foo.cpp
|   main.cpp

My question is, how do I call g++ now, so that it links everything together nicely?

I've already figured out that I need to call it with the -I option pointing to the include/ directory. I'm guessing it would make most sense calling g++ from the project/ folder. Also, I'm considering writing a Makefile to automate this process, but I have to admit I haven't done very much research on that yet.


问:
How do I write helper function in C to return a random number from a specific range and avoid a segmentation fault?
I'm attempting to write a program in which a helper function returns a random integer between -999 and 999 and returns it for use in the main function.

```<code>#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int rand(void) {
    int n;
    n = ((rand() % 1998 + 1) - 999);
    return n;
}

int main() {
    srand(time(NULL));     /* seed the random number generator */
    printf("%d\n",rand());

    return 0;
}
</code>```

However, despite many different tweaks and simplifications of the main function to debug at bare bones, I'm still getting a segmentation fault.

What am I missing? What am I doing wrong?

答:
Compiling with -Wall gives you the clue:

```<code>$ gcc -Wall -o x x.c
x.c:6:16: warning: all paths through this function will call itself
      [-Winfinite-recursion]
int rand(void) {
               ^
1 warning generated.
</code>```

Your rand() function is calling itself, not the library rand(), as they have the same name. Rename your function. Renaming it to rand1 works fine here.

Body:
I'm attempting to write a program in which a helper function returns a random integer between -999 and 999 and returns it for use in the main function.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int rand(void) {
    int n;
    n = ((rand() % 1998 + 1) - 999);
    return n;
}

int main() {
    srand(time(NULL));     /* seed the random number generator */
    printf("%d\n",rand());

    return 0;
}

However, despite many different tweaks and simplifications of the main function to debug at bare bones, I'm still getting a segmentation fault.

What am I missing? What am I doing wrong?

Body:
Compiling with -Wall gives you the clue:

$ gcc -Wall -o x x.c
x.c:6:16: warning: all paths through this function will call itself
      [-Winfinite-recursion]
int rand(void) {
               ^
1 warning generated.

Your rand() function is calling itself, not the library rand(), as they have the same name. Rename your function. Renaming it to rand1 works fine here.


问:
How to Get Groups of Files from GetFiles()
I have to process files everyday.  The files are named like so:

```<code> fg1a.mmddyyyy
 fg1b.mmddyyyy
 fg1c.mmddyyyy

 fg2a.mmddyyyy
 fg2b.mmddyyyy
 fg2c.mmddyyyy
 fg2d.mmddyyyy
</code>```

If the entire file group is there for a particular date, I can process it.  If it isn't there, I should not process it.  I may have several partial file groups that run over several days.  So when I have fg1a.12062017, fg1b.12062017 and fg1c.12062017, I can process that group (fg1) only.

Here is my code so far.  It doesn't work because I can't figure out how to get only the full groups to add to the the processing file list.

```<code>        fileList = Directory.GetFiles(@"c:\temp\");

        string[] fileGroup1 = { "FG1A", "FG1B", "FG1C" }; // THIS IS A FULL GROUP
        string[] fileGroup2 = { "FG2A", "FG2B", "FG2C", "FG2D" };

        List<string> fileDates = new List<string>();
        List<string> procFileList;

        // get a list of file dates
        foreach (string fn in fileList)
        {
            string dateString = fn.Substring(fn.IndexOf('.'), 9);
            if (!fileDates.Contains(dateString))
            {
                fileDates.Add(dateString);
            }
        }

        bool allFiles = true;
        foreach (string fg in fileGroup1)
        {
            foreach (string fd in fileDates)
            {
                string finder = fg + fd;
                bool foundIt = false;
                foreach (string fn in fileList)
                {
                    if (fn.ToUpper().Contains(finder))
                    {
                        foundIt = true;
                    }

                }
                if (!foundIt)
                {
                    allFiles = false;
                }

                else
                {
                    foreach (string fn in fileList)
                    {
                        procFileList.Add(fn);
                    }

                }

            }

        }

        foreach (string fg in fileGroup2)
        {
            foreach (string fd in fileDates)
            {
                string finder = fg + fd;
                bool foundIt = false;
                foreach (string fn in fileList)
                {
                    if (fn.ToUpper().Contains(finder))
                    {
                        foundIt = true;
                    }

                }
                if (!foundIt)
                {
                    allFiles = false;
                }
                else
                {
                    foreach (string fn in fileList)
                    {
                        procFileList.Add(fn);
                    }

                }
            }

        }
</code>```

Any help or advice would be greatly appreciated.

答:
Because it can sometimes get messy dealing with multiple lists, groupings, and parsing file names, I would start by creating a class that represents a FileGroupItem. This class would have a Parse method that takes in a file path, and then has properties that represent the group part and date part of the file name, as well as the full path to the file:

```<code>public class FileGroupItem
{
    public string DatePart { get; set; }
    public string GroupName { get; set; }
    public string FilePath { get; set; }

    public static FileGroupItem Parse(string filePath)
    {
        if (string.IsNullOrWhiteSpace(filePath)) return null;

        // Split the file name on the '.' character to get the group and date parts
        var fileParts = Path.GetFileName(filePath).Split('.');
        if (fileParts.Length != 2) return null;

        return new FileGroupItem
        {
            GroupName = fileParts[0],
            DatePart = fileParts[1],
            FilePath = filePath
        };
    }
}
</code>```

Then, in my main code, I would create a list of the file group definitions, and then populate a list of FileGroupItems from the directory we're scanning. After that, we can determine if any file group definition is complete by comparing it's items (in a case-insensitive way) to the actual FileGroupItems we found in the directory (after first grouping the FileGroupItems by it's DatePart). If the intersection of these two lists has the same number of items as the file group definition, then it's complete and we can process that group.

Maybe it will make more sense in code:

```<code>private static void Main()
{
    var scanDirectory = @"f:\public\temp\";
    var processedDirectory = @"f:\public\temp2\";

    // The lists that define a complete group
    var fileGroupDefinitions = new List<List<string>>
    {
        new List<string> {"FG1A", "FG1B", "FG1C"},
        new List<string> {"FG2A", "FG2B", "FG2C", "FG2D"}
    };

    // Populate a list of FileGroupItems from the files
    // in our directory, and group them on the DatePart
    var fileGroups = Directory.EnumerateFiles(scanDirectory)
        .Select(FileGroupItem.Parse)
        .GroupBy(f => f.DatePart);

    // Now go through each group and compare the items
    // for that date with our file group definitions
    foreach (var fileGroup in fileGroups)
    {
        foreach (var fileGroupDefinition in fileGroupDefinitions)
        {
            // Get the intersection of the group definition and this file group
            var intersection = fileGroup
                .Where(f => fileGroupDefinition.Contains(
                    f.GroupName, StringComparer.OrdinalIgnoreCase))
                .ToList();

            // If all the items in the definition are there, then process the files
            if (intersection.Count == fileGroupDefinition.Count)
            {
                foreach (var fileGroupItem in intersection)
                {
                    Console.WriteLine($"Processing file: {fileGroupItem.FilePath}");

                    // Move the file to the processed directory
                    File.Move(fileGroupItem.FilePath,
                        Path.Combine(processedDirectory,
                            Path.GetFileName(fileGroupItem.FilePath)));
                }
            }
        }
    }

    Console.WriteLine("\nDone!\nPress any key to exit...");
    Console.ReadKey();
}
</code>```

Body:
I have to process files everyday.  The files are named like so:

 fg1a.mmddyyyy
 fg1b.mmddyyyy
 fg1c.mmddyyyy

 fg2a.mmddyyyy
 fg2b.mmddyyyy
 fg2c.mmddyyyy
 fg2d.mmddyyyy

If the entire file group is there for a particular date, I can process it.  If it isn't there, I should not process it.  I may have several partial file groups that run over several days.  So when I have fg1a.12062017, fg1b.12062017 and fg1c.12062017, I can process that group (fg1) only.

Here is my code so far.  It doesn't work because I can't figure out how to get only the full groups to add to the the processing file list.

        fileList = Directory.GetFiles(@"c:\temp\");

        string[] fileGroup1 = { "FG1A", "FG1B", "FG1C" }; // THIS IS A FULL GROUP
        string[] fileGroup2 = { "FG2A", "FG2B", "FG2C", "FG2D" };

        List<string> fileDates = new List<string>();
        List<string> procFileList;

        // get a list of file dates
        foreach (string fn in fileList)
        {
            string dateString = fn.Substring(fn.IndexOf('.'), 9);
            if (!fileDates.Contains(dateString))
            {
                fileDates.Add(dateString);
            }
        }

        bool allFiles = true;
        foreach (string fg in fileGroup1)
        {
            foreach (string fd in fileDates)
            {
                string finder = fg + fd;
                bool foundIt = false;
                foreach (string fn in fileList)
                {
                    if (fn.ToUpper().Contains(finder))
                    {
                        foundIt = true;
                    }

                }
                if (!foundIt)
                {
                    allFiles = false;
                }

                else
                {
                    foreach (string fn in fileList)
                    {
                        procFileList.Add(fn);
                    }

                }

            }

        }

        foreach (string fg in fileGroup2)
        {
            foreach (string fd in fileDates)
            {
                string finder = fg + fd;
                bool foundIt = false;
                foreach (string fn in fileList)
                {
                    if (fn.ToUpper().Contains(finder))
                    {
                        foundIt = true;
                    }

                }
                if (!foundIt)
                {
                    allFiles = false;
                }
                else
                {
                    foreach (string fn in fileList)
                    {
                        procFileList.Add(fn);
                    }

                }
            }

        }

Any help or advice would be greatly appreciated.

Body:
Because it can sometimes get messy dealing with multiple lists, groupings, and parsing file names, I would start by creating a class that represents a FileGroupItem. This class would have a Parse method that takes in a file path, and then has properties that represent the group part and date part of the file name, as well as the full path to the file:

public class FileGroupItem
{
    public string DatePart { get; set; }
    public string GroupName { get; set; }
    public string FilePath { get; set; }

    public static FileGroupItem Parse(string filePath)
    {
        if (string.IsNullOrWhiteSpace(filePath)) return null;

        // Split the file name on the '.' character to get the group and date parts
        var fileParts = Path.GetFileName(filePath).Split('.');
        if (fileParts.Length != 2) return null;

        return new FileGroupItem
        {
            GroupName = fileParts[0],
            DatePart = fileParts[1],
            FilePath = filePath
        };
    }
}

Then, in my main code, I would create a list of the file group definitions, and then populate a list of FileGroupItems from the directory we're scanning. After that, we can determine if any file group definition is complete by comparing it's items (in a case-insensitive way) to the actual FileGroupItems we found in the directory (after first grouping the FileGroupItems by it's DatePart). If the intersection of these two lists has the same number of items as the file group definition, then it's complete and we can process that group.

Maybe it will make more sense in code:

private static void Main()
{
    var scanDirectory = @"f:\public\temp\";
    var processedDirectory = @"f:\public\temp2\";

    // The lists that define a complete group
    var fileGroupDefinitions = new List<List<string>>
    {
        new List<string> {"FG1A", "FG1B", "FG1C"},
        new List<string> {"FG2A", "FG2B", "FG2C", "FG2D"}
    };

    // Populate a list of FileGroupItems from the files
    // in our directory, and group them on the DatePart
    var fileGroups = Directory.EnumerateFiles(scanDirectory)
        .Select(FileGroupItem.Parse)
        .GroupBy(f => f.DatePart);

    // Now go through each group and compare the items
    // for that date with our file group definitions
    foreach (var fileGroup in fileGroups)
    {
        foreach (var fileGroupDefinition in fileGroupDefinitions)
        {
            // Get the intersection of the group definition and this file group
            var intersection = fileGroup
                .Where(f => fileGroupDefinition.Contains(
                    f.GroupName, StringComparer.OrdinalIgnoreCase))
                .ToList();

            // If all the items in the definition are there, then process the files
            if (intersection.Count == fileGroupDefinition.Count)
            {
                foreach (var fileGroupItem in intersection)
                {
                    Console.WriteLine($"Processing file: {fileGroupItem.FilePath}");

                    // Move the file to the processed directory
                    File.Move(fileGroupItem.FilePath,
                        Path.Combine(processedDirectory,
                            Path.GetFileName(fileGroupItem.FilePath)));
                }
            }
        }
    }

    Console.WriteLine("\nDone!\nPress any key to exit...");
    Console.ReadKey();
}


问:
Padded text padding overflow not affecting word break
Word "under" should go to next line, but it doesn't cause of inline padding i think.

Is there anyway i can get text to break to next line when white padding touches edge of container.

Text needs to stay as inline cause i need that blank space between text lines. Tho if you have solution which requires to change that and result looks same as mine only the problem is fixed, than that will work too.

P.S. My container in real situation is 100% 100% so width,height is not fixed for the block.

It seems like it's not possible cause inline padding doesnt affect wrapping in any way and is completely ignored.

body {
  background: #111111;
}
.container {
  width: 338px;
  height: 600px;
  background-color: #000;
  font-family: Arial;
  text-align: center;
}
h1 {
  font-weight: bold;
  font-size: 48px;
  background-color: #fff;
  display: inline;
  line-height: 95px;
  box-decoration-break: clone;
  -webkit-box-decoration-break: clone;
  padding: 10px 20px 10px 20px;
}
.sub {
  display: inline;
  background-color: #fff;
  font-size: 28px;
  padding: 20px 20px;
  line-height: 90px;
  box-decoration-break: clone;
  -webkit-box-decoration-break: clone;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <h1>Heading title</h1>
  <br/>
  <span class="sub">Some random text under heading title</span>
</div></code>```

答:
Without using JS you won't be able to get the needed result just by CSS.
Your current code allows  to overflow container's border (not sure why) while
 tag breaks the word exactly on containers box border. My best guess is to include whole text in
 and use class definition for
 and with  as a child element to change the line-height & general styling of elements below.

I'd suggest to redo your code like an example below.

body {
  width: 100%;
  height: auto;
  padding: 20px;
  background: #000;
}

.container {
  position: relative;
  width: 300px;
  margin: auto;
  height: auto;
  background: #333;
  padding: 20px;
}

h1 {
  font-weight: 800;
  color: #333;
  text-align: center;
}

h1 span {
  -webkit-box-decoration-break: clone;
  box-decoration-break: clone;
}

h1.title span{
  padding: 10px 20px;
  background-color: #fff;
  font-size: 1.5em;
  line-height: 2em;
  margin-bottom: 40px;
}

h1.desc span {
  padding: 5px 10px;
  background-color: #ddd;
  font-size: 1em;
  line-height: 1.8em;
  margin-bottom: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="container">
  <h1 class="title">
    <span>Long heading title here</span>
  </h1>

  <h1 class="desc">
    <span>The quick brown fox jumps over the lazy dog.</span>
  </h1>
</section></code>```

As you can see in snippet both  &
 elements respect the .container border and doesn't overflow it.

Body:
Word "under" should go to next line, but it doesn't cause of inline padding i think.

Is there anyway i can get text to break to next line when white padding touches edge of container.

Text needs to stay as inline cause i need that blank space between text lines. Tho if you have solution which requires to change that and result looks same as mine only the problem is fixed, than that will work too.

P.S. My container in real situation is 100% 100% so width,height is not fixed for the block.

It seems like it's not possible cause inline padding doesnt affect wrapping in any way and is completely ignored.

body {
  background: #111111;
}
.container {
  width: 338px;
  height: 600px;
  background-color: #000;
  font-family: Arial;
  text-align: center;
}
h1 {
  font-weight: bold;
  font-size: 48px;
  background-color: #fff;
  display: inline;
  line-height: 95px;
  box-decoration-break: clone;
  -webkit-box-decoration-break: clone;
  padding: 10px 20px 10px 20px;
}
.sub {
  display: inline;
  background-color: #fff;
  font-size: 28px;
  padding: 20px 20px;
  line-height: 90px;
  box-decoration-break: clone;
  -webkit-box-decoration-break: clone;
}

Heading title

  Some random text under heading title

Body:
Without using JS you won't be able to get the needed result just by CSS.
Your current code allows <span> to overflow container's border (not sure why) while <h1> tag breaks the word exactly on containers box border. My best guess is to include whole text in <h1> and use class definition for <h1> and with <span> as a child element to change the line-height & general styling of elements below.

I'd suggest to redo your code like an example below.

body {
  width: 100%;
  height: auto;
  padding: 20px;
  background: #000;
}

.container {
  position: relative;
  width: 300px;
  margin: auto;
  height: auto;
  background: #333;
  padding: 20px;
}

h1 {
  font-weight: 800;
  color: #333;
  text-align: center;
}

h1 span {
  -webkit-box-decoration-break: clone;
  box-decoration-break: clone;
}

h1.title span{
  padding: 10px 20px;
  background-color: #fff;
  font-size: 1.5em;
  line-height: 2em;
  margin-bottom: 40px;
}

h1.desc span {
  padding: 5px 10px;
  background-color: #ddd;
  font-size: 1em;
  line-height: 1.8em;
  margin-bottom: 20px;
}

<section class="container">
  <h1 class="title">
    <span>Long heading title here</span>
  </h1>

  <h1 class="desc">
    <span>The quick brown fox jumps over the lazy dog.</span>
  </h1>
</section>

As you can see in snippet both <span> & <h1> elements respect the .container border and doesn't overflow it.


问:
QGraphicsItem loses focus after using QComboBox
I am doing a small game in Qt and try to use WASD to move my protagonist(QGraphicsPixmapItem). The map is quite big so I use a QComboBox to change the scale of the scene.

The game looks like this:

The simple game

How I built the protagonist:

```<code>protagonist = new MyProtagonist();
protagonist->setFlag(QGraphicsItem::ItemIsFocusable);
protagonist->setFocus();
scene->addItem(protagonist);
</code>```

How I built the combox:

```<code>sceneScaleCombo = new QComboBox;
QStringList scales;
scales << tr("1%")<<tr("10%") << tr("20%") <<tr("50%") << tr("100%") <<tr("200%");
sceneScaleCombo->addItems(scales);
sceneScaleCombo->setCurrentIndex(4);
connect(sceneScaleCombo,SIGNAL(currentIndexChanged(QString)),this,SLOT(sceneScaleChanged(QString)));

void MainWindow::sceneScaleChanged(const QString &scale)
{
    double newScale = scale.left(scale.indexOf(tr("%"))).toDouble() / 100;
    QMatrix oldMatrix = view->matrix();
    view->resetMatrix();
    view->translate(oldMatrix.dx(),oldMatrix.dy());
    view->scale(newScale,newScale);
    protagonist->setFocus();
}
</code>```

Everything worked well at the beginning. However, after I clicking the combobox, my protagonist cannot be controlled by keyboard any more. I need to click my protagonist to make it focused again.

Is there any way to set it focused automatically?

Thanks a lot.

答: By clicking QComboBox the QGraphicsView looses the focus. You attempt to return it back by calling setFocus(); on the QGraphicsPixmapItem. This approach doesn't work as you expect, because it sets the focus item inside the view, but the view itself still does not have focus. To fix that in MainWindow::sceneScaleChanged instead of protagonist->setFocus(); write view->setFocus();.

Body:
I am doing a small game in Qt and try to use WASD to move my protagonist(QGraphicsPixmapItem). The map is quite big so I use a QComboBox to change the scale of the scene.

The game looks like this:

The simple game

How I built the protagonist:

protagonist = new MyProtagonist();
protagonist->setFlag(QGraphicsItem::ItemIsFocusable);
protagonist->setFocus();
scene->addItem(protagonist);

How I built the combox:

sceneScaleCombo = new QComboBox;
QStringList scales;
scales << tr("1%")<<tr("10%") << tr("20%") <<tr("50%") << tr("100%") <
addItems(scales);
sceneScaleCombo->setCurrentIndex(4);
connect(sceneScaleCombo,SIGNAL(currentIndexChanged(QString)),this,SLOT(sceneScaleChanged(QString)));

void MainWindow::sceneScaleChanged(const QString &scale)
{
    double newScale = scale.left(scale.indexOf(tr("%"))).toDouble() / 100;
    QMatrix oldMatrix = view->matrix();
    view->resetMatrix();
    view->translate(oldMatrix.dx(),oldMatrix.dy());
    view->scale(newScale,newScale);
    protagonist->setFocus();
}

Everything worked well at the beginning. However, after I clicking the combobox, my protagonist cannot be controlled by keyboard any more. I need to click my protagonist to make it focused again.

Is there any way to set it focused automatically?

Thanks a lot.


答: Which rand() do you want? Your version or the system one? Seems it is picking up yours which is recursive and so will blow the stack. Try renaming it int myrand(void) {

Title: How do I write helper function in C to return a random number from a specific range and avoid a segmentation fault?


问:
Add Text to file when performing Get-ChildItem
I've been looking around trying to solve this issue but nothing has worked so far.
I am wanting to pick 1/multiple files, add a hardcoded value (e.g "DIAB`r`n") to the start of the file content and then write to another volume.
Do I have to do multiple statements or is it something I can do in one.
What I have so far is try using 2 statements:

```<code># Find the file/s .HL7, move to a new destination and change the filename to add "DIAB-"
# to the front - this is working
Get-ChildItem -Path $DiabetesPath |
    Where-Object { (!$_.PSIsContainer -and $_.Name -like "*.HL7") } |
    Move-Item -Destination $DestinationPath -PassThru |
    Rename-Item -NewName {"DIAB-" + $_.Name}

# this is what is not working - after files moved to destination trying to add some text
# to the start of the file content
Get-ChildItem $DestinationPath -Recurse -Filter DIAB*.HL7 | ForEach-Object
{
    $content = Get-Content $_.FullName
    Set-Content $_.FullName -Value "DIAB`r`n", $content
}
</code>```

When I try it, it says:

```
cmdlet ForEach-Object at command pipeline position 2
Supply values for the following parameters
process[0]:
```

When I enter something it keeps going:

```
process[1]:
process[2]:
...
```

Not sure what is going on.

答:
Wow! didn't realise the position of { would affect anything.

Moved the { next to the ForEach-Object and it works.

```<code>Get-ChildItem $DestinationPath -Recurse -Filter DIAB*.HL7 | ForEach-Object {
    $content = Get-Content $_.FullName
    Set-Content $_.FullName -Value "DIAB`r`n", $content
}
</code>```

Body:
I've been looking around trying to solve this issue but nothing has worked so far.
I am wanting to pick 1/multiple files, add a hardcoded value (e.g "DIAB`r`n") to the start of the file content and then write to another volume.
Do I have to do multiple statements or is it something I can do in one.
What I have so far is try using 2 statements:

# Find the file/s .HL7, move to a new destination and change the filename to add "DIAB-"
# to the front - this is working
Get-ChildItem -Path $DiabetesPath |
    Where-Object { (!$_.PSIsContainer -and $_.Name -like "*.HL7") } |
    Move-Item -Destination $DestinationPath -PassThru |
    Rename-Item -NewName {"DIAB-" + $_.Name}

# this is what is not working - after files moved to destination trying to add some text
# to the start of the file content
Get-ChildItem $DestinationPath -Recurse -Filter DIAB*.HL7 | ForEach-Object
{
    $content = Get-Content $_.FullName
    Set-Content $_.FullName -Value "DIAB`r`n", $content
}

When I try it, it says:

cmdlet ForEach-Object at command pipeline position 2
Supply values for the following parameters
process[0]:

When I enter something it keeps going:

process[1]:
process[2]:
...

Not sure what is going on.

Body:
Wow! didn't realise the position of { would affect anything.

Moved the { next to the ForEach-Object and it works.

Get-ChildItem $DestinationPath -Recurse -Filter DIAB*.HL7 | ForEach-Object {
    $content = Get-Content $_.FullName
    Set-Content $_.FullName -Value "DIAB`r`n", $content
}