text:
Q: Java Servlet for file download: Works when started from form submit, not when started from jQuery download I have a Java Servlet for File Download (taken from the examples on this page (Implementing a simple file download servlet) that works in general but not when started via query.
The setup works as follows:
When clicking on a button (input type submit) a file is generated and stored on the server. The response is redirected to the file download servlet which then streams the content of the generated file to the response.
This works perfectly fine, except when starting the download procedure via a jQuery post function call.
When looking at the requests the only difference I could find was the accept-header of the request. This was / for the jQuery post and 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,/;q=0.8' for the form submit request.
Could that be the decisive difference? And if so, how can I set what to accept?
This is the function call for the post in js:
$.post("path", {
            action : "action",
            ids: ids.toString()
        }, null, "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");

This is the part where I set the content-disposition:
resp.addHeader("content-disposition:",
                        "attachment; filename=name.csv");

A: Browsers don't handler XHR responses the same way that they handle "normal" HTTP requests. If your servlet is correctly setting the "Content-disposition" header, then you can just do an ordinary form post.


text:
Q: var_dump and print_r cause white screen My template is very simple:
get_header();
$new_p = get_posts(array('post_type' => 'post', 'numberposts' => 6));
get_footer();

whenever I put var_dump($new_p); or print_r($new_p); below $new_p = get_posts(array('post_type' => 'post', 'numberposts' => 6));, it gives me the white screen.
Why on Earth would it do it??
This code is OK, though:
var_dump(wp_get_recent_posts(array('post_type' => 'tdlrm_store_item', 'numberposts' => 8), OBJECT));

Any ideas?

A: Actually, memory was exhausted. Someone has copy-pasted an actual 2MB base64-encoded image into the post content, var_dump was trying to output it. Had to delete the image via PHPMyAdmin, because the WP editor won't open. Once it had been deleted, the problem was gone.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Creating a matrix from a column in an array of hashes I have a dataset as an array of hashes. For example,
id   fruit      amount
1    grape        10
2    banana       6
3    grape        7
4    mango        15
5    strawberry   5

this is stored in an array of hashes as:
[
  {"id" => "1", "fruit" => "grape", "amount" => 10},
  {"id" => "2", "fruit" => "banana", "amount" => 6},
  ...
]

I need to convert the data into a form like the following (to create a matrix as the set matrix for the linear optimization problem using Rglpk):
id   is_grape   is_banana   is_mango    is_strawberry
1     1           0           0            0
2     0           1           0            0
3     1           0           0            0
4     0           0           1            0
5     0           0           0            1

and then get something like this by transposing the columns and rows:
[
  #1    #2    #3    #4     #5    # each column for id 1, 2, ...
  1     0     1     0      0     # row is_grape
  0     1     0     0      0     # row is_banana
  0     0     0     1      0     # row is_mango
  0     0     0     0      1     # row is_strawberry
]

There could be any number of categories in a column. I want to create the values for the is_grape, is_mango type categories dynamically rather than hard code. How do I get the data in the matrix form?

A: arr = [
  {"id" => "1", "fruit" => "grape", "amount" => 10},
  {"id" => "2", "fruit" => "banana", "amount" => 6}
]

# fruits = arr.group_by { |h| h['fruit'] }.keys.map { |e| "is_#{e}" }
fruits = arr.map { |e| "is_#{e['fruit']}" }.uniq
#⇒ [ "is_grape", "is_banana" ]
arr.each_with_object([]) do |h, memo|
  e = fruits.zip([0] * fruits.size).to_h
  e['id'] = h['id']
  e["is_#{h['fruit']}"] += 1
  # e["is_#{h['fruit']}"] += h['amount'].to_i # that seems meaningful
  memo << e
end

Giving:
#⇒ [
#  [0] {
#           "id" => "1",
#    "is_banana" => 0,
#     "is_grape" => 1
#  },
#  [1] {
#           "id" => "2",
#    "is_banana" => 1,
#     "is_grape" => 0
#  }
# ]

A: a = [
  {"id" => "1", "fruit" => "grape", "amount" => 10},
  {"id" => "2", "fruit" => "banana", "amount" => 6},
  {"id" => "3", "fruit" => "grape", "amount" => 7},
  {"id" => "4", "fruit" => "mango", "amount" => 15},
  {"id" => "5", "fruit" => "strawberry", "amount" => 5},
]

fruits = a.map{|h| h["fruit"]}.uniq
m = Array.new(fruits.length){[0] * a.length}
a.each{|h| m[fruits.index(h["fruit"])][h["id"].to_i - 1] = 1}
p m

Output:
[
  [1, 0, 1, 0, 0],
  [0, 1, 0, 0, 0],
  [0, 0, 0, 1, 0],
  [0, 0, 0, 0, 1]
]

A: arr = [
  {"id" => "1", "fruit" => "grape", "amount" => 10},
  {"id" => "2", "fruit" => "banana", "amount" => 6},
  {"id" => "3", "fruit" => "mango", "amount" => 4},
  {"id" => "7", "fruit" => "banana", "amount" => 3},
  {"id" => "5", "fruit" => "strawberry", "amount" => 7},
  {"id" => "6", "fruit" => "banana", "amount" => 1},
  {"id" => "4", "fruit" => "banana", "amount" => 3}
]

fruit_to_row = arr.map { |h| h["fruit"] }.uniq.each_with_index.
  with_object({}) { |(f,i),h| h[f] = i }
  #=> {"grape"=>0, "banana"=>1, "mango"=>2, "strawberry"=>3}

arr.each_with_index.
    with_object(Array.new(fruit_to_row.size) {Array.new(arr.size) {0}}) { |(h,i),a|
      a[fruit_to_row[h["fruit"]]][i] = 1 }
  #=> [[1, 0, 0, 0, 0, 0, 0], grape
  #    [0, 1, 0, 1, 0, 1, 1], banana
  #    [0, 0, 1, 0, 0, 0, 0], mango
  #    [0, 0, 0, 0, 1, 0, 0]] strawberry


text:
Q: Cisco Anywhere VPN - Web Based Installation Was Unsuccessful I am trying to log in to my work machine from home, but my computer is stuck trying to connect using the Cisco AnyConnect VPN Client. I receive the error message Web-based installation was unsuccessful (see attached image). I have tried using Firefox, Chrome, and IE10. I have added my work domain as a trusted site and also the security certificate. I have also uninstalled/reinstalled my Java 7 client but I am still stuck on this screen. Any advice?
Note: I am on Windows 7. I am logged in as the only account on my computer (so I assume I am admin).

A: Click on the link "Windows Vista/64/XP/2000".  The AnyConnect setup .exe should download - make sure to save it to your Desktop or other place you will remember it.  Then run it, and reboot.


text:
Q: how to incorporate TOTP with user migration in AD B2C I'm using the guide here to perform Just-In-Time migration of a user from a legacy Idp to azure ad b2c: https://github.com/azure-ad-b2c/user-migration/tree/master/jit-migration-v2. I have this working properly on its own with a service I am using to query the legacy IdP and returning expected claims.
I also tried out the custom TOTP sample and have it working with a QR code for new user sign ups using this sample and policies: https://github.com/azure-ad-b2c/samples/tree/master/policies/custom-mfa-totp. I have a separate service for generating QR code which is presented to the user when they sign up.
However, I'm not sure how to incorporate the user migration above with the TOTP. When a user that exists in legacy IdP tries to sign in, and if they are validated and their account is created in AD, I would like them to be directed to the QR code page as per the above policy where they must sign up their newly migrated account with microsoft auth app. More specifically, I would like some guidance around how to setup the custom policies above to accomplish this.

A: *

*Inherit the features into a single policy: Chain your files like this by configuing the basePolicy element. Base <- Extensions <- Extensions_TOTP <- Extensions_Migration <- SignInSignUp

*Remove or rename all the UserJourneys

*Create a new UserJourney which creates the logic you want to call the specific functionality (technical profiles) you desire, with preconditions to only call the TOTP technical profiles based on specific claim values. Essentially you can take the JIT migration user journey, and bring in the specific steps from the TOTP user journey to give the TOTP functionality.

*Update the defaultUserJourney id in the  SignInSignUp file.

Your journey should look like
      <UserJourney Id="SignUpOrSignIn">
      <OrchestrationSteps>

        <OrchestrationStep Order="1" Type="CombinedSignInAndSignUp" ContentDefinitionReferenceId="api.signuporsignin">
          <ClaimsProviderSelections>
            <ClaimsProviderSelection TargetClaimsExchangeId="FacebookExchange" />
            <ClaimsProviderSelection TargetClaimsExchangeId="GoogleExchange" />
           <ClaimsProviderSelection ValidationClaimsExchangeId="LocalAccountSigninEmailExchange" />
          </ClaimsProviderSelections>
          <ClaimsExchanges>
            <ClaimsExchange Id="LocalAccountSigninEmailExchange" TechnicalProfileReferenceId="SelfAsserted-LocalAccountSignin-Email" />
          </ClaimsExchanges>
        </OrchestrationStep>

        <!-- Check if the user has selected to sign in using one of the social providers -->
        <OrchestrationStep Order="2" Type="ClaimsExchange">
          <Preconditions>
            <Precondition Type="ClaimsExist" ExecuteActionsIf="true">
              <Value>objectId</Value>
              <Action>SkipThisOrchestrationStep</Action>
            </Precondition>
          </Preconditions>
          <ClaimsExchanges>
            <ClaimsExchange Id="FacebookExchange" TechnicalProfileReferenceId="Facebook-OAUTH" />
            <ClaimsExchange Id="GoogleExchange" TechnicalProfileReferenceId="Google-OAUTH" />
           <ClaimsExchange Id="SignUpWithLogonEmailExchange" TechnicalProfileReferenceId="LocalAccountSignUpWithLogonEmail" />
          </ClaimsExchanges>
        </OrchestrationStep>

        <!-- For social IDP authentication, attempt to find the user account in the directory. -->
        <OrchestrationStep Order="3" Type="ClaimsExchange">
          <Preconditions>
            <Precondition Type="ClaimEquals" ExecuteActionsIf="true">
              <Value>authenticationSource</Value>
              <Value>localAccountAuthentication</Value>
              <Action>SkipThisOrchestrationStep</Action>
            </Precondition>
          </Preconditions>
          <ClaimsExchanges>
            <ClaimsExchange Id="AADUserReadUsingAlternativeSecurityId" TechnicalProfileReferenceId="AAD-UserReadUsingAlternativeSecurityId-NoError" />
          </ClaimsExchanges>
        </OrchestrationStep>

        <!-- Show self-asserted page only if the directory does not have the user account already (i.e. we do not have an objectId).
          This can only happen when authentication happened using a social IDP. If local account was created or authentication done
          using ESTS in step 2, then an user account must exist in the directory by this time. -->
        <OrchestrationStep Order="4" Type="ClaimsExchange">
          <Preconditions>
            <Precondition Type="ClaimsExist" ExecuteActionsIf="true">
              <Value>objectId</Value>
              <Action>SkipThisOrchestrationStep</Action>
            </Precondition>
          </Preconditions>
          <ClaimsExchanges>
            <ClaimsExchange Id="SelfAsserted-Social" TechnicalProfileReferenceId="SelfAsserted-Social" />
          </ClaimsExchanges>
        </OrchestrationStep>

        <!-- This step reads any user attributes that we may not have received when authenticating using ESTS so they can be sent
          in the token. -->
        <OrchestrationStep Order="5" Type="ClaimsExchange">
          <Preconditions>
            <Precondition Type="ClaimEquals" ExecuteActionsIf="true">
              <Value>authenticationSource</Value>
              <Value>socialIdpAuthentication</Value>
              <Action>SkipThisOrchestrationStep</Action>
            </Precondition>
          </Preconditions>
          <ClaimsExchanges>
            <ClaimsExchange Id="AADUserReadWithObjectId" TechnicalProfileReferenceId="AAD-UserReadUsingObjectId" />
          </ClaimsExchanges>
        </OrchestrationStep>
        <!-- The previous step (SelfAsserted-Social) could have been skipped if there were no attributes to collect
             from the user. So, in that case, create the user in the directory if one does not already exist
             (verified using objectId which would be set from the last step if account was created in the directory. -->
        <OrchestrationStep Order="6" Type="ClaimsExchange">
          <Preconditions>
            <Precondition Type="ClaimsExist" ExecuteActionsIf="true">
              <Value>objectId</Value>
              <Action>SkipThisOrchestrationStep</Action>
            </Precondition>
          </Preconditions>
          <ClaimsExchanges>
            <ClaimsExchange Id="AADUserWrite" TechnicalProfileReferenceId="AAD-UserWriteUsingAlternativeSecurityId" />
          </ClaimsExchanges>
        </OrchestrationStep>

       <!-- Demo: The following orchestration step is executed only for unregistered
        accounts (new created account or if user cancel the sign-up process).
        It generates a verification app secret key for the user (none interactive step). -->
        <OrchestrationStep Order="7" Type="ClaimsExchange">
          <Preconditions>
            <Precondition Type="ClaimsExist" ExecuteActionsIf="true">
              <Value>extension_StrongAuthenticationAppSecretKey</Value>
              <Action>SkipThisOrchestrationStep</Action>
            </Precondition>
          </Preconditions>
          <ClaimsExchanges>
            <ClaimsExchange Id="AppFactorGenerateTotpWebHook" TechnicalProfileReferenceId="AppFactor-GenerateTotpWebHook" />
          </ClaimsExchanges>
        </OrchestrationStep>

        <!-- Demo: The following orchestration step is executed only for unregistered
        accounts (new created account or if user cancel the sign-up process).
        It registers a verification app through QR code that mobile authentication app should scan. -->
        <OrchestrationStep Order="8" Type="ClaimsExchange">
          <Preconditions>
            <Precondition Type="ClaimsExist" ExecuteActionsIf="false">
              <Value>strongAuthenticationAppQRCodeBitmap</Value>
              <Action>SkipThisOrchestrationStep</Action>
            </Precondition>
            <Precondition Type="ClaimsExist" ExecuteActionsIf="true">
              <Value>isActiveMFASession</Value>
              <Action>SkipThisOrchestrationStep</Action>
            </Precondition>
          </Preconditions>
          <ClaimsExchanges>
            <ClaimsExchange Id="AppFactorRegisterExchange" TechnicalProfileReferenceId="AppFactor-Register" />
          </ClaimsExchanges>
        </OrchestrationStep>

        <!-- Demo: The following orchestration step is executed only for registered accounts.
        It asks the user to provide the TOTP code and verifies the provided code (using validation technical profile). -->
        <OrchestrationStep Order="9" Type="ClaimsExchange">
          <Preconditions>
            <Precondition Type="ClaimsExist" ExecuteActionsIf="true">
              <Value>strongAuthenticationAppQRCodeBitmap</Value>
              <Action>SkipThisOrchestrationStep</Action>
            </Precondition>
          </Preconditions>
          <ClaimsExchanges>
            <ClaimsExchange Id="AppFactorChallengeExchange" TechnicalProfileReferenceId="AppFactor-Challenge" />
          </ClaimsExchanges>
        </OrchestrationStep>

        <!-- Demo: The following orchestration step is always executed.
        It updates the verification app time step matched for a given user in the Azure Active Directory.
        An error is raised if the user does not exist. -->
        <OrchestrationStep Order="10" Type="ClaimsExchange">
          <ClaimsExchanges>
            <ClaimsExchange Id="AADWriteUserAppCodeByObjectId" TechnicalProfileReferenceId="AAD-WriteUserAppCodeByObjectId" />
          </ClaimsExchanges>
        </OrchestrationStep>

        <OrchestrationStep Order="11" Type="SendClaims" CpimIssuerTechnicalProfileReferenceId="JwtIssuer" />

      </OrchestrationSteps>
      <ClientDefinition ReferenceId="DefaultWeb" />
    </UserJourney>

You will want to add preconditions to Step 7/8/9 such that it triggers only for these migrated accounts. You can use the claims emitted in step 1 from your REST API to indicate whether this is a JIT migration. You can use extension attributes to indicate whether this is a migrated user. These claims can then be used to drive the logic for these steps as you desire.


text:
Q: How to determine why a piece of code produces an infinite loop? This is my binary search function. I can't seem to find the error but every time I try to run the code it gives me a segmentation fault 11. I feel like my mistake has to do with my last else if statement.
void binary(struct list *A[], char search[15], int start, int
end) {

    if(start <= end) {

        int middle = (start + end)/2;

        if(strcmp(search, A[middle]->name) == 0){

            printf("found");
            exit(0);

        } else if (strcmp(search, A[middle]->name) > 0){

            int start = middle + 1;
            int end = end;
            binary(A, search, start, end);

        } else if (strcmp(search, A[middle]->name) < 0){

            int start = start;
            int end = middle - 1;
            binary(A, search, start, end);

        } else if (start == (end - 1)) {

            printf("%s was not found in the list", search);
            exit(0);

       }

    }

}

A: These statements
int end = end;
int start = start;

do not make sense because the variables are initialized by themselves while they have indeterminate values.
There is no need to declare local variables end and start. Use the parameters.
This statement
    } else if (start == (end - 1)) {

        printf("%s was not found in the list", search);
        exit(0);

   }

also does not make sense because initially the variables start and end satisfy the condition of enclosing if statement
if(start <= end) {

And at last it does not make sense to use standard function exit instead of the return statement..

A: First, as others already pointed out, the assignment like int end = end is asking for troubles. Do a simple test and print the start and end values at the beginning of the function to see what happens as your program works...
Next, you do not need recursion here! Shrinking the search area can be easily done in a simple loop:
void binary(struct list *A[], char search[15], int start, int end) {
    while(start <= end) {
        int middle = start + (end - start)/2;

        int cmpresult = strcmp(search, A[middle]->name);
        if (cmpresult > 0) {
            start = middle + 1;
        } else if (cmpresult < 0) {
            end = middle - 1;
        } else {             // cmpresult == 0
            printf("found at %d", middle);
            return;
        }
    }

    printf("%s was not found in the list", search);
}

Finally, please note the middle calculation – adding (start + end) is a common step to do that, however it may lead to error if the array is too long; specifically, if the array length exceeds a half of the maximum value representable by int type.


text:
Q: Cardinality of a basis of an infinite-dimensional vector space How would you find the cardinality of the basis of $\mathbb{R}$ over $\mathbb{Q}$? Is it countable or uncountable?
In general, how do you find the cardinality of a basis of an infinite-dimensional vector space? Do you just search for a bijection between the basis and, say, $\mathbb{N}$ or $\mathbb{R}$? What are some instructive examples?

A: If $V$ is a vector space over the field $F$, and $B$ is a basis for $V$ then every element in $v$ is the unique combination of finitely many elements from $B$ with coefficients from $F$.
So each $v\in V$ can be represented as a finite subset of $B\times F$ which is a function. How? $v(b)=\alpha$ if $b$ is a basis element which has a nonzero coefficient, $\alpha$, in the linear combination of $v$ from $B$.
How many such functions are there? Now let's put into play the assumption that $V$ is infinite.
At least $B\times (F\setminus\{0\})$, since each singleton $\{\langle b,\alpha\rangle\}$ corresponds to the vector $\alpha\cdot b$. But if $X$ is infinite, the set of all finite subsets of $X$ has the same cardinality as $X$. So we get a bijection using Cantor-Bernstein. And since we're talking about infinite sets, we can consider $F$ and not $F\setminus\{0\}$.
So we get that $|V|=|B\times F|=|B|\cdot|F|$. But multiplying two non-zero cardinals, at least one of them is infinite, we get that $|B|\cdot|F|=\max\{|B|,|F|\}$.
In particular, if $|V|>|F|$ then $|V|=|B|$, or in other words $\dim V=|V|$.
So now if we want to apply this to $\Bbb R$ as a vector space over $\Bbb Q$, what do we get?

A: The cardinality of a Hamel basis of $\mathbf R$  over $\mathbf Q$ can't be countable, since it would imply $\mathbf R$  is countable.
A more general result is that if $E$ is an infinite-dimensional Banach space over a subfield $K\subset\mathbf C$, Hamel bases have all cardinality $\lvert E\rvert$.


text:
Q: Access values in a dictionary of dataframes and create a new dataframe with certain columns in pandas Python beginner here.
I have a dictionary of dataframes as:

each dataframe corresponds to a different day:

Each day contains 8 columns with data, I am interested in -> ['WINDSPEED_wspd1[m/s]']
I want to create a new variable (dataframe) that contains only the data regarding windspeed with one column for each day (each key in the dictionary of dataframes)
I created a function to do this
def get_variables(DictOfDataFrames, ColumnsToPlot, filenames):
     for key, df in DictOfDataFrames.items():  # Use magic unpacking to avoid multiple meteo_data[key]-call
    x=pd.DataFrame(index=range(0,86400,1),columns=filenames)

         if key in filenames:

             x[key]=df[ColumnsToPlot[0]][0:86400].copy()
             y=pd.DataFrame(DictOfDataFrames[key][ColumnsToPlot[1][0:86399]])
return xy
WindSpeed, WindDirection = get_variables(DATA_Meteo,['WINDSPEED_wspd1[m/s]','WINDDIR_wdir1[deg]'], filenames_Meteo[1:3])

However, in this way I overwrite y in every iteration, so it returns the values of the last filename it went in the loop. On the other hand, x is returned as full of NaN.
I tried with insert, append, I am going crazy with this which should be super simple to code.

A: I would propose:

*

*Create a empty list

*iterate on the dict and extract the serie  you want , add it to the empty list

*create a dataframe from this list of serie

Please find a exemple  with 2 days and 2 column of data:
    #%% Import lib

import pandas as pd
import numpy as np

#%% Created  dummy of random data , one dataframe per day
dataframe1 = pd.DataFrame(np.random.randint(0,100,size=(100, 2)), columns=['WINDSPEED_wspd1[m/s]','temp'])
dataframe2 = pd.DataFrame(np.random.randint(0,100,size=(100, 2)), columns=['WINDSPEED_wspd1[m/s]','temp'])

#created teh dummy dict
dict_d ={"day1":dataframe1 , "day2":dataframe2}

list_of_serie = []

for key, value in dict_d.items():
    s = value['WINDSPEED_wspd1[m/s]']  #extract the serie you want
    s= s.rename(key) # change the change of teh serie by the day

    list_of_serie.append(s) # add in a list of serie

# then concatenate all
df = pd.concat(list_of_serie, axis=1) # concatenate this list of series

print(df)

A: I finally found the answer from another user that was losing his mind with a similar problem.
def get_variables(DictOfDataFrames, ColumnsToPlot, filenames):
    first = True
    for key, value in DictOfDataFrames.items():
        if first:
            x = pd.DataFrame(value[ColumnsToPlot[0]])
            y = pd.DataFrame(value[ColumnsToPlot[1]])
            first = False
        else:
            x = x.merge(value[ColumnsToPlot[0]], left_index=True, right_index=True)
            y = y.merge(value[ColumnsToPlot[1]], left_index=True, right_index=True)

    y.columns=DictOfDataFrames.keys()
    x.columns=DictOfDataFrames.keys()
    return x, y


text:
Q: Uninitialized constant while trying to include helper module The module that I am trying to include is located here:
test/unit/helpers/test_helpers.rb
Looks like:
module TestHelpers
end

I am trying to include it in:
test/unit/app/models/abc.rb
class Abc < ActiveSupport::TestCase
include TestHelpers
end

gives the following error:

Error executing test/unit/app/models/abc.rb uninitialized constant
  Abc::TestHelpers

Any ideas why this might be happening?

A: To include a module into your class, you need to require that file.

require 'test_helpers'

Add this line at the top of your model class.


text:
Q: If it possible to access AdminConfig in the Liberty Profile (non ND) Is it possible to access AdminConfig.getid inside the WebSphere Liberty Profile (non ND), just pure Liberty profile, or even Base version?
Any particular jars needed?

A: The AdminConfig object is related to the wsadmin tool. According to IBM Documentation for wsadmin, it cannot be used with the Liberty profile. The wsadmin tool should be available with a full profile created under the Base version.
You can refer to this link for more information on using wsadmin. You can use the Java Management Extensions (JMX) framework to make use of the wsadmin objects using Java MBeans. Alternatively, you can use the Administration Thin Client to write your own standalone program to remotely connect to and manage WebSphere Application Servers.


text:
Q: Is it possible to replace text by other text in SqlBase? Is it possible to replace text in a SqlBase? I found there is a @REPLACE function but I see it just replaces using positions in the string:
The following expression returns the value 'RALPH':
@REPLACE('RALF', 3, 1, 'PH')

What I need is to replace a substring by another, In Sql Server it's like this:
This returns 'ABA':
SELECT REPLACE('ABC', 'C', 'A')

Thanks!

A: Using the literals in your 'ABC' to 'ABA' example....
Select @REPLACE( 'ABC', @FIND( 'C', 'ABC', 0 ), @LENGTH('C'),  'A' )

Using the literals in your 'RALF' to 'RALPH' example....
Select @REPLACE( 'RALF', @FIND( 'F', 'RALF', 0 ), @LENGTH('F'),  'PH' )


text:
Q: Does adding simple script tasks to SSIS packages drastically reduce performance? I am creating an SSIS package to import CSV file data into a SQL Server table.
Some of the rows in the CSV files will have missing values.
For example, if a row has the format: value1,value2,value3 and value2 is missing,
then it will render as: value1,,value3 in the csv file.
When the above happens (value2 is missing) in my SSIS package, I want NULL to go into the receiving SQL Server column that would hold value2.
I understand that I can add a "Script" task to my SSIS package to apply this rule.  However, I'm concerned that this will drastically reduce the performance of my SSIS package.  I'm not an expert on the inner workings of SSIS/SQL Server, but I'm concerned that this script will cause my script to lose "BULK INSERT" capabilities (and other efficiencies) since the script will have to inspect every row and apply the changes as needed.
Can anyone confirm if adding such a script will cause major performance impacts?  Or does the SSIS/SQL-Server engine run the script on every row and then bulk-insert?  Is there another way I can apply this rule without taking a performance hit?

A: Firstly, you can use script task when required. Script task will be executed only once for each execution of the whole package not for every row. For every row there is another component called script component. When the other regular SSIS tasks are not enough to achieve what you want you can surely use script component. I don't believe it is a performance killer unless you implement it badly.
Secondly, this particular requirement you can simply use Flat File Source task to import your csv file. It will put the value NULL when there is no value. I'm considering this is a valid csv value and each row has correct number of comma for every fields (total field - 1 actually) even if value is empty or null for some fields.


text:
Q: In Apache why does 502 request do not get registed in in access logs My apache with php throws 502 intermitantly. while other response codes do get registered in apache access logs but, 502 requests do not get registered. Why this behaviour?
Does this mean that ec2 instance is closing off the connection before it reaches apache

A: Out of the box, Apache HTTPD has an error log configured. Most of the errors thrown should be showing up in there. I'd bet your 502s are in there...
Should be in the same directory as the access log, but named error_log.


text:
Q: get callstack of c++ application including shared libraries I wrote a small function to create a callstack in c++, using bfd to resolve the addresses. It works fine and I get detailed information (source file and line) for all functions inside the current application, but I get no information what-so-ever about shared libraries that are included in my application.
For example:
callstack:
[0x00002b54229ba6d3 .none] <not sectioned address>
[0x00002b5422927907 .none] <not sectioned address>
[0x00002b54229286d0 .none] <not sectioned address>
[0x00000000004f8608 .text] tensorNetwork.hxx:63 (inside operator())
[0x00000000005528da .text] /usr/include/c++/4.8/functional:2058 (inside _M_invoke)
[0x000000000058231c .text] /usr/include/c++/4.8/functional:2469 (inside std::function<bool ()>::operator()() const)
[0x00000000005806c0 .text] test.cpp:26 (inside ___test(std::pair<std::string, std::function<bool ()> > const&))
[0x0000000000581693 .text] test.cpp:119 (inside main)
[0x00002b5423fdebe5 .none] <not sectioned address>
[0x000000000042c129 .text] /home/abuild/rpmbuild/BUILD/glibc-2.18/csu/../sysdeps/x86_64/start.S:125 (inside _start)

As you can see the symbols of the executable and the static object that got linked with the application are resolved correctly, but the address in the high ranges (eg. 0x00002b54229ba6d3) are not. These addresses are not part of either my application or my shared library file. Further tools like addr2line thus cannot reconstruct the position of that instruction either.
That I cannot resolve these addresses with the bfd tools is somewhat expected as long as I only open the file on disc to get the symbols (what I currently do is abfd = bfd_openr("/proc/self/exe", 0);), so is there a way to get the bfd of the currently running process (thus including the sections of the shared libraries)? If not: how can I get a list of loaded shared objects and their offset and how can I relate these offsets to the shared object files on disc (such that I may load the bfd of the .so file separately)?

A: The glibc adds a function to the dl library called dladdr. With it it is possible to find the filename of the shared object and its loaded memory offset. Loading these object files with bfd_openr allowed me to dump the source-files and lines similar to how addr2line would do it (but still dump some information in case these are not available). For example (notice that the libc6.so does not contain debug symbols on my system and thus only the closest exported symbol is shown):
callstack:
[0x00002b3d744b4340 .text] /homes/numerik/huber/store/code/tensorDev/algorithm/als.hpp:11 (inside xerus::ALSVariant::lapack_solver(xerus::TensorNetwork const&, xerus::Tensor&, xerus::Tensor const&))
[0x0000000000571f0a .text] /usr/include/c++/4.8/functional:2073 (inside std::_Function_handler<void (xerus::TensorNetwork const&, xerus::Tensor&, xerus::Tensor const&), void (*)(xerus::TensorNetwork const&, xerus::Tensor&, xerus::Tensor const&)>::_M_invoke(std::_Any_data const&, xerus::TensorNetwork const&, xerus::Tensor&, xerus::Tensor const&))
[0x00002b3d744ddcba .text] /usr/include/c++/4.8/functional:2469 (inside std::function<void (xerus::TensorNetwork const&, xerus::Tensor&, xerus::Tensor const&)>::operator()(xerus::TensorNetwork const&, xerus::Tensor&, xerus::Tensor const&) const)
[0x00002b3d744b98bc .text] /homes/numerik/huber/store/code/tensorDev/algorithm/als.hpp:117 (inside xerus::ALSVariant::operator()(xerus::TTNetwork<true> const&, xerus::TTNetwork<false>&, xerus::TTNetwork<false> const&, double, std::vector<double, std::allocator<double> >*) const)
[0x0000000000547ac3 .text] /homes/numerik/huber/store/code/tensorDev/unitTests/als.hxx:4 (inside operator())
[0x0000000000554744 .text] /usr/include/c++/4.8/functional:2058 (inside _M_invoke)
[0x00000000005827c8 .text] /usr/include/c++/4.8/functional:2469 (inside std::function<bool ()>::operator()() const)
[0x0000000000580b6c .text] /homes/numerik/huber/store/code/tensorDev/misc/test.cpp:26 (inside ___test(std::pair<std::string, std::function<bool ()> > const&))
[0x0000000000581b3f .text] /homes/numerik/huber/store/code/tensorDev/misc/test.cpp:119 (inside main)
[0x00002b3d75b5dbe5 .text] ??:? (inside __libc_start_main +0x245)
[0x000000000042c269 .text] /home/abuild/rpmbuild/BUILD/glibc-2.18/csu/../sysdeps/x86_64/start.S:125 (inside _start)

In case someone needs the same functionality (I found it annoyingly difficult to create a nice callstack) here is the sourcecode (as part of our library licensed under the AGPLv3):
// Xerus - A General Purpose Tensor Library
// Copyright (C) 2014-2015 Benjamin Huber and Sebastian Wolf.
//
// Xerus is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License,
// or (at your option) any later version.
//
// Xerus is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with Xerus. If not, see <http://www.gnu.org/licenses/>.
//
// For further information on Xerus visit https://libXerus.org
// or contact us at contact@libXerus.org.

std::string demangle_cxa(const std::string &_cxa) {
    int status;
    std::unique_ptr<char[]> realname;
    realname.reset(abi::__cxa_demangle(_cxa.data(), 0, 0, &status));
    if (status != 0) {
        return _cxa;
    }
    if (realname) {
        return std::string(realname.get());
    } else {
        return "";
    }
}

struct bfdResolver {
    struct storedBfd {
        bfd* abfd;
        asymbol** symbols;
        intptr_t offset;
    };
    static std::map<void *, storedBfd> bfds;
    static bool bfd_initialized;

    static std::string resolve(void *address) {
        if (!bfd_initialized) {
            bfd_init();
            bfd_initialized = true;
        }

        std::stringstream res;
        res << "[0x" << std::setw((int)sizeof(void*)*2) << std::setfill('0') << std::hex << (uintptr_t)address;

        // get path and offset of shared object that contains this address
        Dl_info info;
        dladdr(address, &info);
        if (info.dli_fbase == nullptr) {
            return res.str()+" .?] <object to address not found>";
        }

        // load the corresponding bfd file (from file or map)
        if (bfds.count(info.dli_fbase) == 0) {
            std::unique_ptr<storedBfd> newBfd(new storedBfd);
            newBfd->abfd = bfd_openr(info.dli_fname, 0);
            if (!newBfd->abfd) {
                return res.str()+" .?] <could not open object file>";
            }
            bfd_check_format(newBfd->abfd,bfd_object);
            size_t storage_needed = bfd_get_symtab_upper_bound(newBfd->abfd);
            newBfd->symbols =reinterpret_cast<asymbol**>(new char[storage_needed]);
            /*size_t numSymbols = */bfd_canonicalize_symtab(newBfd->abfd, newBfd->symbols );

            newBfd->offset = (intptr_t)info.dli_fbase;

            bfds.insert(std::pair<void *, storedBfd>(info.dli_fbase, *newBfd.release()));
        }

        storedBfd &currBfd = bfds.at(info.dli_fbase);

        asection *section = currBfd.abfd->sections;
        bool relative = section->vma < (uintptr_t)currBfd.offset;
//      std::cout << '\n' << "sections:\n";
        while (section != nullptr) {
            intptr_t offset = ((intptr_t)address) - (relative?currBfd.offset:0) - section->vma;
//          std::cout << section->name << " " << section->id << " file: " << section->filepos << " flags: " << section->flags
//                      << " vma: " << std::hex << section->vma << " - " << std::hex << (section->vma+section->size) << std::endl;

            if (offset < 0 || (size_t)offset > section->size) {
                section = section->next;
                continue;
            }
            res << ' ' << section->name;
            if (!(section->flags | SEC_CODE)) {
                return res.str()+"] <non executable address>";
            }
            // get more info on legal addresses
            const char *file;
            const char *func;
            unsigned line;
            if (bfd_find_nearest_line(currBfd.abfd, section, currBfd.symbols, offset, &file, &func, &line)) {
                if (file) {
                    return res.str()+"] "+std::string(file)+":"+to_string(line)+" (inside "+demangle_cxa(func)+")";
                } else {
                    if (info.dli_saddr) {
                        return res.str()+"] ??:? (inside "+demangle_cxa(func)+" +0x"+std::to_string((intptr_t)address-(intptr_t)info.dli_saddr)+")";
                    } else {
                        return res.str()+"] ??:? (inside "+demangle_cxa(func)+")";
                    }
                }
            } else {
                return res.str()+"] <bfd_error> (inside "+demangle_cxa((info.dli_sname?info.dli_sname:""))+")";
            }
        }
//      std::cout << " ---- sections end ------ " << std::endl;
        return res.str()+" .none] <not sectioned address>";
    }
};

std::map<void *, bfdResolver::storedBfd> bfdResolver::bfds;
bool bfdResolver::bfd_initialized = false;

std::string get_call_stack() {
    const size_t MAX_FRAMES = 100;
    std::vector<void *> stack(MAX_FRAMES);
    int num = backtrace(&stack[0], MAX_FRAMES);
    if (num <= 0) {
        return "Callstack could not be built.";
    }
    stack.resize((size_t) num);
    std::string res;
    //NOTE i=0 corresponds to get_call_stack and is omitted
    for (size_t i=1; i<(size_t)num; ++i) {
        res += bfdResolver::resolve(stack[i]) + '\n';
    }
    return res;
}


text:
Q: MaterializeCSS Icon do not work on navbar in Angular 7 I am trying to use MaterializeCSS Icon to work on the navbar. In the code posted, arrow-drop_down doesn't seem to work. Instead, it shows just a text. Icons render on other pages except in the app.component.html file.
I tried to import the below code directly in the index.html file. Still the same result. Am I missing something here? Also, I cannot figure out a reason why Icons display in any other component apart from app.component.html
Any help would be much appreciated. Thank you. Let me know if more details are required.

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

index.html

<!doctype html>

  <meta charset="utf-8">
  <title>UiCommunity</title>
  <base href="/">

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

  <app-root></app-root>

app.component.html

      Community

          HOME

          EVENTS

          LOGIN

          SIGNUP

          LOGOUT

          PROFILEarrow_drop_down

          Donate

one

two

three

view_modulefour

cloudfive

  <router-outlet></router-outlet>

This is my style.css

/* You can add global styles to this file, and also import other style files */
@import "../node_modules/materialize-css/dist/css/materialize.css";
@import url('https://fonts.googleapis.com/css?family=Philosopher');
@import url('https://fonts.googleapis.com/icon?family=Material+Icons');

A: Can you try to import your styles file directly on your app component ts/js file? If you got all the dependencies installed and it works on other pages, it is probably an importing or wrong path issue.


text:
Q: HipHop Fatal error: Class undefined: mysqli I'm using:
HipHop VM v2.3.3 (rel) (so HHVM-fastcgi)
When I use this: $mysqli = new mysqli("... I get:
HipHop Fatal error: Class undefined: mysqli
What can this mean?
PS:
Php -v = PHP 5.4.24-1+sury.org~precise+1 (cli) (built: Jan 24 2014 11:05:09)

A: The mysqli extension is being worked on. It is expected to land in HHVM 2.5.0 as the 2.4.0 branch has already been cut.
https://github.com/facebook/hhvm/wiki/Release-Schedule

A: Ok according to what I found, mysqli isn't implemented in hiohop, only the older mysql extention is though, you'll need to convert your db calls to use mysql not mysqli.
Also here's an issue link on github


text:
Q: postgresql concurrent queries debug There is a multithreaded application executing some PL/pgsql function. That function produces record inserts to a critically important resource( table ). Also it executes some select/update/etc operations while executing.
The issue is, sometimes we face duplicate( 2-3 ) records each one passed to the function in a parallel thread. And they all are inserted into table as a function execution result, while they should not.
It happens, because both transactions are executed in parallel, and have no idea that the same record is being prepared to insert in a parallel transaction.
The table is critically important and all kinds of LOCK TABLE are extremely not welcomed (LOCK FOR SHARE MODE meanwhile gave as some useful experience).
So, the question is, is there any best practice how to organize PL/pgsql function working with a critical resource (table) to be executed by multithreaded app and producing no harmful locks on this resource?
PS. I know, that some thread partinioning by record.ID in the app is a possible solution. But I.m interested in a PL/pgsql solution first of all.

A: Sometimes you can use a advisory locks - http://www.postgresql.org/docs/current/static/explicit-locking.html .With these locks some subset of numbers. I used it for synchronization of parallel inserts with success.


text:
Q: when jQuery FadeOut an element, which attribute changes in css? When we fade an element in or out, which CSS property is changing? Is it visibility, or display?
I want to write code with a if clause condition that says (pseudo):
when the div is visible, do something
Example:
if ( $('#div').is(':visible') ) {
  do something;
}

...but I'm not sure which property or attribute in the CSS has changed.

A: fadeIn() will change the opacity from 0 to 1 (assuming the element is hidden from the start).
display will be set to block once the animation is finished (400ms by default).
fadeOut() does the opposite.

A: As far as I know it will change the opacity property, not the display or visibility properties, which will work cross-browser so if it's firefox -moz-opacity will change etc.
http://api.jquery.com/fadeIn/

A: When you fadeOut() any element, its opacity is toggled from 1 to 0 and the display property is set to none. The opposite happens in fadeIn() method (display property is set to block.)

A: The opacity.
You can test if by your self too. If you set a long fadeOut (ie: 10seconds), then you can open your browser console and check the values as they change.
Add the following code in your HTML document:
HTML

CSS
#testItem
{
    display : block;
    width   : 100px;
    height  : 100px;
    background: #0AF;
}

JavaScript/jQuery
jQuery(document).ready(
    function(e)
    {
        $('#testItem').click(
            function(e)
            {
                $(this).fadeOut(10000);
            }
        );
    }
);

Then, open the document with Chrome and right click the div element we just created. From the menu that open choose the "Inspect Element" (If your browser is in other language, it should be the last option of the menu). Then, the Chrome console should be open and it should have marked the .
Finally, click the div element and you will see what hapens when you fadeOut/In some element.


text:
Q: In Android, how to render a video with Filters by VidEffects I can successfully apply filters to a recorded video in my app by using VidEffects (https://github.com/krazykira/VidEffects). The problem is that such plugin doesn't render a filtered video, anyway I'm trying to apply permanent video effects by using this class:
public class VideoProcessing extends AsyncTask {
    private final File myDirectory;
    private FFmpegFrameGrabber VIDEO_GRABBER;
    private FFmpegFrameRecorder videoRecorder;
    File file;
    int totalLength;
    private Context mContext;
    private FFmpegFrameFilter filter;

    VideoProcessing(Context context, String path) {
        mContext = context;
        file = new File(path);
        VIDEO_GRABBER = new FFmpegFrameGrabber(file);
        myDirectory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/_Pikky-Edited-Video/");
        Log.i(Configurations.TAG, "VIDEO PROCESSING PATH: " + myDirectory);

        if (!myDirectory.exists()) { myDirectory.mkdirs(); }
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Object doInBackground(Object[] params) {
        Log.i(Configurations.TAG, "DO IN BACKGROUND: " + params);
        Frame tempVideoFrame;
        try {
            VIDEO_GRABBER.start();
            initVideoRecorder(myDirectory + "/video" + System.currentTimeMillis() + ".mp4");
            filter.start();
            while (VIDEO_GRABBER.grab() != null) {
                tempVideoFrame = VIDEO_GRABBER.grabImage();
                if (tempVideoFrame != null) {
                    filter.push(tempVideoFrame);
                    tempVideoFrame = filter.pull();
                    videoRecorder.record(tempVideoFrame);
                }
            }
            filter.stop();
            videoRecorder.stop();
            videoRecorder.release();
            VIDEO_GRABBER.stop();
            VIDEO_GRABBER.release();

            Log.i(Configurations.TAG, "VIDEO GRABBER STOP");

        } catch (FrameGrabber.Exception | FrameRecorder.Exception | FrameFilter.Exception e) { e.printStackTrace(); }
        return null;
    }

    @Override
    protected void onPostExecute(Object o) {
        super.onPostExecute(o);
        Log.i(Configurations.TAG, "ON POST EXECUTED: " + o);
    }

    private void initVideoRecorder(String path) {
        try {
            // FFmpeg effect/filter that will be applied
            filter = new FFmpegFrameFilter("colorchannelmixer=.393:.769:.189:0:.349:.686:.168:0:.272:.534:.131", VIDEO_GRABBER.getImageWidth(), VIDEO_GRABBER.getImageHeight());
            videoRecorder = FFmpegFrameRecorder.createDefault(path, VIDEO_GRABBER.getImageWidth(), VIDEO_GRABBER.getImageHeight());
            videoRecorder.start();
            Log.i(Configurations.TAG, "VIDEO PROCESSING - VIDEO RECORDER START");

        } catch (FrameRecorder.Exception e) { e.printStackTrace(); }
    }
}

This class gets called in a switch case from my EditVideo activity as follows - where surfaceView is a custom GLSurfaceView:
 case 2: surfaceView.init(mediaPlayer, new InvertColorsEffect());
                            new VideoProcessing(EditVideo.this, Configurations.videoToShareURL);
                        break;

Anyway, it seems that the doInBackground function doesn't get called anywhere, since the app only creates the custom folder in my Pictures directory (_Pikky-Edited-Video), prints its path in the Logcat - see Log.i(Configurations.TAG, "VIDEO PROCESSING PATH: " + myDirectory); and that's it, the video preview keeps playing in my Activity - that's because I've set my MediaPlayer's looping as true - but the other functions of my VideoProcessing class don't get called, initVideoRecorder() either.
This is my build.gradle, all necessary dependencies have been downloaded:
    implementation 'com.writingminds:FFmpegAndroid:0.3.2'
    implementation group: 'org.bytedeco', name: 'javacv', version: '1.1'
    implementation group: 'org.bytedeco.javacpp-presets', name: 'opencv', version: '3.0.0-1.1', classifier: 'android-arm'
    implementation group: 'org.bytedeco.javacpp-presets', name: 'ffmpeg', version: '2.8.1-1.1', classifier: 'android-arm'

I am open also to slternative solutions to render a video with filters.

A: SOLUTION:
I've found this awesome and easy to implement framework: https://github.com/MasayukiSuda/Mp4Composer-android
Just add its dependency in build.gradle:
dependencies {
        // jCenter
        implementation 'com.daasuu:Mp4Composer-android:0.1.6'
    }

And use this code to export your filtered video based on each effect:
renderVideoIntoMp4(myVideoURL, new GlInvertFilter()); // add the Filter you want

void renderVideoIntoMp4(String filePath, GlFilter filter) {
    tempVideoPath = getVideoFilePath();
            //Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/temp_video.mp4";

    new Mp4Composer(filePath, tempVideoPath)
            // .rotation(Rotation.ROTATION_270)
            //.size(720, 1280)
            .fillMode(FillMode.PRESERVE_ASPECT_FIT)
            .filter(filter)
            .mute(false)
            .flipHorizontal(false)
            .flipVertical(false)
            .listener(new Mp4Composer.Listener() {
                @Override
                public void onProgress(double progress) {
                    Log.i(Configurations.TAG, "SAVING PROGRESS: " + progress);
                }

                @Override
                public void onCompleted() {
                    Log.i(Configurations.TAG, "onCompleted()");
                    exportMp4ToGallery(getApplicationContext(), tempVideoPath);
                    Log.i(Configurations.TAG, "SAVED VIDEO PATH: " + tempVideoPath);

                    File file = new File(tempVideoPath);
                    file.delete();
                }

                @Override
                public void onCanceled() {

                }

                @Override
                public void onFailed(Exception e) {
                    Log.i(Configurations.TAG, "onFailed(): " + e.getMessage());
                }
            })
            .start();
}

public static void exportMp4ToGallery(Context context, String filePath) {
    final ContentValues values = new ContentValues(2);
    values.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4");
    values.put(MediaStore.Video.Media.DATA, filePath);
    context.getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI,
            values);
    context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
            Uri.parse("file://" + filePath)));
}

public File getAndroidMoviesFolder() {
    return Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
}

public String getVideoFilePath() {
    return getAndroidMoviesFolder().getAbsolutePath() + "/temp_video.mp4";
}


text:
Q: Passing a parameter in the header (XML RPC) I'm trying to set up a server status for the MMORPG Champions Online. I got some basic information from the web master and this is all he told me:

*

*XML-RPC call to server: http://www.champions-online.com/xmlrpc.php

*function name:  wgsLauncher.getServerStatus

*Parameter (language): en-US

Now, I found a nice example to start with here, and I ended up with this code:
<?php
 ini_set('display_errors', 1);
 error_reporting(E_ALL);

# Using the XML-RPC extension to format the XML package
$request = xmlrpc_encode_request("wgsLauncher.getServerStatus", "<param><value><string>en-US</string></value></param>", null );

# Using the cURL extension to send it off,
# first creating a custom header block
$header[] = "Host: http://www.champions-online.com:80/";
$header[] = "Content-type: text/xml";
$header[] = "Content-length: ".strlen($request) . "\r\n";
$header[] = $request;

$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, "http://www.champions-online.com/xmlrpc.php"); # URL to post to
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 ); # return into a variable
curl_setopt( $ch, CURLOPT_HTTPHEADER, $header ); # custom headers, see above
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, 'POST' ); # This POST is special, and uses its specified Content-type
$result = curl_exec( $ch ); # run!
curl_close($ch);

echo $result;
?>

But I'm getting a "400 Bad Request" error. I'm new to XML RPC and I barely know php, so I'm at a loss. The examples from the php site show how to use an array as a parameter, but nothing else.
I obtained the parameter string <param><value><string>en-US</string></value></param> from this XMLRPC Debugger (very nice btw). I entered the parameter I needed in the "payload" box and this was the output.
So, I would appreciate any help on how to pass this parameter to the header.
Note: My host supports xmlrpc but it seems the function "xmlrpc_client" doesn't exist.

Update: The web master replied with this information, but it's still not working... it's getting to the point I may just scrape the status off the page.
$request = xmlrpc_encode_request("wgsLauncher.getServerStatus", "en-US" );

A: Ok, I finally figured out my answer... It seemed to be a problem in the header, because it worked when I changed the cURL code to match the code I found it on this site. The post is about how to remotely post to wordpress using XMLRPC in php.
This is the code I ended up with:
<?php

// ini_set('display_errors', 1);
// error_reporting(E_ALL);

# Using the XML-RPC extension to format the XML package
$request = xmlrpc_encode_request( "wgsLauncher.getServerStatus", "en-US" );

$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $request);
curl_setopt($ch, CURLOPT_URL, "http://www.champions-online.com/xmlrpc.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 1);
$result = curl_exec($ch);
curl_close($ch);

$method = null;
$params = xmlrpc_decode_request($result, &$method);

# server status result = true (up) or false (down)
$status = ($params['status']) ? 'up' : 'down';
$notice = ($params['notice'] == "") ? "" : "Notice: " + $params['notice'];
echo "Server Status: " . $status . "<br>";
echo $notice;

?>


text:
Q: Error inflating class fragment occurs when marking location (lat and longitude from sql) onto the google map I encountered error inflating class fragment when I tried to mark the location (lat and longitude from SQL) onto the google map for the android java app. In MapsActivity.java, it is already using onCreate, not onCreateView. Do I have to change it or is there any way I can solve the error?
MapsActivity.java
package com.example.paddy_disease_tracker;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.widget.Toast;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;

import com.example.paddy_disease_tracker.databinding.ActivityMapsBinding;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    String query;
    Statement st;
    ResultSet rs;
    Toast toast;
    String disease;
    float lat,lon;
    private GoogleMap mMap;
    private ActivityMapsBinding binding;
    LatLng centerLocation,place;
    Connection connect;
    ArrayList<LatLng> places=new ArrayList<LatLng>();
    ArrayList<String> dis=new ArrayList<String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityMapsBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        centerLocation=new LatLng(6.0,101);

        try {
            ConnectionHelper connectionHelper = new ConnectionHelper();
            connect = connectionHelper.connectionclass();

            if (connect != null) {
                query = "Select * from Disease";
                st = connect.createStatement();
                rs = st.executeQuery(query);
                while (rs.next()) {
                    disease=rs.getString(3);
                    lat=rs.getFloat(4);
                    lon=rs.getFloat(5);
                    places.add(new LatLng(lat,lon));
                    dis.add(disease);
                }
            } else {
                toast=Toast.makeText(getApplicationContext(),"Check Connection",Toast.LENGTH_LONG);
                toast.show();
            }
        }catch(Exception e){
            toast=Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_LONG);
            toast.show();
        }
    }

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {

        mMap = googleMap;
        enableMyLocation();
        // Add a marker in Sydney and move the camera
        for(int i=0; i<places.size();i++){
            mMap.addMarker(new MarkerOptions().position(places.get(i)).title(dis.get(i)+" found"));
        }
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(centerLocation,6));
    }

    private void enableMyLocation() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            if (mMap != null) {
                mMap.setMyLocationEnabled(true);
            }
        } else {
            String []perms={"android.permission.ACCESS_FINE_LOCATION"};
            // Permission to access the location is missing. Show rationale and request permission
            ActivityCompat.requestPermissions(this,perms,200);

        }
    }
}


text:
Q: Incoming Remote Desktop Connection causes my system to power cycle Using Remote Desktop Connection (from a laptop), I can connect to my desktop system and reach the Log On to Windows dialog. When I enter my account info and attempt to log on, the desktop system immediately power cycles. It doesn't go through any shutdown process, so I would guess some severe system error is causing it to reboot. Has anyone seen something like this before?
EDIT:
The above behavior occurs when I'm logged into the same account. I tried logging out (on the desktop machine) before connecting and the desktop system froze instead of power cycling.
System:
Running XP Pro Version 2002 Service Pack 3
NVIDIA Quadro FX 3450/4000 SDI

A: Problems like this are sometimes caused by buggy video drivers in the remote machine. It's possible that the remote machine (desktop) blue-screens and that causes the automatic restart.
You could try updating your desktop's graphics driver.

A: I know that, for this case, there is a solution, but i would like to share my case.
I have many Virtual Machines, Im using VMware Workstation 9 in many hosts; only the VMs with Windows XP rebooted when a RDP connection was tried.
Here we are many users, and not all of us where using the same resolution, so finally i found that was the cause, the driver in the guests XP machines, I upgraded it to the latest on the guests, but no solution
So here is an alternative solution:
In XP guest VM, run gpedit.msc, then go to
Computer configuration > Administrative Templates > Windows Components >Terminal Services
There in the right window select "Limit maximum color depth" or something like that (im using Spanish Language) and enable this feature, I selected 15 bits.
Now, it does not matter if someone select 15, 16, 24 or 32 bits, the guest, in this case server, will connect the clients to 15 bits
Hope this helps


text:
Q: mpirun breaks out the while-loop in bash I'm trying to run a batch script with mpirun nested in a while-loop, like this
while read line
do
    mpirun -np 4 myexec > /dev/null
done < case.txt

But this script only returns one loop result. Whenever the executable is done the loop is broken.
I also tried to run the code without parallel and it works fine.
If I replace the while read line with a normal while-loop, say, while [ $count -le 9 ], it also works.
For-loop is Okay as well.
I just cannot figure it out. Hope somebody could tell me why this happens.

A: Looks like mpirun reads from stdin, which is case.txt in this case. That would read all lines from the file during the first run of the loop. On the next attempt of read the file has been fully read already and that's why the loop ends.
Try to assign /dev/null to its stdin:
while read line
do
    mpirun -np 4 myexec > /dev/null < /dev/null
done < case.txt


text:
Q: How to use use same configuration between .NET Framework, .NET Standard, and .NET Core project? Since the ConfigurationManager doesn't exist in .NET Standard, what is the best way to retrieve application settings for the executing assembly, whether it be a web.config or an appSettings.{env}.json, within a .NET standard class library?
We have three projects:

*

*ASP.NET Core Web App (1.1)

*ASP.NET Web App (4.6.1 )

*.NET Standard Class Library (1.4) -> Referenced by both projects

In the .NET Standard class lib, we have a URL which needs to change based on the environment it's deployed to.
This is fine for the .NET Core app, we simply add the URLs to the appropriate appSettings.{env}.json file, add the appropriate values to the DI container, then use the Microsoft.Extensions.Options library to retrieve the configuration.
However, we also need to call the library from our .NET Framework 4.6.1 application, but since there is no method (at least none that I could find) to retrieve the values from a web.config file, we don't have a good way to set the URL within the class library.
We've gotten around this for now by making the URL variable static and setting its value from within the Application_Start() method of each .NET Framework project we reference it from, we determine which environment it is via an appSetting key we added to each web.config, then manually set the URL based on the environment.
Is there a more robust way to handle retrieving appSettings values from both a .NET Core and .NET Framework application within a .NET Standard class library?
Preferably where we can set the value solely within the class library.

A: You should read the value from configuration before calling your library, and pass it by parameter, either into a method or constructor.
In general, library code shouldn't depend on side effects from the configuration of its host environment.  Doing so makes it very difficult to reuse code, or to test effectively.


text:
Q: Styling Sherlock Action Bar drop down items I've been trying for a while to style the items in a drop down list I added to the Action Bar, but I can't come up with the right code.
I tried looking into the abs__styles.xml and abs__themes.xml in the SherlockActionBar project but none of the items I added to my project worked.
The way I'm creating the menus is the following:
@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Sharing icons
        SubMenu submenu = menu.addSubMenu(null);
        submenu.add(getResources().getString(R.string.twitter));
        submenu.add(getResources().getString(R.string.facebook));
        submenu.add(getResources().getString(R.string.email));

        // Share button itself
        MenuItem ShareButton = submenu.getItem();
        ShareButton.setIcon(R.drawable.icon_share_triangle);
        ShareButton.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);

        // Twitter submenu button
        MenuItem TwitterItem = submenu.getItem(0);
        TwitterItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
        TwitterItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
            public boolean onMenuItemClick(MenuItem item) {
                setShareTwitterIntent();
                return true;
            }
        });
...
}

I also tried taking a look at this post using the following code, but still no luck:
<!-- style the list navigation -->
<style name="MyDropDownNav" parent="android:style/Widget.Holo.Light.Spinner.DropDown.ActionBar">
    <item name="android:background">@drawable/ad_spinner_background_holo_light</item>
    <item name="android:popupBackground">@drawable/ad_menu_dropdown_panel_holo_light</item>
    <item name="android:dropDownSelector">@drawable/ad_selectable_background</item>
</style>

I just need to change the background color of the items in the drop down list.
Thanks a lot for your help!
EDIT:
I also tried this, and it still doesn't work:
<item name="android:actionDropDownStyle">@style/MyApp.DropDownNav</item>
<item name="actionDropDownStyle">@style/MyApp.DropDownNav</item>
...
<style name="MyApp.DropDownNav" parent="Widget.Sherlock.Light.Spinner.DropDown.ActionBar">
        <item name="android:background">@drawable/sharing_panel</item>
</style>

A: To change the background drawable of the menu item in Sherlock Action Bar (v4.1.0), use the following:
<style name="My_Theme" parent="Theme.Sherlock">
  <item name="android:popupMenuStyle">@style/MyApp.PopupMenuStyle</item>
  <item name="popupMenuStyle">@style/MyApp.PopupMenuStyle</item>
</style>

<style name="MyApp.PopupMenuStyle" parent="Widget.Sherlock.ListPopupWindow">
  <item name="android:popupBackground">@drawable/menu_item_background</item>
</style>

hope this helps.

A: i used this, and its work for me
<style name="MyDropDownItem" parent="Widget.Sherlock.Spinner.DropDown.ActionBar">
    <item name="android:background">@drawable/spinner_background_holo_light</item>
    <item name="android:popupBackground">@color/actionbar_normal</item>
    <item name="android:dropDownSelector">@drawable/list_selector_holo_light</item>
</style>

<style name="myTheme" parent="@style/Theme.Sherlock">
    ...
    ...
    ...
    <item name="android:actionDropDownStyle">@style/MyDropDownItem</item>
    <item name="actionDropDownStyle">@style/MyDropDownItem</item>
</style>

where,
"spinner_background_holo_light" and "list_selector_holo_light" are selectors
and
"actionbar_normal" drawable (image OR color)

A: I had the same problem and after a lot of head scratching - the sort of scratching like a dog with a bad case of fleas - I got it to work. This is with ABS 4.1 (90). The below code will change the background colour of the drop down item.
SomeActivity.java
Context context = ab.getThemedContext();
ArrayAdapter<CharSequence> list = ArrayAdapter.createFromResource(
    context, R.array.map_activity_view_list,
    R.layout.sherlock_spinner_item);
list.setDropDownViewResource(R.layout.sherlock_spinner_dropdown_item);

Note: You use R.layout.sherlock_spinner_item for the createFromResource and R.layout.sherlock_spinner_dropdown_item for the setDropDownViewResource.
This is what appears in the sample in the ABS source:
https://github.com/JakeWharton/ActionBarSherlock/blob/master/samples/demos/src/com/actionbarsherlock/sample/demos/ListNavigation.java
This is because the unselected dropdown in the action bar when is the sherlock_spinner_item layout and the actual dropdown items use the sherlock_spinner_dropdown_item layout which means the styles are different for each:

*

*sherlock_spinner_item

*

*android:spinnerItemStyle

*spinnerItemStyle

*sherlock_spinner_dropdown_item

*

*android:spinnerDropDownItemStyle

*spinnerDropDownItemStyle

Remember both styles are needed - android: prefixed styles for for the native ICS ActionBar and the style without the android: prefix is for the AcrionBarSherlock style on devices older than ICS.
res/values/styles.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="Theme.MyApp" parent="Theme.Sherlock.Light">
        <!--  the text when loading -->
        <!--
        <item name="actionBarStyle">@style/Widget.MyApp.ActionBar</item>
        <item name="android:actionBarStyle">@style/Widget.MyApp.ActionBar</item>
        -->

        <!-- the dropdown items -->
        <item name="android:spinnerDropDownItemStyle">@style/MyApp.Widget.Holo.DropDownItem</item>
        <item name="spinnerDropDownItemStyle">@style/MyApp.Widget.Holo.DropDownItem</item>

        <!--  the action bar dropdown menu item -->
        <!--
        <item name="android:spinnerItemStyle">@style/MyApp.Widget.Holo.SpinnerItem</item>
        <item name="spinnerItemStyle">@style/MyApp.Widget.Holo.SpinnerItem</item>
        -->
    </style>

    <style name="Widget.MyApp.ActionBar" parent="Widget.Sherlock.Light.ActionBar">
        <item name="titleTextStyle">@style/Widget.MyApp.TitleTextStyle</item>
        <item name="android:titleTextStyle">@style/Widget.MyApp.TitleTextStyle</item>
    </style>

   <style name="Widget.MyApp.TitleTextStyle" parent="TextAppearance.Sherlock.Widget.ActionBar.Title">
    <item name="android:textColor">@color/orange</item>
    </style>

   <style name="MyApp.Widget.Holo.DropDownItem" parent="Widget.Sherlock.Light.DropDownItem.Spinner">
       <item name="android:background">@color/orange</item>
    </style>

   <style name="MyApp.Widget.Holo.SpinnerItem" parent="Widget.Sherlock.TextView.SpinnerItem">
       <item name="android:background">@color/orange</item>
    </style>

</resources>

res/values/color.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>

 <color name="orange">#ffEf4f1f</color>

</resources>

Please mark as answer if this solves it for you. Thanks!
Links:
Browse styles:
https://github.com/JakeWharton/ActionBarSherlock/blob/master/actionbarsherlock/res/values/abs__styles.xml
Browse themes:
https://github.com/JakeWharton/ActionBarSherlock/blob/master/actionbarsherlock/res/values/abs__themes.xml

A: I am not sure if this question has been answered in a satisfactory way, but I ran into this problem and did not find an answer that I liked.  It seemed like I had a pretty standard configuration of ActionBarSherLock and using the drop down navigation gave me some bad results out of the box.  Black text on a black background.  I want to make the text white.  Here is how I accomplished it:
For starters, my application's base theme extends Theme.Sherlock:
<style name="AppBaseTheme" parent="Theme.Sherlock">
</style>

My actual application theme AppTheme extends my base (I can't remember why I did this at the time, it is likely unnecessary).
<style name="AppTheme" parent="AppBaseTheme">
    <item name="spinnerItemStyle">@style/SpinnerItemStyle</item>
    <item name="android:spinnerItemStyle">@style/SpinnerItemStyle</item>
</style>

I needed to override Widget.Sherlock.TextView.SpinnerItem and so as below:
<style name="SpinnerItemStyle" parent="Widget.Sherlock.TextView.SpinnerItem">
<item name="android:textAppearance">@style/TextAppearance.MySpinnerItem</item>
</style>

The reason for doing this was to access the TextApperance widget: TextAppearance.Sherlock.Widget.TextView.SpinnerItem
This was overridden as below:
<style name="TextAppearance.MySpinnerItem"    parent="TextAppearance.Sherlock.Widget.TextView.SpinnerItem">
  <item name="android:textColor">#FFFFFF</item>
  <item name="android:textSize">16sp</item>
  <item name="android:textStyle">normal</item>
</style>

My biggest mistake in tying to get the text in trying to fix this was trying to directly set textColor in the overridden SpinnerItemStyle.  Since it used a textAppearance widget, it was just not working.
Then my code to make this work looks like this (in my activity's onCreate method):
SpinnerAdapter spinnerAdapter = ArrayAdapter.createFromResource(this,
            R.array.call_type, R.layout.sherlock_spinner_item);

OnNavigationListener onNavigationListener = new OnNavigationListener() {
        // Get the same strings provided for the drop-down's ArrayAdapter
        String[] strings = getResources().getStringArray(R.array.call_type);

        @Override
        public boolean onNavigationItemSelected(int position, long itemId) {
            String filter = strings[position];
            filterCalls(filter);
            return true;
        }
    };

ActionBar actionBar = getSupportActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
    actionBar.setListNavigationCallbacks(spinnerAdapter,
            onNavigationListener);

This allowed my to change the color of the text, on the spinner drop down using ActionBarSherlock.

A: ActionBarSherlock requires you to use one of its 3 themes. You can extend them though, and override the dropdown style, like this:
<style name="MySherlockLightTheme" parent="Theme.Sherlock.Light">
   <item name="actionDropDownStyle">@style/MyDropDownNav</item>
</style>

This is assuming you want the holo light theme, and your dropdown style is MyDropDownDav.
Then in your code, you just switch to use your theme (either in the manifest, or do it in Activity's onCreate).


text:
Q: write one's own little ftp server I'd like to code an ftp server in java, just for practice. What I would need to do is have a client send the ftp commands and then "parse" those commands on the server and translate them to file system access, right? I don't want anything fancy, just implement some basic commands.
So when the client sends "cd directoryname" I check the substrings before and after the space and then get a list of the files from the specified directory. Something along those lines, right?
I looked a bit at this source code here: http://svn.apache.org/viewvc/mina/asyncweb/trunk/server/src/main/java/org/apache/asyncweb/server/ but couldn't find any< code that reads in the ftp commands...
Am I going in the right direction with this or am I completely off?


text:
Q: Save changes to Visualforce page in detail page I have a Visualforce page that has been added to the detail layout. When I make changes to files in the visualforce page the save button is not enabled. It does happen for any other field added to the layout be using the drap and drop method.
I am using the standar controller with no extension and the following code for each field:
 <apex:outputField value="{!Installation__c.Serial_Number_1__c}">
   <apex:inlineEditSupport event="ondblclick"/>
 </apex:outputField>

I know I can add a save button but that is not what I need.


text:
Q: How do I vertically center my li's in my ul in my header? I want to vertically center my li's in my header's ul.
You can check out the JSBin here: http://jsbin.com/xeven/1/edit
I don't see what I'm doing wrong here? Can someone help me?
I would also like to center the whole thing... Thanks!

A: Change your .header ul li rule to:
.header ul li {
  display:inline-block;
  vertical-align:middle;
  text-transform: uppercase;
  margin-left: 35px;
  letter-spacing: 3px;
}

jsFiddle example
I removed the float rule and changed the display type from table-cell to inline-block.

A: You can create an inner header with fixed width and center it.
This way the background with still fill the 100% width of the screen but you will be able to center the menu.
HTML

BASE

home

products

features

contact

CSS
.inner-header{
  margin:0 auto;
  width:400px;
}

http://jsbin.com/xeven/3/edit


text:
Q: Cloud Firestore multiple documents and unknown collection path I am using Firestore database with real time updates on web javascript app.
The purpose is to show sensor data (temperature, ultrasonic, etc) for each existent device:
devices/devices01/sensors/sensor01/value:10
devices/devices01/sensors/sensor02/value:15
devices/devices02/sensors/sensor01/value:30
devices/devices03/sensors/sensor01/value:20

The user can have a list of devices it wants to get sensors data real-time updated.
users/userA/devices/{device01:true,device03:true}
users/userB/devices/{device02:true}

I don't know how to query and get the snapshots when:
 1. Use device name from a list of devices
 2. Get all sensors on change
Of course, this doesn't work:
db.collection("devices").doc("[device01,device03]").collection("pins").doc("*").get()

Any suggestion?

A: You need to identify each document individually and attach a listener to them all.  There are no list-like or wildcard methods to refer to documents.
The only way you can listen to multiple documents at once is when you're able to identify them all with a query.  The only kind of query that might help you here is one that identifies all the documents under pins.  A CollectionReference is a query that listens to all the documents in that collection.


text:
Q: Newell's Method to Calculate Plane Equation of Concave Polygon - Improvements? 3 points are needed to define a plane.  Newell's method is known to fail if the 3 points are chosen around a concave corner - the normal of the resulting plane will point in the direction opposite to the expected one.
Are there any improvements to Newell's method that help in choosing a valid starting point?  Or is there an alternative algorithm that doesn't have this issue?

A: Since your only interest in the plane is whether a given point is "deeper" or "closer" than it, I suppose you expect the normal of the plane to point towards the viewpoint (or away from it, depending on your convention). So just calculate the dot-product of the normal and the vector from the viewpoint to one of the three points, and look at its sign; if it's positive when you generally expect negative (or vice-versa), then reverse the normal.

A: Just came across this after some Googling for Newell's Plane algorithm. I'm also interested in using the algorithm, but my reading of various literature leaves me thinking that it is the "three point" method that fails on the concave corner case, while Newell's Method will work correctly. Here is the relevant passage:

This technique, first suggested by Newell (Sutherland et al., 1974),
  works for concave polygons and polygons containing collinear vertices,
  as well as for nonplanar polygons, e.g., polygons resulting from
  perturbed vertex locations...

Newell's method may seem inefficient for planar polygons, since it
  uses all the vertices of a polygon when, in fact, only three
  points are needed to define a plane. It should be noted, though, that
  for arbitrary planar polygons, these three points must be chosen very
  carefully:

*

*Three points uniquely define a plane if and only if they are not
  collinear; and

*if the three points are chosen around a "concave" corner, the normal
  of the resulting plane will point in the direction opposite to the
  expected one.
Checking for the properties would reduce the efficiency of the
  three-point method as well as making its coding rather inelegant. A
  good strategy may be that of using the three-point method for polygons
  that are already known to be planar and strictly convex (no collinear
  vertices,) and using Newell's method for the rest.

Source: Filippo Tampieri. "Newell's Method for Computing the Plane Equation of a Polygon". In Graphics Gems III, Academic Press, 1992, pp. 231–232.


text:
Q: c++ pointer assignment operator overload(not just object assignment but pointer assignment) Is there a way to overload the pointer assignment operator?
e.g.
overload pointer assignment operator for class A when
A *x, *y;
x = y;

A: No, this is not possible. Pointer types are scalar types, but overloading operators requires a non-scalar parameter. In particular ([over.oper]p6):

An operator function shall either be a non-static member function or be a non-member function that has
  at least one parameter whose type is a class, a reference to a class, an enumeration, or a reference to an
  enumeration.

If you had a binary operator where one parameter was a user-defined type and the other a pointer, that would work, but in the situation you're asking about, both operands are pointers.

A: No, because overloaded operators are only considered when at least one argument has a class or enum type.  (A pointer to class type is considered a fundamental type and does not count as a "class type" itself.)
C++ Standard [over.match.oper]/1-2:

If no operand of an operator in an expression has a type that is a class or an enumeration, the operator is assumed to be a built-in operator and interpreted according to Clause [expr].
If either operand has a type that is a class or enumeration, a user-defined operator function might be declared that implements this operator or a user-defined conversion can be necessary to convert the operand to a type that is appropriate for a built-in operator. In this case, overload resolution is used to determine which operator function or built-in operator is to be invoked to implement the operator.

(Though you might instead encourage users of A to use some smart pointer-like class APtr instead of raw pointers to get the desired behavior.)

A: There is no "pointer assignment operator". This is the assignment operator and you are using it with pointer operands.
It's not possible to overload an operator unless at least one operand has class or enum type. (Pointer type is not class type).


text:
Q: How to override equals() in google app engine data model type? I'm using the Python libraries for Google App Engine.  How can I override the equals() method on a class so that it judges equality on the user_id field of the following class:
class UserAccount(db.Model):
    # compare all equality tests on user_id
    user = db.UserProperty(required=True)
    user_id = db.StringProperty(required=True)
    first_name = db.StringProperty()
    last_name = db.StringProperty()
    notifications = db.ListProperty(db.Key)

Right now, I'm doing equalty by getting a UserAccount object and doing user1.user_id == user2.user_id.  Is there a way I can override it so that 'user1 == user2' will look at only the 'user_id' fields?
Thanks in advance

A: Override operators __eq__ (==) and __ne__ (!=)
e.g.
class UserAccount(db.Model):

    def __eq__(self, other):
        if isinstance(other, UserAccount):
            return self.user_id == other.user_id
        return NotImplemented

    def __ne__(self, other):
        result = self.__eq__(other)
        if result is NotImplemented:
            return result
        return not result


text:
Q: Tell me please about the 301 redirect Nginx if there is a GET parameter Tell me please.
There is a link like: mysite.com/blablabla/efefefe.html/? Param_a = 1
How to make 301 redirects to mysite.com / blablabla / efefefe.html /
Thanks a lot

A: Use a question mark after $uri - $uri?. Nginx will remove all get parameters.


text:
Q: Limit Points of A Set? I have the following two sets:
$A = \{{\frac{n}{n+1},\  n = 1,2,3..}\}$

$B = \{\frac{-n+2}{n+1},\  n = 0,1,2..\}$
And I need to find the limit points of $A$ and $B$. For each, I know that if I can find a convergent subsequence that converges to a value in these sets that is not included in their respective set definitions. Is this the proper thought process?
For $A$, the set converges to 1, despite 1 not being in the set.
For $B$, the set converges to -1, despite 1 not being in the set.


text:
Q: Работа с LocalStorage из фреймворка gin Есть необходимость работать с LocalStorage из back.
Вообще для проекта использую gin.
Перебрал кучку библиотек, похожа на рабочую: github.com/gopherjs/gopherjs/js
Пытаюсь получить
obj := js.Global.Get("UID")

И что то у меня падает паника.
Возможно требуется как то подключить ее к gin?
Либо посоветуйте как мне получить данные из LocalStorage в golang.

*

*Таблица: UID;

*Переменная: UID_VAR;


text:
Q: Having jQuery UI Selectable both as grid and a list in a table I have prepared a jsFiddle for my question -

I am trying to have jQuery UI Selectable in a table with yellow header and footer rows. Once as a grid of numbers in the left cell and then as a list of letters in the right cell.
Also I am trying to have the table occupy both 100% of browser width and height.
That is why I have assigned CSS-properties width: 100% and height: 100vh to the table and overflow-y: scroll to the both selectables.
For some reason however the right scroll is not working, i.e. the whole list of letters is displayed and thus blows up the table height.
TLDR:

*

*Numbers/Letters lists should have same height and be scrollable

*Yellow header/footer should be visible at top/bottom of browser window

Here is my code -
Javascript:
  $(function() {
    $("#selectable1").selectable();
    $("#selectable2").selectable();
  });

CSS:

    Header1

1

2

3

4

5

6

7

8

9

10

11

12

A

B

C

D

E

F

G

H

I

J

    Footer1

CSS:
table {
  width: 100%;
  height: 100vh;
}

#selectable1 {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow-y: scroll;
}

#selectable2 {
  list-style-type: none;
  margin: 0;
  padding: 0;
  width: 100px;
  overflow-y: scroll; /* WHY IS THIS NOT WORKING? */
}

#selectable1 li,
#selectable2 li {
  margin: 3px;
  padding: 1px;
  float: left;
  width: 100px;
  height: 80px;
  font-size: 4em;
  text-align: center;
}

The background for my question is that I am trying to create a card game with playing tables on the left and list of players in the lobby on the right -

A: Consider the following: https://jsfiddle.net/Twisty/uro3b2ps/17/
HTML

Header1

1

2

3

4

5

6

7

8

9

10

11

12

A

B

C

D

E

F

G

H

I

J

    Footer1

CSS
.header,
.footer {
  width: 100%;
  background-color: yellow;
}

.content {
  height: 100vh;
  overflow: hidden;
}

#selectable1 {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow-y: auto;
  width: calc(100% - 150px);
  float: left;
}

#selectable2 {
  list-style-type: none;
  margin: 0;
  padding: 10px;
  width: 100px;
  height: 100vh;
  overflow-y: scroll;
}

#selectable1 li,
#selectable2 li {
  margin: 3px;
  padding: 1px;
  float: left;
  width: 100px;
  height: 80px;
  font-size: 4em;
  text-align: center;
}

There are lots of other ways to do this. inline-block is another way of the many ways to block something but allow space after it for other elements. float is also another way.
Basically, you have to set a height for the list element and this will create a scrollbar when there is overflow.
Updated
https://jsfiddle.net/Twisty/uro3b2ps/21/
#selectable2 {
  list-style-type: none;
  margin: 0;
  padding: 10px;
  width: 110px;
  height: 200px;
  overflow-y: scroll;
}

Update 2
https://jsfiddle.net/Twisty/uro3b2ps/25/
This uses jQuery to dynamically set the height based on the Window.

A: Update:
To support IE 11, you can update your CSS to include -ms-grid specific styles and it should work but again you might have to test it thoroughly:

$(function() {
  $("#selectable1").selectable();
  $("#selectable2").selectable();
});
body {
  margin: 0;
  padding: 0;
}

.header {
  background: yellow;
  -ms-grid-row: 1; /* for IE */
}

.footer {
  background: yellow;
  -ms-grid-row: 3; /* for IE */
}

div.table {
  display: grid;
  width: 100vw;
  height: 100vh;

  /* for IE */
  display: -ms-grid;
  -ms-grid-columns: 1fr;
  -ms-grid-rows: 20px 1fr 20px;
}

div.container {
  display: grid;
  grid-template-columns: auto 140px;
  grid-column-gap: 10px;
  overflow: hidden;

  /* for IE */
  display: -ms-grid;
  -ms-grid-columns: 1fr 140px;
  -ms-grid-rows: 1fr;
  -ms-grid-row: 2;
}

div.container div {
  overflow: auto;
}

div.container div.column1 {
    -ms-grid-column: 1; /* for IE */
}

div.container div.column2 {
    -ms-grid-column: 2; /* for IE */
}

#selectable1 {
  list-style-type: none;
  margin: 0;
  padding: 0;
  flex: 1;
}

#selectable2 {
  list-style-type: none;
  margin: 0;
  padding: 0;
}

#selectable1 li,
#selectable2 li {
  margin: 3px;
  padding: 1px;
  float: left;
  width: 100px;
  height: 80px;
  font-size: 4em;
  text-align: center;
}
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />

Header1

1

2

3

4

5

6

7

8

9

10

11

12

A

B

C

D

E

F

G

H

I

J

Footer1

You should be able to use CSS Grid to achieve what you want if you are willing to replace table with them:

$(function() {
  $("#selectable1").selectable();
  $("#selectable2").selectable();
});
body {
  margin: 0;
  padding: 0;
}

.header,
.footer {
  background: yellow;
}

div.table {
  display: grid;
  width: 100vw;
  height: 100vh;
}

div.container {
  display: grid;
  grid-template-columns: auto 140px;
  grid-column-gap: 10px;
  overflow: auto;
}

div.container div {
  overflow-y: auto;
  height: 100%;
}

#selectable1 {
  list-style-type: none;
  margin: 0;
  padding: 0;
  flex: 1;
}

#selectable2 {
  list-style-type: none;
  margin: 0;
  padding: 0;
}

#selectable1 li,
#selectable2 li {
  margin: 3px;
  padding: 1px;
  float: left;
  width: 100px;
  height: 80px;
  font-size: 4em;
  text-align: center;
}
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />

Header1

1

2

3

4

5

6

7

8

9

10

11

12

A

B

C

D

E

F

G

H

I

J

Footer1


text:
Q: Using ReCaptcha with jquery Validation Script I have a form that utilizes query.validate.js to perform field validation before submitting the form. It works, but now I'm trying to a Recaptcha 2.0 (the cool one where you just click a button). However, the form is being submitted without checking the ReCaptcha box. I'm assuming they are conflicting with each other somehow?

<form id="register" name="register" action="ce/ce_register_process.php" method="post" >

FIELD:

        <input id="field" size="40" name="field" type="text" required>

<input type="submit" value="Enter">


text:
Q: Decode Values in Controller or View in MVC Please consider this scenario: in some business domain there is some simple and constant options that we may implement them as combo box or radio buttons.
For example consider this sample for status combo box:
(Bad , 1),
(Medium , 2),
(Good , 3),
(Well , 4)

For this base information we create a static method (or property) of type List in a class and for this simple and constant we did not save them in database.
Now consider we want to create a read-only view and in model we use StatusID but we should decode this ID for showing it's text. I know (according to my incomplete information) 2 solution:

*

*Create a viewmodel and add a StatusText property to it and in my control decode StatusID using my static method

*Pass my model to view and decode it there
I want to know what the best practice is for such scenarios.
Thanks a lot

A: I would make them as Enum and use in the view @Html.EnumDropDownListFor(m=>m.StatusId, m=> m.MyEnum).
If you want custom display labels use the DisplayAttribute on the enum members.
Update
If you only want to show the value in a label, I would still recommend using an Enum and in the view: <div>(@Model.Status.ToString() , @((int)Model.Status))</div>. You can replace <div> with whatever element you need.


text:
Q: How to fix the Datepicker in sharepoint Client object?

 //Date Picker Object
        $(document).ready(function () {

            var myCounter = 1;
            $(".myDate").datepicker();

            $(".myDate").on('focus', function () {
                var $this = $(this);
                if (!$this.data('datepicker')) {
                    $this.removeClass("hasDatepicker");
                    $this.datepicker();
                    $this.datepicker("show");
                }
            });

        });
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
  <script src="http://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" />

 <input class="myDate" type="text" name="inputDate1" size="autofill" placeholder="Select End Date"
                        style="margin-right: 20px; text-align: right" readonly /></input>

I have a problem to fix the datepicker js file into sharepoint. I tried datepicker() function but it shows "Uncaught TypeError: $(...).datepicker is not a function".
But actually i got ans without sharepoint content. I required the flow which works in sharepoint. Can you please suggest me how to rectify the issue.
Thanks in Advance...
//Date Picker Object
        $(document).ready(function () {
        var myCounter = 1;
        $(".myDate").datepicker();

        $(".myDate").on('focus', function () {
            var $this = $(this);
            if (!$this.data('datepicker')) {
                $this.removeClass("hasDatepicker");
                $this.datepicker();
                $this.datepicker("show");
            }
        });

    });

A: Not sure  why you add focus function for datepicker.
Below script works fine in my local.
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
    <script src="http://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" />

    <input class="myDate" type="text" name="inputDate1" size="autofill" placeholder="Select End Date"
           style="margin-right: 20px; text-align: right" readonly />

    <script type="text/javascript">
        $(document).ready(function () {
            var myCounter = 1;
            $(".myDate").datepicker();
            //$(".myDate").on('focus', function () {
            //    var $this = $(this);
            //    if (!$this.data('datepicker')) {
            //        $this.removeClass("hasDatepicker");
            //        $this.datepicker();
            //        $this.datepicker("show");
            //    }
            //});
        });
    </script>

For troubleshooting.
Use developer tool to check the libraries loaded successfully.
If the libraries not loaded successfully, download and save to SharePoint and load form SharePoint.
for example:
<script src="/SiteAssets/jquery-1.8.3.js"></script>
    <script src="/SiteAssets/jquery-ui.js"></script>


text:
Q: Placeholder is not working in angularjs select2 Here is the code which i was tried. i tried to add placeholder with angularjs code and html code but it is not working in both the case. please help me or suggest me how to do in this case
 <select ui-select2="select2Options"
style="width:100%"
ng-model="SelectedProcessandIngredients"
 data-placeholder="Select or Add Process/Ingredient"
ng-options="c.name group by c.status for c in colors"
 ng-change="selectedinnerLoop()" >
        </select>

Angular js Code:
$scope.select2Options = {
        placeholder : "Select or Add Process/Ingredient",
        formatResult : processList,
        formatSelection : processList,
        escapeMarkup : function (m) {
        return m;
        }

    };

A: Add an empty option tag inside your select tag and the placeholder will be shown.
Also, use ng-repeat instead of ng-options. Select2 is incompatible with ng-options.
<select ui-select2 ng-model="select2" data-placeholder="Pick a number">
    <!-- empty option gets placeholder working -->
    <option value=""></option>
    <!-- ng-repeat to populate dynamic options -->
    <option ng-repeat="number in range" value="{{number.value}}">{{number.text}}</option>
</select>


text:
Q: DataGridView not visible on form Windows 10 I had an issue with a DataGridView not being shown on a Form that was initialised from another Form on Windows 10 in Release mode. The issue is not present when debugging code in Debug Mode. I even tried turning off optimization.
It took me 2 days to work out the issue so im making this with the hope it helps someone else facing this issue as there it NOTHING online for this specific issue.
Scenario (Issue ONLY occurs in this scenario in Release built code)
Form1 - Click button to show Form2
Form2 - Has a DataGridView which is not loaded/shown on the form

A: If ColumnHeadersHeight is set to anything other than default (21) on FormLoad then the DataGridView will not be shown on the form.
You can change the ColumnHeadersHeight property AFTER the form has loaded.