问:
Error from JM package in R
JM is a package to fit a model with joint longitudinal and survival data. I can get it to run with their example data, but I get an error with my own data. Any idea what the issue with JMfit1 or JMfit2 is? </p>

<p>My Data:
https://1drv.ms/u/s!AkG9wyz5G1c1gR4Vs_xohO--4Rb5 </p>

```<code>install.packages('JM')
require(JM)
?jointModel

# Example from vignette
# linear mixed model fit (random intercepts + random slopes)
fitLME <- lme(log(serBilir) ~ drug * year, random = ~ year | id, data = pbc2)
summary(fitLME)
# survival regression fit
fitSURV <- survreg(Surv(years, status2) ~ drug, data = pbc2.id, x = TRUE)
summary(fitSURV)
# joint model fit, under the (default) Weibull model
fitJOINT <- jointModel(fitLME, fitSURV, timeVar = "year")
fitJOINT
summary(fitJOINT)
# we can also include an interaction term of log(serBilir) with drug
fitJOINT <- jointModel(fitLME, fitSURV, timeVar = "year",
                       # interFact = list(value = ~ drug, data = pbc2.id))
fitJOINT
summary(fitJOINT)

# With my data:
data = readRDS('data.list.d1.dk.RDS')
d1 = data$d1
dk = data$dk
dim(d1); names(d1)
dim(dk); names(dk)

slct.cov = c('ID','Yi','Ai','zi.1','zi.2','zi.3','xi_A','di')

fmla.fix = as.formula('Yi ~ Ai*(zi.1+zi.2+zi.3)')
fmla.rnd = as.formula(' ~ Ai|ID')

fit.Yi = lme(fixed= fmla.fix, random=reStruct(fmla.rnd),
              method="ML", data = dk[,slct.cov] )

surv.model = survreg(Surv(xi_A, di) ~ zi.1+zi.2+zi.3, data = d1[,slct.cov], x = TRUE)

JMfit1 = jointModel(lmeObject = fit.Yi, survObject = surv.model, timeVar = 'Ai')
# Error in if (t1 || t2) { : missing value where TRUE/FALSE needed

dForm <- list(fixed = ~ 1 + zi.1 + zi.2 + zi.3, indFixed = c(2,6,7,8), random = ~ 1, indRandom = 2)

JMfit2 = jointModel(lmeObject = fit.Yi, survObject = surv.model, timeVar = 'Ai',
                   derivForm = dForm, parameterization = c("both")) #"both", "value", "slope"
                   # method = "weibull-PH-aGH",
                   # "weibull-PH-aGH", "weibull-PH-GH", "weibull-AFT-aGH","weibull-AFT-GH",
                   # "piecewise-PH-aGH", "piecewise-PH-GH", "Cox-PH-aGH", "Cox-PH-GH",
                   # "spline-PH-aGH", "spline-PH-GH", # "ch-Laplace"
                   # interFact = NULL, lag = 0, scaleWB = NULL,
                   # CompRisk = FALSE, init = NULL, control = list())
</code>```

答:
It looks to me that your fmla.fix model needs more investigation in its own right maybe.

Simplifying the interactions to Yi ~ Ai+zi.1+zi.3 + Ai*(zi.2) or even Yi ~ Ai+zi.1+zi.2+zi.3 seem to give a valid JMfit1 output.

I suspect you'll get a different error for JMfit2 (do you??), so that may be a subsequent SO question.

Title: Error from JM package in R

Body:
JM is a package to fit a model with joint longitudinal and survival data. I can get it to run with their example data, but I get an error with my own data. Any idea what the issue with JMfit1 or JMfit2 is?

My Data:
https://1drv.ms/u/s!AkG9wyz5G1c1gR4Vs_xohO--4Rb5

install.packages('JM')
require(JM)
?jointModel

# Example from vignette
# linear mixed model fit (random intercepts + random slopes)
fitLME <- lme(log(serBilir) ~ drug * year, random = ~ year | id, data = pbc2)
summary(fitLME)
# survival regression fit
fitSURV <- survreg(Surv(years, status2) ~ drug, data = pbc2.id, x = TRUE)
summary(fitSURV)
# joint model fit, under the (default) Weibull model
fitJOINT <- jointModel(fitLME, fitSURV, timeVar = "year")
fitJOINT
summary(fitJOINT)
# we can also include an interaction term of log(serBilir) with drug
fitJOINT <- jointModel(fitLME, fitSURV, timeVar = "year",
                       # interFact = list(value = ~ drug, data = pbc2.id))
fitJOINT
summary(fitJOINT)

# With my data:
data = readRDS('data.list.d1.dk.RDS')
d1 = data$d1
dk = data$dk
dim(d1); names(d1)
dim(dk); names(dk)

slct.cov = c('ID','Yi','Ai','zi.1','zi.2','zi.3','xi_A','di')

fmla.fix = as.formula('Yi ~ Ai*(zi.1+zi.2+zi.3)')
fmla.rnd = as.formula(' ~ Ai|ID')

fit.Yi = lme(fixed= fmla.fix, random=reStruct(fmla.rnd),
              method="ML", data = dk[,slct.cov] )

surv.model = survreg(Surv(xi_A, di) ~ zi.1+zi.2+zi.3, data = d1[,slct.cov], x = TRUE)

JMfit1 = jointModel(lmeObject = fit.Yi, survObject = surv.model, timeVar = 'Ai')
# Error in if (t1 || t2) { : missing value where TRUE/FALSE needed

dForm <- list(fixed = ~ 1 + zi.1 + zi.2 + zi.3, indFixed = c(2,6,7,8), random = ~ 1, indRandom = 2)

JMfit2 = jointModel(lmeObject = fit.Yi, survObject = surv.model, timeVar = 'Ai',
                   derivForm = dForm, parameterization = c("both")) #"both", "value", "slope"
                   # method = "weibull-PH-aGH",
                   # "weibull-PH-aGH", "weibull-PH-GH", "weibull-AFT-aGH","weibull-AFT-GH",
                   # "piecewise-PH-aGH", "piecewise-PH-GH", "Cox-PH-aGH", "Cox-PH-GH",
                   # "spline-PH-aGH", "spline-PH-GH", # "ch-Laplace"
                   # interFact = NULL, lag = 0, scaleWB = NULL,
                   # CompRisk = FALSE, init = NULL, control = list())


来源: stackexchange

问:
What causes udp reception delay?
I have noticed that when I am sending packets at even intervals from a udp socket, the first packet sent seems to be delayed. For example, if I am sending the packets every 100 ms, I find the delay between receiving the packets to be normally distributed with mean 100ms and average standard deviation of 4, on my network. However, the gap between the receive time for the first and second packets is usually around 10 to 40 ms - as you can see, that's clearly a statistically significant difference, and so my question is, what's causing it?

I'm using the sendto function from C on linux. Someone suggested the delay might be caused by arp resolution preventing the packet from being sent until the destination ip has been converted to a mac address - is this likely? If I restart the sending program the first packet again takes too long though, and the delay is inconsistent - 10 to 40 ms is a pretty big range.

I need to find out why this first packet is taking too long, and how to work around it.

Edit: Further analysis with pcap indicates that the sending program is sending the packets at the right interval. Problem must be with the receiver, which is using select() to wait for a readable socket, then calling recvfrom and printing the packet. Is there some sort of buffering going on there I might not know about?

答:
You have asked about workarounds.  One possible workaround, if the reception time of the packet is important to know, is to set the SO_TIMESTAMP socket option.  This will allow you to obtain the time that each packet was received by the destination kernel - you can then use this time in subsequent processing rather than the "current time".

Alternatively, you could have the sender include a high resolution timestamp in the packet that it sends, and use those.

ContentLicense: CC BY-SA 2.5

Title: What causes udp reception delay?


问:
LeapMotion new sdk missing classes from older SDK for Unity
I am developing an app using leap motion and Unity 5.6. Earlier I was using LeapMotion 3.0 SDK which was working properly in my app but had few issues which I read somewhere are fixed in the newer SDK. So I tried implementing newer sdk version i.e 3.2.1 in my project.

I am successful in integrating SDK but there are certain classes that I was using from previous leap motion SDK but those are not present in the newer SDK version provided by leap motion, which are causing compilation error in my application.

I have searched all the unity API docs provided by Leap Motion but haven't found description on how to replace those missing classes using newer SDK.

Few classes/references that I am missing in newer SDK are:

InteractionBehaviourBase

HandCollisionCallbacks

Physical Button

I haven't found alternative classes/references for the above classes.

答:
You're describing classes from the beta version of the Interaction Engine. The Interaction Engine is now out-of-beta, but didn't maintain total backwards-compatibility with projects that used the beta version.

The analogous classes you're looking for would be:

InteractionBehaviourBase -> InteractionBehaviour.  The main class to refer to interactive objects is no longer InteractionBehaviourBase; it's just InteractionBehaviour.

HandCollisionCallbacks: This class has been removed in favor of callbacks that are accessible through InteractionBehaviours themselves. Here's the API documentation for InteractionBehaviours.

PhysicalButton: Actually, I can't find any reference to a class with this name in Leap Motion's Unity SDK. But the new Interaction Engine provides example scenes that demonstrate how to use the new InteractionButton class that provides physically-simulated buttons suitable for user interfaces. Check out Example 2, "Basic UI."

For a general reference, you can find more helpful information on the new Interaction Engine via the documentation wiki.

ContentLicense: CC BY-SA 3.0


问:
Trigger click on a tag when pressing fake read more button
Structure is as following:

```<code>div
  h1
    a
  p
  .more-info
</code>```

When I click on .more-info div I need to simulate a click on the 'a'.

```<code> $(".more-info").click(function() {
   $(this).parent().find('h1').find('a').get(0).trigger('click');
 })
</code>```

This gives following error:

```<code>$(...).parent(...).find(...).find(...).get(...).trigger is not a function
</code>```

Output of

```<code> console.log($(this).parent().find('h1').find('a').get(0))
</code>```

is the correct element I need to click.

I've tried without .get(0) and get following when I log that

```<code> [a, prevObject: jQuery.fn.init(1), context: p.more-info, selector: "h1 a"]
</code>```

答:
.get(0) returns the DOM element within the jQuery object, but .trigger() is a jQuery function, so it needs to operate on the jQuery object.

But if you're trying to emulate the browser's built-in action when clicking on a link, .trigger() won't do it. You need to call the DOM element's .click() method.

```<code> $(".more-info").click(function() {
   $(this).parent().find('h1').find('a').get(0).click();
 });
</code>```

See How to trigger a click on a link using jQuery

Body:
Structure is as following:

div
  h1
    a
  p
  .more-info

When I click on .more-info div I need to simulate a click on the 'a'.

 $(".more-info").click(function() {
   $(this).parent().find('h1').find('a').get(0).trigger('click');
 })

This gives following error:

$(...).parent(...).find(...).find(...).get(...).trigger is not a function

Output of

 console.log($(this).parent().find('h1').find('a').get(0))

is the correct element I need to click.

I've tried without .get(0) and get following when I log that

 [a, prevObject: jQuery.fn.init(1), context: p.more-info, selector: "h1 a"]

Body:
.get(0) returns the DOM element within the jQuery object, but .trigger() is a jQuery function, so it needs to operate on the jQuery object.

But if you're trying to emulate the browser's built-in action when clicking on a link, .trigger() won't do it. You need to call the DOM element's .click() method.

 $(".more-info").click(function() {
   $(this).parent().find('h1').find('a').get(0).click();
 });

See How to trigger a click on a link using jQuery


问:
programe name .exe stops working in c IDE ,whenever i use SCANF funtion
programe name .exe stops working in c IDE ,whenever i use SCANF funtion....even when it builds and runs correctly.....please help me with this...i am a beginner</p>

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

int main() {
    int age;
    printf("please enter the age");
    scanf("%d, &age");

    if (age > 18) {
        printf("the age is grater than 18");
    }

    if  (age == 18) {
        printf("the age is equal to 18");
    }

    if (age < 18) {
        printf("the age is less than 18");
    }

}
</code>```

答:
```<code>scanf("%d, &age");
</code>```

is

```<code>scanf("%d", &age);
</code>```

Also, if you defined main as "int main()", then it has to return an int.

Body:
programe name .exe stops working in c IDE ,whenever i use SCANF funtion....even when it builds and runs correctly.....please help me with this...i am a beginner

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

int main() {
    int age;
    printf("please enter the age");
    scanf("%d, &age");

    if (age > 18) {
        printf("the age is grater than 18");
    }

    if  (age == 18) {
        printf("the age is equal to 18");
    }

    if (age < 18) {
        printf("the age is less than 18");
    }

}

Body:
scanf("%d, &age");

is

scanf("%d", &age);

Also, if you defined main as "int main()", then it has to return an int.


问:
Disable Visual Studio warning CS2008
I have a visual studio project (VS2012) that just contains some configuration files.  When I build I get the following warning:

CSC : warning CS2008: No source files specified [C:\Project\Config\Config.csproj]

Is there any way to disable this warning?

答: I experienced the same problem with VS2017 (<nowarn> attribute didn't work).  Adding an empty VersionInfo.cs prevented the build warning.

Title: Disable Visual Studio warning CS2008


问:
How can you update Day Night Mode Instantly in PreferenceFragment?
I've seen some apps like Pocket that can toggle between Day and Night mode in the settings instantly without reloading, but I'm not able to do that in my own example:

```<code>public class SettingsActivity extends PreferenceActivity {
    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getFragmentManager().beginTransaction().replace(android.R.id.content, new PrefsFragment()).commit();
    }

    public static class PrefsFragment extends PreferenceFragment{
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            final Context context = getActivity();
            addPreferencesFromResource(R.xml.preferences);
            SwitchPreference dayNightSwitch = (SwitchPreference) findPreference(getString(R.string.pref_day_night_key));
            dayNightSwitch.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
                @Override
                public boolean onPreferenceChange(Preference preference, Object newValue) {
                    boolean isNightMode = (boolean) newValue;
                    AppCompatDelegate.setDefaultNightMode(isNightMode? AppCompatDelegate.MODE_NIGHT_YES:AppCompatDelegate.MODE_NIGHT_NO);
                    return true;
                }
            });
        }
    }
}
</code>```

It looks like AppCompatDelegate.setDefaultNightMode doesn't work in PreferenceFragment and PreferenceActivity at all. Is there any way to update day night mode instantly?

答:
First of all, you should call getActivity().recreate() to apply the change to the current activity.

But that was not enough, as I used the AppCompatPreferenceActivity template, which seems to be a bit incomplete. I have checked the AppCompatActivity source code and found the code responsible for handling the day/night switch.

```<code>private int mThemeId = 0;

...

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    final AppCompatDelegate delegate = getDelegate();
    delegate.installViewFactory();
    delegate.onCreate(savedInstanceState);
    if (delegate.applyDayNight() && mThemeId != 0) {
        // If DayNight has been applied, we need to re-apply the theme for
        // the changes to take effect. On API 23+, we should bypass
        // setTheme(), which will no-op if the theme ID is identical to the
        // current theme ID.
        if (Build.VERSION.SDK_INT >= 23) {
            onApplyThemeResource(getTheme(), mThemeId, false);
        } else {
            setTheme(mThemeId);
        }
    }
    super.onCreate(savedInstanceState);
}

@Override
public void setTheme(@StyleRes final int resid) {
    super.setTheme(resid);
    // Keep hold of the theme id so that we can re-set it later if needed
    mThemeId = resid;
}
</code>```

After adding it, calling getActivity().recreate() in the preference callback worked as expected.

Body:
I've seen some apps like Pocket that can toggle between Day and Night mode in the settings instantly without reloading, but I'm not able to do that in my own example:

public class SettingsActivity extends PreferenceActivity {
    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getFragmentManager().beginTransaction().replace(android.R.id.content, new PrefsFragment()).commit();
    }

    public static class PrefsFragment extends PreferenceFragment{
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            final Context context = getActivity();
            addPreferencesFromResource(R.xml.preferences);
            SwitchPreference dayNightSwitch = (SwitchPreference) findPreference(getString(R.string.pref_day_night_key));
            dayNightSwitch.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
                @Override
                public boolean onPreferenceChange(Preference preference, Object newValue) {
                    boolean isNightMode = (boolean) newValue;
                    AppCompatDelegate.setDefaultNightMode(isNightMode? AppCompatDelegate.MODE_NIGHT_YES:AppCompatDelegate.MODE_NIGHT_NO);
                    return true;
                }
            });
        }
    }
}

It looks like AppCompatDelegate.setDefaultNightMode doesn't work in PreferenceFragment and PreferenceActivity at all. Is there any way to update day night mode instantly?

Body:
First of all, you should call getActivity().recreate() to apply the change to the current activity.

But that was not enough, as I used the AppCompatPreferenceActivity template, which seems to be a bit incomplete. I have checked the AppCompatActivity source code and found the code responsible for handling the day/night switch.

private int mThemeId = 0;

...

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    final AppCompatDelegate delegate = getDelegate();
    delegate.installViewFactory();
    delegate.onCreate(savedInstanceState);
    if (delegate.applyDayNight() && mThemeId != 0) {
        // If DayNight has been applied, we need to re-apply the theme for
        // the changes to take effect. On API 23+, we should bypass
        // setTheme(), which will no-op if the theme ID is identical to the
        // current theme ID.
        if (Build.VERSION.SDK_INT >= 23) {
            onApplyThemeResource(getTheme(), mThemeId, false);
        } else {
            setTheme(mThemeId);
        }
    }
    super.onCreate(savedInstanceState);
}

@Override
public void setTheme(@StyleRes final int resid) {
    super.setTheme(resid);
    // Keep hold of the theme id so that we can re-set it later if needed
    mThemeId = resid;
}

After adding it, calling getActivity().recreate() in the preference callback worked as expected.


答:
You could use the element's .click() method, but I would recommend putting a link on the more-info element itself.

Anyhow, this should work:

$(this).parent().find('h1 > a').get(0).click();

Check out the fiddle here:
https://jsfiddle.net/Lpyctuga/4/

Title: Trigger click on a tag when pressing fake read more button


问:
Google Oauth2: Is it possible to retrieve token information from an expired access token?
I have a Google App Engine endpoints projects which is protected by Oauth2. I saw some request has failed due to Invalid token.

Request URL: https://example.appspot.com/_ah/api/mm/v1/list?filter=q%3Dtest&alt=json
Method: example.resource.list
Error Code: 401
Reason: required
Message: Invalid token.

I could log out the token from the HEADER of the request.
The token I get is access token, format like, ya29.vwGg-....

When I tried with
https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=
to find out token information, like issue_to, client_id, extra.

It returns back with
{
error: "invalid_token",
error_description: "Invalid Value"
}

I have tested with
https://developers.google.com/oauthplayground
the url returns back the same error if the token has been expired.

My guess for the reason my request has failed is the token used has expired.
But not 100% sure.

Is there way to find token info about expired access token?
Or maybe more widely,
is there any way to find more info about invalid access token, like why it is invalid or anything else?

答: There are many ways to get token information. Generally token will be invalid for various reasons so of the important reasons are Invalid Signature and Token expired. You can use https://jwt.io to decode your token and get the info. Your error description clearly tells the reason about why your token is considered invalid. Try deep diving into the code and see why it says invalid value. </p>


问:
C++ primitive array accessing by class
I want to access a primitive type array using a class.
I'm using Visual C++ 2013

```<code>class CInt
{
public:
    CInt() { val_ = 0; }
    CInt(int x) { val_ = x; }

private:
    int val_;
};

int arr[2];
CInt index;

arr[index] = 2; // ERROR!
</code>```

I tried to overload size_t() operator but still doesn't work.
Is something like that possible in C++/C++11?

答:
How did you do the overloading of the size_t() operator? The following works for me:</p>

```<code>#include <iostream>

class CInt
{
public:
    CInt() { val_ = 0; }
    CInt(int x) { val_ = x; }

    operator size_t() const { return val_; }

private:
    int val_;
};

int main() {
    int arr[2];
    CInt index;

    arr[index] = 2;

    // output: 2
    std::cout << arr[index] << std::endl;
}
</code>```

Title: C++ primitive array accessing by class

Body:
I want to access a primitive type array using a class.
I'm using Visual C++ 2013

class CInt
{
public:
    CInt() { val_ = 0; }
    CInt(int x) { val_ = x; }

private:
    int val_;
};

int arr[2];
CInt index;

arr[index] = 2; // ERROR!

I tried to overload size_t() operator but still doesn't work.
Is something like that possible in C++/C++11?

Body:
How did you do the overloading of the size_t() operator? The following works for me:

#include <iostream>

class CInt
{
public:
    CInt() { val_ = 0; }
    CInt(int x) { val_ = x; }

    operator size_t() const { return val_; }

private:
    int val_;
};

int main() {
    int arr[2];
    CInt index;

    arr[index] = 2;

    // output: 2
    std::cout << arr[index] << std::endl;
}


答:
You could easily do this by using a distinct clause and removing the id column. If you want to keep the id column you need to specify how one would chose which id to keep.

```<code>select distinct
  `group`
  , name
  , sold
from
  products
where
  sold = 0;
</code>```

To keep the row with the smallest id (as your example shows) something along the lines of the example below would work.

```<code>select
  id
  , `group`
  , name
  , sold
from
  products
where
  sold = 0
  and id = (
    select
      min(p.id)
    from
      products p
    where
      p.`group`    = products.`group`
      and p.sold = 0
  );
</code>```

Title: How to select only one record of each category?

Body:
Products :
--------------------------------------------
|   ID   |   Group   |   Name   |   Sold   |
--------------------------------------------
|   1    |     A     |   Dell   |    0     |
--------------------------------------------
|   2    |     A     |   Dell   |    0     |
--------------------------------------------
|   3    |     B     |   Dell   |    1     |
--------------------------------------------
|   4    |     B     |   Dell   |    1     |
--------------------------------------------
|   5    |     C     |   Dell   |    0     |
--------------------------------------------
|   6    |     C     |   Dell   |    1     |
--------------------------------------------

Hi everyone, i have a table (products) stored in MySql with many records, for now i'm using this query SELECT * FROM products WHERE sold = 0, in results i get :

--------------------------------------------
|   ID   |   Group   |   Name   |   Sold   |
--------------------------------------------
|   1    |     A     |   Dell   |    0     |
--------------------------------------------
|   2    |     A     |   Dell   |    0     |
--------------------------------------------
|   5    |     C     |   Dell   |    0     |
--------------------------------------------

i want to get only one record from each group, so the results will be like :

--------------------------------------------
|   ID   |   Group   |   Name   |   Sold   |
--------------------------------------------
|   1    |     A     |   Dell   |    0     |
--------------------------------------------
|   5    |     C     |   Dell   |    0     |
--------------------------------------------

Body:
You could easily do this by using a distinct clause and removing the id column. If you want to keep the id column you need to specify how one would chose which id to keep.

select distinct
  `group`
  , name
  , sold
from
  products
where
  sold = 0;

To keep the row with the smallest id (as your example shows) something along the lines of the example below would work.

select
  id
  , `group`
  , name
  , sold
from
  products
where
  sold = 0
  and id = (
    select
      min(p.id)
    from
      products p
    where
      p.`group`    = products.`group`
      and p.sold = 0
  );


问:
Convert results of Request() to variable
I have this code:

```<code>request('http://steamcommunity.com/market/priceoverview/?currency=1&appid=730&market_hash_name=Gamma Case', function (e, r, body){
    var req_data = JSON.parse(body);
    console.log(req_data);
    });
</code>```

It returns me
{ success: true,
  lowest_price: '$0.03',
  volume: '30,502',
  median_price: '$0.01' }

How can I do for convert the lowest_price into a variable? I tryed:

```<code> var results = req_data.map(function(item){
 return {lowest_price : item["lowest_price"]};
 });
 console.log(results);
</code>```

But its says that .req_data.map is not a function.

Thank you!

答:
Is this what you're looking for?</p>

```<code>request('http://steamcommunity.com/market/priceoverview/?currency=1&appid=730&market_hash_name=Gamma Case', function (e, r, body){
    return {lowest_price: JSON.parse(body).lowest_price};
    });
</code>```

Body:
I have this code:

request('http://steamcommunity.com/market/priceoverview/?currency=1&appid=730&market_hash_name=Gamma Case', function (e, r, body){
    var req_data = JSON.parse(body);
    console.log(req_data);
    });

It returns me
{ success: true,
  lowest_price: '$0.03',
  volume: '30,502',
  median_price: '$0.01' }

How can I do for convert the lowest_price into a variable? I tryed:

 var results = req_data.map(function(item){
 return {lowest_price : item["lowest_price"]};
 });
 console.log(results);

But its says that .req_data.map is not a function.

Thank you!

Body:
Is this what you're looking for?

request('http://steamcommunity.com/market/priceoverview/?currency=1&appid=730&market_hash_name=Gamma Case', function (e, r, body){
    return {lowest_price: JSON.parse(body).lowest_price};
    });


问:
slideshow with page number in js
I created simple slideshow. If yu want to change image, you have to click on arrows button on keyboard. I want to add description e.g. "1 item from 7" etc.

Here is my source:

var img_index = 0;
var imgs = [
  "assets/1.jpg",
  "assets/2.jpg",
  "assets/3.jpg",
  "assets/4.jpg",
  "assets/5.jpg",
  "assets/6.jpg",
  "assets/7.jpg"

];

function changeImage() {
  var img = document.getElementById("images");
  img_index = ++img_index % 7;
  img.src = imgs[img_index];
}

function checkKey(e) {

  e = e || window.event;
  if (e.keyCode == '37') {
    changeImage();
  } else if (e.keyCode == '39') {
    changeImage();
  }

}

document.onkeydown = checkKey;

function sliderText (){

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="style12.css">
  <title>Task 12</title>
</head>
<div id="slideshow_section">
  <img id="images" src="assets/1.jpg" />
</div>

<body>

</body>
<script src="script12.js"></script>

</html></code>```

Can you give me some hints how can I do that?

Thank you,
Megi

答:
Try this, this may helps to you!

refer this link (or) try this code

In HTML

```<code>    <div class="slideshow-container">
  <div class="mySlides fade">
    <div class="numbertext">1 / 3</div>
    <img src="img1.jpg" style="width:100%">
    <div class="text">Caption Text</div>
  </div>

  <div class="mySlides fade">
    <div class="numbertext">2 / 3</div>
    <img src="img2.jpg" style="width:100%">
    <div class="text">Caption Two</div>
  </div>

  <div class="mySlides fade">
    <div class="numbertext">3 / 3</div>
    <img src="img3.jpg" style="width:100%">
    <div class="text">Caption Three</div>
  </div>

  <a class="prev" onclick="plusSlides(-1)">❮</a>
  <a class="next" onclick="plusSlides(1)">❯</a>
</div>
<br>

<div style="text-align:center">
  <span class="dot" onclick="currentSlide(1)"></span>
  <span class="dot" onclick="currentSlide(2)"></span>
  <span class="dot" onclick="currentSlide(3)"></span>
</div>
</code>```

In Css :

```<code>{box-sizing:border-box}

/* Slideshow container */
.slideshow-container {
  max-width: 1000px;
  position: relative;
  margin: auto;
}

.mySlides {
    display: none;
}

/* Next & previous buttons */
.prev, .next {
  cursor: pointer;
  position: absolute;
  top: 50%;
  width: auto;
  margin-top: -22px;
  padding: 16px;
  color: white;
  font-weight: bold;
  font-size: 18px;
  transition: 0.6s ease;
  border-radius: 0 3px 3px 0;
}

/* Position the "next button" to the right */
.next {
  right: 0;
  border-radius: 3px 0 0 3px;
}

/* On hover, add a black background color with a little bit see-through */
.prev:hover, .next:hover {
  background-color: rgba(0,0,0,0.8);
}

/* Caption text */
.text {
  color: #f2f2f2;
  font-size: 15px;
  padding: 8px 12px;
  position: absolute;
  bottom: 8px;
  width: 100%;
  text-align: center;
}

/* Number text (1/3 etc) */
.numbertext {
  color: #f2f2f2;
  font-size: 12px;
  padding: 8px 12px;
  position: absolute;
  top: 0;
}

/* The dots/bullets/indicators */
.dot {
  cursor:pointer;
  height: 13px;
  width: 13px;
  margin: 0 2px;
  background-color: #bbb;
  border-radius: 50%;
  display: inline-block;
  transition: background-color 0.6s ease;
}

.active, .dot:hover {
  background-color: #717171;
}

/* Fading animation */
.fade {
  -webkit-animation-name: fade;
  -webkit-animation-duration: 1.5s;
  animation-name: fade;
  animation-duration: 1.5s;
}

@-webkit-keyframes fade {
  from {opacity: .4}
  to {opacity: 1}
}

@keyframes fade {
  from {opacity: .4}
  to {opacity: 1}
}
</code>```

In JS:

```<code>var slideIndex = 1;
showSlides(slideIndex);

function plusSlides(n) {
  showSlides(slideIndex += n);
}

function currentSlide(n) {
  showSlides(slideIndex = n);
}

function showSlides(n) {
  var i;
  var slides = document.getElementsByClassName("mySlides");
  var dots = document.getElementsByClassName("dot");
  if (n > slides.length) {slideIndex = 1}
  if (n < 1) {slideIndex = slides.length}
  for (i = 0; i < slides.length; i++) {
      slides[i].style.display = "none";
  }
  for (i = 0; i < dots.length; i++) {
      dots[i].className = dots[i].className.replace(" active", "");
  }
  slides[slideIndex-1].style.display = "block";
  dots[slideIndex-1].className += " active";
}
</code>```

All the best for your JS project ;)

Title: slideshow with page number in js

Body:
I created simple slideshow. If yu want to change image, you have to click on arrows button on keyboard. I want to add description e.g. "1 item from 7" etc.

Here is my source:

var img_index = 0;
var imgs = [
  "assets/1.jpg",
  "assets/2.jpg",
  "assets/3.jpg",
  "assets/4.jpg",
  "assets/5.jpg",
  "assets/6.jpg",
  "assets/7.jpg"

];

function changeImage() {
  var img = document.getElementById("images");
  img_index = ++img_index % 7;
  img.src = imgs[img_index];
}

function checkKey(e) {

  e = e || window.event;
  if (e.keyCode == '37') {
    changeImage();
  } else if (e.keyCode == '39') {
    changeImage();
  }

}

document.onkeydown = checkKey;

function sliderText (){

}

<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" href="style12.css">
  <title>Task 12</title>

Can you give me some hints how can I do that?

Thank you,
Megi

Body:
Try this, this may helps to you!

refer this link (or) try this code

In HTML

    <div class="slideshow-container">
  <div class="mySlides fade">
    <div class="numbertext">1 / 3</div>
    <img src="img1.jpg" style="width:100%">
    <div class="text">Caption Text</div>
  </div>

  <div class="mySlides fade">
    <div class="numbertext">2 / 3</div>
    <img src="img2.jpg" style="width:100%">
    <div class="text">Caption Two</div>
  </div>

  <div class="mySlides fade">
    <div class="numbertext">3 / 3</div>
    <img src="img3.jpg" style="width:100%">
    <div class="text">Caption Three</div>
  </div>

  <a class="prev" onclick="plusSlides(-1)">&#10094;</a>
  <a class="next" onclick="plusSlides(1)">&#10095;</a>
</div>
<br>

<div style="text-align:center">
  <span class="dot" onclick="currentSlide(1)"></span>
  <span class="dot" onclick="currentSlide(2)"></span>
  <span class="dot" onclick="currentSlide(3)"></span>
</div>

In Css :

{box-sizing:border-box}

/* Slideshow container */
.slideshow-container {
  max-width: 1000px;
  position: relative;
  margin: auto;
}

.mySlides {
    display: none;
}

/* Next & previous buttons */
.prev, .next {
  cursor: pointer;
  position: absolute;
  top: 50%;
  width: auto;
  margin-top: -22px;
  padding: 16px;
  color: white;
  font-weight: bold;
  font-size: 18px;
  transition: 0.6s ease;
  border-radius: 0 3px 3px 0;
}

/* Position the "next button" to the right */
.next {
  right: 0;
  border-radius: 3px 0 0 3px;
}

/* On hover, add a black background color with a little bit see-through */
.prev:hover, .next:hover {
  background-color: rgba(0,0,0,0.8);
}

/* Caption text */
.text {
  color: #f2f2f2;
  font-size: 15px;
  padding: 8px 12px;
  position: absolute;
  bottom: 8px;
  width: 100%;
  text-align: center;
}

/* Number text (1/3 etc) */
.numbertext {
  color: #f2f2f2;
  font-size: 12px;
  padding: 8px 12px;
  position: absolute;
  top: 0;
}

/* The dots/bullets/indicators */
.dot {
  cursor:pointer;
  height: 13px;
  width: 13px;
  margin: 0 2px;
  background-color: #bbb;
  border-radius: 50%;
  display: inline-block;
  transition: background-color 0.6s ease;
}

.active, .dot:hover {
  background-color: #717171;
}

/* Fading animation */
.fade {
  -webkit-animation-name: fade;
  -webkit-animation-duration: 1.5s;
  animation-name: fade;
  animation-duration: 1.5s;
}

@-webkit-keyframes fade {
  from {opacity: .4}
  to {opacity: 1}
}

@keyframes fade {
  from {opacity: .4}
  to {opacity: 1}
}

In JS:

var slideIndex = 1;
showSlides(slideIndex);

function plusSlides(n) {
  showSlides(slideIndex += n);
}

function currentSlide(n) {
  showSlides(slideIndex = n);
}

function showSlides(n) {
  var i;
  var slides = document.getElementsByClassName("mySlides");
  var dots = document.getElementsByClassName("dot");
  if (n > slides.length) {slideIndex = 1}
  if (n < 1) {slideIndex = slides.length}
  for (i = 0; i < slides.length; i++) {
      slides[i].style.display = "none";
  }
  for (i = 0; i < dots.length; i++) {
      dots[i].className = dots[i].className.replace(" active", "");
  }
  slides[slideIndex-1].style.display = "block";
  dots[slideIndex-1].className += " active";
}

All the best for your JS project ;)


问:
Python subprocess stdout iterator always blocks
I want to capture the output while printing it, but I'm blocking forever without reading even a single line. What's going on? I'm using Python2.

Generator script:

```<code>#!/usr/bin/env python2.7

import random
import time

while True:
    print(random.random())
    time.sleep(1)
</code>```

Sample generator output:

```<code>$ ./generator.py
0.334835137212
0.896609571236
0.833267988558
0.55456332113
^CTraceback (most recent call last):
</code>```

Reader script:

```<code>import subprocess

cmd = ['./generator.py']
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)

for line in p.stdout:
    print(line)
    print('Looping')

p.wait()
</code>```

I've also tried:

```<code>import subprocess
import sys

cmd = ['./generator.py']
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)

while True:
    line = p.stdout.readline()
    print(line)

    print('Looping')

p.wait()
</code>```

...and:

```<code>import sys
import subprocess
import select
import time

cmd = ['./generator.py']
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)

s = select.poll()
s.register(p.stdout, select.POLLIN)

while True:
    if s.poll(1):
        line = p.stdout.read()
    else:
        p.poll()
        if p.returncode is not None:
            break

    print('Looping')
    time.sleep(1)

p.wait()
</code>```

答:
As @dhke mentioned, one of the issues is implicit output-buffering in the producer. If you have the ability to change the producer, and you're willing to, and the production is done by calls to the print-function then just add "flush=True" as an argument to the print function. You can also fall-back to doing a sys.stdout.flush() at key points in the producer.

The second problem appears to be iterating over sys.stdout. This never seems to work for a long-running process. The second and third methods

Body:
I want to capture the output while printing it, but I'm blocking forever without reading even a single line. What's going on? I'm using Python2.

Generator script:

#!/usr/bin/env python2.7

import random
import time

while True:
    print(random.random())
    time.sleep(1)

Sample generator output:

$ ./generator.py
0.334835137212
0.896609571236
0.833267988558
0.55456332113
^CTraceback (most recent call last):

Reader script:

import subprocess

cmd = ['./generator.py']
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)

for line in p.stdout:
    print(line)
    print('Looping')

p.wait()

I've also tried:

import subprocess
import sys

cmd = ['./generator.py']
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)

while True:
    line = p.stdout.readline()
    print(line)

    print('Looping')

p.wait()

...and:

import sys
import subprocess
import select
import time

cmd = ['./generator.py']
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)

s = select.poll()
s.register(p.stdout, select.POLLIN)

while True:
    if s.poll(1):
        line = p.stdout.read()
    else:
        p.poll()
        if p.returncode is not None:
            break

    print('Looping')
    time.sleep(1)

p.wait()


问:
Issue downloading .xlsm document with activex controls using NPOI
I am trying to implement an excel file download functionality in my asp.net MVC application and using NPOI.

The file has three sheets and Sheet2 has two activex buttons.

I am reading the source file, adding values to sheet2, save it in temporary location and download the file later using the following code.

```<code>        using (var fs = new FileStream(xlsFilePath, FileMode.Open, FileAccess.Read))
        {
            var templateWorkbook = new XSSFWorkbook(fs);

            //Sheet update operation done here

            fs.Close();
            var memoryStream = new MemoryStream();
            templateWorkbook.Write(memoryStream);

            System.IO.File.WriteAllBytes(groupDocumentPath, memoryStream.ToArray());
        }
</code>```

Issue:
Because of the activex control the downloaded file is corrupt and when trying to open the file it is throwing an error:

```<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<recoveryLog xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><logFileName>error728720_01.xml</logFileName><summary>Errors were detected in file 'C:\Users\dsekaran\Downloads\5B87FFF306BE8040D10B702 (5).xlsm'</summary><repairedParts><repairedPart>Repaired Part: /xl/worksheets/sheet2.xml part with XML error.  Catastrophic failure Line 1, column 0.</repairedPart></repairedParts><repairedRecords><repairedRecord>Repaired Records: Drawing from /xl/drawings/drawing1.xml part (Drawing shape)</repairedRecord></repairedRecords></recoveryLog>
</code>```

Clarification:
Does this mean NPOI doesn't support activex buttons?
What can be done to overcome this issue?

答:
you'll have to use correct MIME type while downloading the .xlsm file. I am downloading .xltm file after creating it through NPOI. See the below function </p>

```<code>public ActionResult DownloadXLTMFile()
        {
            try
            {
               //Using Resposne Stream to Make File Available for User to Download;
                Response.Clear();

                Response.ContentType = "application/vnd.ms-excel.template.macroEnabled.12";
                Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}",  "YourFileName.xltm"));

                Response.BinaryWrite(System.IO.File.ReadAllBytes(HostingEnvironment.MapPath("~/App_Data/YourManupulatedFile.xltm")));
                Response.End();
            }
            catch (Exception Ex)
            {
            }
            finally
            {   }
            return View();
        }
</code>```

<p>check this link for appropriate MIME type </p>

Body:
I am trying to implement an excel file download functionality in my asp.net MVC application and using NPOI.

The file has three sheets and Sheet2 has two activex buttons.

I am reading the source file, adding values to sheet2, save it in temporary location and download the file later using the following code.

        using (var fs = new FileStream(xlsFilePath, FileMode.Open, FileAccess.Read))
        {
            var templateWorkbook = new XSSFWorkbook(fs);

            //Sheet update operation done here

            fs.Close();
            var memoryStream = new MemoryStream();
            templateWorkbook.Write(memoryStream);

            System.IO.File.WriteAllBytes(groupDocumentPath, memoryStream.ToArray());
        }

Issue:
Because of the activex control the downloaded file is corrupt and when trying to open the file it is throwing an error:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<recoveryLog xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><logFileName>error728720_01.xml</logFileName>Errors were detected in file 'C:\Users\dsekaran\Downloads\5B87FFF306BE8040D10B702 (5).xlsm'<repairedParts><repairedPart>Repaired Part: /xl/worksheets/sheet2.xml part with XML error.  Catastrophic failure Line 1, column 0.</repairedPart></repairedParts><repairedRecords><repairedRecord>Repaired Records: Drawing from /xl/drawings/drawing1.xml part (Drawing shape)</repairedRecord></repairedRecords></recoveryLog>

Clarification:
Does this mean NPOI doesn't support activex buttons?
What can be done to overcome this issue?

Body:
you'll have to use correct MIME type while downloading the .xlsm file. I am downloading .xltm file after creating it through NPOI. See the below function

public ActionResult DownloadXLTMFile()
        {
            try
            {
               //Using Resposne Stream to Make File Available for User to Download;
                Response.Clear();

                Response.ContentType = "application/vnd.ms-excel.template.macroEnabled.12";
                Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}",  "YourFileName.xltm"));

                Response.BinaryWrite(System.IO.File.ReadAllBytes(HostingEnvironment.MapPath("~/App_Data/YourManupulatedFile.xltm")));
                Response.End();
            }
            catch (Exception Ex)
            {
            }
            finally
            {   }
            return View();
        }

check this link for appropriate MIME type


问:
Liferay: GA4 on an empty MySQL 5.7 results in a fatal exception
I am trying to install Liferay GA4 and a Master build for development purposes. However I keep falling into a fatal exception with MySQL 5.7.

As described at: https://issues.liferay.com/browse/LPS-73410

In an empty database, MySQL 5.7, when the servers is brought up the follow exception is raised. (seem on both drivers com.mysql.jdbc.Driver and com.mysql.cj.jdbc.Driver)

liferay          | 21:45:35,927 ERROR [localhost-startStop-1][MainServlet:275] com.liferay.portal.kernel.events.ActionException: com.liferay.portal.verify.VerifyException: com.liferay.portal.verify.VerifyException: java.sql.SQLSyntaxErrorException: Table 'XXXXX.EVENTS' doesn't exist

liferay          | com.liferay.portal.kernel.events.ActionException: com.liferay.portal.verify.VerifyException: com.liferay.portal.verify.VerifyException: java.sql.SQLSyntaxErrorException: Table 'XXXXX.EVENTS' doesn't exist

I was wondering if this is something I can get around by some procedure done directly into the database...Any thoughts?

答:
I have found my way out this issue with new JDBC defaults.

```<code>jdbc.default.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.default.url=jdbc:mysql://${database.host}/${database.schema}?useUnicode=true&characterEncoding=UTF-8&useFastDateParsing=false&useSSL=false&nullNamePatternMatchesAll=true&&nullCatalogMeansCurrent=true
</code>```

From: https://www.e-systems.tech/web/guest/blog/-/blogs/liferay-with-mysql-5-7-driver-changes

Body:
I have found my way out this issue with new JDBC defaults.

jdbc.default.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.default.url=jdbc:mysql://${database.host}/${database.schema}?useUnicode=true&characterEncoding=UTF-8&useFastDateParsing=false&useSSL=false&nullNamePatternMatchesAll=true&&nullCatalogMeansCurrent=true

From: https://www.e-systems.tech/web/guest/blog/-/blogs/liferay-with-mysql-5-7-driver-changes


问:
c++CLI event handler's not triggered
I am just getting into c++ CLI and am running into a problem where some event handlers are called and some are not.

here is a list of my event handlers:

```<code>    private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) {
             }
    private: System::Void exitToolStripMenuItem_Click(System::Object^  sender, System::EventArgs^  e) {
                 Application::Exit();
             }
private: System::Void aboutToolStripMenuItem_Click(System::Object^  sender, System::EventArgs^  e) {
             MessageBox::Show("Paul Madsen\nLab 13",
                 "About lab 13", MessageBoxButtons::OK,
                 MessageBoxIcon::Asterisk);
         }

private: System::Void textBox1_TextChanged(System::Object^  sender, System::EventArgs^  e)
         {
             try
             {
                double tmp = Double::Parse(textBox1->Text);
             }
             catch(...)
             {
                 textBox1->ResetText();
             }

         }
private: System::Void textBox2_TextChanged(System::Object^  sender, System::EventArgs^  e)
         {
             try
             {
                double tmp = Double::Parse(textBox2->Text);
             }
             catch(...)
             {
                 textBox2->ResetText();
             }
         }
private: System::Void textBox1_Enter(System::Object^  sender, System::EventArgs^  e)
         {
             MessageBox::Show("Test",
                 "test", MessageBoxButtons::OK,
                 MessageBoxIcon::Asterisk);
         }
private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
             double tmp = (Double::Parse(textBox1->Text) - 32) * 5/9;
             textBox2->Text = System::Convert::ToString(tmp);

         }
private: System::Void button2_Click(System::Object^  sender, System::EventArgs^  e) {
              double tmp = (Double::Parse(textBox1->Text) - 32) * 5/9;
              textBox1->Text = System::Convert::ToString(tmp);

          }
</code>```

button1_Click works just fine but button2_Click is never triggered even though they are essentially the same.  Why is that?

答:
Look back toward the beginning of the source code file, inside InitializeComponent().  You should have no trouble seeing the button1->Click event handler assignment.  Do you see the one for button2->Click?

Delete the button in the designer, add it back.  Double click it.  Or just leave it out, no point in having two buttons doing the same thing.

Title: c++CLI event handler's not triggered

Body:
I am just getting into c++ CLI and am running into a problem where some event handlers are called and some are not.

here is a list of my event handlers:

    private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) {
             }
    private: System::Void exitToolStripMenuItem_Click(System::Object^  sender, System::EventArgs^  e) {
                 Application::Exit();
             }
private: System::Void aboutToolStripMenuItem_Click(System::Object^  sender, System::EventArgs^  e) {
             MessageBox::Show("Paul Madsen\nLab 13",
                 "About lab 13", MessageBoxButtons::OK,
                 MessageBoxIcon::Asterisk);
         }

private: System::Void textBox1_TextChanged(System::Object^  sender, System::EventArgs^  e)
         {
             try
             {
                double tmp = Double::Parse(textBox1->Text);
             }
             catch(...)
             {
                 textBox1->ResetText();
             }

         }
private: System::Void textBox2_TextChanged(System::Object^  sender, System::EventArgs^  e)
         {
             try
             {
                double tmp = Double::Parse(textBox2->Text);
             }
             catch(...)
             {
                 textBox2->ResetText();
             }
         }
private: System::Void textBox1_Enter(System::Object^  sender, System::EventArgs^  e)
         {
             MessageBox::Show("Test",
                 "test", MessageBoxButtons::OK,
                 MessageBoxIcon::Asterisk);
         }
private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
             double tmp = (Double::Parse(textBox1->Text) - 32) * 5/9;
             textBox2->Text = System::Convert::ToString(tmp);

         }
private: System::Void button2_Click(System::Object^  sender, System::EventArgs^  e) {
              double tmp = (Double::Parse(textBox1->Text) - 32) * 5/9;
              textBox1->Text = System::Convert::ToString(tmp);

          }

button1_Click works just fine but button2_Click is never triggered even though they are essentially the same.  Why is that?


问:
I was wondering if there is any way to treat delimiters inside quotes as merely characters and not delimiters
I have a massive amount of files that are all made using the same schema. They are put into a format where they are space delimited. A sample file row looks like this:

1 2 abc def "g h" 3

And when I try to use the schema INT, INT, STRING, STRING, STRING, INT, it fails for me because of the space inside the quotation marks.
I know this is where the error is because if I make a sample tab separated instead of space separated, no such error occurs, but that is not feasible for me to do with all of my data. I was wondering if there is any way to be able to indicate in a file upload that delimiters in quotes should not be treated as delimiters but rather as characters? (Rather that all quoted text should be treated as one string.)

I know this feature exists for new line characters, and so I was wondering about delimiters.

Thank you!

答: I figured it out. The error was there was an extra delimiter character at the end of the file. Now I just need to trim each line of the file before uploading.</p>


答: req_data is an object, not an array, so you can't use map on it. Just do return {lowest_price : req_data["lowest_price"]};.

Title: Convert results of Request() to variable


问:
I have a query reguarding publishing android game in google play?
I know how to publish an normal application in (Google Play Developer Console). I want to know how to publish a game in (Google Play Developer Console) which is implementing Game Services. My game application is running well and Game Service is working properly.But now I am confused about debug sha1 debug key and sha1 release key.
and do I have to linked my game with both debug and release sha1 keys?

答: I have provided details for generating and specifying the release version of the SHA1 fingerprint in this post: Getting Android Google Map v2 working in release version by generating SHA1 fingerprint for API key</p>


问:
Android CollapsingToolbarLayout collapse Listener
I am using CollapsingToolBarLayout alongside with AppBarLayout and CoordinatorLayout, and they are working Fine altogether. I set my Toolbar to be fixed when I scroll up, I want to know if there is a way to change the title text of the Toolbar, when CollapsingToolBarLayout it is collapsed.

Wrapping up, I want two different titles when scrolled and when expanded.

Thank you all in advance

答:
This code is working perfect for me. You can use percentage scale How you like</p>

```<code>@Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
    double percentage = (double) Math.abs(verticalOffset) / collapsingToolbar.getHeight();
    if (percentage > 0.8) {
        collapsingToolbar.setTitle("Collapsed");
    } else {
        collapsingToolbar.setTitle("Expanded");
    }
}
</code>```

Body:
This code is working perfect for me. You can use percentage scale How you like

@Override
public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
    double percentage = (double) Math.abs(verticalOffset) / collapsingToolbar.getHeight();
    if (percentage > 0.8) {
        collapsingToolbar.setTitle("Collapsed");
    } else {
        collapsingToolbar.setTitle("Expanded");
    }
}


问:
Assign a different macro per click of VBA Button
I have an excel button that hides columns "S-U" when I click it. I want to click the button a 2nd time and it hides columns "P-R" and etc. Can you manipulate an excel button per click?</p>

答:
One solution to this problem is be declaring a global variable, and assigning a counter to it:

```<code>Private i As Integer

Sub Button1_Click()

If i = 0 Then
    Do Stuff 'This is the first click
    i = i + 1
Else
    Do Stuff the Second Time 'This is the second time and beyond.
    i = i + 1
End If

End Sub
</code>```

i will automatically be assigned a value of 0.  The first time it checks i = 0 it will operate however you want the first time.  Once it sets i = i + 1 then it will do whatever else you want it to do for the second time.  If you want to make it a third time, you can always do Else If i = 1 Then, etc.

Under the Visual Basic Editor, create a new module if you don't already have one and place this in there.  Create a button and assign the Button1_Click Macro to the Button.

Body:
One solution to this problem is be declaring a global variable, and assigning a counter to it:

Private i As Integer

Sub Button1_Click()

If i = 0 Then
    Do Stuff 'This is the first click
    i = i + 1
Else
    Do Stuff the Second Time 'This is the second time and beyond.
    i = i + 1
End If

End Sub

i will automatically be assigned a value of 0.  The first time it checks i = 0 it will operate however you want the first time.  Once it sets i = i + 1 then it will do whatever else you want it to do for the second time.  If you want to make it a third time, you can always do Else If i = 1 Then, etc.

Under the Visual Basic Editor, create a new module if you don't already have one and place this in there.  Create a button and assign the Button1_Click Macro to the Button.


问:
Assigning updated value to $_SESSION array
Can someone tell me why the $_SESSION array is not getting modified by the code below.  The object is to put the date in DoNotShipBefore of each record. It is obviously putting the value somewhere as the output of $Row['DoNotShipBefore'] shows the correct date.  But, when the loop is done, it doesn't appear to have taken.

```<code>session_start();
print_r($_SESSION[cart_array]);
foreach($_SESSION[cart_array] as $Row) {

      $Row['DoNotShipBefore'] = date("m/d/Y") ;
      echo "<br>New Value of DoNotShipBefore (From cart_array): ". $Row['DoNotShipBefore'] ;

}
print "<br><br>";
print_r($_SESSION[cart_array]);
die();
</code>```

Output follows:

```<code>Array ( [0] => Array ( [groupId] => 26141 [DoNotShipBefore] => 10/01/2017))

New Value of DoNotShipBefore (From cart_array): 07/06/2017

Array ( [0] => Array ( [groupId] => 26141  [DoNotShipBefore] => 10/01/2017))

// Should be (or what I want is):
Array ( [0] => Array ( [groupId] => 26141  [DoNotShipBefore] => 07/06/2017))
</code>```

I'm having a hard time wrapping my head around how to address Arrays within the SESSION, so would really appreciate any help.

答: What is cart_array? Maybe you should use $_SESSION['cart_array']? Any PHP notice?

Body:
Can someone tell me why the $_SESSION array is not getting modified by the code below.  The object is to put the date in DoNotShipBefore of each record. It is obviously putting the value somewhere as the output of $Row['DoNotShipBefore'] shows the correct date.  But, when the loop is done, it doesn't appear to have taken.

session_start();
print_r($_SESSION[cart_array]);
foreach($_SESSION[cart_array] as $Row) {

      $Row['DoNotShipBefore'] = date("m/d/Y") ;
      echo "
New Value of DoNotShipBefore (From cart_array): ". $Row['DoNotShipBefore'] ;

}
print "

";
print_r($_SESSION[cart_array]);
die();

Output follows:

Array ( [0] => Array ( [groupId] => 26141 [DoNotShipBefore] => 10/01/2017))

New Value of DoNotShipBefore (From cart_array): 07/06/2017

Array ( [0] => Array ( [groupId] => 26141  [DoNotShipBefore] => 10/01/2017))

// Should be (or what I want is):
Array ( [0] => Array ( [groupId] => 26141  [DoNotShipBefore] => 07/06/2017))

I'm having a hard time wrapping my head around how to address Arrays within the SESSION, so would really appreciate any help.


问:
Mod rewrite page anchor
I've been trying to solve this for the past two hours. I already tried every solution mentioned on google, but without any luck.

Let's start with the problem. I'm trying to use this plugin:
http://www.gethifi.com/blog/a-jquery-plugin-to-create-an-interactive-filterable-portfolio-like-ours

on my website. The problem is that this plugin is using Anchor tags. Without it, it doesn't seem to work.
Well, I'm trying to work with User Friendly URL's on the website I'm working on right now. So the anchors are not working.

This is my .htaccess file right now:

```<code>RewriteEngine On
RewriteBase /
RewriteRule ^([^/]*)\.html$ /mysite/category.php?cat=$1 [L]
RewriteRule ^([^/]*)/([^/]*)\.html$ /mysite/category.php?cat=$1&lang=$2 [L]
</code>```

Nothing fancy, just some rewrites for categories and languages. The only thing that seems to work is this:

```<code>RewriteEngine On
RewriteBase /
RewriteRule ^([^/]*)\.html$ /mysite/category.php?cat=$1 [L]
RewriteRule ^([^/]*)/([^/]*)\.html$ /mysite/category.php?cat=$1&lang=$2 [NE,R,L]
</code>```

But my User Friendly URL is also gone when I use this. Instead I see: category.php?cat=....

I don't know if this is important but I use <base href=""> to point to the host I'm working on.

Thanks in advance for any ideas.

答:
Anchor # is an URL fragment, apache will ignore and not cater for rewrite.

Using client approach is the only workaround.

Or you can try PHP parse_url - PHP_URL_FRAGMENT

Title: Mod rewrite page anchor

Body:
I've been trying to solve this for the past two hours. I already tried every solution mentioned on google, but without any luck.

Let's start with the problem. I'm trying to use this plugin:
http://www.gethifi.com/blog/a-jquery-plugin-to-create-an-interactive-filterable-portfolio-like-ours

on my website. The problem is that this plugin is using Anchor tags. Without it, it doesn't seem to work.
Well, I'm trying to work with User Friendly URL's on the website I'm working on right now. So the anchors are not working.

This is my .htaccess file right now:

RewriteEngine On
RewriteBase /
RewriteRule ^([^/]*)\.html$ /mysite/category.php?cat=$1 [L]
RewriteRule ^([^/]*)/([^/]*)\.html$ /mysite/category.php?cat=$1&lang=$2 [L]

Nothing fancy, just some rewrites for categories and languages. The only thing that seems to work is this:

RewriteEngine On
RewriteBase /
RewriteRule ^([^/]*)\.html$ /mysite/category.php?cat=$1 [L]
RewriteRule ^([^/]*)/([^/]*)\.html$ /mysite/category.php?cat=$1&lang=$2 [NE,R,L]

But my User Friendly URL is also gone when I use this. Instead I see: category.php?cat=....

I don't know if this is important but I use <base href=""> to point to the host I'm working on.

Thanks in advance for any ideas.


问:
way to set connection string for database migration in web.config
I have an ASP MVC 5 app with code first migrations enabled.  Whenever I publish it to a server, it adds an extra connection string to the Web.Config file along with a "parameter" element, and it breaks the site until I replace it.  It looks like:

```<code><entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
        <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
    <contexts>
        <context type="MyApp.DataLayer.MyContext, MyApp">
            <databaseInitializer type="System.Data.Entity.MigrateDatabaseToLatestVersion`2[[MyApp.DataLayer.MyContext, MyApp], [MyApp.Migrations.Configuration, MyApp]], EntityFramework, PublicKeyToken=b77a5c561934e089">
                <parameters>
                    <parameter value="MyContext_DatabasePublish" />
                </parameters>
            </databaseInitializer>
        </context>
    </contexts>
</entityFramework>
<connectionStrings>
    <add name="MyContext" connectionString="Data Source=SQLServerName;Initial Catalog=MyDB;Integrated Security=SSPI" providerName="System.Data.SqlClient" />
    <add name="MyContext_DatabasePublish" connectionString="MyContext_DatabasePublish.ConnetionString" providerName="System.Data.SqlClient" />
</connectionStrings>
</code>```

I presume that extra connection string is for the database migrations, is that right?  All I have to do to get things working is replace the connection string with the one above it, so replace MyContext_DatabasePublish.ConnetionString with Data Source=SQLServerName;Initial Catalog=MyDB;Integrated Security=SSPI for example.

First, is that connection string even needed?  This is all in dev, and my migrations were all done from my local machine.

If it is needed, is there a way to keep it from coming in as MyContext_DatabasePublish.ConnetionString and instead come in as the connection string that works so I don't have to manually replace it every time I publish an update?

Thank you in advance for any information and advice!

答:
See post here:

https://blogs.msdn.microsoft.com/aspnetue/2012/06/12/deployment-in-visual-studio-2012-rc-using-entity-framework-code-first-migrations/

This occurs when you setup code first migrations so that you can define a privileged account to run your migrations without having to elevate the privileges of your normal context user.

Body:
I have an ASP MVC 5 app with code first migrations enabled.  Whenever I publish it to a server, it adds an extra connection string to the Web.Config file along with a "parameter" element, and it breaks the site until I replace it.  It looks like:

<entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
        <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
    <contexts>
        <context type="MyApp.DataLayer.MyContext, MyApp">
            <databaseInitializer type="System.Data.Entity.MigrateDatabaseToLatestVersion`2[[MyApp.DataLayer.MyContext, MyApp], [MyApp.Migrations.Configuration, MyApp]], EntityFramework, PublicKeyToken=b77a5c561934e089">
                <parameters>
                    <parameter value="MyContext_DatabasePublish" />
                </parameters>
            </databaseInitializer>
        </context>
    </contexts>
</entityFramework>
<connectionStrings>
    <add name="MyContext" connectionString="Data Source=SQLServerName;Initial Catalog=MyDB;Integrated Security=SSPI" providerName="System.Data.SqlClient" />
    <add name="MyContext_DatabasePublish" connectionString="MyContext_DatabasePublish.ConnetionString" providerName="System.Data.SqlClient" />
</connectionStrings>

I presume that extra connection string is for the database migrations, is that right?  All I have to do to get things working is replace the connection string with the one above it, so replace MyContext_DatabasePublish.ConnetionString with Data Source=SQLServerName;Initial Catalog=MyDB;Integrated Security=SSPI for example.

First, is that connection string even needed?  This is all in dev, and my migrations were all done from my local machine.

If it is needed, is there a way to keep it from coming in as MyContext_DatabasePublish.ConnetionString and instead come in as the connection string that works so I don't have to manually replace it every time I publish an update?

Thank you in advance for any information and advice!


问:
How can I pass my user entered information to my database using php?
The users enter their name and number in the textfields. The this information is passed then sent to the data.php file where I am trying to get it to write to my database. The data base name is called hello.

```<code><!-- connect to database -->
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "hello";

// Create connection
 $conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
echo "wooo connected";
}

//<!-- post added information to database -->
if ($_POST['name']) {
 if ($_POST['number']) {

 $sql = "INSERT INTO hello (id, name, number)
VALUES ('', '$_POST['name']', '$_POST['number'')";
if(mysqli_query($conn, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
  }
 }
} ?>
</code>```

From looking at my code I believe the issue is with this line.

```<code>   $sql = "INSERT INTO hello (id, name, number)
VALUES ('', '$_POST['name']', '$_POST['number']')";
</code>```

There is a blank left at the star for the auto incremented id that I have set in phpmyadmin.
I can hard code an entry such as:

```<code>$sql = "INSERT INTO hello (id, name, number)
VALUES ('', 'john', '12345)";
</code>```

These hard coded entries are put into the database but i can't get the user entered data to go in.

答:
Create variables for the $_POST values and add the vars for ease of code understanding:

```<code>$name = $_POST['name'];
$number = $_POST['number'];
$sql = "INSERT INTO hello (id, name, number) VALUES ('', $name, $number)";
</code>```

One reason your code may not be working because you have the single quotes around the $_POST values, then you can also do what Jasbeer Rawal recommended.

UPDATE

Based on the kind comments... I would personally take a different approach to adding the data to your database, instead use prepared statements. I use MySQLi, but you can also use PDO.

Start by creating your connection:

```<code><?php
define("HOST", "localhost");
define("USER", "");
define("PASSWORD", "");
define("DATABASE", "");

$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
if ($mysqli->connect_error) {
    echo "There was a slight problem, please contact your webmaster before continuing.";
    exit();
}
</code>```

Then when the user submits the form handle it:

```<code>if(isset($_POST['submit']
{
    $name = $_POST['name'];
    $number = $_POST['number'];

    if ($stmt = $mysqli->prepare("INSERT hello (name, number) VALUES (?, ?)"))
    {
            $stmt->bind_param("ss", $name, $number);
            $stmt->execute();
            $stmt->close();
    }
    else
    {
        echo "ERROR: Could not prepare SQL statement.";
    }
}
</code>```

This will add $name and $number and your ID role has to be a primary role and set to auto_increment. IDs will be automatically generated.

Body:
The users enter their name and number in the textfields. The this information is passed then sent to the data.php file where I am trying to get it to write to my database. The data base name is called hello.

<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "hello";

// Create connection
 $conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
echo "wooo connected";
}

//
if ($_POST['name']) {
 if ($_POST['number']) {

 $sql = "INSERT INTO hello (id, name, number)
VALUES ('', '$_POST['name']', '$_POST['number'')";
if(mysqli_query($conn, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
  }
 }
} ?>

From looking at my code I believe the issue is with this line.

   $sql = "INSERT INTO hello (id, name, number)
VALUES ('', '$_POST['name']', '$_POST['number']')";

There is a blank left at the star for the auto incremented id that I have set in phpmyadmin.
I can hard code an entry such as:

$sql = "INSERT INTO hello (id, name, number)
VALUES ('', 'john', '12345)";

These hard coded entries are put into the database but i can't get the user entered data to go in.

Body:
Create variables for the $_POST values and add the vars for ease of code understanding:

$name = $_POST['name'];
$number = $_POST['number'];
$sql = "INSERT INTO hello (id, name, number) VALUES ('', $name, $number)";

One reason your code may not be working because you have the single quotes around the $_POST values, then you can also do what Jasbeer Rawal recommended.

UPDATE

Based on the kind comments... I would personally take a different approach to adding the data to your database, instead use prepared statements. I use MySQLi, but you can also use PDO.

Start by creating your connection:

<?php
define("HOST", "localhost");
define("USER", "");
define("PASSWORD", "");
define("DATABASE", "");

$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
if ($mysqli->connect_error) {
    echo "There was a slight problem, please contact your webmaster before continuing.";
    exit();
}

Then when the user submits the form handle it:

if(isset($_POST['submit']
{
    $name = $_POST['name'];
    $number = $_POST['number'];

    if ($stmt = $mysqli->prepare("INSERT hello (name, number) VALUES (?, ?)"))
    {
            $stmt->bind_param("ss", $name, $number);
            $stmt->execute();
            $stmt->close();
    }
    else
    {
        echo "ERROR: Could not prepare SQL statement.";
    }
}

This will add $name and $number and your ID role has to be a primary role and set to auto_increment. IDs will be automatically generated.


问:
Get image link from div using xPath
Need help to get album cover from webpage.

```<code><div class="cover" style="background-image: url("http://is5.mzstatic.com/image/thumb/Music/v4/68/b5/08/68b50896-607e-2950-3530-de172fdbf878/source/100x100bb.jpg");"></div>
</code>```

Tried everything but nothing works.

```<code>HttpClient http = new HttpClient();
var response = await http.GetByteArrayAsync("http://www.antena1.com.br/stream/player");
String source = Encoding.GetEncoding("utf-8").GetString(response, 0, response.Length - 1);
source = WebUtility.HtmlDecode(source);
HtmlDocument resultat = new HtmlDocument();
resultat.LoadHtml(source);

HtmlNode nodes1 = resultat.DocumentNode.SelectSingleNode("//*[@id='CuboPlayer1']/div[1]");

txtImgLink.Text = nodes1.ToString();
</code>```

Thanks a lot

答:
You can use a regular expression to parse out the URL from the InnerHtml of your CuboPlayer1 div.
Why the parent div and not the cover itself? Because there is a problem with the HtmlAgilityPack where it can't parse out quotes inside Attributes["style"].Value, that's why you need to go to the parent node CuboPlayer1 and manually extract the URL from the entire HTML instead.

You can do that with this code:

```<code>string nodeHTML = resultat.DocumentNode
    .SelectSingleNode("//div[@id='CuboPlayer1']").InnerHtml;

string pattern = @"(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\/\\\+&%\$#_]*)?";

Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
string backgroundURL = regex.Match(nodeHTML).Value;
</code>```

I tested this using the code below and it works:

```<code>using System;
using System.Text.RegularExpressions;
using System.Xml;
using HtmlAgilityPack;

public class Program
{
    public static void Main()
    {
        var html =
        "<div id=\"CuboPlayer1\"><div class=\"cover\" style=\"background-image: url(\"http://is5.mzstatic.com/image/thumb/Music/v4/68/b5/08/68b50896-607e-2950-3530-de172fdbf878/source/100x100bb.jpg\");\"></div></div>";

        var htmlDoc = new HtmlDocument();
        htmlDoc.LoadHtml(html);

        string nodeHTML = htmlDoc.DocumentNode
            .SelectSingleNode("//div[@id='CuboPlayer1']").InnerHtml;

        string pattern = @"(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\/\\\+&%\$#_]*)?";
        Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
        string backgroundURL = regex.Match(nodeHTML).Value;

        Console.WriteLine(backgroundURL);
    }
}
</code>```

EDIT:
There is a problem with what you're trying to achieve, in that the background-image is constantly changing. Depending on what is on the screen at the time the document loads, you may not get any URL back because no cover is being displayed.

In any case, here's updated code which points directly at the page you're working with using your URL instead of static HTML like my first example:

```<code>var url = "http://www.antena1.com.br/stream/player";
var web = new HtmlWeb();
var htmlDoc = web.Load(url);

// Convert each line of HTML into a list of strings
List<string> nodeHTML = htmlDoc.DocumentNode
    .SelectSingleNode("//div[@id='CuboPlayer1']").InnerHtml.Split('\n').ToList();

// Find div with "cover" attribute
string coverHTML = nodeHTML.Where(n => n.Contains("<div class=\"cover\"")).FirstOrDefault();

// Define regular expression to match
string pattern = @"(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\/\\\+&%\$#_]*)?";
Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);

// Extract backgroundURL
string backgroundURL = regex.Match(coverHTML).Value;
</code>```

Title: Get image link from div using xPath

Body:
Need help to get album cover from webpage.

Tried everything but nothing works.

HttpClient http = new HttpClient();
var response = await http.GetByteArrayAsync("http://www.antena1.com.br/stream/player");
String source = Encoding.GetEncoding("utf-8").GetString(response, 0, response.Length - 1);
source = WebUtility.HtmlDecode(source);
HtmlDocument resultat = new HtmlDocument();
resultat.LoadHtml(source);

HtmlNode nodes1 = resultat.DocumentNode.SelectSingleNode("//*[@id='CuboPlayer1']/div[1]");

txtImgLink.Text = nodes1.ToString();

Thanks a lot

Body:
You can use a regular expression to parse out the URL from the InnerHtml of your CuboPlayer1 div.
Why the parent div and not the cover itself? Because there is a problem with the HtmlAgilityPack where it can't parse out quotes inside Attributes["style"].Value, that's why you need to go to the parent node CuboPlayer1 and manually extract the URL from the entire HTML instead.

You can do that with this code:

string nodeHTML = resultat.DocumentNode
    .SelectSingleNode("//div[@id='CuboPlayer1']").InnerHtml;

string pattern = @"(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\/\\\+&amp;%\$#_]*)?";

Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
string backgroundURL = regex.Match(nodeHTML).Value;

I tested this using the code below and it works:

using System;
using System.Text.RegularExpressions;
using System.Xml;
using HtmlAgilityPack;

public class Program
{
    public static void Main()
    {
        var html =
        "<div id=\"CuboPlayer1\"><div class=\"cover\" style=\"background-image: url(\"http://is5.mzstatic.com/image/thumb/Music/v4/68/b5/08/68b50896-607e-2950-3530-de172fdbf878/source/100x100bb.jpg\");\"></div></div>";

        var htmlDoc = new HtmlDocument();
        htmlDoc.LoadHtml(html);

        string nodeHTML = htmlDoc.DocumentNode
            .SelectSingleNode("//div[@id='CuboPlayer1']").InnerHtml;

        string pattern = @"(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\/\\\+&amp;%\$#_]*)?";
        Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
        string backgroundURL = regex.Match(nodeHTML).Value;

        Console.WriteLine(backgroundURL);
    }
}

EDIT:
There is a problem with what you're trying to achieve, in that the background-image is constantly changing. Depending on what is on the screen at the time the document loads, you may not get any URL back because no cover is being displayed.

In any case, here's updated code which points directly at the page you're working with using your URL instead of static HTML like my first example:

var url = "http://www.antena1.com.br/stream/player";
var web = new HtmlWeb();
var htmlDoc = web.Load(url);

// Convert each line of HTML into a list of strings
List<string> nodeHTML = htmlDoc.DocumentNode
    .SelectSingleNode("//div[@id='CuboPlayer1']").InnerHtml.Split('\n').ToList();

// Find div with "cover" attribute
string coverHTML = nodeHTML.Where(n => n.Contains("<div class=\"cover\"")).FirstOrDefault();

// Define regular expression to match
string pattern = @"(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\/\\\+&%\$#_]*)?";
Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);

// Extract backgroundURL
string backgroundURL = regex.Match(coverHTML).Value;


问:
SAP Vora: Not able to add Vora table as Virtual table via Smart Data Access in HANA Studio
I'm using a VM with HANA Express 2 SP 01. On a small test cluster I installed the Hortonworks Data Platform 2.6 with Spark 1.6.3, and also added HANA Vora 1.4 and the Spark Controller 2.1.

I followed the SAP Vora Installation and Administration guide: https://help.sap.com/http.svc/rc/f09ec811fe634f588647c342cac84c38/1.4/en-US/SAP_Vora_Installation_Admin_Guide_1.4_en.pdf until chapter 2.9. Everything works fine, but the Zeppelin part with the %jdbc interpreter:

```<code>%jdbc
select * from sys.tables using com.sap.spark.engines
============================================================

java.lang.NoSuchMethodError: org.apache.hive.service.cli.thrift.TExecuteStatementReq.setQueryTimeout(J)V
...
</code>```

Here I get a NoSuchMethodError. However, if I follow the instructions in the next chapter (2.9 Connect SAP HANA Spark Controller to SAP Vora), I'm also not able to add a table from the Vora DataSource to my HANA Express Database. See also this screenshot:

答:
Regarding the java.lang.NoSuchMethodError, most likely the wrong Hive jar file was attached.

The link in your comment refers to the Spark Controller, but in this post/question you are using the HANA Wire. Both are valid methods of adding virtual tables from Vora.

The issue you are experiencing here is handled in section 3.3 of the Vora troubleshooting guide

Body:
I'm using a VM with HANA Express 2 SP 01. On a small test cluster I installed the Hortonworks Data Platform 2.6 with Spark 1.6.3, and also added HANA Vora 1.4 and the Spark Controller 2.1.

I followed the SAP Vora Installation and Administration guide: https://help.sap.com/http.svc/rc/f09ec811fe634f588647c342cac84c38/1.4/en-US/SAP_Vora_Installation_Admin_Guide_1.4_en.pdf until chapter 2.9. Everything works fine, but the Zeppelin part with the %jdbc interpreter:

%jdbc
select * from sys.tables using com.sap.spark.engines
============================================================

java.lang.NoSuchMethodError: org.apache.hive.service.cli.thrift.TExecuteStatementReq.setQueryTimeout(J)V
...

Here I get a NoSuchMethodError. However, if I follow the instructions in the next chapter (2.9 Connect SAP HANA Spark Controller to SAP Vora), I'm also not able to add a table from the Vora DataSource to my HANA Express Database. See also this screenshot:


问:
Kendo Grid jQuery - Make column visible again on ungroup
Currently, I hide grouped columns using the k-group-indicator element field attributes.

```<code> $("div.k-group-indicator").each(function (i, v) {
     grid.hideColumn($(v).data("field"));
 });
</code>```

I need to then make them visible again when they are ungrouped. I cannot use the same method to do this though as I also allow the user to hide and show columns, also saving their configuration in localStorage and using it to keep the grid the same when they come back to the page.

I guess my question should be, is there an event I can use; something like OnUngroup() to capture when the grid is ungrouped and use the field name to make the column visible again?

答:
You can subscribe group event and check groups length:

```<code>group: function(e) {
  if (e.groups.length == 0) {
    alert('ungrouped!');
  }
}
</code>```

To make column visible again use function:

```<code>grid.showColumn();
</code>```

EDIT:

e.groups collection contains info about columns which are actually in grouping. Using this information you can save your grouping ids in localStorage or global variable or somewhere and compare  every time group event is fired.

Body:
Currently, I hide grouped columns using the k-group-indicator element field attributes.

 $("div.k-group-indicator").each(function (i, v) {
     grid.hideColumn($(v).data("field"));
 });

I need to then make them visible again when they are ungrouped. I cannot use the same method to do this though as I also allow the user to hide and show columns, also saving their configuration in localStorage and using it to keep the grid the same when they come back to the page.

I guess my question should be, is there an event I can use; something like OnUngroup() to capture when the grid is ungrouped and use the field name to make the column visible again?

Body:
You can subscribe group event and check groups length:

group: function(e) {
  if (e.groups.length == 0) {
    alert('ungrouped!');
  }
}

To make column visible again use function:

grid.showColumn();

EDIT:

e.groups collection contains info about columns which are actually in grouping. Using this information you can save your grouping ids in localStorage or global variable or somewhere and compare  every time group event is fired.


问:
Dealing with polymorphic association: is there such a thing as "too many" LEFT JOIN?
I have ten tables (Product_A, Product_B, Product_C, etc.), each of them having a primary key pointing to a row in a the parent table Product.

Basically, I have applied the recommendations coming from the SQL antipattern book from Bill Karwin (this antipattern solution described here:
https://fr.slideshare.net/billkarwin/practical-object-oriented-models-in-sql/34-Polymorphic_Assocations_Exclusive_Arcs_Referential )

In order to load a child product, I use something like this:

```<code>SELECT * FROM Product
LEFT JOIN Product_A USING (product_id)
LEFT JOIN Product_B USING (product_id)
LEFT JOIN Product_C USING (product_id)
LEFT JOIN Product_D USING (product_id)
WHERE product_id = 1337
etc.
</code>```

I fear that the more types of child table products I get, the more JOIN clause I will have to add, causing the query to end up incredibly slow.

Is using LEFT JOIN in order to prevent polymorphic associations antipattern still a solution if we work on tens of sub child tables?

Should I start thinking of up using a query on parent table Product in order to grab a "product_type" and then execute another query on the appropriate child table depending on the value stored in the "product_type" column in the parent table?

Update: first replies on this topic state that this is bad design and that I should create a single table combining the colums from the child tables. But each product type has its own attributes. To say it otherwise: "A TV might have a pixel count, but that wouldn't make much sense for a blender." @TomH

Thank you

答:
MySQL has a hard limit on the number of joins. The limit is 61 joins, and it's not configurable (I looked at the source code and it's really just hard-coded). So if you have more than 62 product types, this is not going to work in a single query.

If the data were stored in the structure you describe, I would run a separate query per product type, so you don't make too many joins.

Or do a query against the Product table first, and then additional queries to the product-type specific tables if you need details.

For example, when would you need to gather the product-specific details all at once? On some kind of search page? Do you think you could design your code to show only the attributes from your primary Product table on the search page?

Then only if a user clicks on a specific product, you'd go to a different page to display detailed information. Or if not a different page, maybe it'd be a dynamic HTML thing where you expand a "+" button to fetch detailed info, and each time you do that, run an AJAX request for the details.

Body:
I have ten tables (Product_A, Product_B, Product_C, etc.), each of them having a primary key pointing to a row in a the parent table Product.

Basically, I have applied the recommendations coming from the SQL antipattern book from Bill Karwin (this antipattern solution described here:
https://fr.slideshare.net/billkarwin/practical-object-oriented-models-in-sql/34-Polymorphic_Assocations_Exclusive_Arcs_Referential )

In order to load a child product, I use something like this:

SELECT * FROM Product
LEFT JOIN Product_A USING (product_id)
LEFT JOIN Product_B USING (product_id)
LEFT JOIN Product_C USING (product_id)
LEFT JOIN Product_D USING (product_id)
WHERE product_id = 1337
etc.

I fear that the more types of child table products I get, the more JOIN clause I will have to add, causing the query to end up incredibly slow.

Is using LEFT JOIN in order to prevent polymorphic associations antipattern still a solution if we work on tens of sub child tables?

Should I start thinking of up using a query on parent table Product in order to grab a "product_type" and then execute another query on the appropriate child table depending on the value stored in the "product_type" column in the parent table?

Update: first replies on this topic state that this is bad design and that I should create a single table combining the colums from the child tables. But each product type has its own attributes. To say it otherwise: "A TV might have a pixel count, but that wouldn't make much sense for a blender." @TomH

Thank you


问:
upload from telegram bot
I want to upload a file that exists in a telegram server to another server but telegram does not provide a download url link.

I tried to use some bots like pwrtelegrambot or something like that but none of them works.
i tried to write a bot to do this for me but i understand that the bot only can download files up to 20mb and i got this error

{"ok":false,"error_code":400,"description":"Bad Request: file is too big"}

Is there any way to generate download url from the files that exists in telegram server and upload them to another server like uploadboy or something else??

I will appreciate for any help!!

答:
as it mentioned in this link, you can't download files bigger than 20MB.

if you really want to download big files, you should forget about the bots and try to modify telegram clients source codes.(telegram cli , android, webogram)

Title: upload from telegram bot


问:
Permission Level for Accessing the Always Encrypted (azure Key Vault)
I'm try to create a Column Encryption in Azure(via Always Encrypted Wizard).I have one big doubt in these Scenario.

There are several other ways to store the CMK like Windows Store,Azure Key Vault.

In Windows Store there are two options User/LocalMachine,Where in
User Options the CMK will be work for that particular Local Machine and that Particular User alone.(able to decrypt Using Column Encryption Setting=Enabled )

Where as Local Machine option can be work for all the Users in the Same Machine.(able to decrypt using Column Encryption Setting=Enabled)

My Doubt is ,
When coming to Azure Key Vault for storing CMK who can able to decrypt the Encrypted Column ?

My understanding is
The User who have the access(Under Access Policies) to Azure Key Vault can only be able to decrypt the Encrypted Column ? Is that right ?

Please anyone guide me

Thanks in advance,

Jay

答:
My understanding is The User who have the access(Under Access
  Policies) to Azure Key Vault can only be able to decrypt the Encrypted
  Column ? Is that right ?

Yes that is correct. You would need the following permissions : create,get,wrapKey,unwrapKey,sign,verify,list

Here are a couple of articles that will walk you through basic Always encrypted workflow using AKV

Article 1

Article 2


答:
There is nothing in your code that is actually assigning any values in the session array.

```<code>$_SESSION['some_var'] = "Some Value";
</code>```

But you're not doing that so the session you have remains untouched.

Title: Assigning updated value to $_SESSION array

Body:
There is nothing in your code that is actually assigning any values in the session array.

$_SESSION['some_var'] = "Some Value";

But you're not doing that so the session you have remains untouched.