问:
difference beetwen path.join(__dirname , 'views') and path.join(__dirname + 'views') in node.js
im stuck with node.js again.

i try the first path.join in my code for setup view engine its not working, the index won't showing up, then i change to path.join(__dirname , 'views'); and its working well, the index showing, i dont know how

can someone explain how this work ?

```<code>path.join(__dirname + 'views');

path.join(__dirname, 'views');
</code>```

this is my script

```<code>app.set('views', path.join(__dirname, 'views')); //its work
app.set('views', path.join(__dirname + 'views')); // if i change like this, its not work
</code>```

答:
From Official documentation:
 https://nodejs.org/api/path.html#path_path_join_paths

Paths that u join must be separated by a delimiter;

Also if all paths are not strings, then an error will be thrown.

So, I presume the addition of + makes path go crazy because, it cannot find a delimiter and also it finds that the paths that u have mentioned are not all strings.

Hope this helps.

Body:
im stuck with node.js again.

i try the first path.join in my code for setup view engine its not working, the index won't showing up, then i change to path.join(__dirname , 'views'); and its working well, the index showing, i dont know how

can someone explain how this work ?

path.join(__dirname + 'views');

path.join(__dirname, 'views');

this is my script

app.set('views', path.join(__dirname, 'views')); //its work
app.set('views', path.join(__dirname + 'views')); // if i change like this, its not work


来源: stackexchange

问:
Defining the data structure for reading the XML Data
I am trying to read the data from XML File,but not able to proceed further.

Here is my XML File:

```<code><CollectionOfVehicles>
    <Vehicle>
        <Motors>
            <Motor>
                <Screw>100</Screw>
                <Nut>200</Nut>
                <Bolt>300</Bolt>
            </Motor>
            <Motor>
                <Screw>100</Screw>
                <Nut>200</Nut>
                <Bolt>45</Bolt>
            </Motor>
        </Motors>
        <GearBoxes>
            <GearBox>
                <gear>0</gear>
                <Shaft>1</Shaft>
                <Bearings>2</Bearings>
            </GearBox>
        </GearBoxes>
    </Vehicle>
</CollectionOfVehicles>
</code>```

My Data Structure is as follows:

```<code>   public class Motor
    {
       public double Screw {get; set; }
       public double Nut {get; set; }
       public double Bolt {get; set; }
       public Motor() {}
    }

    public class GearBox
    {
       public uint gear {get; set; }
       public uint Shaft {get; set; }
       public uint Bearings {get; set; }
       public GearBox() {}
    }

    public class Vehicle
    {
        public List<Motor> motors {get; set;}
        public List<GearBox> gearBoxes {get; set;}
        public Vehicle() {}
    };

   **I tried to write the following lines of code to feed the XML Data:**

   Vehicle cars = null;
   string path = @"C:\Users\Semantics\Desktop\New.xml";
   XmlSerializer serializer = new XmlSerializer(typeof(Vehicle));
   var reader = XmlReader.Create(path);
   cars = (Vehicle)serializer.Deserialize(reader);
   reader.Close();
</code>```

I basically,want to retrieve Vehicles as  and then loop over each vehicle,and retrieve the associated Motor and GearBox.I am not sure,how to retrieve the data like nut,screw and bolt using XMLAttributor (or) XMLElement in my data structure.

Thanks in Advance!

答:
You said you get multiple vehicles, so you need to be prepared for that:

```<code>var cars = (IEnumerable<Vehicle>)serializer.Deserialize(reader);
</code>```

Other than that... looks good.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to read the data from XML File,but not able to proceed further.

Here is my XML File:

<CollectionOfVehicles>
    <Vehicle>
        <Motors>
            <Motor>
                <Screw>100</Screw>
                <Nut>200</Nut>
                <Bolt>300</Bolt>
            </Motor>
            <Motor>
                <Screw>100</Screw>
                <Nut>200</Nut>
                <Bolt>45</Bolt>
            </Motor>
        </Motors>
        <GearBoxes>
            <GearBox>
                <gear>0</gear>
                <Shaft>1</Shaft>
                <Bearings>2</Bearings>
            </GearBox>
        </GearBoxes>
    </Vehicle>
</CollectionOfVehicles>

My Data Structure is as follows:

   public class Motor
    {
       public double Screw {get; set; }
       public double Nut {get; set; }
       public double Bolt {get; set; }
       public Motor() {}
    }

    public class GearBox
    {
       public uint gear {get; set; }
       public uint Shaft {get; set; }
       public uint Bearings {get; set; }
       public GearBox() {}
    }

    public class Vehicle
    {
        public List<Motor> motors {get; set;}
        public List<GearBox> gearBoxes {get; set;}
        public Vehicle() {}
    };

   **I tried to write the following lines of code to feed the XML Data:**

   Vehicle cars = null;
   string path = @"C:\Users\Semantics\Desktop\New.xml";
   XmlSerializer serializer = new XmlSerializer(typeof(Vehicle));
   var reader = XmlReader.Create(path);
   cars = (Vehicle)serializer.Deserialize(reader);
   reader.Close();

I basically,want to retrieve Vehicles as  and then loop over each vehicle,and retrieve the associated Motor and GearBox.I am not sure,how to retrieve the data like nut,screw and bolt using XMLAttributor (or) XMLElement in my data structure.

Thanks in Advance!

Body:
You said you get multiple vehicles, so you need to be prepared for that:

var cars = (IEnumerable<Vehicle>)serializer.Deserialize(reader);

Other than that... looks good.


答:
path.join constructs a path from your arguments by concatenating them with "/".
So path.join(__dirname, 'views') results in /path_to_dir/views

On the  other hand, (__dirname + 'views') only has one parameter (__dirname+views). This means there are no additional arguments to join to the first and so you end up with "/path_to_dirviews" (No joining "/")

Title: difference beetwen path.join(__dirname , 'views') and path.join(__dirname + 'views') in node.js


问:
How to get autocomplete `super` on PyCharm
I'm searching for an autocomplete to super function.

Usually the super is something like:

```<code>super(MyClass, self).my_func(*func_args, *func_kwargs)
</code>```

It there a shortcut/macro to have it auto completed?

Many thanks!

答: Press ctrl+j to list available macros and start typing super to select autocompleteon:

Body:
I'm searching for an autocomplete to super function.

Usually the super is something like:

super(MyClass, self).my_func(*func_args, *func_kwargs)

It there a shortcut/macro to have it auto completed?

Many thanks!


问:
How to make a python list from a .csv list?
I want to know how to make a .csv list into a python list which I can do plotting and calculating:

I used:

```<code>    fpath = r'C:112017\temp\tT.csv'
    with open(fpath,'r') as csvfile:
         reader = csv.reader(csvfile, delimiter=',')
         for row in reader:
             print(list(reader))
</code>```

it gives me lists like this (which I dont' want):

```<code>    [['2014-12-30', '18.34244791666665'], ['2014-12-31', '18.540224913494818'], ['2015-01-01', '18.15729166666666'],......
</code>```

If I use

```<code>    print(row)
</code>```

it gives me lists like this (looks better but I still can not use it for calculating):

```<code>    ...
    ['2016-07-27', '20.434809022479584']
    ['2016-07-28', '21.395138886239796']
    ['2016-07-29', '20.81571181284057']
    ['2016-07-30', '20.565711801250778']
    ...
</code>```

How can I use panda to make a list? Or is there any easier way to achieve this? Is that possible to use something like:

```<code>    date = row[0]
    temp = row[1]
    lis = pd.DataFrame(date,temp)
</code>```

I guess there are some basic mistakes, but I can't fix it by myself.
Thank you for your time to help.

答:
There is pandas.read_csv() method which will read the csv file and return a dataframe

Eg:

```<code>fpath = r'C:112017\temp\tT.csv'
df = pd.read_csv(fpath, delimiter=',', names=['date', 'temp'])
</code>```

Body:
I want to know how to make a .csv list into a python list which I can do plotting and calculating:

I used:

    fpath = r'C:112017\temp\tT.csv'
    with open(fpath,'r') as csvfile:
         reader = csv.reader(csvfile, delimiter=',')
         for row in reader:
             print(list(reader))

it gives me lists like this (which I dont' want):

    [['2014-12-30', '18.34244791666665'], ['2014-12-31', '18.540224913494818'], ['2015-01-01', '18.15729166666666'],......

If I use

    print(row)

it gives me lists like this (looks better but I still can not use it for calculating):

    ...
    ['2016-07-27', '20.434809022479584']
    ['2016-07-28', '21.395138886239796']
    ['2016-07-29', '20.81571181284057']
    ['2016-07-30', '20.565711801250778']
    ...

How can I use panda to make a list? Or is there any easier way to achieve this? Is that possible to use something like:

    date = row[0]
    temp = row[1]
    lis = pd.DataFrame(date,temp)

I guess there are some basic mistakes, but I can't fix it by myself.
Thank you for your time to help.

Body:
There is pandas.read_csv() method which will read the csv file and return a dataframe

Eg:

fpath = r'C:112017\temp\tT.csv'
df = pd.read_csv(fpath, delimiter=',', names=['date', 'temp'])


问:
create custom curved in a layout, like this image
First of all, Forgive me, my English is not good.
I want to design a custom xml layout like below:

I am trying to create top curved, but I don't know how it designed!

This my output:

and my xml code:

```<code><layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:top="100dp"
    android:bottom="10dp">

    <shape android:shape="rectangle">
        <stroke
            android:width="3dp"
            android:color="#000000" />
        <solid android:color="@android:color/background_light" />
        <corners
            android:bottomLeftRadius="0dp"
            android:bottomRightRadius="0dp"
            android:topLeftRadius="0dp"
            android:topRightRadius="0dp" />

    </shape>
</item>
</code>```

And I have another question:
There is a site that can make this design online?

答:
That shape is to complex for a shape xml.

Easy/Fast solution: create a VectorDrawable or any other drawable and import it to your project.

Complex/Time consuming option: you can start by playing with Bezier curves. Since your curve is symmetric, you can first take care of half of your image and then mirror the curve you did on the first half.
There are many examples on how to work with bezier curves, but this will be time consuming, you need to understand the concept, and keep testing to achieve what you want.

Best approach is to have a VectorDrawable: fast to get results, clean approach, no need to write a single line of code :)

Body:
First of all, Forgive me, my English is not good.
I want to design a custom xml layout like below:

I am trying to create top curved, but I don't know how it designed!

This my output:

and my xml code:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:top="100dp"
    android:bottom="10dp">

    <shape android:shape="rectangle">
        <stroke
            android:width="3dp"
            android:color="#000000" />
        <solid android:color="@android:color/background_light" />
        <corners
            android:bottomLeftRadius="0dp"
            android:bottomRightRadius="0dp"
            android:topLeftRadius="0dp"
            android:topRightRadius="0dp" />

    </shape>
</item>

And I have another question:
There is a site that can make this design online?


问:
Change title in App Bar when user navigates to a different component in React
I have a React app with a bunch of components and have it structured in the following way

```<code>class App extends Component {
  render() {
    return (
      <Router>
        <ResponsiveDrawer>
          <div className="App">
              <div>
                <Route exact path="/" component={Administrator} />
                <Route path="/admin" component={Administrator} />
                <Route exact path="/jobs" component={Jobs} />
                <Route path="/jobs/:id" render={({match}) => <ViewJob id={match.params.id} />} />
                <Route path="/entries/:jobId/:entryId" render={({match}) => <Entry jobId={match.params.jobId} entryId={match.params.entryId} />} />
                <Route exact path="/reports" component={Reports} />
                <Route path="/reports/:jobId" render={({match}) => <JobReport id={match.params.jobId} />} />
                <Route path="/reports/activity" component={ActivityReport} />
              </div>
          </div>
         </ResponsiveDrawer>
     </Router>

    );
  }
}

export default App;
</code>```

Part of the ResponsiveDrawer contains a title that I want to change based on which component the user is currently in. Is there any way that I can pass props up to a parent like that?

答:
Maybe you can try something like this using this.context.router.

```<code>class App extends Component {
  findComponent = () => {
    switch (this.context.router.history.location.pathname.split('/')[0]) {
      case 'admin':
        return 'Administrator';
      // ...
      default:
        return 'Administrator';
    }
  }

  render() {
    return (
     <Router>
       <ResponsiveDrawer component={this.findComponent()}>
         {/* Your routes */}
       </ResponsiveDrawer>
     </Router>
    );
  }
}

App.contextTypes = {
  router: PropTypes.object.isRequired,
};
</code>```

Body:
I have a React app with a bunch of components and have it structured in the following way

class App extends Component {
  render() {
    return (
      <Router>
        <ResponsiveDrawer>

                <Route exact path="/" component={Administrator} />
                <Route path="/admin" component={Administrator} />
                <Route exact path="/jobs" component={Jobs} />
                <Route path="/jobs/:id" render={({match}) => <ViewJob id={match.params.id} />} />
                <Route path="/entries/:jobId/:entryId" render={({match}) => <Entry jobId={match.params.jobId} entryId={match.params.entryId} />} />
                <Route exact path="/reports" component={Reports} />
                <Route path="/reports/:jobId" render={({match}) => <JobReport id={match.params.jobId} />} />
                <Route path="/reports/activity" component={ActivityReport} />

         </ResponsiveDrawer>
     </Router>

    );
  }
}

export default App;

Part of the ResponsiveDrawer contains a title that I want to change based on which component the user is currently in. Is there any way that I can pass props up to a parent like that?

Body:
Maybe you can try something like this using this.context.router.

class App extends Component {
  findComponent = () => {
    switch (this.context.router.history.location.pathname.split('/')[0]) {
      case 'admin':
        return 'Administrator';
      // ...
      default:
        return 'Administrator';
    }
  }

  render() {
    return (
     <Router>
       <ResponsiveDrawer component={this.findComponent()}>
         {/* Your routes */}
       </ResponsiveDrawer>
     </Router>
    );
  }
}

App.contextTypes = {
  router: PropTypes.object.isRequired,
};


问:
Wagtail document links downloading instead of displaying as a page
It seems that the default configuration for Wagtail CMS is to have links to documents trigger an automatic download of the document instead of displaying the document in the browser. Is there a simple way to change this configuration?</p>

答:
Another approach to this could be to hook into the  before_serve_document wagtail hook.

https://docs.wagtail.io/en/v2.9.3/reference/hooks.html?highlight=document%20serving#document-serving

You could customize the response based on the document this way, here is a pretty rough example that shows how the hook works.

You still need to resolve how to generate a viewable URL that shows the file though.

```<code>from wagtail.wagtailcore import hooks
from django.shortcuts import redirect

@hooks.register('before_serve_document')
def serve_document(document, request):
    # eg. use document.file_extension, document.url, document.filename
    if document.file_extension == 'pdf':
        google_view_pdf_base = 'https://docs.google.com/viewer?url='
        # document.url is a relative URL so more work needed here
        # also URL should probably be URL encoded
        redirect_url = google_view_pdf_base + document.url
        # must return an instance of HTTPResponse
        return redirect(redirect_url)
    # no return means the normal page serve will operate
</code>```

Body:
Another approach to this could be to hook into the  before_serve_document wagtail hook.

https://docs.wagtail.io/en/v2.9.3/reference/hooks.html?highlight=document%20serving#document-serving

You could customize the response based on the document this way, here is a pretty rough example that shows how the hook works.

You still need to resolve how to generate a viewable URL that shows the file though.

from wagtail.wagtailcore import hooks
from django.shortcuts import redirect

@hooks.register('before_serve_document')
def serve_document(document, request):
    # eg. use document.file_extension, document.url, document.filename
    if document.file_extension == 'pdf':
        google_view_pdf_base = 'https://docs.google.com/viewer?url='
        # document.url is a relative URL so more work needed here
        # also URL should probably be URL encoded
        redirect_url = google_view_pdf_base + document.url
        # must return an instance of HTTPResponse
        return redirect(redirect_url)
    # no return means the normal page serve will operate

ContentLicense: CC BY-SA 4.0


问:
Django: Why 'Class' object is not iterable
I built a dictionary list like this

```<code>lst = [{'name': nameobj, Classobj1: "string", Classobj2: "string"}, \
{'name': nameobj, Classobj1: "string", Classobj2: "string"}]
</code>```

and I'm using

```<code>for dic in lst:
   for k,v in dic:   # here is the line has probloem! What it happens?
       #process
</code>```

The error message is like "Classname" object is not iterable.

答: You need to use dic.iteritems().

ContentLicense: CC BY-SA 2.5

Body:
I built a dictionary list like this

lst = [{'name': nameobj, Classobj1: "string", Classobj2: "string"}, \
{'name': nameobj, Classobj1: "string", Classobj2: "string"}]

and I'm using

for dic in lst:
   for k,v in dic:   # here is the line has probloem! What it happens?
       #process

The error message is like "Classname" object is not iterable.

Body: You need to use dic.iteritems().


问:
Install ad-hoc ipa
Through my react-native app I am trying to make the user able to install another enterprise app. The link to the second app looks like this

```<code>itms-services://?action=download-manifest&url=https://example.com//667/app-667.plist?token=jhsdbafkjkwdsfqkjdwkdjqs
</code>```

I tried to open the URL using Linking

```<code>Linking.openURL(url)
</code>```

and also using WebView

```<code><View>
  <WebView
   source={{uri: this.state.appUrl}}
  />
</code>```

But nothing happens. Have you an idea aboout the issue?
To use Linking shall I link RCTLinking to my project? I read something about it here but I am not sure.

答:
Several things:

In general, it doesn't matter from where you want to install the app from browser or from your app.

If you don't have Enterprise Developer Program, it is not possible.

The app should be upload to a server with the supported files for it. Files should be configured for thees build.

Detail explanation you can find here: Download and install an ipa from url on iOS

Title: Install ad-hoc ipa

Body:
Through my react-native app I am trying to make the user able to install another enterprise app. The link to the second app looks like this

itms-services://?action=download-manifest&url=https://example.com//667/app-667.plist?token=jhsdbafkjkwdsfqkjdwkdjqs

I tried to open the URL using Linking

Linking.openURL(url)

and also using WebView

<View>
  <WebView
   source={{uri: this.state.appUrl}}
  />

But nothing happens. Have you an idea aboout the issue?
To use Linking shall I link RCTLinking to my project? I read something about it here but I am not sure.


问:
how to generate rest_framework_jwt token in the login process
I'm trying to implement django-rest-framework-jwt for authentication. I did all what jwt tutorials said (adding the setting, url and curl testing). and I did successfully obtain the token using 127.0.0.1:8000/api/auth/token/ in the browsable api.

but what I don't get is how to generate the token in the login process. My guess is to generate it in the LoginSerializer maybe? (or I misunderstood the concept!)

Here's what I have:

```<code># settings.py
REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
}

# project/urls.py
url(r'^api/auth/token/', obtain_jwt_token),
</code>```

login serializer and view:

```<code>class UserLoginSerializer(ModelSerializer):
    token = CharField(allow_blank=True, read_only=True)
    class Meta:
        model = User
        fields = ('username', 'password', 'token')

    def validate(self, data):
        username = data.get('username',None)
        password = data['password']

        user = authenticate(username=username, password=password)
        if not user or not user.is_active:
            raise ValidationError("Invalid username/password.")

        # generate jwt token ??
        # data['token'] = generated jwt token??

        return data

class UserLoginAPIView(APIView):
    permission_classes = [AllowAny]
    serializer_class = UserLoginSerializer

    def post(self, request, *args, **kwargs):
        data = request.data
        serializer = UserLoginSerializer(data=data)
        if serializer.is_valid(raise_exception=True):
            new_data = serializer.data
            return Response(new_data, status=HTTP_200_OK)
        return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)
</code>```

So what do I have to do?

答:
Here is what i did.

```<code>from rest_framework_jwt.settings import api_settings

class LoginView(APIView):
    '''
    Post call for user login.
    '''

    def post(self, request, format=None):
        serializer = LoginSerializer(data=request.data)

        if serializer.is_valid():

            # Check if user has valid credentials and return user instance else None
            user = authenticate(username=serializer.validated_data['username'],
                                password=serializer.validated_data['password'])

            if user is not None:

                jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
                jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

                payload = jwt_payload_handler(user)
                token = jwt_encode_handler(payload)

                return Response({'msg':'Login successful', 'token': token, 'is_login_success': True}, status=status.HTTP_200_OK)
            else:
                return Response({'msg': 'Credentials are not valid!'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
</code>```

But you dont have to do that since your 127.0.0.1:8000/api/auth/token/ is doing pretty exactly the same, unless you want to record something before logging in.

If you want more information how obtain_jwt_token view works, its JSONWebTokenSerializer will help you.

Body:
I'm trying to implement django-rest-framework-jwt for authentication. I did all what jwt tutorials said (adding the setting, url and curl testing). and I did successfully obtain the token using 127.0.0.1:8000/api/auth/token/ in the browsable api.

but what I don't get is how to generate the token in the login process. My guess is to generate it in the LoginSerializer maybe? (or I misunderstood the concept!)

Here's what I have:

# settings.py
REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
        'rest_framework.authentication.SessionAuthentication',
    ),
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
}

# project/urls.py
url(r'^api/auth/token/', obtain_jwt_token),

login serializer and view:

class UserLoginSerializer(ModelSerializer):
    token = CharField(allow_blank=True, read_only=True)
    class Meta:
        model = User
        fields = ('username', 'password', 'token')

    def validate(self, data):
        username = data.get('username',None)
        password = data['password']

        user = authenticate(username=username, password=password)
        if not user or not user.is_active:
            raise ValidationError("Invalid username/password.")

        # generate jwt token ??
        # data['token'] = generated jwt token??

        return data

class UserLoginAPIView(APIView):
    permission_classes = [AllowAny]
    serializer_class = UserLoginSerializer

    def post(self, request, *args, **kwargs):
        data = request.data
        serializer = UserLoginSerializer(data=data)
        if serializer.is_valid(raise_exception=True):
            new_data = serializer.data
            return Response(new_data, status=HTTP_200_OK)
        return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)

So what do I have to do?

Body:
Here is what i did.

from rest_framework_jwt.settings import api_settings

class LoginView(APIView):
    '''
    Post call for user login.
    '''

    def post(self, request, format=None):
        serializer = LoginSerializer(data=request.data)

        if serializer.is_valid():

            # Check if user has valid credentials and return user instance else None
            user = authenticate(username=serializer.validated_data['username'],
                                password=serializer.validated_data['password'])

            if user is not None:

                jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
                jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

                payload = jwt_payload_handler(user)
                token = jwt_encode_handler(payload)

                return Response({'msg':'Login successful', 'token': token, 'is_login_success': True}, status=status.HTTP_200_OK)
            else:
                return Response({'msg': 'Credentials are not valid!'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

But you dont have to do that since your 127.0.0.1:8000/api/auth/token/ is doing pretty exactly the same, unless you want to record something before logging in.

If you want more information how obtain_jwt_token view works, its JSONWebTokenSerializer will help you.


问:
Join multi-line strings into one string
I'm trying to parse a log file that looks like this:

```<code>24/01/2016, 11:50:17 pm: Line to skip
24/01/2016, 11:50:17 pm: Line to skip
25/01/2016, 11:51:47 pm: User1: Message one is here
25/01/2016, 11:53:04 pm: User2: A long message that spans multiple lines, so I have to write a really long and tedious message here to illustrate my point. The point is that this message is really long and

can
[span]

Several lines.
24/01/2016, 11:51:47 pm: User3: My first message
27/10/2017, 12:54:03 am: +44 012 3456789 left
28/10/2017, 02:54:03 pm: User3: My second message!
</code>```

```<code>rawData <- structure(list(V1 = c("24 01 2016, 11:50:17 pm: Line to skip",
        "24 01 2016, 11:50:17 pm: Line to skip", "24 01 2016, 11:51:47 pm: User1: Message one is here",
        "24 01 2016, 11:53:04 pm: User2: A long message that spans multiple lines, so I have to write a really long and tedious message here to illustrate my point. The point is that this message is really long and ",
        "can", "[span]", "Several lines.", "24 01 2016, 11:51:47 pm: User3: My first message",
        "27 10 2017, 12:54:03 am: +44 012 3456789 left")), .Names = "V1", row.names = c(NA,
        -9L), class = "data.frame")
</code>```

Each message starts with a date, and I'm having trouble parsing messages that span multiple lines (like on line 4).

Here's what I have so far:

```<code>suppressMessages(library(lubridate))
suppressMessages(library(dplyr))
suppressMessages(library(plyr))
suppressMessages(library(tidyr))

parseR <- function(file='data/chat_log.txt',drop="44"){
  rawData <- read.delim(file, quote = "",
                  row.names = NULL,
                  stringsAsFactors = FALSE,
                  header = F)

  # remove blank lines
  # rawData<-rawData[!apply(rawData == "", 1, all),]

  empty_lines = grepl('^\\s*$', rawData)
  rawData = rawData[! empty_lines]

  # join multi line messages into single line
  # rawData$V1<-gsub("[\r\n]", " ", rawData$V2)

  sepData<-suppressWarnings(separate(rawData, V1, c("datetime", "sender", "message"), sep = ": ", extra = "merge"))

  sepData$message <- trimws(sepData$message)
  sepData$sender<-factor(sepData$sender)

  data <- sepData %>%
    filter(!is.na(message)) %>%
    filter(!grepl(drop, sender)) %>%
    droplevels()

  cleanData<-separate(data, datetime, c("date", "time"), sep = " ", remove =TRUE)
  cleanData$date<-ymd(cleanData$date)
  cleanData$time<-hms(cleanData$time)

  return(cleanData)
}
</code>```

However, when I inspect the returned data frame, muliti line messages are not being parsed correctly:

```<code>> head(parseR())
        date        time sender                                                                                message
1 2016-01-25 23H 51M 47S  User1                                                                                Message one is here
2 2016-01-25  23H 53M 4S  User2 A long message that spans multiple lines, so I have to write a really long and tedious message here to illustrate my point. The point is that this message is really long and
3 2016-01-24 23H 51M 47S  User3                                                                                My first message
4 2017-10-28  14H 54M 3S  User3
</code>```

Can anyone suggest a way of removing blank lines and joining text that doesn't start with a date into one string?

Desired format for line 4:

```<code>25/01/2016, 11:53:04 pm: User2: A long message that spans multiple lines, so I have to write a really long and tedious message here to illustrate my point. The point is that this message is really long and can [span] Several lines.
</code>```

答:
Here's a caveman approach to this problem. I'm taking the timestamp to be a unique beginning of line identifier. If none is present, it pastes the line (or element) to the previous one. The example below is adapted to a vector, but it can easily be changed to work on other classes, such as matrices or data.frames.</p>

```<code>rd <- c("24 01 2016, 11:50:17 pm: Line to skip",
        "24 01 2016, 11:50:17 pm: Line to skip", "24 01 2016, 11:51:47 pm: User1: Message one is here",
        "24 01 2016, 11:53:04 pm: User2: A long message that spans multiple lines, so I have to write a really long and tedious message here to illustrate my point. The point is that this message is really long and ",
        "can", "[span]", "Several lines.", "24 01 2016, 11:51:47 pm: User3: My first message",
        "27 10 2017, 12:54:03 am: +44 012 3456789 left")
rd

out <- rep(NA, length(rd))

gr <- 1
for (i in 1:length(rd)) {
  # if starting with timestamp, save into out and move on (gr)
  find.startline <- grepl("^\\d{2} \\d{2} \\d{4}, \\d{2}:\\d{2}:\\d{2} (am|pm):", rd[i])
  if (find.startline) {
    out[gr] <- rd[i]
    gr <- gr + 1
  }

  if (!find.startline) {
    # if doesn't start with timestamp, append to previous (ss)
    ss <- gr - 1
    out[ss] <- paste(out[ss], rd[i])
  }
}

# if there are any multiline comments, some residual NAs should be present, removed
out <- out[!is.na(out)]
out

[1] "24 01 2016, 11:50:17 pm: Line to skip"
[2] "24 01 2016, 11:50:17 pm: Line to skip"
[3] "24 01 2016, 11:51:47 pm: User1: Message one is here"
[4] "24 01 2016, 11:53:04 pm: User2: A long message that spans multiple lines, so I have to write a really long and tedious message here to illustrate my point. The point is that this message is really long and  can [span] Several lines."
[5] "24 01 2016, 11:51:47 pm: User3: My first message"
[6] "27 10 2017, 12:54:03 am: *+44 ,012 3456789 left"
</code>```

Title: Join multi-line strings into one string

Body:
I'm trying to parse a log file that looks like this:

24/01/2016, 11:50:17 pm: Line to skip
24/01/2016, 11:50:17 pm: Line to skip
25/01/2016, 11:51:47 pm: User1: Message one is here
25/01/2016, 11:53:04 pm: User2: A long message that spans multiple lines, so I have to write a really long and tedious message here to illustrate my point. The point is that this message is really long and

can
[span]

Several lines.
24/01/2016, 11:51:47 pm: User3: My first message
27/10/2017, 12:54:03 am: +44 012 3456789 left
28/10/2017, 02:54:03 pm: User3: My second message!

rawData <- structure(list(V1 = c("24 01 2016, 11:50:17 pm: Line to skip",
        "24 01 2016, 11:50:17 pm: Line to skip", "24 01 2016, 11:51:47 pm: User1: Message one is here",
        "24 01 2016, 11:53:04 pm: User2: A long message that spans multiple lines, so I have to write a really long and tedious message here to illustrate my point. The point is that this message is really long and ",
        "can", "[span]", "Several lines.", "24 01 2016, 11:51:47 pm: User3: My first message",
        "27 10 2017, 12:54:03 am: +44 012 3456789 left")), .Names = "V1", row.names = c(NA,
        -9L), class = "data.frame")

Each message starts with a date, and I'm having trouble parsing messages that span multiple lines (like on line 4).

Here's what I have so far:

suppressMessages(library(lubridate))
suppressMessages(library(dplyr))
suppressMessages(library(plyr))
suppressMessages(library(tidyr))

parseR <- function(file='data/chat_log.txt',drop="44"){
  rawData <- read.delim(file, quote = "",
                  row.names = NULL,
                  stringsAsFactors = FALSE,
                  header = F)

  # remove blank lines
  # rawData<-rawData[!apply(rawData == "", 1, all),]

  empty_lines = grepl('^\\s*$', rawData)
  rawData = rawData[! empty_lines]

  # join multi line messages into single line
  # rawData$V1<-gsub("[\r\n]", " ", rawData$V2)

  sepData<-suppressWarnings(separate(rawData, V1, c("datetime", "sender", "message"), sep = ": ", extra = "merge"))

  sepData$message <- trimws(sepData$message)
  sepData$sender<-factor(sepData$sender)

  data <- sepData %>%
    filter(!is.na(message)) %>%
    filter(!grepl(drop, sender)) %>%
    droplevels()

  cleanData<-separate(data, datetime, c("date", "time"), sep = " ", remove =TRUE)
  cleanData$date<-ymd(cleanData$date)
  cleanData$time<-hms(cleanData$time)

  return(cleanData)
}

However, when I inspect the returned data frame, muliti line messages are not being parsed correctly:

> head(parseR())
        date        time sender                                                                                message
1 2016-01-25 23H 51M 47S  User1                                                                                Message one is here
2 2016-01-25  23H 53M 4S  User2 A long message that spans multiple lines, so I have to write a really long and tedious message here to illustrate my point. The point is that this message is really long and
3 2016-01-24 23H 51M 47S  User3                                                                                My first message
4 2017-10-28  14H 54M 3S  User3

Can anyone suggest a way of removing blank lines and joining text that doesn't start with a date into one string?

Desired format for line 4:

25/01/2016, 11:53:04 pm: User2: A long message that spans multiple lines, so I have to write a really long and tedious message here to illustrate my point. The point is that this message is really long and can [span] Several lines.

Body:
Here's a caveman approach to this problem. I'm taking the timestamp to be a unique beginning of line identifier. If none is present, it pastes the line (or element) to the previous one. The example below is adapted to a vector, but it can easily be changed to work on other classes, such as matrices or data.frames.

rd <- c("24 01 2016, 11:50:17 pm: Line to skip",
        "24 01 2016, 11:50:17 pm: Line to skip", "24 01 2016, 11:51:47 pm: User1: Message one is here",
        "24 01 2016, 11:53:04 pm: User2: A long message that spans multiple lines, so I have to write a really long and tedious message here to illustrate my point. The point is that this message is really long and ",
        "can", "[span]", "Several lines.", "24 01 2016, 11:51:47 pm: User3: My first message",
        "27 10 2017, 12:54:03 am: +44 012 3456789 left")
rd

out <- rep(NA, length(rd))

gr <- 1
for (i in 1:length(rd)) {
  # if starting with timestamp, save into out and move on (gr)
  find.startline <- grepl("^\\d{2} \\d{2} \\d{4}, \\d{2}:\\d{2}:\\d{2} (am|pm):", rd[i])
  if (find.startline) {
    out[gr] <- rd[i]
    gr <- gr + 1
  }

  if (!find.startline) {
    # if doesn't start with timestamp, append to previous (ss)
    ss <- gr - 1
    out[ss] <- paste(out[ss], rd[i])
  }
}

# if there are any multiline comments, some residual NAs should be present, removed
out <- out[!is.na(out)]
out

[1] "24 01 2016, 11:50:17 pm: Line to skip"
[2] "24 01 2016, 11:50:17 pm: Line to skip"
[3] "24 01 2016, 11:51:47 pm: User1: Message one is here"
[4] "24 01 2016, 11:53:04 pm: User2: A long message that spans multiple lines, so I have to write a really long and tedious message here to illustrate my point. The point is that this message is really long and  can [span] Several lines."
[5] "24 01 2016, 11:51:47 pm: User3: My first message"
[6] "27 10 2017, 12:54:03 am: *+44 ,012 3456789 left"


问:
Regular expression string search in Java
I know this can be done in many ways but im curious as to what the regex would be to pick out all strings not containing a particular substring, say GDA from
strings like GADSA, GDSARTCC, , THGDAERY. </p>

答:
you can do negative lookaround</p>

```<code>"^((?!GAD).)*$"
</code>```

Body:
you can do negative lookaround

"^((?!GAD).)*$"


问:
Rails - Cancel destroy on before_destroy callback
is there any way, given certain condition, cancel the destroy of an object on the before_destroy callback of active record? Thanks</p>

答:
You can also override the #destroy method:

```<code>def destroy
  study_assignments.empty? ? super : raise("can not be destroyed")
end
</code>```

Body:
You can also override the #destroy method:

def destroy
  study_assignments.empty? ? super : raise("can not be destroyed")
end


问:
Initializing a view in XAML with WPF (Caliburn.Micro)
I've been trying to get a tooltip to work inside of each row of a datagrid. I was able to displaythe info inside the Tooltipproperty using a simple StackPanel and some labels, but now I wanted to insert a view to use as a tooltip.

I was able to display the ciew and the viewmodel is working, yet I cannot make the custom object to work(named AppointmentConfirmationNotification). I am able to use the empty object 'ToolTipContent' yet I want to bind it to the Datagrid.

here is the code I'm cureently working on. Be aware that I left a comment on my working Stackpanel 'experiment'. Basically I assume somehow I have to inser a mere ´{Binding}´ somewhere... But not sure where.

```<code><DataGrid.RowStyle>
                    <Style TargetType="DataGridRow">
                        <Style.Resources>
                            <model:AppointmentConfirmationNotification x:Key="ToolTipContent">
                            </model:AppointmentConfirmationNotification>

                        </Style.Resources>
                        <Setter Property="ToolTip">
                            <Setter.Value >
                                <!--
                                OLD STACKPANEL WORKING SAMPLE
                                <StackPanel>
                                    <Grid>
                                        <Grid.RowDefinitions>
                                            <RowDefinition Height="*"></RowDefinition>
                                        </Grid.RowDefinitions>

                                        <WrapPanel Grid.Row="0">
                                            <Label>ID : </Label>
                                            <Label Content="{Binding AppointmentConfirmation.AppointmentID}"/>
                                        </WrapPanel>

                                    </Grid>
                                </StackPanel>
                                -->

                                <v:APTooltipView>
                                    <v:APTooltipView.DataContext>
                                        <ObjectDataProvider ObjectType="{x:Type vm:APTooltipViewModel}">
                                            <ObjectDataProvider.ConstructorParameters>
                                                <StaticResource ResourceKey="ToolTipContent"/>
                                            </ObjectDataProvider.ConstructorParameters>
                                        </ObjectDataProvider>
                                    </v:APTooltipView.DataContext>
                                </v:APTooltipView>
                            </Setter.Value>
                        </Setter>

                        <Setter Property="TextElement.FontWeight" Value="{Binding Path=Read,Converter={StaticResource BooleanToFontweight}}"/>
                    </Style>
                </DataGrid.RowStyle>
</code>```

I was trying to do this on the XAML in order to follow a more MVVM approach, but feel free to advice another approach. Thank you

答:
You can just make a new view and pass the DataContext through. You could put whatever you like in that view. It would look like this in your main view.

```<code><StackPanel>
   <local:"YOUR_VIEW" DataContext="{Binding AppointmentConfirmation, Mode=TwoWay}"/>
</StackPanel>
</code>```

Your freshly made view will look like this. You can add whatever you like (as long as it exists in your DataContext) and maybe reuse this view for other purposes.

```<code><UserControl x:Name="YOUR_VIEW" ....
...... >
   <Grid>
     <Grid.RowDefinitions>
         <RowDefinition Height="*" />
     </Grid.RowDefinitions>
     <WrapPanel Grid.Row="0">
         <Label>ID : </Label>
         <Label Content="{Binding AppointmentID}"/>
     </WrapPanel>
   </Grid>
</UserControl>
</code>```

Body:
I've been trying to get a tooltip to work inside of each row of a datagrid. I was able to displaythe info inside the Tooltipproperty using a simple StackPanel and some labels, but now I wanted to insert a view to use as a tooltip.

I was able to display the ciew and the viewmodel is working, yet I cannot make the custom object to work(named AppointmentConfirmationNotification). I am able to use the empty object 'ToolTipContent' yet I want to bind it to the Datagrid.

here is the code I'm cureently working on. Be aware that I left a comment on my working Stackpanel 'experiment'. Basically I assume somehow I have to inser a mere ´{Binding}´ somewhere... But not sure where.

<DataGrid.RowStyle>

                        <Setter Property="ToolTip">
                            <Setter.Value >

                                <v:APTooltipView>
                                    <v:APTooltipView.DataContext>
                                        <ObjectDataProvider ObjectType="{x:Type vm:APTooltipViewModel}">
                                            <ObjectDataProvider.ConstructorParameters>
                                                <StaticResource ResourceKey="ToolTipContent"/>
                                            </ObjectDataProvider.ConstructorParameters>
                                        </ObjectDataProvider>
                                    </v:APTooltipView.DataContext>
                                </v:APTooltipView>
                            </Setter.Value>
                        </Setter>

                        <Setter Property="TextElement.FontWeight" Value="{Binding Path=Read,Converter={StaticResource BooleanToFontweight}}"/>
                    </Style>
                </DataGrid.RowStyle>

I was trying to do this on the XAML in order to follow a more MVVM approach, but feel free to advice another approach. Thank you

Body:
You can just make a new view and pass the DataContext through. You could put whatever you like in that view. It would look like this in your main view.

<StackPanel>
   <local:"YOUR_VIEW" DataContext="{Binding AppointmentConfirmation, Mode=TwoWay}"/>
</StackPanel>

Your freshly made view will look like this. You can add whatever you like (as long as it exists in your DataContext) and maybe reuse this view for other purposes.

<UserControl x:Name="YOUR_VIEW" ....
...... >
   <Grid>
     <Grid.RowDefinitions>
         <RowDefinition Height="*" />
     </Grid.RowDefinitions>
     <WrapPanel Grid.Row="0">
         <Label>ID : </Label>
         <Label Content="{Binding AppointmentID}"/>
     </WrapPanel>
   </Grid>
</UserControl>


问:
Mongoose validation error while sending data using ExpressJS post route
I am working on a Mean stack application, I have defined an expressjs backend post route to store some data on server, but its not working and giving mongoose validation error on fields, although I have provided all the fields.

```<code>message:"Path `controlType` is required."
name:"ValidatorError"
path:"controlType"
properties:{type: "required", message: "Path `{PATH}` is required.", path: "controlType"}
__proto__
:
Object
</code>```

If I print req.body it prints all the fields with their correct values, see the console output:
[ { controlType: 'text',
    label: 'name',
    required: false,
    placeholder: 'first name' } ]

But when I print a single field using req.body.controlType it prints false on console. I don't know why?
Its the mongoose schema:

```<code>var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var formSchema = new Schema({
    controlType: {type: String, required: true},
    label: {type: String, required: true},
    required: {type: Boolean},
    placeholder: {type: String},
    options: [String],    //to store options for select or radio input
} ,  {collection: 'inputForm'});

module.exports = mongoose.model('Form', formSchema);
</code>```

its my post route:

```<code>const express = require('express');
const router = express.Router();
var Form = require('../../models/form');

/* GET api listing. */
router.get('/', (req, res) => {
  res.send('api works');
});

router.post('/userform', function (req, res, next) {
    console.log('in form api 0528');
    var keyName1=req.body;
    console.log(keyName1);

    var form = new Form({
        controlType: req.body.controlType,
        label: req.body.label,
        required:req.body.required ,
        placeholder: req.body.placeholder,
        options: req.body.options
    });
    form.save(function(err, result) {
        if (err) {
            return res.status(500).json({
                title: 'An error occurred in form api 0528',
                error: err
            });
        }
        res.status(201).json({
            message: 'Form created',
            obj: result
        });
    });
});

module.exports = router;
</code>```

答: It looks like your req.body is returning and array. Try something like req.body[0].contentType. I'm not sure but you can give it a try. Tell me if it solved your problem or not. </p>

Body:
I am working on a Mean stack application, I have defined an expressjs backend post route to store some data on server, but its not working and giving mongoose validation error on fields, although I have provided all the fields.

message:"Path `controlType` is required."
name:"ValidatorError"
path:"controlType"
properties:{type: "required", message: "Path `{PATH}` is required.", path: "controlType"}
__proto__
:
Object

If I print req.body it prints all the fields with their correct values, see the console output:
[ { controlType: 'text',
    label: 'name',
    required: false,
    placeholder: 'first name' } ]

But when I print a single field using req.body.controlType it prints false on console. I don't know why?
Its the mongoose schema:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var formSchema = new Schema({
    controlType: {type: String, required: true},
    label: {type: String, required: true},
    required: {type: Boolean},
    placeholder: {type: String},
    options: [String],    //to store options for select or radio input
} ,  {collection: 'inputForm'});

module.exports = mongoose.model('Form', formSchema);

its my post route:

const express = require('express');
const router = express.Router();
var Form = require('../../models/form');

/* GET api listing. */
router.get('/', (req, res) => {
  res.send('api works');
});

router.post('/userform', function (req, res, next) {
    console.log('in form api 0528');
    var keyName1=req.body;
    console.log(keyName1);

    var form = new Form({
        controlType: req.body.controlType,
        label: req.body.label,
        required:req.body.required ,
        placeholder: req.body.placeholder,
        options: req.body.options
    });
    form.save(function(err, result) {
        if (err) {
            return res.status(500).json({
                title: 'An error occurred in form api 0528',
                error: err
            });
        }
        res.status(201).json({
            message: 'Form created',
            obj: result
        });
    });
});

module.exports = router;


问:
How to handle tempo and pitch in android using MediaPlayer or SoundPool
I try to handle tempo and pitch using SoundPool. In the play() method, if we change the rate (last argument) the tempo and pitch both are changing. And I am not able to play the full sound file using SoundPool. I got solution using FileDescriptor in SoundPool we can mention the length of the file to play but its not working. Please share your ideas.

Thank You

答:
As my knowledge Mediaplayer or Soundpool can not let us change the pitch and temp(speed) independently.

You can try using soundtouch, a github project maintained by xanaduo.

It made my day after 2 days of searching over the net.


问:
Codeigniter list only files non-recursively
I'd like to list the names of files from a specific location, without names of the subdirectories and files they may contain.

I've used CI's directory_map function with a success, but had to make a small workaround to get rid of the folder names in not quite a neat way:

```<code>$files = directory_map('src/img/example/', 1);

foreach($files as $i => $file) {
    if(strpos($file, '\\') !== false) {
        unset($files[$i]);
    }
}
</code>```

I'm sure there has to be a way easier and better solution, but had no luck finding it

答:
a possible option would be to use a DirectoryIterator

```<code>$arrFiles = [];

foreach (new DirectoryIterator('src/img/example/') as $objFile)
{
    if($objFile->isFile()) $arrFiles[] = $objFile->getFilename();
}
</code>```

Body:
I'd like to list the names of files from a specific location, without names of the subdirectories and files they may contain.

I've used CI's directory_map function with a success, but had to make a small workaround to get rid of the folder names in not quite a neat way:

$files = directory_map('src/img/example/', 1);

foreach($files as $i => $file) {
    if(strpos($file, '\\') !== false) {
        unset($files[$i]);
    }
}

I'm sure there has to be a way easier and better solution, but had no luck finding it

Body:
a possible option would be to use a DirectoryIterator

$arrFiles = [];

foreach (new DirectoryIterator('src/img/example/') as $objFile)
{
    if($objFile->isFile()) $arrFiles[] = $objFile->getFilename();
}


问:
Angular 4 smooth animation
I'm trying to do a kind of Homepage in Angular 4 with different cards like stats, charts etc using some animations.
For the chart cards I made an icon button to toggle the div to make it bigger (fullscreen-like). The animation code currently works this way:

```<code>state('small', style({position: 'relative', width: '50%'})),
state('large', style({
    transform: 'translateY(-150px)',
    position: 'absolute',
    width: '100%'
})),
transition('small => large', animate('600ms ease', keyframes([
    style({position: 'absolute', width: '100%', offset: 0}),
    style({transform: 'translateY(-150px)',  offset: 1.0}),
]))),
transition('large => small', animate('600ms ease', keyframes([
    style({transform: 'translateY(-150px)',  offset: 0}),
    style({width: '50%', right: 0, offset: 1.0}),
])))
</code>```

This doesn't work as expected since for the first step (small => lage) the width is not animated, and for the reverse animation the translate is not either.
I would like to do something "smoother" but I've been struggling for days to make it.

Here is a quick plunkr I made to show you what I did and the different things I tried (commented) (first plunkr don't judge me x)

Thanks for your help !

答:
I think you will be able to get the desired animation effects by not using keyframes and switching to using ease-in-out transitions. If you were to edit your plunkr with these changes to the states and graphAnimation trigger:

```<code>animations: [
        trigger('panelAnimation', [
            state('in', style({transform: 'translateX(0)'})),
            transition('void => *', animate('600ms ease-in', keyframes([
                style({opacity: 0, offset: 0}),
                style({opacity: 1, offset: 1.0})
            ])))
        ]),
        trigger('graphAnimation', [
            state('small', style({
              position: 'absolute',
              right: 0,
              width: '50%'
              transform: 'translateY(0px)'
            })),
            state('large', style({
                transform: 'translateY(-150px)',
                position: 'absolute',
                right: 0,
                width: '100%'
            })),
            transition('small => large', animate('600ms 0.2ms ease-in-out')),
            transition('large => small', animate('600ms 0.2ms ease-in-out'))

        ])
    ]
</code>```

That should give you effect you are looking for. Alternatively you could look into using groups to allow independent animation timings.

Title: Angular 4 smooth animation

Body:
I'm trying to do a kind of Homepage in Angular 4 with different cards like stats, charts etc using some animations.
For the chart cards I made an icon button to toggle the div to make it bigger (fullscreen-like). The animation code currently works this way:

state('small', style({position: 'relative', width: '50%'})),
state('large', style({
    transform: 'translateY(-150px)',
    position: 'absolute',
    width: '100%'
})),
transition('small => large', animate('600ms ease', keyframes([
    style({position: 'absolute', width: '100%', offset: 0}),
    style({transform: 'translateY(-150px)',  offset: 1.0}),
]))),
transition('large => small', animate('600ms ease', keyframes([
    style({transform: 'translateY(-150px)',  offset: 0}),
    style({width: '50%', right: 0, offset: 1.0}),
])))

This doesn't work as expected since for the first step (small => lage) the width is not animated, and for the reverse animation the translate is not either.
I would like to do something "smoother" but I've been struggling for days to make it.

Here is a quick plunkr I made to show you what I did and the different things I tried (commented) (first plunkr don't judge me x)

Thanks for your help !

Body:
I think you will be able to get the desired animation effects by not using keyframes and switching to using ease-in-out transitions. If you were to edit your plunkr with these changes to the states and graphAnimation trigger:

animations: [
        trigger('panelAnimation', [
            state('in', style({transform: 'translateX(0)'})),
            transition('void => *', animate('600ms ease-in', keyframes([
                style({opacity: 0, offset: 0}),
                style({opacity: 1, offset: 1.0})
            ])))
        ]),
        trigger('graphAnimation', [
            state('small', style({
              position: 'absolute',
              right: 0,
              width: '50%'
              transform: 'translateY(0px)'
            })),
            state('large', style({
                transform: 'translateY(-150px)',
                position: 'absolute',
                right: 0,
                width: '100%'
            })),
            transition('small => large', animate('600ms 0.2ms ease-in-out')),
            transition('large => small', animate('600ms 0.2ms ease-in-out'))

        ])
    ]

That should give you effect you are looking for. Alternatively you could look into using groups to allow independent animation timings.


问:
How to display dates a person is working
I have created a basic rota that I can input data into blank cells which highlight depending on the code. See images below

When I type the code DW it will highlight blue, I want to display these dates in a seperate table so staff can easily see what dates they should be working. e.g. Joe Bloggs is woking on the 2nd April 2018 so I want to show this date in the cell below so it's easy for them to see.

Would this be possible using the LOOKUP function and if so how would you do this?

答:
You could do it with INDEX MATCH. I've entered the following into cell B8 This is an array formula so it is entered with Ctrl+Shift+Enter

```<code>=IFNA(INDEX($C$2:$G$2, MATCH(1,($C3:$G3="DW")*(COUNTIF($A8:A8,$C$2:$G$2)=0),0)),"")
</code>```

If using a version of Excel pre 2013 IFNA won't work and so you can use IFERROR instead

Body:
You could do it with INDEX MATCH. I've entered the following into cell B8 This is an array formula so it is entered with Ctrl+Shift+Enter

=IFNA(INDEX($C$2:$G$2, MATCH(1,($C3:$G3="DW")*(COUNTIF($A8:A8,$C$2:$G$2)=0),0)),"")

If using a version of Excel pre 2013 IFNA won't work and so you can use IFERROR instead


问:
RoboGuice with Standard Android JUnit test cases
I want to use RoboGuice in a standard Android JUnit instrumentation test case and override one piece of my app's actual wiring with a mock for testing. I can't find anything online that explains how to do this as all of my search results go to Robolectric with RoboGuoice. I am not using Robolectric nor can I use it in my app for various reasons. Has anyone wired an app with RoboGuice and injected mocks for standard Android Intrumentation test cases?

答:
I've managed to get it work in a simple usage way, you just bind dependencies inside rule using builder and may forget about them later, it will do everything by itself. You may think it's over engineered, but it's realy good for reusing if tyou have a many test classes with robo guice dependencies inside.
Usage in test classes looks like:

```<code>@Rule
    public InjectWithMocksRule injectWithMocksRule = new InjectWithMocksRule(
            this,
            () -> new InjectRule
                    .BindingBuilder()
                    .add(MyClass.class, mockedClassImpl)
                    .add(SomeInterface.class, mockedInterfaceImpl));
</code>```

I wrote helper class TestBindingModule:

```<code>public class TestBindingModule extends AbstractModule {

    private HashMap<Class<?>, Object> bindings = new HashMap<Class<?>, Object>();

    @Override
    @SuppressWarnings("unchecked")
    protected void configure() {
        Set<Entry<Class<?>, Object>> entries = bindings.entrySet();
        for (Entry<Class<?>, Object> entry : entries) {
            bind((Class<Object>) entry.getKey()).toInstance(entry.getValue());
        }
    }

    public void addBinding(Class<?> type, Object object) {
        bindings.put(type, object);
    }

    public void addBindings(HashMap<Class<?>, Object> bindings) {
        this.bindings.putAll(bindings);
    }

    public static void setUp(Object testObject, TestBindingModule module) {
        Module roboGuiceModule = RoboGuice.newDefaultRoboModule(RuntimeEnvironment.application);
        Module testModule = Modules.override(roboGuiceModule).with(module);
        RoboGuice.getOrCreateBaseApplicationInjector(RuntimeEnvironment.application, RoboGuice.DEFAULT_STAGE, testModule);
        RoboInjector injector = RoboGuice.getInjector(RuntimeEnvironment.application);
        injector.injectMembers(testObject);
    }

    public static void tearDown() {
        Application app = RuntimeEnvironment.application;
        DefaultRoboModule defaultModule = RoboGuice.newDefaultRoboModule(app);
        RoboGuice.getOrCreateBaseApplicationInjector(app, RoboGuice.DEFAULT_STAGE, defaultModule);
    }

}
</code>```

Than I use custom Rule to make it work easy:

```<code>public class InjectRule implements TestRule {

    public interface BindingBuilderFactory {
        BindingBuilder create();
    }

    public static class BindingBuilder {
        private HashMap<Class<?>, Object> bindings = new HashMap<>();

        public BindingBuilder add(Class<?> dependencyClass, Object implementation) {
            bindings.put(dependencyClass, implementation);
            return this;
        }

        HashMap<Class<?>, Object> buildBindings() {
            return this.bindings;
        }
    }

    private Object target;
    private BindingBuilderFactory bindingBuilderFactory;

    public InjectRule(Object target, BindingBuilderFactory bindingBuilderFactory) {
        this.target = target;
        this.bindingBuilderFactory = bindingBuilderFactory;
    }

    private void overrideTestInjections(Object target) {
        TestBindingModule module = new TestBindingModule();
        module.addBindings(this.bindingBuilderFactory.create().buildBindings());
        TestBindingModule.setUp(target, module);
    }

    @Override
    public Statement apply(Statement base, Description description) {
        return new StatementDecorator(base);
    }

    private class StatementDecorator extends Statement {

        private Statement baseStatement;

        StatementDecorator(Statement b) {
            baseStatement = b;
        }

        @Override
        public void evaluate() throws Throwable {
            before();
            try {
                baseStatement.evaluate();
            } catch (Error e) {
                throw e;
            } finally {
                after();
            }
        }

        void after() {
            TestBindingModule.tearDown();
        }

        void before() {
            overrideTestInjections(target);
        }
    }

}
</code>```

Also you may want to init mocks with @Mock annotation inside of your test classes, so you need another custom rule:

```<code>public class MockitoInitializerRule implements TestRule {

    private Object target;

    public MockitoInitializerRule(Object target) {
        this.target = target;
    }

    @Override
    public Statement apply(Statement base, Description description) {
        return new MockitoInitializationStatement(base, target);
    }

    private class MockitoInitializationStatement extends Statement {
        private final Statement base;
        private Object test;

        MockitoInitializationStatement(Statement base, Object test) {
            this.base = base;
            this.test = test;
        }

        @Override
        public void evaluate() throws Throwable {
            MockitoAnnotations.initMocks(test);
            base.evaluate();
        }
    }
}
</code>```

And, finaly, you want to combine them to mock mocks first and then set them as dependencies:

```<code>public class InjectWithMocksRule implements TestRule {

    private final RuleChain delegate;

    public InjectWithMocksRule(Object target, InjectRule.BindingBuilderFactory bindingBuilderFactory) {
        delegate = RuleChain
                .outerRule(new MockitoInitializerRule(target))
                .around(new InjectRule(target, bindingBuilderFactory));
    }

    @Override
    public Statement apply(Statement base, Description description) {
        return delegate.apply(base, description);
    }
}
</code>```

Body:
I've managed to get it work in a simple usage way, you just bind dependencies inside rule using builder and may forget about them later, it will do everything by itself. You may think it's over engineered, but it's realy good for reusing if tyou have a many test classes with robo guice dependencies inside.
Usage in test classes looks like:

@Rule
    public InjectWithMocksRule injectWithMocksRule = new InjectWithMocksRule(
            this,
            () -> new InjectRule
                    .BindingBuilder()
                    .add(MyClass.class, mockedClassImpl)
                    .add(SomeInterface.class, mockedInterfaceImpl));

I wrote helper class TestBindingModule:

public class TestBindingModule extends AbstractModule {

    private HashMap<Class<?>, Object> bindings = new HashMap<Class<?>, Object>();

    @Override
    @SuppressWarnings("unchecked")
    protected void configure() {
        Set<Entry<Class<?>, Object>> entries = bindings.entrySet();
        for (Entry<Class<?>, Object> entry : entries) {
            bind((Class<Object>) entry.getKey()).toInstance(entry.getValue());
        }
    }

    public void addBinding(Class<?> type, Object object) {
        bindings.put(type, object);
    }

    public void addBindings(HashMap<Class<?>, Object> bindings) {
        this.bindings.putAll(bindings);
    }

    public static void setUp(Object testObject, TestBindingModule module) {
        Module roboGuiceModule = RoboGuice.newDefaultRoboModule(RuntimeEnvironment.application);
        Module testModule = Modules.override(roboGuiceModule).with(module);
        RoboGuice.getOrCreateBaseApplicationInjector(RuntimeEnvironment.application, RoboGuice.DEFAULT_STAGE, testModule);
        RoboInjector injector = RoboGuice.getInjector(RuntimeEnvironment.application);
        injector.injectMembers(testObject);
    }

    public static void tearDown() {
        Application app = RuntimeEnvironment.application;
        DefaultRoboModule defaultModule = RoboGuice.newDefaultRoboModule(app);
        RoboGuice.getOrCreateBaseApplicationInjector(app, RoboGuice.DEFAULT_STAGE, defaultModule);
    }

}

Than I use custom Rule to make it work easy:

public class InjectRule implements TestRule {

    public interface BindingBuilderFactory {
        BindingBuilder create();
    }

    public static class BindingBuilder {
        private HashMap<Class<?>, Object> bindings = new HashMap<>();

        public BindingBuilder add(Class<?> dependencyClass, Object implementation) {
            bindings.put(dependencyClass, implementation);
            return this;
        }

        HashMap<Class<?>, Object> buildBindings() {
            return this.bindings;
        }
    }

    private Object target;
    private BindingBuilderFactory bindingBuilderFactory;

    public InjectRule(Object target, BindingBuilderFactory bindingBuilderFactory) {
        this.target = target;
        this.bindingBuilderFactory = bindingBuilderFactory;
    }

    private void overrideTestInjections(Object target) {
        TestBindingModule module = new TestBindingModule();
        module.addBindings(this.bindingBuilderFactory.create().buildBindings());
        TestBindingModule.setUp(target, module);
    }

    @Override
    public Statement apply(Statement base, Description description) {
        return new StatementDecorator(base);
    }

    private class StatementDecorator extends Statement {

        private Statement baseStatement;

        StatementDecorator(Statement b) {
            baseStatement = b;
        }

        @Override
        public void evaluate() throws Throwable {
            before();
            try {
                baseStatement.evaluate();
            } catch (Error e) {
                throw e;
            } finally {
                after();
            }
        }

        void after() {
            TestBindingModule.tearDown();
        }

        void before() {
            overrideTestInjections(target);
        }
    }

}

Also you may want to init mocks with @Mock annotation inside of your test classes, so you need another custom rule:

public class MockitoInitializerRule implements TestRule {

    private Object target;

    public MockitoInitializerRule(Object target) {
        this.target = target;
    }

    @Override
    public Statement apply(Statement base, Description description) {
        return new MockitoInitializationStatement(base, target);
    }

    private class MockitoInitializationStatement extends Statement {
        private final Statement base;
        private Object test;

        MockitoInitializationStatement(Statement base, Object test) {
            this.base = base;
            this.test = test;
        }

        @Override
        public void evaluate() throws Throwable {
            MockitoAnnotations.initMocks(test);
            base.evaluate();
        }
    }
}

And, finaly, you want to combine them to mock mocks first and then set them as dependencies:

public class InjectWithMocksRule implements TestRule {

    private final RuleChain delegate;

    public InjectWithMocksRule(Object target, InjectRule.BindingBuilderFactory bindingBuilderFactory) {
        delegate = RuleChain
                .outerRule(new MockitoInitializerRule(target))
                .around(new InjectRule(target, bindingBuilderFactory));
    }

    @Override
    public Statement apply(Statement base, Description description) {
        return delegate.apply(base, description);
    }
}


问:
How to insert sum of col grouped by another col in new col
I'm trying to multiply 2 columns "qty*price_dl" of table and but the value in new column "total1" in the same table and this work with me without problems

after that trying to get sum of "total1" column grouped by "seq" column and but the values in "total2" column in the same table
I'm stuck in process of summation it doesn't work with me
this is the code:

```<code><?php
require_once("dbconfig.php");
$q=mysql_query('select * from sale_menu')
or die(mysql_error());
echo "<table border='2'>
<tr>
    <th>Select</th>
    <th>qty</th>
    <th>price_dl</th>
    <th>total1</th>

</tr><tr>";
while($rw=mysql_fetch_array($q)){
    ?>
    <td><input type="checkbox" value="<?php echo $rw['seq']; ?>" name="seq[]" ></td>
    <td><b><?php echo $rw['qty']; ?></b></td>
    <td><b><?php echo $rw['price_dl']; ?></b></td>
    <td><b><?php echo $rw['total1']; ?></b></td>
    <tr>
    </tbody>
    <?php } ?>
    <?php
    error_reporting(0);
    $seq=$_POST['seq'];
    if (isset($_POST['submit']))
    {
        $impid=implode(", ",$seq);
        $qdel=mysql_query("SELECT * FROM sale_menu WHERE seq IN(".$impid.")");
        while($row=mysql_fetch_array($qdel)){
            $qty=$row['qty'];
            $price_dl=$row['price_dl'];
            $qdel=mysql_query("UPDATE sale_menu set total1=qty*price_dl WHERE seq IN(".$impid.")");
            $qdel=mysql_query("UPDATE sale_menu set total2=sum(total1) WHERE seq IN(".$impid.")");
        }
    }
    ?>
    <button name="submit" type="submit" value="Checked" id="submit" >Move</button>
</code>```

this is where I stuck:

```<code>$qdel=mysql_query("SELECT * FROM sale_menu WHERE seq IN(".$impid.")");
$qdel=mysql_query("select sum(total1) as total from sale_menu group by seq");
while($row=mysql_fetch_array($qdel)){
$total =  $row['total'];
$qdel=mysql_query("UPDATE sale_menu set total1=qty*price_dl WHERE seq IN(".$impid.")");
$qdel=mysql_query("UPDATE sale_menu set total2= $total WHERE seq IN(".$impid.")");
</code>```

答:
You cant put total1 as column here because you need to make query inside query and there is two ways to do it

The first it to do nested query like this

```<code>$qdel=mysql_query("UPDATE sale_menu set total2= (select sum(total1) as total from table_name) WHERE seq IN(".$impid.")");
</code>```

The second is way much easier just make another query before this query and store the value of sum(total1) inside a variable then you can use the variable in this query for example

```<code>$q=mysql_query('select sum(total1) as total from table_name')
while($rw=mysql_fetch_array($q)){

   $total =  $rw['total'];
 }
$qdel=mysql_query("UPDATE sale_menu set total2= $total WHERE seq IN(".$impid.")");
</code>```

I hope it works for you

Body:
I'm trying to multiply 2 columns "qty*price_dl" of table and but the value in new column "total1" in the same table and this work with me without problems

after that trying to get sum of "total1" column grouped by "seq" column and but the values in "total2" column in the same table
I'm stuck in process of summation it doesn't work with me
this is the code:

<?php
require_once("dbconfig.php");
$q=mysql_query('select * from sale_menu')
or die(mysql_error());
echo "

    Select
    qty
    price_dl
    total1

";
while($rw=mysql_fetch_array($q)){
    ?>
    <input type="checkbox" value="<?php echo $rw['seq']; ?>" name="seq[]" >
    <?php echo $rw['qty']; ?>
    <?php echo $rw['price_dl']; ?>
    <?php echo $rw['total1']; ?>

    <?php } ?>
    <?php
    error_reporting(0);
    $seq=$_POST['seq'];
    if (isset($_POST['submit']))
    {
        $impid=implode(", ",$seq);
        $qdel=mysql_query("SELECT * FROM sale_menu WHERE seq IN(".$impid.")");
        while($row=mysql_fetch_array($qdel)){
            $qty=$row['qty'];
            $price_dl=$row['price_dl'];
            $qdel=mysql_query("UPDATE sale_menu set total1=qty*price_dl WHERE seq IN(".$impid.")");
            $qdel=mysql_query("UPDATE sale_menu set total2=sum(total1) WHERE seq IN(".$impid.")");
        }
    }
    ?>
    <button name="submit" type="submit" value="Checked" id="submit" >Move</button>

this is where I stuck:

$qdel=mysql_query("SELECT * FROM sale_menu WHERE seq IN(".$impid.")");
$qdel=mysql_query("select sum(total1) as total from sale_menu group by seq");
while($row=mysql_fetch_array($qdel)){
$total =  $row['total'];
$qdel=mysql_query("UPDATE sale_menu set total1=qty*price_dl WHERE seq IN(".$impid.")");
$qdel=mysql_query("UPDATE sale_menu set total2= $total WHERE seq IN(".$impid.")");

Body:
You cant put total1 as column here because you need to make query inside query and there is two ways to do it

The first it to do nested query like this

$qdel=mysql_query("UPDATE sale_menu set total2= (select sum(total1) as total from table_name) WHERE seq IN(".$impid.")");

The second is way much easier just make another query before this query and store the value of sum(total1) inside a variable then you can use the variable in this query for example

$q=mysql_query('select sum(total1) as total from table_name')
while($rw=mysql_fetch_array($q)){

   $total =  $rw['total'];
 }
$qdel=mysql_query("UPDATE sale_menu set total2= $total WHERE seq IN(".$impid.")");

I hope it works for you


问:
Exception Passing In Python
I have a bit of code that does some functional exception handling and everything works well, exceptions are raised when I want them to be, but when I'm debugging, the line-traces don't always do quite what I want them to.

Example A:

```<code>>>> 3/0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
</code>```

Example B:

```<code>>>> try: 3/0
... except Exception as e: raise e
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ZeroDivisionError: integer division or modulo by zero
</code>```

In both of these examples, the exception really occurs in line 1, where we attempt to do 3/0, but in the latter example, we are told it has occurred on line 2, where it is raised.

Is there a way in Python to raise an exception, as if it were another exception, something that would produce the following output:

```<code>>>> try: 3/0
... except Exception as e: metaraise(e)
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
</code>```

答:
When you re-raise an exception that you caught, such as

```<code>except Exception as e: raise e
</code>```

it resets the stack trace. It's just like re-raising a new exception. What you want is this:

```<code>except Exception as e: raise
</code>```

Title: Exception Passing In Python

Body:
I have a bit of code that does some functional exception handling and everything works well, exceptions are raised when I want them to be, but when I'm debugging, the line-traces don't always do quite what I want them to.

Example A:

>>> 3/0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero

Example B:

>>> try: 3/0
... except Exception as e: raise e
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ZeroDivisionError: integer division or modulo by zero

In both of these examples, the exception really occurs in line 1, where we attempt to do 3/0, but in the latter example, we are told it has occurred on line 2, where it is raised.

Is there a way in Python to raise an exception, as if it were another exception, something that would produce the following output:

>>> try: 3/0
... except Exception as e: metaraise(e)
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero

Body:
When you re-raise an exception that you caught, such as

except Exception as e: raise e

it resets the stack trace. It's just like re-raising a new exception. What you want is this:

except Exception as e: raise


问:
How to mute twilio calls in javascript
I am able to mute the sound going into the microphone, but not the sound coming out of the speakers.  To be specific, I'm only trying to mute the Twilio call, not other sounds in the browser, and certainly not system sounds.</p>

答:
Its straightforward using the Javascript 1.4 library, without needing conference calls etc.

https://www.twilio.com/docs/api/client/connection

e.g.

```<code>Twilio.Device.activeConnection().mute(true);
</code>```

Title: How to mute twilio calls in javascript

Body:
Its straightforward using the Javascript 1.4 library, without needing conference calls etc.

https://www.twilio.com/docs/api/client/connection

e.g.

Twilio.Device.activeConnection().mute(true);


问:
export default class Book extends Component VS export default Book
I'm new to react so its just a question that i want to know which one is more efficient and which give the best time complexity.

No. 1

```<code>    export default class BookingTabs extends Component {
  render() {
    return (
    );
  }
}
</code>```

No. 2

```<code>class Book extends Component {
  render() {
    return (
    );
  }
}
export default Book
</code>```

Questions:

which one is more efficient to use?

which one take less time? even difference in micro seconds?

what is the different between export default and module.export?

答:
* which one is more efficient to use?

They are equally efficient. It's a matter of coding style and preference.

No. 1 gives possibility to declare class without name such as

```<code>export default class extends Component {
  render() {
    return (
      <div>markup</div>
    );
  }
}
</code>```

No. 2 gives possibilities for further working with the class before exporting it. Such as adding proptypes Book.propTypes = { /* prop-types defintion */} or used with higher order components.

* which one take less time? even difference in micro seconds?

Your target is probably for browsers which does not understand ES6 modules (import/export) natively. The compiled code is the same. I would recommend to play with https://babeljs.io/repl/ to get an idea what's is generated

* what is the different between export default and module.export?

The first is ES6 modules (to be understand by the browsers in the near future), the latter is NodeJS modules (https://nodejs.org/docs/latest/api/modules.html#modules_module). It's already well explained in Stackoverflow if you search around, e.g. https://stackoverflow.com/a/40295288/815507

Body:
I'm new to react so its just a question that i want to know which one is more efficient and which give the best time complexity.

No. 1

    export default class BookingTabs extends Component {
  render() {
    return (
    );
  }
}

No. 2

class Book extends Component {
  render() {
    return (
    );
  }
}
export default Book

Questions:

which one is more efficient to use?

which one take less time? even difference in micro seconds?

what is the different between export default and module.export?

Body:
* which one is more efficient to use?

They are equally efficient. It's a matter of coding style and preference.

No. 1 gives possibility to declare class without name such as

export default class extends Component {
  render() {
    return (
      <div>markup</div>
    );
  }
}

No. 2 gives possibilities for further working with the class before exporting it. Such as adding proptypes Book.propTypes = { /* prop-types defintion */} or used with higher order components.

* which one take less time? even difference in micro seconds?

Your target is probably for browsers which does not understand ES6 modules (import/export) natively. The compiled code is the same. I would recommend to play with https://babeljs.io/repl/ to get an idea what's is generated

* what is the different between export default and module.export?

The first is ES6 modules (to be understand by the browsers in the near future), the latter is NodeJS modules (https://nodejs.org/docs/latest/api/modules.html#modules_module). It's already well explained in Stackoverflow if you search around, e.g. https://stackoverflow.com/a/40295288/815507


问:
jQuery animate on previously appended div
I'm trying to animate a div that I previously appended, but the animation doesn't happen, even though the complete function is executed.

Here is a very simple example:

EDIT: I corrected the typo in my jsFiddle and the problem is still there, but thank you for pointing it out.

HTML:

```<code><button id="test">
    Go
</button>
<div class="elements">
</div>
</code>```

JS:

```<code>$('#test').click(function(){
  $("<div class='element-test'><img src='https://image.flaticon.com/icons/png/128/148/148836.png' style='position:absolute; z-index:40; top:400px; left:200px; width:2%;'></div>")
  .appendTo('.elements').animate({top:'100px', left:'400px'}, 500, function(){
      $('.element-test').fadeOut(200);
    });
});
</code>```

I wrote a jsFiddle showing the problem.

In my application, I would need to animate this with % positions, and I thought that was the problem in the beginning. However, changing it to pixel positions or even pure int numbers in the animate parameters doesn't solve it.

At the beginning, I was using .append() and then animate(). The idea of using appendTo().animate() comes from there.

答:
You must first wait for the image, until it will be fully loaded, with onload event. Then, in callback of onload event, you can run the animation:

var $container = $('.elements')
var imageSrc = 'https://image.flaticon.com/icons/png/128/148/148836.png'
var element = `

  </div
`

function appendElement (elm) {
  $(elm).appendTo($container)
  $('.element-test img').on('load', animateElement)
}

function animateElement () {
  $(this)
    .animate({
      top: '+=100',
      left: '+=400'
    }, 1000)
    .promise()
    .then($(this).fadeOut())
}

$('#test').click(appendElement.bind(this, element))```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.element-test img {
  position:absolute;
}</code>```

<button id="test">Go</button>

```

Body:
I'm trying to animate a div that I previously appended, but the animation doesn't happen, even though the complete function is executed.

Here is a very simple example:

EDIT: I corrected the typo in my jsFiddle and the problem is still there, but thank you for pointing it out.

HTML:

<button id="test">
    Go
</button>

JS:

$('#test').click(function(){
  $("

")
  .appendTo('.elements').animate({top:'100px', left:'400px'}, 500, function(){
      $('.element-test').fadeOut(200);
    });
});

I wrote a jsFiddle showing the problem.

In my application, I would need to animate this with % positions, and I thought that was the problem in the beginning. However, changing it to pixel positions or even pure int numbers in the animate parameters doesn't solve it.

At the beginning, I was using .append() and then animate(). The idea of using appendTo().animate() comes from there.

Body:
You must first wait for the image, until it will be fully loaded, with onload event. Then, in callback of onload event, you can run the animation:

var $container = $('.elements')
var imageSrc = 'https://image.flaticon.com/icons/png/128/148/148836.png'
var element = `
  <div class="element-test">
    <img src="${imageSrc}">
  </div
`

function appendElement (elm) {
  $(elm).appendTo($container)
  $('.element-test img').on('load', animateElement)
}

function animateElement () {
  $(this)
    .animate({
      top: '+=100',
      left: '+=400'
    }, 1000)
    .promise()
    .then($(this).fadeOut())
}

$('#test').click(appendElement.bind(this, element))

.element-test img {
  position:absolute;
}

<button id="test">Go</button>
<div class="elements"></div>

<script src="https://unpkg.com/jquery"></script>


问:
Mutex for two threads in C++
I've created two threads that use a variable declared in main via pthread_create's last argument. I want thread2  to use modify the value of that variable after thread1 is done with a set of particular instructions. I know how we can use mutex in one thread but how about two or more threads?
Refer to the following code:</p>

```<code>#include<iostream>
#include<unistd.h>
#include<stdlib.h>
#include<pthread.h>
#define NUM 6
using namespace std;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void *even(void *arg)
{
    int sum = 0;
    int count = 0;
    for (int i = 1; count < NUM/2; i++)
    {
        if( !(i % 2) )
        {
            count++;
            sum += i;
        }
    }
    cout << "In Even Thread: " << sum << endl;
    pthread_mutex_lock(&mutex);
    *((int*)arg) = sum;
    pthread_mutex_unlock(&mutex);
    pthread_cond_signal(&cond);
}
void *odd(void *arg)
{
    int sum = 0;
    int count = 0;
    for (int i = 1; count < NUM/2; i++)
    {
        if( i % 2 )
        {
            count++;
            sum += i;
        }
    }
    cout << "In Odd Thread: " << sum << endl;
    pthread_cond_wait(&cond, &mutex);
    *((int*)arg) = *((int*)arg) + sum;
}

int main()
{
    int mainSum = 0;
    pthread_t tidO, tidE;
    pthread_create(&tidO, NULL, odd, (void *)&mainSum);
    pthread_create(&tidE, NULL, even, (void *)&mainSum);
    pthread_join(tidO, NULL);
    pthread_join(tidE, NULL);
    cout << "Sum of first " << NUM << " Natural Numbers: " << mainSum << endl;
    return 0;
}
</code>```

答:
You should lock mutex before accessing the variable and unlock after you finish you finish you job with the variable. Use lock_guard to keep mutex locked and use brackets for lock_guard lifetime.  http://www.cplusplus.com/reference/mutex/lock_guard/

std::mutex mtx; //global mutex
int v; //global variable;

```<code>int k;
...
//repeat this code in each thread to access the variable
{
   std::lock_guard<std::mutex> lck (mtx);
   //access the variable;
   k = v; //read global variable or
   v = k; //write
}
</code>```

Title: Mutex for two threads in C++

Body:
I've created two threads that use a variable declared in main via pthread_create's last argument. I want thread2  to use modify the value of that variable after thread1 is done with a set of particular instructions. I know how we can use mutex in one thread but how about two or more threads?
Refer to the following code:

#include<iostream>
#include<unistd.h>
#include<stdlib.h>
#include<pthread.h>
#define NUM 6
using namespace std;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void *even(void *arg)
{
    int sum = 0;
    int count = 0;
    for (int i = 1; count < NUM/2; i++)
    {
        if( !(i % 2) )
        {
            count++;
            sum += i;
        }
    }
    cout << "In Even Thread: " << sum << endl;
    pthread_mutex_lock(&mutex);
    *((int*)arg) = sum;
    pthread_mutex_unlock(&mutex);
    pthread_cond_signal(&cond);
}
void *odd(void *arg)
{
    int sum = 0;
    int count = 0;
    for (int i = 1; count < NUM/2; i++)
    {
        if( i % 2 )
        {
            count++;
            sum += i;
        }
    }
    cout << "In Odd Thread: " << sum << endl;
    pthread_cond_wait(&cond, &mutex);
    *((int*)arg) = *((int*)arg) + sum;
}

int main()
{
    int mainSum = 0;
    pthread_t tidO, tidE;
    pthread_create(&tidO, NULL, odd, (void *)&mainSum);
    pthread_create(&tidE, NULL, even, (void *)&mainSum);
    pthread_join(tidO, NULL);
    pthread_join(tidE, NULL);
    cout << "Sum of first " << NUM << " Natural Numbers: " << mainSum << endl;
    return 0;
}

Body:
You should lock mutex before accessing the variable and unlock after you finish you finish you job with the variable. Use lock_guard to keep mutex locked and use brackets for lock_guard lifetime.  http://www.cplusplus.com/reference/mutex/lock_guard/

std::mutex mtx; //global mutex
int v; //global variable;

int k;
...
//repeat this code in each thread to access the variable
{
   std::lock_guard<std::mutex> lck (mtx);
   //access the variable;
   k = v; //read global variable or
   v = k; //write
}


问:
How can I implement user sessions with android app and node server?
I've built an android app and it can connect to my node express server just fine. However I don't know how to implement user sessions so that when users 'post' or 'get' from my server, my server can find which user it is.

My previous experience was with a simple website, where I used express-sessions, and the attached username to the session was used to search the MySql database and find the relevant information about the user.

I'm currently using OkHTTP3 in my app for connections.

Is there a simple idea to make this work?

答:
In this scenario you need a WebAPI - there are no cookies nor sessions in the API. The only thing that is linking the user from the client code to the backend code is the JWT.

You could write your own, but there is no need to since you can find a decent middleware that does exactly that ...  express-jwt

This will allow you not only to create the JSON WEB TOKENS but also to verify them, It is a nice Middleware and it can solve your issue easily.

This middleware lets you authenticate HTTP requests using JWT tokens in your Node.js applications. JWTs are typically used to protect API endpoints, and are often issued using OpenID Connect

```<code>var jwt = require('express-jwt');

app.get('/protected',
  jwt({secret: 'your-super shhhhhhared-secret'}),
  function(req, res) {
    if (!req.user.admin) return res.sendStatus(401);
    res.sendStatus(200);
  });
</code>```

Body:
In this scenario you need a WebAPI - there are no cookies nor sessions in the API. The only thing that is linking the user from the client code to the backend code is the JWT.

You could write your own, but there is no need to since you can find a decent middleware that does exactly that ...  express-jwt

This will allow you not only to create the JSON WEB TOKENS but also to verify them, It is a nice Middleware and it can solve your issue easily.

This middleware lets you authenticate HTTP requests using JWT tokens in your Node.js applications. JWTs are typically used to protect API endpoints, and are often issued using OpenID Connect

var jwt = require('express-jwt');

app.get('/protected',
  jwt({secret: 'your-super shhhhhhared-secret'}),
  function(req, res) {
    if (!req.user.admin) return res.sendStatus(401);
    res.sendStatus(200);
  });


问:
Sort Java Collection
I have a Java collection:

```<code>Collection<CustomObject> list = new ArrayList<CustomObject>();
</code>```

CustomObject has an id field now before display list I want to sort this collection by that id.

Is there any way I could that do that?

答: You can use java Custom Class for the purpose of sorting.</p>

Title: Sort Java Collection

Body:
I have a Java collection:

Collection<CustomObject> list = new ArrayList<CustomObject>();

CustomObject has an id field now before display list I want to sort this collection by that id.

Is there any way I could that do that?


问:
How to get two select query and condition checking from two tables
I have two tables one is transfer and other one is hardwareSKU ....

Transfer is having below columns

```<code>certid,
part_id
part_desc
snum
.....
</code>```

and hardwareSKU is having below columns

```<code>part_id,
productname
numusers..
</code>```

I need to pass snum as input to single storedprocedure and i need to return two select queries

first i need to find whether snum exists in Transfer table if it exists i need to get part_id from Transfer table and pass this part_id info to hardwareSKU to get the all details..

Here i need to return both select statement queries (one is from Transfer table for corresponding snum and other one is from hardwareSKU for corresponding part_id)

how can i get two queries with part_id check from second table ..

I am using sql server ..

Would any one please help on this query that would be very grateful to me.

答:
Try the following:</p>

```<code>CREATE PROCEDURE Proc_Name @Psnum INT
AS
BEGIN

IF EXISTS(SELECT 1 FROM Transfer WHERE snum=@Psnum)
BEGIN
SELECT * FROM Transfer WHERE snum = @Psnum

SELECT * FROM hardwareSKU WHERE part_id in (SELECT part_id FROM Transfer WHERE snum = @Psnum)

END
END
</code>```

Body:
I have two tables one is transfer and other one is hardwareSKU ....

Transfer is having below columns

certid,
part_id
part_desc
snum
.....

and hardwareSKU is having below columns

part_id,
productname
numusers..

I need to pass snum as input to single storedprocedure and i need to return two select queries

first i need to find whether snum exists in Transfer table if it exists i need to get part_id from Transfer table and pass this part_id info to hardwareSKU to get the all details..

Here i need to return both select statement queries (one is from Transfer table for corresponding snum and other one is from hardwareSKU for corresponding part_id)

how can i get two queries with part_id check from second table ..

I am using sql server ..

Would any one please help on this query that would be very grateful to me.

Body:
Try the following:

CREATE PROCEDURE Proc_Name @Psnum INT
AS
BEGIN

IF EXISTS(SELECT 1 FROM Transfer WHERE snum=@Psnum)
BEGIN
SELECT * FROM Transfer WHERE snum = @Psnum

SELECT * FROM hardwareSKU WHERE part_id in (SELECT part_id FROM Transfer WHERE snum = @Psnum)

END
END