text:
Q: Modules with mixed scopes I am trying to achieve the following behavior:

*

*Use an object provided by a module under a singleton scope in another module with a different scope.

Here is what I have. I have tried a lot of changes based on several answers but I still cannot solve this issue.
The first module (Should be bound to the application's lifecycle)
@Module
public class AModule {

private Context context;

public AModule(Context context) {
   this.context = context;
}

@Provides
@Singleton
MySharedPreference provideMySharedPreference(SharedPreferences prefs) {
   return new MySharedPreferences(prefs);
}

@Provides
@Singleton
SharedPreference provideSharedPreference() {
   return context.getSharedPreferences("prefs", 0);
}

It's component
@Component(modules = AModule.class)
@Singleton
public interface AComponent {
   void inject(...);
}

The second module (bounded to Activity Lifecycle)
@Module
public class BModule {

   @Provides
   @ActivityScope
   X provideX(MySharedPreferences prefs) {
      return new Y(prefs);
   }
}

It's component
@Component(modules = BModule.class)
@ActivityScope
public interface BComponent {
   Y Y();
}

I declared the Activity Scope
@Scope
@Retenion(RetentionPolicy.RUNTIME)
public @interface ActivityScope{}

And MySharedPreferences is as follows
public class MySharedPreferences {

   private SharedPreferences mSharedPrefs;

   @Inject
   public MySharedPreferences(SharedPreferences prefs) {
      mSharedPrefs = prefs;
   }

   // some methods
}

Finally, in my application class, I create the A Component
aComponent = DaggerAComponent.builder().aModule(new AModule(getApplicationContext())).build();

EDIT Some of the things I tried
I tried adding includes = AModule.class to the BModule.
I tried adding dependencies = AComponent.class to the BComponent.
I tried creating a new Component with the ActivityScope annotation.

A: If you are using dependent components (dependencies =) you need to write a provision method to expose the dependency from the @Singleton scoped component to the @ActivityScope component.
@Component(modules = AModule.class)
@Singleton
public interface AComponent {
   void inject(...);

   SharedPreferences exposeSharedPreferences();
}

The provision method will allow the dependent @ActivityScope component to use @Singleton binding for SharedPreferences:
@Component(modules = BModule.class, dependencies = AComponent.class)
@ActivityScope
public interface BComponent {
   Y Y();
}

See this question for a more detailed explanation of provision methods.


text:
Q: Disable buttons in ReactJS
How can i disable other buttons(AiOutlinePlus) while clicking on one button(AiOutlinePlus)in ReactJS.It should be in the form of one button can be clicked at a time.

xxxxxxxxxxxxxxxxxx

                setShowLinks(!showLinks)}>
                  <AiOutlinePlus />

                xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

              <button id={showLinks ? "hidden" : ""}xxxxxxxx</button>

xxxxxxxxxxxxxxxxxx

                setShowLinks(!showLinks)}>
                  <AiOutlinePlus />

                xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

              <button id={showLinks ? "hidden" : ""}xxxxxxxx</button>

xxxxxxxxxxxxxxxxxx

                setShowLinks(!showLinks)}>
                  <AiOutlinePlus />

                xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

              <button id={showLinks ? "hidden" : ""}xxxxxxxx</button>

A: You need to pass some unique identifier to each button to identify each button. When you click on any one button you need to set a variable in the state which would be used to identify the button clicked. Once the state is updated, you could use it to not set the event handler onClick on the other buttons. The same state could also be used to disable the other buttons.

A: Using disabled attribute and state, you can make buttons disabled in Reactjs.
Firstly you have to use the <button> HTML tag and use the icons inside it.
The  element has a disabled attribute. Below given is a sample component for understanding. Say these are two buttons & here I have used React icons. Clicking the first button disables the second.
 class Button extends React.Component{
    constructor(props){
     super(props)

    this.state={btn1:false}
    this.handleClick=this.handleClick.bind(this)
  }

  handleClick(){
   this.setState({btn1: true})
  }
 render(){
  const{btn1}=this.state

     return(

    <button onClick={this.handleClick}> <AiFillEyeInvisible color="red" size={60}/></button>
    <button disabled={alert1}> <AiFillEye color="green" size={60}/></button>

   )
  }
 }

If you want to know more check this answer-
How to disable button in React.js

redpajama_set_name: RedPajamaStackExchange


text:
Q: include files, typedefs and forward decl I have a C++ thread wrapper class around win32/pthreads. The problem is in my header I need alot of the biggie-include like windows.h and boost::function, for declaring my typedefs below.
Is there any way around this? I know you can forward declare classes and structs, but datatypes like the win32 HANDLE and templated functions in a namespace...?
    #include "boost/function.hpp"

    /* Thread wrapper class */
    class IThread
    {
    public:
        #if defined _WIN32 || _WIN64
            #define WIN32_LEAN_AND_MEAN
            #include <Windows.h>
            #undef WIN32_LEAN_AND_MEAN
            typedef HANDLE ThreadHandle;
        #else
            #include <pthread.h>
            typedef pthread_t ThreadHandle;
        #endif

        enum ThreadState
        {
            DETACHED = 0,
            RUNNING,
            FINISHED
        };

        typedef boost::function1<void, void*> Task;

        virtual ~IThread() { }

        IThread& operator=(IThread& other);
        virtual int32_t Join() = 0;
        virtual int32_t SetPriority(int32_t priority) = 0;

        virtual ThreadHandle& GetNativeHandle() = 0;
        virtual ThreadState GetThreadState() const = 0;

    };

Thanks

A: I'll assume this isn't your real code because I can't see how includes could work in the middle of your class definition.
In this case you probably want to not expose the native thread identifier at all. Instead, provide abstract capabilities to act on threads in a sane manner and at no time expose the implementation details such as HANDLE. Then you can move the includes to your source file and problem averted.
Also note that doing the WIN32_LEAN_AND_MEAN + #include <Windows.h> in a header file means that someone that doesn't WANT WIN32_LEAN_AND_MEAN but includes your header before their own windows.h include will get the lean-and-mean unexpectedly.
EDIT: I think it's fine to use boost::function in the header because the include is always the same regardless of environment. As long as you always expose it as Task instead of as the function itself it can be considered part of the interface.


text:
Q: Differentiating $x+2x^2\sin(1/x)$ near $0$, discontinuity of the derivative I have this function
$$
\begin{array}{l}
f:\mathbb{R}\rightarrow\mathbb{R}\\
x\rightarrow\left\{\begin{array}{ll}
x+2x^2\sin\left(\frac{1}{x}\right)&x\neq 0\\
0&x=0
\end{array}\right.
\end{array}
$$
I need to calculate its derivative in $x=0$. I'm not sure how can I compute it at zero, since the limit of its derivative goes to 1 when x tends to zero but at zero I thought $f'(0)$ must be zero (therefore its derivative is not continuous at the origin). If is not zero then it is invertible around the origin via the Inverse Function Theorem, right?

A: The derivative is discontinuous at the origin, but not for the reasons you stated.
Calculate the derivative at $x=0$ using the limit definition, $f'(0)=\lim\limits_{h\to 0}\dfrac{f(h)-f(0)}{h}$.  You will find that it is $1$, not $0$.
Calculate the derivative at $x\neq 0$ using the ordinary shortcuts from calculus.  You will have a general expression for $f'(x)$ when $x\neq 0$, and you will find that $\lim\limits_{x\to 0}f'(x)$ does not exist.

I seem to have neglected the question about invertibility.  A continuous function on an interval in $\mathbb R$ is invertible if and only if it is strictly monotone (a consequence of the intermediate value theorem).  A function with everywhere existing nonzero derivative in an interval is strictly monotone (a consequence of the mean value theorem). In particular, if a function has a continuous derivative and nonzero derivative at zero, then the function is invertible in a neighborhood of the origin, and the inverse function theorem even applies.
For your function, although $f'(0)$ exists and is nonzero, discontinuity of $f'$ means the inverse function theorem doesn't apply, and more work is required to determine whether $f$ is invertible.  A necessary condition for a differentiable function to be monotone on an interval is that the derivative doesn't change signs on the interval.  For your function, $f'(0)=1>0$, but evaluating at $x_n = \dfrac{1}{2n\pi}$ gives $f'(x_n)=-1$ with $x_n\to 0$ as $n\to \infty$.  Hence, $f$ is not monotone in any interval containing $0$.

A: Use the definition of the derivative to evaluate it at zero:
$$f'(0) = \lim_{x \to 0} \frac{f(x) - f(0)}{x - 0}.$$
In this case we have
\begin{align}
\lim_{x \to 0} \frac{f(x) - f(0)}{x - 0} & = \lim_{x \to 0} \frac{x + 2x^2 \sin(1/x)}{x} \\
& = \lim_{x \to 0} (1 + 2x \sin(1/x)) \\
& = 1 + 0 = 1,
\end{align}
where we use the squeeze theorem to conclude that
$$\lim_{x \to 0} 2x \sin(1/x) = 0.$$


text:
Q: Creating a 2D string array in C So basically I am trying to read from a huge text file and need to store the data in a 2D string array in C. But I am getting a segmentation fault every time.
Here is the code I use to create the array:
Y = 3
X = 12
char ***some_array=NULL;
some_array = (char ***)malloc(Y * sizeof(char *));
    for (int i=0; i<Y; i++)
        for (int j=0; j<X; j++){
            some_array[i] = (char **)malloc(X * sizeof(char *));
            some_array[i][j] = (char *)malloc(16 * sizeof(char));
        }

So technically, I am creating a 3D char array for this means. Am I doing something wrong here?

A: Error is in your loop:
for (int i=0; i<Y; i++) {
    some_array[i] = (char **)malloc(X * sizeof(char *));
    for (int j=0; j<X; j++){
        some_array[i][j] = (char *)malloc(16 * sizeof(char));
    }
}

You are supposed to allocate memory to some_array[i] outside the inner loop.

A: You need to move the allocation of some_array[i] = (char **)malloc(X * sizeof(char *)); from the inner most loop to the outer loop. Moreover, you should not cast the malloc return value. For the final code:
Y = 3
X = 12
char ***some_array = NULL;
some_array = malloc(Y * sizeof(char *));
    for (int i = 0; i < Y; i++){
        some_array[i] = malloc(X * sizeof(char *));
        for (int j = 0; j < X; j++){
            some_array[i][j] = malloc(16 * sizeof(char));
        }
    }

Alternatively you can create a statically allocated array:
char some_array [X][Y][16];


text:
Q: RgexPattern, can't get it working I have the following pattern which searches for "timer": till } is found:
(?<="timer":)[^}]*(?=\})

I need that to be modified so that it searches for "timer": till } OR , is found. So, if I have:
bc7","timer":20,"referrer":"<default>"},

20 will be matched, and if I have:
com","timer":18}

18 will be matched, with the same pattern.

A: It seems that you are using regex to parse json. regex are not the right tool to parse json, instead use a proper JSON parser.
All modern language including shell (see jq), python, perl, ruby, go, java and such have bindings to properly parse json inputs.

A: Solution:
(?<=\"timer\":)[^},]*(?=[\x2C\x7D])

A: How about:
"timer":(\d+)

The timer value will be in group 1.


text:
Q: CHtml submit button is not working when 'enter' key press in Yii In my Yii web application, CHtml submit button is not working when 'enter' key press in Login form. My login form is,
<?php echo CHtml::beginForm(); ?>

Login to your account

<button class="close" data-close="alert"></button>
 Enter any username and password.

Username

    <?php echo CHtml::activeTextField($model, 'username', array("class" => "form-control placeholder-no-fix", 'placeholder' => "Username")) ?>

Password

    <?php echo CHtml::activePasswordField($model, 'password', array("class" => "form-control placeholder-no-fix", 'placeholder' => "Password")) ?>

<?php echo CHtml::submitButton(UserModule::t("Login "), array('class' => 'btn green pull-right')); ?>

<?php echo CHtml::errorSummary($model); ?>

<?php echo CHtml::endForm(); ?>

<?php
$form = new CForm(array(
'elements' => array(
    'username' => array(
        'type' => 'text',
        'maxlength' => 32,
    ),
    'password' => array(
        'type' => 'password',
        'maxlength' => 32,
    ),
    'rememberMe' => array(
        'type' => 'checkbox',
    )
),
'buttons' => array(
    'login' => array(
        'type' => 'submit',
        'label' => 'Login',
    ),
),
    ), $model);
?>

In this login form using chtml submit button. I want to submit this login form by press enter key.
How to resolve this problem.
Please help me.

A: If you  want to use onclick:
<?php echo CHtml::submitbutton(UserModule::t("Login "), array('class ' => 'btn green pull-right', 'onclick' => ' '));?>


text:
Q: Heavy memory utilization Sails.js app upgraded from node 12 to 14 keeps rebooting in Cloud Foundry After upgrading 2 of our Sails application from Node 12 to 14 the application started rebooting or getting stuck in CloudFoundry, there are no visible errors on the logs and the memory spikes to 800Mb (each deployment has 4GB available). When running the applications locally with any node version the issue is not reproducible. Has anyone experience issues with CloudFoundry is there some configuration to allow the application to better manage the available memory?
Attached New Relic data for the failure which happened around 2:15 memory and CPU went all the way down to 0


text:
Q: Error while using fn:string-length in Xquery I am trying to use fn:string-length function in Xquery and strangely I am getting this error.

line 19, column 66: {err}XP0004 [{bea-err}XP0004a]: Operator "gt" is not applicable for arguments of type {http://www.w3.org/2001/XMLSchema}integer and {http://www.w3.org/2001/XMLSchema}string

All I am trying to do is, to get a length of a XPath expression and compare it with some value.
{
  let $PlaceofDeliveryZoneCodeVal := $getRevenueRequest1/ns0:AlternativeCode/ns0:AlternativeCodeVal/text()
  return
    if(fn:string-length($PlaceofDeliveryZoneCodeVal) > "8") then
      <ns1:GeoId>
        <ns1:AlternativeCodeVal>{$PlaceofDeliveryZoneCodeVal}</ns1:AlternativeCodeVal>
      </ns1:GeoId>
    else()
}

A: The problem is that because the integer is wrapped in quotes, you are comparing an integer to a string:
(fn:string-length($PlaceofDeliveryZoneCodeVal) > "8")

If you remove the quotes, the comparison will succeed:
(fn:string-length($PlaceofDeliveryZoneCodeVal) > 8)


text:
Q: Does enabling CICP activity logging log activity for Firebase authentication? My project uses Firebase authentication.
I want to enable the logging of authentication activity for compliance. Google has this feature for its Google Cloud CICP (Cloud Identity for Customers and Partners) (documentation here).
I know that CICP says it's compatible with Firebase authentication, but does this mean it will log my Firebase project's authentication activity if I do enable it? Or will it only log activity from accounts created directly by CICP? Thanks!

A: For Stackdriver activity logging, it will work for activity across both CICP and Firebase Auth. As you've probably seen from the documentation, the first step is to enable this on your project:
curl -d "{'monitoring':{'requestLogging':{'enabled':true}}}" -H 'Authorization: Bearer [AUTH_TOKEN]' -X PATCH -H 'Content-Type: application/json' https://identitytoolkit.googleapis.com/admin/v2/projects/[PROJECT_ID]/config?updateMask=monitoring.requestLogging.enabled

*

*You can get an AUTH_TOKEN any number of ways, but a simple method is using the Google OAuth Playground and authorizing the Google Identity Toolkit API v3 scopes.

Once you have some activity that's worthy of reviewing, you can check it out directly in StackDriver logs viewer within the "Identity Toolkit Project" resource.
One thing to be aware of is that if you have a large number of users, or really significant activity on your project, you might also want to specify exclusions to minimize cost/traffic/noise. Details are included in the Activity Logging docs you've specified.


text:
Q: Regular expression to pick the longest option I'm trying to create a regular expression that will pick the longest of two options from a string.
Either a numeric value up to 15 characters long or a whatever value up to 11 characters long.
So far i have this:
^([0-9]{1,15}|.{1,11})

But for example the string: '7elevenshopfood' gets shortened to '7' because it looks at the first part of the paranthesis. And if I switch it to
^(.{1,11}|[0-9]{1,15})

the string '123456789123456789' gets shortened to '12345678912' since it looks at the first part of the expression again.
Anyone with greater regexp knowledge have an idea?

A: That is how most regex dialects work, alternations are tested in order they are written and the first matching part will end the search.
In your case you can work around that with something like:
^(\d{12,15}|.{1,11})


text:
Q: request wcf Web service with postman i am trying to request WCF web service but i am getting error 500 with this message

The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://tempuri.org/:messageSet. The InnerException message was 'Element Value from namespace http://schemas.datacontract.org/2004/07/Sanay.Suip.Library cannot have child contents to be deserialized as an object. Please use XmlNode[] to deserialize this pattern of XML.

if you know what should i do please help
thanks
my request xml img
<x:Envelope xmlns:x="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tem="http://tempuri.org/" xmlns:san="http://schemas.datacontract.org/2004/07/Sanay.Suip.Library">
<x:Header/>
<x:Body>
    <tem:QueryMessage>
        <tem:messageSet>
            <san:ActionId>?</san:ActionId>
            <san:Ip>::1</san:Ip>
            <san:Parameters>
                  <san:Parameter>
                    <san:Name>Username</san:Name>
                    <san:Value>tipex</san:Value>
                </san:Parameter>

                 <san:Parameter>
                    <san:Name>Password</san:Name>
                    <san:Value>123456</san:Value>
                </san:Parameter>

            </san:Parameters>
            <san:Title>Authenticate</san:Title>
            <san:Token>?</san:Token>
            <san:Username>?</san:Username>
        </tem:messageSet>
    </tem:QueryMessage>
</x:Body>

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Body>
    <s:Fault>
        <faultcode xmlns:a="http://schemas.microsoft.com/net/2005/12/windowscommunicationfoundation/dispatcher">a:DeserializationFailed</faultcode>
        <faultstring xml:lang="en-US">The formatter threw an exception while trying to deserialize the message: There was an error while trying to deserialize parameter http://tempuri.org/:messageSet. The InnerException message was 'Element Value from namespace http://schemas.datacontract.org/2004/07/Sanay.Suip.Library cannot have child contents to be deserialized as an object. Please use XmlNode[] to deserialize this pattern of XML.'.  Please see InnerException for more details.</faultstring>
    </s:Fault>
</s:Body>


text:
Q: InstallShield Dynamic Dialogs I want to create an InstallShield Project that has a custom dialog containing a few text boxes that will be dynamically filled in with data from a text file (date, version info etc..) when the install runs. Is this possible?

A: I think that depends on where the file lives.
If the file exists already in the system (XML or INI formats, it could also be the registry), you could use System Search to find them. If found, the values would be stored in properties, which then you can use in your dialog (there's a Property field that you can use).
If it's a file you are installing then that's a different story, because at the time of the GUI execution, you will not have access to it.
If you provide more information then I could give some more specific advice. Things like: Where does the file live? who modifies it? is it part of the installation?
Regards,
Juan Carlos


text:
Q: Let ABCD be a trapezium with AD parallel to BC, there is a point M in the interior of the segment BC, AB=AM, DC=DM. Find [AMD]:[ABCD] Does the phrase 'in the interior of' refer to M being on the line? Because all solutions online to the question have assumed that M is on the line BC like this one:

It becomes very easy if we assume M to be on the line but I'm confused by how the question's phrased

A: Triangles ABM and DMC must be isoceles, with bases BM and MC respectively. Draw perpendicular lines to the parallel sides through A and D to see, that the quotient of the area of the triangle and the area of the trapezium is one half.


text:
Q: Split View like Settings I have created a basic Split View and instead of loading a UIView on the right hand side, I have loaded a UITableView. The UITableView is made up of UITableViewCell's and what I want to do is when I click on the Cell, it loads up another UITableView for selection much like that in the iPad settings. However I cannot the UITableView to load after selection.
Any ideas how to achieve this? I've seen similiar questions and had a look at the apple site with uitableviews but haven't been able to solve the issue as they're geared towards iphone which doesn't have the split view.
On the didSelectRowAtIndexPath i've loaded it like so which other apps have done but to no avail.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    if(indexPath.row == 0)
    {
        LevelTwoController *leveltwoController = [[LevelTwoController alloc] initWithNibName:@"LevelTwoTableView" bundle:nil];
        [self.navigationController pushViewController:leveltwoController animated:YES];

        [leveltwoController release];

    }
}

Another thing also is my leveltwoController is a UITableViewController and I just keep getting this import error literal-pointer@_OBJC@_cls_refs.

A: Your main view that has the TableViewController needs to be controlled by a UINavigationController, and then you could push the subsequent views onto the view stack. My guess is your current implementation is having self.navigationController be nil so nothing is happening.
If you take a look at some of the basic xcode templates that use uinavigationcontroller's you should be able to figure out the proper path.


text:
Q: How is it possible to get elements by class name in PHP (DOM selectors)? Apparently, in PHP, there are a few DOM selectors like getElementById and getElementsByTagName but not the class selector, getElementsByClassName that is in javaScript, but strangely, not in PHP. Now, I have made a project that has to use class selectors in order to locate the elements in that particular page's DOM, but nethertheless, considering there's no getElementsByClassName method in PHP;
I can't complete my project correctly.

So, how is it possible to apply "get elements by class name" in the
  PHP Document Object Model(DOM)?

Any help would be appreciated!

A: Use DOMXPath with a custom XPath query. See How can I find an element by CSS class with XPath?


text:
Q: How to implement JQgrid in asp.net? I have worked with JQgrid in asp.net mvc, but now i am trying to implement this in asp.net.
I find a hard time making a JQgrid sample in asp.net.
Do i have to use the JSON response in asp.net or i have to implement this in any other way.
Please suggest.

A: I don't full understand your requirements. ASP.NET MVC is also ASP.NET application. Do you have restriction to .NET version? Do you can use only some specific .NET technology?
In general you can mix the main code of your size with the code in other ASP.NET technology. For example WCF service can be the part of ASP.NET MVC or ASP.NET Web Form application. The main code can provide the user interface of your web site and the WFC service will provide JSON data for any Ajax requests from jqGrid.
So you can just use any examples of WCF, ASMX Web Service or even simple ASHX handler.
The demo project from the answer shows how to use ASHX handler in ASP.NET Web Form application.
Another demo project from the answer shows how to use WCF service.
The demo project from the answer or another demo from the answer demonstrate the usage of ASMX web services.


text:
Q: Parent/child checkboxes with label I'd like to have parent/checkboxes with this behavior :

*

*A click on the parent select/unselect all children

*Parent is checked if one or more child is selected

*Parent is unchecked if no child is selected

That code works:

<input type="checkbox" name="parent1" id="parent1" value=""> Parent 1

<input type="checkbox" name="child11" value=""> Child 11

<input type="checkbox" name="child12" value=""> Child 12

<input type="checkbox" name="child13" value=""> Child 31

<input type="checkbox" name="parent2" value=""> Parent 2

<input type="checkbox" name="child21" value=""> Child 21

<input type="checkbox" name="child22" value=""> Child 22

JS:
$('input[type=checkbox]').click(function(){
   $(this).next().find('input[type=checkbox]').prop('checked',this.checked);
   $(this).parents('ul').prev('input[type=checkbox]').prop('checked',function(){
      return $(this).next().find(':checked').length;
   });
});

My concern is that as soon as I set a  tag, it doesn't work anymore. I can't figure out why.
Here is Pen : https://codepen.io/Jibeji/pen/povYKXo

A: It doesn't work anymore because $(this).next() no longer refers to the next input since there are labels there. It seems you want .next().next(). You might want a different way to select the ul though because you can see how easily this setup can break.

A: Answering myself. This is more elegant and supports labels:
$('input[type=checkbox]').click(function(){
   $(this).nextUntil('li').find('input[type=checkbox]').prop('checked',this.checked);
   $(this).closest('ul').siblings('input:checkbox').prop('checked',function(){
      return $(this).nextUntil('li').find(':checked').length;
   });
});

Original Pen edited.


text:
Q: Trying to run a command in a changing command prompt I'm writing a powershell script that remotely gets the workspace info on a remote computer's TFS.
What I need to do is either invoke-command or psexec the path of the batch file to open up the visual studio dev command prompt, and then run a command inside that prompt. What I'm having trouble with is executing the second command inside the dev command prompt. What is happing right now is I'm able to open the dev command prompt, but only when I exit it does the second command run. Below is some code I was trying.
.
Invoke-Command -ComputerName computer1 {cmd /k '"C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\Tools\LaunchDevCmd.bat" & tf'}

^ I get a tf is not recognized, which it isn't when in a normal command prompt. If it ran in the dev prompt I'd get some version info and help commands.
.
@echo off

"C:\Users\me\Downloads\PSTools\PsExec.exe" \\computer1 cmd /c "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\Tools\LaunchDevCmd.bat" & "tf"

^ This opens the dev prompt, and upon exiting it gives an error that tf is not a command.
.
What I want to do is: Normal Prompt > Dev Prompt > Run Command > Leave Both. Is this possible? Is there a way to just start at the dev prompt?

A: You could invoke tf.exe command in your powershell directly:
PS> & "$env:Program Files (x86)\Microsoft Visual Studio\2017\\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\tf.exe" @("workspace", "/new", "xxx", "/noprompt", "/login:xxx,xxx", "/collection:xxx")


text:
Q: From C to C++: function was not declared in this scope I'm importing some methods from a C library to use them in my C++ main code but I have compilation errors:
$ make
g++ -c main.cpp
main.cpp: In function 'int main(int, char**)':
main.cpp:419:67: error: 'kmedoids' was not declared in this scope
 kmedoids(class_num, N, distanceMatrix, 1, clusterid, error, ifound);
                                                                   ^
main.cpp: In function 'void kmedoids(int, int, double**, int, int*, double*, int*)':
main.cpp:537:64: error: 'randomassign' was not declared in this scope
     if (npass!=0) randomassign(nclusters, nelements, tclusterid);
                                                                ^
main.cpp:550:42: error: 'getclustermedoids' was not declared in this scope
                         centroids, errors);
                                          ^
main.cpp: In function 'void randomassign(int, int, int*)':
main.cpp:644:20: error: 'binomial' was not declared in this scope
   j = binomial(n, p);
                    ^
main.cpp:654:40: error: 'uniform' was not declared in this scope
 { j = (int) (i + (nelements-i)*uniform());
                                        ^
main.cpp: In function 'int binomial(int, double)':
main.cpp:704:24: error: 'uniform' was not declared in this scope
     double u = uniform();
                        ^
main.cpp:732:26: error: 'uniform' was not declared in this scope
       double u = uniform();
                          ^
make: *** [main.o] Error 1

this is the last part of my code with the new C methods:
#include "profileManager.h"
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <limits.h>
#include <float.h>
#include <time.h>

int main(int argc, char *argv[])
{
//......PREVIOUS CODE.......

kmedoids(class_num, N, distanceMatrix, 1, clusterid, error, ifound);

    return 0;
}

//NEW C METHODS
void kmedoids (int nclusters, int nelements, double** distmatrix,
  int npass, int clusterid[], double* error, int* ifound)
{ int i, j, icluster;
  int* tclusterid;
  int* saved;
  int* centroids;
  double* errors;
  int ipass = 0;

  if (nelements < nclusters)
  { *ifound = 0;
    return;
  } /* More clusters asked for than elements available */

  *ifound = -1;

  /* We save the clustering solution periodically and check if it reappears */
  saved = (int*)malloc(nelements*sizeof(int));
  if (saved==NULL) return;

  centroids = (int*)malloc(nclusters*sizeof(int));
  if(!centroids)
  { free(saved);
    return;
  }

  errors = (double*)malloc(nclusters*sizeof(double));
  if(!errors)
  { free(saved);
    free(centroids);
    return;
  }

  /* Find out if the user specified an initial clustering */
  if (npass<=1) tclusterid = clusterid;
  else
  { tclusterid = (int*)malloc(nelements*sizeof(int));
    if(!tclusterid)
    { free(saved);
      free(centroids);
      free(errors);
      return;
    }
  }

  *error = DBL_MAX;
  do /* Start the loop */
  { double total = DBL_MAX;
    int counter = 0;
    int period = 10;

    if (npass!=0) randomassign(nclusters, nelements, tclusterid);
    while(1)
    { double previous = total;
      total = 0.0;

      if (counter % period == 0) /* Save the current cluster assignments */
      { for (i = 0; i < nelements; i++) saved[i] = tclusterid[i];
        if (period < INT_MAX / 2) period *= 2;
      }
      counter++;

      /* Find the center */
      getclustermedoids(nclusters, nelements, distmatrix, tclusterid,
                        centroids, errors);

      for (i = 0; i < nelements; i++)
      /* Find the closest cluster */
      { double distance = DBL_MAX;
        for (icluster = 0; icluster < nclusters; icluster++)
        { double tdistance;
          j = centroids[icluster];
          if (i==j)
          { distance = 0.0;
            tclusterid[i] = icluster;
            break;
          }
          tdistance = (i > j) ? distmatrix[i][j] : distmatrix[j][i];
          if (tdistance < distance)
          { distance = tdistance;
            tclusterid[i] = icluster;
          }
        }
        total += distance;
      }
      if (total>=previous) break;
      /* total>=previous is FALSE on some machines even if total and previous
       * are bitwise identical. */
      for (i = 0; i < nelements; i++)
        if (saved[i]!=tclusterid[i]) break;
      if (i==nelements)
        break; /* Identical solution found; break out of this loop */
    }

    for (i = 0; i < nelements; i++)
    { if (clusterid[i]!=centroids[tclusterid[i]])
      { if (total < *error)
        { *ifound = 1;
          *error = total;
          /* Replace by the centroid in each cluster. */
          for (j = 0; j < nelements; j++)
            clusterid[j] = centroids[tclusterid[j]];
        }
        break;
      }
    }
    if (i==nelements) (*ifound)++; /* break statement not encountered */
  } while (++ipass < npass);

  /* Deallocate temporarily used space */
  if (npass > 1) free(tclusterid);

  free(saved);
  free(centroids);
  free(errors);

  return;
}

static void randomassign (int nclusters, int nelements, int* clusterid)
{ int i, j;
int k = 0;
double p;
int n = nelements-nclusters;
/* Draw the number of elements in each cluster from a multinomial
 * distribution, reserving ncluster elements to set independently
 * in order to guarantee that none of the clusters are empty.
 */
for (i = 0; i < nclusters-1; i++)
{ p = 1.0/(nclusters-i);
  j = binomial(n, p);
  n -= j;
  j += k+1; /* Assign at least one element to cluster i */
  for ( ; k < j; k++) clusterid[k] = i;
}
/* Assign the remaining elements to the last cluster */
for ( ; k < nelements; k++) clusterid[k] = i;

/* Create a random permutation of the cluster assignments */
for (i = 0; i < nelements; i++)
{ j = (int) (i + (nelements-i)*uniform());
  k = clusterid[j];
  clusterid[j] = clusterid[i];
  clusterid[i] = k;
}

return;
}

static int binomial(int n, double p)
{ const double q = 1 - p;
  if (n*p < 30.0) /* Algorithm BINV */
  { const double s = p/q;
    const double a = (n+1)*s;
    double r = exp(n*log(q)); /* pow() causes a crash on AIX */
    int x = 0;
    double u = uniform();
    while(1)
    { if (u < r) return x;
      u-=r;
      x++;
      r *= (a/x)-s;
    }
  }
  else /* Algorithm BTPE */
  { /* Step 0 */
    const double fm = n*p + p;
    const int m = (int) fm;
    const double p1 = floor(2.195*sqrt(n*p*q) -4.6*q) + 0.5;
    const double xm = m + 0.5;
    const double xl = xm - p1;
    const double xr = xm + p1;
    const double c = 0.134 + 20.5/(15.3+m);
    const double a = (fm-xl)/(fm-xl*p);
    const double b = (xr-fm)/(xr*q);
    const double lambdal = a*(1.0+0.5*a);
    const double lambdar = b*(1.0+0.5*b);
    const double p2 = p1*(1+2*c);
    const double p3 = p2 + c/lambdal;
    const double p4 = p3 + c/lambdar;
    while (1)
    { /* Step 1 */
      int y;
      int k;
      double u = uniform();
      double v = uniform();
      u *= p4;
      if (u <= p1) return (int)(xm-p1*v+u);
      /* Step 2 */
      if (u > p2)
      { /* Step 3 */
        if (u > p3)
        { /* Step 4 */
          y = (int)(xr-log(v)/lambdar);
          if (y > n) continue;
          /* Go to step 5 */
          v = v*(u-p3)*lambdar;
        }
        else
        { y = (int)(xl+log(v)/lambdal);
          if (y < 0) continue;
          /* Go to step 5 */
          v = v*(u-p2)*lambdal;
        }
      }
      else
      { const double x = xl + (u-p1)/c;
        v = v*c + 1.0 - fabs(m-x+0.5)/p1;
        if (v > 1) continue;
        /* Go to step 5 */
        y = (int)x;
      }
      /* Step 5 */
      /* Step 5.0 */
      k = abs(y-m);
      if (k > 20 && k < 0.5*n*p*q-1.0)
      { /* Step 5.2 */
        double rho = (k/(n*p*q))*((k*(k/3.0 + 0.625) + 0.1666666666666)/(n*p*q)+0.5);
        double t = -k*k/(2*n*p*q);
        double A = log(v);
        if (A < t-rho) return y;
        else if (A > t+rho) continue;
        else
        { /* Step 5.3 */
          double x1 = y+1;
          double f1 = m+1;
          double z = n+1-m;
          double w = n-y+1;
          double x2 = x1*x1;
          double f2 = f1*f1;
          double z2 = z*z;
          double w2 = w*w;
          if (A > xm * log(f1/x1) + (n-m+0.5)*log(z/w)
                + (y-m)*log(w*p/(x1*q))
                + (13860.-(462.-(132.-(99.-140./f2)/f2)/f2)/f2)/f1/166320.
                + (13860.-(462.-(132.-(99.-140./z2)/z2)/z2)/z2)/z/166320.
                + (13860.-(462.-(132.-(99.-140./x2)/x2)/x2)/x2)/x1/166320.
                + (13860.-(462.-(132.-(99.-140./w2)/w2)/w2)/w2)/w/166320.)
             continue;
          return y;
        }
      }
      else
      { /* Step 5.1 */
        int i;
        const double s = p/q;
        const double aa = s*(n+1);
        double f = 1.0;
        for (i = m; i < y; f *= (aa/(++i)-s));
        for (i = y; i < m; f /= (aa/(++i)-s));
        if (v > f) continue;
        return y;
      }
    }
  }
  /* Never get here */
  return -1;
}

static double uniform(void)
{ int z;
  static const int m1 = 2147483563;
  static const int m2 = 2147483399;
  const double scale = 1.0/m1;

  static int s1 = 0;
  static int s2 = 0;

  if (s1==0 || s2==0) /* initialize */
  { unsigned int initseed = (unsigned int) time(0);
    srand(initseed);
    s1 = rand();
    s2 = rand();
  }

  do
  { int k;
    k = s1/53668;
    s1 = 40014*(s1-k*53668)-k*12211;
    if (s1 < 0) s1+=m1;
    k = s2/52774;
    s2 = 40692*(s2-k*52774)-k*3791;
    if(s2 < 0) s2+=m2;
    z = s1-s2;
    if(z < 1) z+=(m1-1);
  } while (z==m1); /* To avoid returning 1.0 */

  return z*scale;
}

void getclustermedoids(int nclusters, int nelements, double** distance,
  int clusterid[], int centroids[], double errors[])

{ int i, j, k;
  for (j = 0; j < nclusters; j++) errors[j] = DBL_MAX;
  for (i = 0; i < nelements; i++)
  { double d = 0.0;
    j = clusterid[i];
    for (k = 0; k < nelements; k++)
    { if (i==k || clusterid[k]!=j) continue;
      d += (i < k ? distance[k][i] : distance[i][k]);
      if (d > errors[j]) break;
    }
    if (d < errors[j])
    { errors[j] = d;
      centroids[j] = i;
    }
  }
}

What do these errors mean? How can I fix them?

A: You are using kmedoids before you have declared it. This has nothing to do with C++, the same warning should occur with a modern C compiler as well.
What you have to do is to declare kmedoids before using it (i.e. you have to write the function signature in the code somewhere above main -- alternatively, you can define it by moving the complete implementation before main.)
Right now, the function is undeclared at the first point where you use it (that means, the compiler doesn't know its signature and cannot check the types.)
Also: Read this for some background on how to declare functions: http://en.cppreference.com/w/cpp/language/function

A: You need a declaration before you can use a function.
Either move your function body before the main method, or use a forward declaration:
void kmedoids (int nclusters, int nelements, double** distmatrix, int npass, int clusterid[], double* error, int* ifound);

This also has to be placed before your usage.


text:
Q: How to Install and deploy a custom XML indexing connector for SharePoint Server 2016 I have gone through the link https://blogs.msdn.microsoft.com/xml_connector_for_sharepoint_2013/2012/10/01/create-a-custom-xml-indexing-connector-for-sharepoint-2013/
and trying to implement the same in SharePoint server 2016 and initially got  this error.
Item not crawled due to one of the following reasons: Preventive crawl rule; Specified content source hops/depth exceeded; URL has query string parameter; Required protocol handler not found; Preventive robots directive. ( This item was deleted because it was excluded by a crawl rule. )
Then I could able to narrow down to the point that Required protocol handler not found;
After checking in Registry editor (HKEY_LOCAL_MACHINE-->Microsoft-->Office Server-->16.0 -->Search--> ProtocolHandlers )
found that the same Protocol handler is not available and then I copied the same which was found in (HKEY_LOCAL_MACHINE-->Microsoft-->Office Server-->15.0 -->Search--> ProtocolHandlers ) and modified the value to OSearch16.ConnectorProtocolHandler.1 from earlier OSearch15.ConnectorProtocolHandler.1 which was found in 15.0 version and then restarted the search service.
Even then I full crawled. Got the below error.
Error while crawling LOB contents. ( Error caused by exception: Microsoft.SharePoint.BusinessData.Parser.PackageFormatException The LobSystem with Name 'XmlDocumentSystem' and Id '2147483658' has a value in Field 'SystemUtilityType' that is invalid. Error was encountered at or just before Line: '25' and Position: '10'.; SearchID = B2567254-D024-49BB-A03E-D9978ADB55F6 )
Can anyone suggest how to Install and deploy a custom XML indexing connector for SharePoint Server 2016
Or even if you have answer to resolve my issues that would be great!


text:
Q: itimerval timer restart and stop how can I stop the timer and give it a new time to expire?
how can I restart the timer after it been ended?
how can I restart the timer from the signal handler (handler_func)?
example:
struct sigaction real_sa;
struct itimerval real_timer;
real_sa.sa_handler = &handler_func;

if (sigaction(SIGALRM, &real_sa,NULL) < 0) {
    std::cerr << "system error: sigaction error\\n" <<
              std::endl;
    exit(1);
}
real_timer.it_value.tv_sec = (absolute_time/1000000);
real_timer.it_value.tv_usec = (absolute_time % 1000000);
if (setitimer (ITIMER_REAL, &real_timer, NULL))
{
    std::cerr << "system error: setitimer error\\n" <<
              std::endl;
    exit(1);
}

thanks in advance
edit : this code  develop on linux environment and should work on linux (other platform are not important to me)

A:
how can I stop the timer and give it a new time to expire?

By calling setitimer with a zeroed it_value (it's in the manpage).

how can I restart the timer after it been ended?

By calling setitimer  again.

how can I restart the timer from the signal handler (handler_func)?

You shouldn't. it's not a guaranteed to be async-signal-safe. You can send a message to a thread to restart it for you.


text:
Q: Applying Spark reduceByKey to generic with context bounds I'm still new to context bounds in Scala and I'm trying to write a function that can perform a reduceByKey on any any generic that satisfies a context bound.
eg
def myReduce[K: ClassTag, V: ClassTag: Numeric[V]](in: RDD[(K, V)]): RDD[(K, V)] = {
  in.reduceByKey{case (v1, v2) =>
    implicityly[Numeric[V]].plus(v1, v2)
  }

As far as I understand this should work however when trying to compile I get the following errors.

*

*error: could not find implicit value for parameter e: Numeric

*error: Numeric[V] does not take type parameters

These I don't understand.
I'm not passing in type parameters to Numeric[V] anywhere. Also shouldn't the context bound automatically import the 'evidence' for the conversion?
I was hoping to instead to eventually use my own trait instead of Numeric.
Edit:
I tried explicitly writing the implicit evdience in the function as follows:
def myReduce[K: ClassTag, V: ClassTag](in: RDD[(K, V)])(implicit ev: V => Numeric[V]): RDD[(K, V)] = {
  in.reduceByKey{case (v1, v2) =>
    implicityly[Numeric[V]].plus(v1, v2)
  }

But I still get the "error: could not find implicit value for parameter e: Numeric" error.

A: Ok so I solved the issue
def myReduce[K: ClassTag, V: ClassTag: Numeric](in: RDD[(K, V)]): RDD[(K, V)] = {
  in.reduceByKey{case (v1, v2) =>
    implicityly[Numeric[V]].plus(v1, v2)
  }

The issue was specifying Numeric[V] instead of just Numeric.
I've ran into more issues now but that's for another day.


text:
Q: Oreo: android.content.res.Resources$NotFoundException my app seems to have a specific bug with some Android 8.0 devices on google play.
Unfortunately, I haven't been able to replicate the bug myself so far.
Here is the error log:
android.content.res.Resources$NotFoundException:
  at android.content.res.ResourcesImpl.getValueForDensity (ResourcesImpl.java:204)
  at android.content.res.Resources.getDrawableForDensity (Resources.java:875)
  at android.content.res.Resources.getDrawable (Resources.java:818)
  at android.content.res.Resources.getDrawable (Resources.java:793)
  at com.aresproductions.booksummaries.fragments.RecyclerViewAdapterBook.onBindViewHolder (RecyclerViewAdapterBook.java:188)
  at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder (RecyclerView.java:6508)
  at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder (RecyclerView.java:6541)
  at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline (RecyclerView.java:5484)
  at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline (RecyclerView.java:5750)
  at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition (RecyclerView.java:5589)
  at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition (RecyclerView.java:5585)
  at android.support.v7.widget.LinearLayoutManager$LayoutState.next (LinearLayoutManager.java:2231)
  at android.support.v7.widget.LinearLayoutManager.layoutChunk (LinearLayoutManager.java:1558)
  at android.support.v7.widget.LinearLayoutManager.fill (LinearLayoutManager.java:1518)
  at android.support.v7.widget.LinearLayoutManager.onLayoutChildren (LinearLayoutManager.java:610)
  at android.support.v7.widget.RecyclerView.dispatchLayoutStep2 (RecyclerView.java:3719)
  at android.support.v7.widget.RecyclerView.dispatchLayout (RecyclerView.java:3436)
  at android.support.v7.widget.RecyclerView.onLayout (RecyclerView.java:3988)
  at android.view.View.layout (View.java:19692)
  at android.view.ViewGroup.layout (ViewGroup.java:6057)
  at android.support.v4.view.ViewPager.onLayout (ViewPager.java:1769)
  at android.view.View.layout (View.java:19692)
  at android.view.ViewGroup.layout (ViewGroup.java:6057)
  at android.support.design.widget.HeaderScrollingViewBehavior.layoutChild (HeaderScrollingViewBehavior.java:132)
  at android.support.design.widget.ViewOffsetBehavior.onLayoutChild (ViewOffsetBehavior.java:42)
  at android.support.design.widget.AppBarLayout$ScrollingViewBehavior.onLayoutChild (AppBarLayout.java:1361)
  at android.support.design.widget.CoordinatorLayout.onLayout (CoordinatorLayout.java:874)
  at android.view.View.layout (View.java:19692)
  at android.view.ViewGroup.layout (ViewGroup.java:6057)
  at android.support.v4.widget.DrawerLayout.onLayout (DrawerLayout.java:1172)
  at android.view.View.layout (View.java:19692)
  at android.view.ViewGroup.layout (ViewGroup.java:6057)
  at android.widget.FrameLayout.layoutChildren (FrameLayout.java:323)
  at android.widget.FrameLayout.onLayout (FrameLayout.java:261)
  at android.view.View.layout (View.java:19692)
  at android.view.ViewGroup.layout (ViewGroup.java:6057)
  at android.widget.LinearLayout.setChildFrame (LinearLayout.java:1791)
  at android.widget.LinearLayout.layoutVertical (LinearLayout.java:1635)
  at android.widget.LinearLayout.onLayout (LinearLayout.java:1544)
  at android.view.View.layout (View.java:19692)
  at android.view.ViewGroup.layout (ViewGroup.java:6057)
  at android.widget.FrameLayout.layoutChildren (FrameLayout.java:323)
  at android.widget.FrameLayout.onLayout (FrameLayout.java:261)
  at android.view.View.layout (View.java:19692)
  at android.view.ViewGroup.layout (ViewGroup.java:6057)
  at android.widget.LinearLayout.setChildFrame (LinearLayout.java:1791)
  at android.widget.LinearLayout.layoutVertical (LinearLayout.java:1635)
  at android.widget.LinearLayout.onLayout (LinearLayout.java:1544)
  at android.view.View.layout (View.java:19692)
  at android.view.ViewGroup.layout (ViewGroup.java:6057)
  at android.widget.FrameLayout.layoutChildren (FrameLayout.java:323)
  at android.widget.FrameLayout.onLayout (FrameLayout.java:261)
  at com.android.internal.policy.DecorView.onLayout (DecorView.java:759)
  at android.view.View.layout (View.java:19692)
  at android.view.ViewGroup.layout (ViewGroup.java:6057)
  at android.view.ViewRootImpl.performLayout (ViewRootImpl.java:2515)
  at android.view.ViewRootImpl.performTraversals (ViewRootImpl.java:2224)
  at android.view.ViewRootImpl.doTraversal (ViewRootImpl.java:1410)
  at android.view.ViewRootImpl$TraversalRunnable.run (ViewRootImpl.java:6834)
  at android.view.Choreographer$CallbackRecord.run (Choreographer.java:1039)
  at android.view.Choreographer.doCallbacks (Choreographer.java:851)
  at android.view.Choreographer.doFrame (Choreographer.java:742)
  at android.view.Choreographer$FrameDisplayEventReceiver.run (Choreographer.java:1025)
  at android.os.Handler.handleCallback (Handler.java:789)
  at android.os.Handler.dispatchMessage (Handler.java:98)
  at android.os.Looper.loop (Looper.java:164)
  at android.app.ActivityThread.main (ActivityThread.java:6809)
  at java.lang.reflect.Method.invoke (Native Method)
  at com.android.internal.os.Zygote$MethodAndArgsCaller.run (Zygote.java:240)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:767)

So it's a android.content.res.Resources$NotFoundException inside my onBindViewHoler.
Here is my code
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

    BookItemViewHolder bookItemHolder = (BookItemViewHolder) holder;
    BookModel book = mRecyclerViewItems.get(position);

    // Add the book item details to the book item view.
    bookItemHolder.getTextViewName().setText(book.getName());
    bookItemHolder.getTextViewAuthor().setText(book.getAuthor());
    bookItemHolder.getTextViewYear().setText(book.getYear() + "");

    // Book Covers
    int resourceId = mContext.getResources().getIdentifier(book.getCover(), "drawable", mContext.getPackageName());
    Drawable drawable = mContext.getResources().getDrawable(resourceId); //Error Here!
    bookItemHolder.getImageViewCover().setImageDrawable(drawable);
}

My book cover images are contained inside the drawable-nodpi folder.
To remind you again, this happens ONLY on some Android 8.0 devices.
Thank you

A: I get the same error, but only when downloaded from google play, local apk load from Android Studio work just fine.
11-28 17:13:16.271 788-7441/? I/ActivityManager: START u10 {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=au.com.forward.pfodAppDemo/.pfodAppDemo bnds=[297,434][579,758] (has extras)} from uid 1010035
11-28 17:13:16.294 788-913/? W/WindowManager: Token{153434f ActivityRecord{731b9ae u10 au.com.forward.pfodAppDemo/.pfodAppDemo t1000970}} failed creating starting window
    android.content.res.Resources$NotFoundException: Resource ID #0x7f080074
        at android.content.res.ResourcesImpl.getValueForDensity(ResourcesImpl.java:224)
        at android.content.res.Resources.getDrawableForDensity(Resources.java:876)
        at android.content.res.Resources.getDrawable(Resources.java:819)
        at android.content.Context.getDrawable(Context.java:605)
        at com.android.internal.widget.ToolbarWidgetWrapper.setIcon(ToolbarWidgetWrapper.java:322)
        at com.android.internal.widget.ActionBarOverlayLayout.setIcon(ActionBarOverlayLayout.java:742)
        at com.android.internal.policy.PhoneWindow.installDecor(PhoneWindow.java:2685)
        at com.android.internal.policy.PhoneWindow.getDecorView(PhoneWindow.java:2067)
        at com.android.server.policy.PhoneWindowManager.addSplashScreen(PhoneWindowManager.java:2965)
        at com.android.server.wm.SplashScreenStartingData.createStartingSurface(SplashScreenStartingData.java:55)
        at com.android.server.wm.AppWindowContainerController.lambda$-com_android_server_wm_AppWindowContainerController_4735(AppWindowContainerController.java:145)
        at com.android.server.wm.-$Lambda$aEpJ2RCAIjecjyIIYTv6ricEwh4.$m$4(Unknown Source:4)
        at com.android.server.wm.-$Lambda$aEpJ2RCAIjecjyIIYTv6ricEwh4.run(Unknown Source:27)
        at android.os.Handler.handleCallback(Handler.java:790)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:164)
        at android.os.HandlerThread.run(HandlerThread.java:65)
        at com.android.server.ServiceThread.run(ServiceThread.java:46)

Update - 30th Nov 2018
I have 3 apps with the same base code.  But when this app is downloaded from Google Play it is missing its icon (which happens to be the resource ID in the error above)
Now the other two apps have icons for ALL the screen densitys, while this app only as 3 densities specified, drawable, drawable_hdpi and drawable_mdpi.
I.E. the other apps that download correctly have icons for all the densities, the above 3 plus extra ones for xhdpi, xxhdpi and xxxhdpi.
Perhaps Google's new resource stripping procedure is removing the icon's whose densities don't match Android 8 Nexus 3 but not leaving a default one.
Awaiting a response from Google Play to this problem.


text:
Q: How to safely prevent graceful close of SSLSocket from sending "user canceled" alert We have a Java 17 Quarkus application compiled to a native executable (ubi-quarkus-native-image:22.2-java17), running in Kubernetes. It is connecting to an old integration server with SSL, making a HTTP request. Our application creates a SSLSocket using a socket factory and connects it; the request is successful. When it is done, we call SSLSocket#close. This works too, but on the other side they log this:
12:51:16 : ssl_debug(58): Shutting down SSL layer...
12:51:16 : ssl_debug(58): Sending alert: Alert Warning: close notify
12:51:16 : ssl_debug(58): Read 15328 bytes in 3 records, 15214 bytes net, 5071 average.
12:51:16 : ssl_debug(58): Wrote 175 bytes in 1 records, 152 bytes net, 152 average.
12:51:16 : ssl_debug(58): Closing transport...
12:51:16 : ssl_debug(58): Waiting on peer close notify...
12:51:16 : ssl_debug(58): Received alert message: Alert Warning: user canceled
12:51:16 : ssl_debug(58): Exception reading SSL message: iaik.security.ssl.SSLException: Peer sent alert: Alert Warning: user canceled
12:51:16 : ssl_debug(58): Closing transport...
12:51:16 : ssl_debug(58): Transport closed.

As far as I can understand they should get a close notify alert from us and we should get a close notify alert from them. Unfortunately our side sends a user canceled alert (code 90). It is only a warning, but they treat it as an error and throw away the entire request, even though they have answered.
I have found a way to circumvent this. If I call shutdownOutput on the socket before close, things work. However, according to properly close SSLSocket this is wrong and it really feels like a dirty workaround.
I can't get the other vendor to fix the error handling in their application. Is there a nicer way to avoid sending the user canceled alert? Is it a bug in the SSL implementation, or is it expected?
The socket has been flushed before close in both cases and reading from it (making sure there is no pending inbound data) makes no difference. Waiting for up to a minute before closing makes no difference either.


text:
Q: Differential continuity equation for Fluid (conservation of mass) I know the equation can be written in this way:
$$\frac{\partial \rho}{\partial t} + \nabla  \cdot (\rho \vec{v})=0$$
How can i write this equation to
$$\frac{\partial \rho}{\partial t} + \rho \nabla  \cdot (  \vec{v})=0$$

A: In general, $\nabla \cdot (\rho \vec v)=\nabla (\rho) \cdot \vec v+\rho \nabla \cdot (\vec v)$.  If $\nabla \rho =0$, then
$$\nabla \cdot (\rho \vec v)=\rho \nabla \cdot (\vec v)$$
Note that $\nabla \rho =0$ implies that $\rho$ does not depend on the spatial coordinates.


text:
Q: How can I get "index out of range" when I am not indexing Long time programmer - total newbie in go.
Here's the code. It is my first attempt at a generator. I am trying to generate an lfsr sequence. Essentially, every time around you shift right one. If you just shifted out a 1 bit, xor with the tap value.
package main

import (
    "fmt"
    "math/big"
)

// lfsr returns an lfsr generator.
func lfsr(tap, start big.Int) func() big.Int {
    // Keep track of next.
    next := &start
    // The generator.
    return func() big.Int {
        // Remember where we are.
        ret := *next
        // Work out next.
        fmt.Println("next", next.String(), "bit(0)", next.Bit(0))
        // Is it currently odd?
        odd := next.Bit(0)
        // Shift right one.
        next = next.Rsh(next, 1)

        // If odd - tap!
        if odd != 0 {
            // Tap!
            next = next.Xor(next, &tap)
            fmt.Printf("Tap!", next.String())
        }

        // Return where we were.
        return ret
    }
}

func main() {
    ten := new(big.Int)
    ten.SetString("10", 32)
    f := lfsr(*ten, *ten)
    for i := 0; i < 10; i++ {
        n := f()
        fmt.Println("lfsr ", n.String())
    }
}

The printout I am getting is:
next 32 bit(0) 0
lfsr  16
next 16 bit(0) 0
lfsr  8
next 8 bit(0) 0
lfsr  4
next 4 bit(0) 0
lfsr  2
next 2 bit(0) 0
lfsr  1
next 1 bit(0) 1
Tap! 0
panic: runtime error: index out of range

What am I doing wrong - and why does it look right?
Play - Interestingly - it outputs:
...
next 1 bit(0) 1
Tap!%!(EXTRA string=0)panic: runtime error: index out of range

goroutine 1 [running]:
math/big.nat.string(0xc010045150, 0x1, 0x5, 0x12b23d0, 0xa, ...)
    go/src/pkg/math/big/nat.go:819 +0x67f
math/big.nat.decimalString(0xc010045150, 0x1, 0x5, 0x1, 0x1, ...)
    go/src/pkg/math/big/nat.go:731 +0x8f
math/big.(*Int).String(0x7f851e0eff40, 0xc010045150, 0x1)
    go/src/pkg/math/big/int.go:331 +0xfe
main.main()
    /tmpfs/gosandbox-94dce1ec_430947f1_6360662e_01c3d6ad_a7071d20/prog.go:41 +0x120

which is a) slightly different and b) suggesting that the fmt.Println("lfsr ", n.String()) is what is failing but I am no nearer working out why.
Added
After experimentation (changing ten.SetString("10", 32) to ten.SetString("10", 10)) I now get:
lfsr  5
next 5 bit(0) 1
Tap!%!(EXTRA string=0)panic: runtime error: index out of range

Going to sleep now - hope someone can help.

A: It seems to be caused by the String() implementation on big.Int. You can leave out the String() call on n and let Println figure out how to print the argument itself:
func main() {
    ten := new(big.Int)
    ten.SetString("10", 32)
    f := lfsr(*ten, *ten)
    for i := 0; i < 10; i++ {
        n := f()
        fmt.Println("lfsr ", n)
    }
}

A: It is not safe to copy big.Int. In particular dereferencing a *big.Int and assigning it to a value does not work. The underlying array is aliased instead of copied. as the array can mutate in ways that break the invariants.
The line ret := *next is the source of your bug.
http://play.golang.org/p/W_qOCDsO2A
i := big.NewInt(1)
j := *i
fmt.Println("i:", *i, "j:", j) // i: {false [1]} j: {false [1]}
i = i.Xor(i, i)
fmt.Println("i:", *i, "j:", j) // i: {false []} j: {false [0]}
//j's state has changed, it now violates the invariants
j.String() //boom

The way to copy a big.Int is ret := *new(big.Int).Set(next). I think there should be func Copy(n *big.Int) *big.Int that does this, as the syntax is a bit ugly. Also I would avoid using big.Int as a value at all and change lfsr to return a pointer.
Working example http://play.golang.org/p/WEFRnGlU1H.


text:
Q: Where does BioPython store information related to various chemical molecules? If we reconstruct a protein from a PDB file, is it enough to have a PDB file, or do we need more info external to the PDB?
Take, for example, the BioPython framework. If any info is needed external to the PDB files, where does this framework store them?
Can I open and check to see those files?

A:
If we reconstruct a protein from a PDB file, is it enough to have a   PDB file, or do we need more info external to the PDB?

To my mind come up the missing hydrogens problem and the incomplete protein sequence, but I could be missing more
copied from https://www.umass.edu/microbio/chime/pe_beta/pe/protexpl/help_hyd.htm

Hydrogens in PDB files.

X-ray crystallography cannot resolve hydrogen atoms in most protein crystals, so in most PDB files, hydrogen atoms are absent. Sometimes hydrogens are added by modeling. Hydrogens are always present in PDB files resulting from NMR analysis, and usually present in theoretical models. For a brief introduction to X-ray crystallography, resolution, and NMR, see Nature of 3D Structural Data.

In proteins, the average number of hydrogens per non-hydrogen atom, weighted to take into account the frequencies of amino acids, is 1.01. Thus, hydrogens are ~50% of all atoms in protein. Nucleic acids have fewer, ~35%. High resolution protein crystallography (1.2 Ångstroms or less) can assign some hydrogen positions from the electron density map. Thus, the X-ray model of a tyrosine kinase SH2 domain 1lkk at 1.0 Angstrom resolution contains 902 hydrogens and 923 non-hydrogen protein atoms (ratio 0.98, 49%), so approximately all of the hydrogens actually present are assigned positions.

NMR methods also determine some hydrogen positions. Typically all hydrogens are modeled in before the molecule is folded to fit the NMR interatomic distance restraints; hence, all hydrogens are usually present in NMR models submitted to the PDB. The calmodulin ensemble of 25 NMR models 1cfc contains 1096 protein hydrogens and 1166 non-hydrogen protein atoms per model (ratio 0.94, 48.5%), thereby assigning positions for approximately all of the hydrogens actually present.

Most macromolecular crystals do not provide enough resolution to detect hydrogen positions. The X-ray model in PDB file 1hho for oxyhemoglobin (2.1 A resolution) contains no hydrogens, while the X-ray file 1lfa (1.8 A resolution; an integrin adhesion protein domain) contains 312 waters each with 2 hydrogens, and 645 protein hydrogens for 2,941 non-hydrogen protein atoms, accounting for only 22% of the hydrogens actually present in this protein. The protein hydrogens consist of one hydrogen on each backbone nitrogen (three hydrogens/amino terminal nitrogen), and hydrogens on sidechain oxygens or nitrogens in ser,thr,tyr, lys,arg,his, asn,gln. (None of the hydrogens covalently bonded to carbons are present.) The hydrogens which are present are required for the molecular dynamics stages of refinement of the X-ray model in the popular crystallographic refinement program X-PLOR; some authors strip them out before submitting a PDB file and others leave them in. (The Protein Data Bank accepts X-ray models either way, according to the preference of the depositor.)

Adding Hydrogens

If you wish to add hydrogens to a PDB file, see methods .........

References & Acknowledgements

Average protein hydrogens per non-hydrogen protein atom, weighted by average frequencies of amino acids, are based on 1,021 unrelated proteins of known sequence. Weights are tabulated on page 5 in Thomas E. Creighton's book "Proteins, Structures and Molecular Properties", 2nd ed. 1993, W. H. Freeman and Co.

Thanks to John Badger for contributing important information included in this document.

for the protein missing parts as an example you have program that could fill them comparing your protein to a similar complete one: https://salilab.org/modeller/wiki/Missing_residues, or other that could try to fill missing loops http://opig.stats.ox.ac.uk/webapps/fread/php/tutorial.php, no idea if you could use https://alphafold.ebi.ac.uk/ in same way, or could just get their structure
Better explained here:
https://pdb101.rcsb.org/learn/guide-to-understanding-pdb-data/missing-coordinates-and-biological-assemblies


text:
Q: How to extract a numeric id from a string using groovy in SOAP UI One of the service is returning a field with a value like this one below , I want to extract the number '2734427' from the below string using Groovy in SOAP UI
[[https%3a%2f%2fthis.is.a.sample.link%2fproduct-data-v1%2f/jobs/2734427]]
I have used the below lines of codes - which works , but it looks a bit hacky .Was wondering if anyone could suggest a better option.
//Get the value of the Job Id Link
def gtm2joblink = "[[https%3a%2f%2fthis.is.a.sample.link%2fproduct-data-v1%2f/jobs/2734427]]"
// split jobid full link for extracting the actual id
def sub1 = { it.split("jobs/")[1] }
def jobidwithbrackets = sub1(gtm2joblink)
// split jobid full link for extracting the actual id
def sub2 = { it.split("]]")[0] }
def jobid = sub2(jobidwithbracket)

log.info gtm2joblink

A: Sounds like a job for a regular expression. If the job ID always follows /jobs, and is always numeric, and there are always double brackets ]] at the end, then the following will extract the ID:
import java.util.regex.Matcher

//Get the value of the Job Id Link
def gtm2joblink = "[[https%3a%2f%2fthis.is.a.sample.link%2fproduct-data-v1%2f/jobs/2734427]]"

Matcher regexMatcher = gtm2joblink =~ /(?ix).*\\/jobs\\/([0-9]*)]]/
if (regexMatcher.find()) {
    String jobId = regexMatcher.group(1);
    log.info(jobId)
} else  {
    log.info('No job ID found')
}


text:
Q: How do I install Ubuntu in Xen virtual machine? Installing Xen on a host machine is easy, but installing an operating system inside a Xen virtual machine is poorly documented. Assume that the system I wish to setup:

*

*uses paravirtualization.

*uses an image file instead of LVM.

*has the kernel and initial RAM disk residing on the host machine instead of in the virtual machine image.

Where do I get the appropriate kernel and initial RAM disk files? How do I install the operating system in the virtual machine?

A: I guess the easiest way, would be using a graphical interface such as virt-manager. If you want to do it from command line, here is another post were they explain it:
How do I use Xen hypervisor?

A: You can install the Xen Tools from here and then use the command line tool to setup your PV Ubuntu VM per your specifications.
I've personally used these tools via the debootstrap method for a PV Debian VM and had terrific results.
More information on Xen Tools can be found here.
Keep in mind (taken from Xen Tools link): The biggest limitation is that it can only install a limited set of guests. The version of xen-tools in Debian testing can install most versions of Debian or Ubuntu, and also has support for CentOS 5 and 6. (The CentOS support is done using rinse rather than debootstrap.)
Hope this helps.


text:
Q: What happens when invoke Object.defineProperty for a function's prototype? var Foo = function(){};

Object.defineProperty(Foo.prototype,'x',{
    get(){
        return 3;
    }
});

var foo = new Foo();

console.dir(foo);

The result I am looking for should be
Foo {
    __proto__:{
        constructor: ƒ (),
        x: 3,
        __proto__: Object
    }
}

But the real result is
Foo {
    x: 3,
    __proto__:{
        constructor: ƒ (),
        x: 3,
        __proto__: Object
    }
}

Why is the x attribute already appearing at the outermost layer?

A: What Happened (Step-by-step)
var Foo = function(){};

A new function is defined, named - Foo. If we use console.dir(Foo) we will see that Foo has 2 special members prototype and __proto__
Object.defineProperty(Foo.prototype,'x',{
    get(){
        return 3;
    }
});

The prototype of Foo is updated. About defineProperty (From MDN):

The static method Object.defineProperty() defines a new property
directly on an object, or modifies an existing property on an object,
and returns the object.

So the prototype object is now modified with a new member named x. The prototype here acts as a c'tor and will "kick-off" when a new instance of Foo will be created
var foo = new Foo();

A new instance of Foo is created. the c'tor call is using Foo prototype and x getter is applied
Alternatives
Extending Foo prototype, thus making sure it will effect only objects created from Foo (as a class)
Object.defineProperty(Foo.prototype, 'x',
{
    get: () => 3
});

console.dir(new Foo().x) // will show 3
console.dir(Foo.x) // undefined - protorype is for class objects

Or extending Foo __proto__, thus updating Foo as a function and while not affecting objectes created from it
Object.defineProperty(Foo.__proto__, 'x',
{
    get: () => 3
});

console.dir(new Foo().x) // undefined - x is not a member of Foo
console.dir(Foo.x) // 3

Bonus: a very good article about JS prototypes and why this is happening
Original Answer
This is happening because in JS function is a way to declare BOTH functions and classes!
So your Foo function can be also used as a class
var Foo = function(){};
Foo(); // call Foo as a function
var obj = new Foo(); // initiate an instance from class Foo

Because you are using Foo.prototype object (as a function) and then you create a new instance from your Foo class you guarantee that:

*

*Your function prototype will be modified with your new getter

*Every new object (that inherits) from your class will also use your new getter (in object level)

I really think that your code should be something like this instead:
function Foo ()
{
    Object.defineProperty(this,'x',{
       get(){
           return 3;
       }
    });
}


text:
Q: Why I can't get the input value in my web service? I am trying to get my input value (which I posted to my restful web service using $http.post, AngularJS) using @POST, JAXB
Here is my java code:
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public StackDTO setNour(.....,
        @QueryParam("stack") String stack)
{
    System.out.println("nour call post");
    StackDTO json = new StackDTO();
    json.setStack(stack);
    return json;
}

In the StackDTO class, I have:
String stack;
....
public String getStack() {
    return stack;
}

public void setStack(String stack) {
    stack = stack;
}

I didn't get an error, post method is working since in the console , I got the call "nour call post"
Why I can't get the input value in my web service?

var req = {
 method: 'POST',
 url: 'http://example.com',
 headers: {
   'Content-Type':'application/x-www-form-urlencoded'
   // or  'Content-Type':'application/json'
 },
 data: { test: 'test' }
}

$http(req).then(function(){...}, function(){...});
<form ng-submit="save()">
      <input ng-model="stack"></input>
      <button type="submit">Save</button>
</form>

A: Try this-:
     String stack;
      ....
     public String getStack() {
     return stack;
      }

   public void setStack(String stack) {
    this.stack = stack;
 }


text:
Q: How can I efficiently find out what certs I need to add to my Java keystore? PKIX path building failed; We've all seen it before.  In a complex environment there can be many certs missing.  Is there a simple way to determine which urls are failing to reduce the amount of guess & check work on the keystore?
For a little more context, I did find the class making the call and attempt to do some logging, but the url being requested is pretty obfuscated.  Is it possible to get javax.net.ssl to give more information about the failed request?

A: If you need to see thorough and detailed output about the certificate store, you can pass the debug SSL flag into the program's execution arguments.
-Djavax.net.debug=ssl
More info can be found on the official Oracle documentation page: "Debugging SSL/TLS Connections"


text:
Q: DateTimePicker Date formatting value I am getting date value correctly from DateTimePicker using DateTimePicker.Value.
However I wish to format my date to be YYYYMMDD (ex: "20151020"). Is this possible please?

A: Simple formating can be achieved by using the following code.
DateTimePicker.Value.ToString("yyyyMMdd");

A: DateTimePicker.Value returns DateTime, not a string. A DateTime does not have any implicit format. It just have date and time values. It's textual representation can have a format which is usually done with ToString() method like;
string myFormat = DateTimePicker.Value.ToString("yyyyMMdd", CultureInfo.InvariantCulture);

Remember, there is no YYYY and DD as a custom date and time format strings. They should be as yyyy and dd since they are case sensitive.

A: Seems you want to have your result in string format:
string dateFormat = "yyyyMMdd";
string result = DateTimePicker.Value.ToString(dateFormat);

For other formats, here's the reference:
http://www.csharp-examples.net/string-format-datetime/


text:
Q: Replacement for Jquery UI command growlUI in JQuery? $.growlUI - is there a replacement for this.  I want to go from Jquery UI to Jquery in Bootstrap.
Basically a button in a modal is being pressed:

and here is the Jquery UI being called:
$(".remove").click(function(){
var auditID = this.id;
// $.blockUI({message: $('#question_alert')});
//Continue with unanswered questions
$('#yes_delete').click(function() {
  $.post("edit_audits.php?action=delete&auditID="+auditID,
  function(data) {

    if(data) alert(data);
      $.growlUI('Success','You have successfully DELETED the audit.','success',1000);
       setTimeout(function() {
         window.location.reload();
      }, 2000);
    return false;
  });
});
//Fix answered questions
$('#no_delete').click(function() {
  $.unblockUI();
  return false;
});
});

How would you call a new modal instead of using $.growlUI?

A: Haven't used the growl UI tool; but Bootstrap has excellent documentation on working with the built-in modal component: http://v4-alpha.getbootstrap.com/components/modal/


text:
Q: PostgreSQL need to compare with a set of values, and results shouldnt be empty I need to compare my field with each value in the array
My queries in code are somehing like this:
1) SELECT agentVersion, lastModified
FROM am.agents
WHERE "name"='xxx';
if err != sql.ErrNoRows {
return
}

2) SELECT agentVersion, lastModified
FROM am.agents
WHERE "name"='xyz';
if err != sql.ErrNoRows {
return
}

3) SELECT agentVersion, lastModified
FROM am.agents
WHERE "name"='zzz';
if err != sql.ErrNoRows {
return
}

Can I make it all in one postgresql query? Thank you!

A: This presupposes your dataset is reasonably small OR indexed with the number of actual choices being small.  If your dataset is huge and there are tens of thousands of possibilities, then this would not scale well at all.  If that's the case, I'd recommend a function where you pass an array (or variadic).
So simple solution if you are guaranteed to only have one row of output:
SELECT agentVersion, lastModified
FROM am.agents
WHERE "name" in ('xxx','xyz','zzz')
order by array_position (array['xxx','xyz','zzz'], name)
limit 1

If it's possible to have more than one row (from each of your queries 1, 2 and 3) then something like this might be necessary.
with cte as (
  SELECT
    agentVersion, lastModified,
    array_position (array['xxx','xyz','zzz'], name) as pos
  FROM am.agents
  WHERE "name" in ('xxx','xyz','zzz')
)
select agentVersion, lastModified
from cte
where pos = (select min (pos) from cte)

What I hate about these is they fetch data only to discard it.  Your solution is actually more efficient.


text:
Q: ¿Cómo enviar un correo de respuesta automática de un formulario? estoy haciendo un codigo en Google Apps Script, lo que deseo que haga es que envíe un correo de respuesta automática cada vez que envíe una respuesta nueva de un formulario que tengo asociado a una hoja de  calculo, tengo este codigo pero cuando envio varias respuesta, se envía el correo, pero cada vez que alguien envíe una nueva respuesta vuelve a ejecutarse y vuelve a enviarse todos los correos que hay en la hoja de cálculo. Tengo el trigger, pero tengo ese problema.
Este es el codigo que estoy utilizando.
function myFunction() {
  var sheet = SpreadsheetApp.getActive();
  var rows = sheet.getDataRange();
  var numRows = rows.getNumRows() - 1;
  var values= rows.getValues();

for(var i = 1; i<= numRows; i++){
  var email=values[i][2];
  var nombre=values[i][1];
  var archivo=values[i][3];
  var file;
  var adminEmail="CorreoDondeVaAllegarTodosLosRegistrados@correo.com";

GmailApp.sendEmail(email, "Correo de confirmacion", "Hola "+nombre+", gracias por haberte registrado");
GmailApp.sendEmail(adminEmail, "Nuevo usuario registrado", "Nuevo usuario registrado desde el formulario de bienestar: "+nombre+"\nEmail: "+email);
  }

}

A: Usando el objeto evento del form, recupera las respuestas de tu formulario para despues con ellas construir el mensaje y enviar el correo cada vez que se reciba una nueva respuesta, configura el trigger para que se ejecute al enviar el formulario.
function formSubmitReply(e) {

var timestamp =e.values[0];
var Respuesta1 =e.values[1];
var Respuesta2 =e.values[2];

var correo ="micorreo@ejemplo.com.mx";
var Asunto = "Mi asunto ";
var emailBody = "Se obtuvieron las siguintes respuestas"+
               "\n" +
               "\nPregunta1:"  + Respuesta1 +
               "\nPregunta2:"  + Respuesta2 ;

MailApp.sendEmail(correo, Asunto, emailBody);
}

A: El problema ocurre porque tu script está recorriendo todos los datos.
Tienes varias alternativas

*

*Mejor opción Usa objeto evento del activador "form submit" de la hoja cálculo como argumento de tu función y en lugar de usar getDataRange usa alguna de las propiedades de dicho objeto. Tal vez lo más sencillo sea usar la propiedad range pues haciendo esto serían mínimos los cambios que deberás realizar a tu código. En mi respuesta a ¿Cómo puedo probar una función disparadora en Google Apps Script hay un ejemplo además que trata sobre cómo probar este tipo de funciones.

*Agrega una columna para registrar el estado de enviado y una condición para hacer que el envío ocurra sólo para las filas que no tengan dicho estado. Esto podría causar problemas si tienes envíos de respuesta simultáneos o varios usuarios modificando la hoja de cálculo.


text:
Q: I am trying to convert xml to json using groovy script .how can i get in iteratively so that i dont need to give index manually here is the xml
  <book>
    <title>Groovy</title>
    <author>Ken Barclay</author>
    <publisher>Elsevier</publisher>
    <isbn number='1111111111' />
  </book>
  <book>
    <title>Object Oriented Design</title>
    <author>John Savage</author>
    <publisher>Elsevier</publisher>
    <isbn number='2222222222' />
  </book>
  <book>
    <title>C Programming</title>
    <author>Ken Barclay</author>
    <publisher>Prentice Hall</publisher>
    <isbn number='3333333333' />
  </book>
</catalogoue>

and here is the script that i wrote
import groovy.util.*
import java.io.*
import groovy.xml.*
import groovy.json.JsonBuilder
def trial = new XmlParser()
def test = trial. Parse("C:/Users/lenovo/Desktop/1b adangals/groovy/library.xml");
def nam ="${test.book[0].title.text()}"
println "${it.test.book[0].publisher. Text()}"
def writer = new StringWriter()
def builder = new JsonBuilder(writer)
builder.doc {
    dox {
    /*doc "${(test.book[0].text())}"*/
    name "${nam}"
    }
    scripter "${test.book[0].publisher. Text()}"

}
println builder.toPrettyString()
println "${nam}"

i have to develop a customized json from above xml ,where I am getting data from the first part only due to given index [0] .how can get it in iterative way?
the solution I needed is without ',' separator in JSON and "doc" as Root node .
      "doc": {
          "dox": { "name": "Groovy"
                 }
          "dox": { "name": "Object Oriented Design"
                 }
          "dox": { "name": "C Programming"
                 }
          } ```
 like this .
"scripter" is not required.
Could you help me out here.It would be helpful to me if you suggest me any references to work on JSON-XML & vice versa conversions using groovy.

A: import groovy.xml.*
import groovy.json.JsonBuilder

def trial = new XmlParser()
def test = trial.parseText('''
<catalogoue>
  <book>
    <title>Groovy</title>
    <author>Ken Barclay</author>
    <publisher>Elsevier</publisher>
    <isbn number='1111111111' />
  </book>
  <book>
    <title>Object Oriented Design</title>
    <author>John Savage</author>
    <publisher>Elsevier</publisher>
    <isbn number='2222222222' />
  </book>
  <book>
    <title>C Programming</title>
    <author>Ken Barclay</author>
    <publisher>Prentice Hall</publisher>
    <isbn number='3333333333' />
  </book>
</catalogoue>
''')

def data =
    [
        doc: test.book.collect{book->
            [
                dox:[
                    name: book.title.text()
                ],
                //scripter: book.publisher.text()
            ]
        }
    ]

def builder = new JsonBuilder(data)
println builder.toPrettyString()

result:
{
    "doc": [
        {
            "dox": {
                "name": "Groovy"
            }
        },
        {
            "dox": {
                "name": "Object Oriented Design"
            }
        },
        {
            "dox": {
                "name": "C Programming"
            }
        }
    ]
}


text:
Q: C# WPF не работает команда dotnet publish я хочу собрать свое WPF приложение со всеми его зависимостями в архив с .exe файлом, чтобы я мог перекидывать готовый проект на другие компьютеры. Из глубин интернета я выудил, что мне может помочь вот эта команда
dotnet publish -c Release --self-contained -r win-x64

Но при попытке запустить ее с моим wpf проектом, я получаю вот такую гору ишибок
Microsoft (R) Build Engine версии 16.9.0+57a23d249 для .NET
(C) Корпорация Майкрософт (Microsoft Corporation). Все права защищены.

  Определение проектов для восстановления...
  Работы нет. Ни в одном из указанных проектов нет пакетов, которые можно было бы восстановить.
C:\Program Files\dotnet\sdk\5.0.201\Microsoft.Common.CurrentVersion.targets(3136,5): error MSB4216: не удалось выполнить задачу "GenerateResource", поскольку MSBuild не удалось создать сервер задач со средой выполнения "CLR4" и архитектурой "x86" или подключиться к нему.  Убедитесь, что (1) запрошенные среда выполнения и архитектура существуют на компьютере и (2) необходимый исполняемый файл "C:\Program Files\dotnet\sdk\5.0.201\MSBuild.exe" существует и может быть запущен. [D:\Code\Decoder_Study\Decoder_Study\Decoder_Study.csproj]
C:\Program Files\dotnet\sdk\5.0.201\Microsoft.Common.CurrentVersion.targets(3158,7): error MSB4028: не удалось получить выходные спецификации задачи "GenerateResource" из параметра "FilesWritten". Object does not match target type. [D:\Code\Decoder_Study\Decoder_Study\Decoder_Study.csproj]

И я понятия не имею в чем проблема, а интернет только запутывает. Проект не очень сложный, но использует стороннюю тему Material Desing. В проекте многое разбито на разные файлы, лежащие в разных директориях(Например, классы и flowdocument'ы)
В файле App.config нашел вот такую строчку. Возможно это поможет.
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />


text:
Q: IOs Swift Progress View Password Evaluacion Necesitaria poder reproducir algun componente parecido a

El cual tenga como una barra que indique con diferentes colores si la password esta muy debil , si es seguro   etc ,
Swift Xcode cualquier link de interes me ayuda, nisiquiera se como poder googlear esto gracias

A: Nunca lo he utilizado, pero tal vez esto te podría servir.
https://github.com/mattt/Navajo


text:
Q: Testing JSON Results from MVC 4 C# Controller So I have a controller that returns json to my views that I need to test. I have tried using reflection with a dynamic data type to access a sub property of a list but I keep getting something similar to 'unable to cast' errors. Basically I have a list within a list that I want to access and verify things about but I can't access it. Has anyone tested json returned from their controller before in MVC4 and have advice?
Code:
// arrange
        var repositoryMock = new Mock<IEdwConsoleRepository>();
        var date = -1;
        var fromDate = DateTime.Today.AddDays(date);
        EtlTableHistory[] tableHistories =
            {
                new EtlTableHistory
                    {
                        Table = new Table(),
                        RelatedStatus = new BatchStatus(),
                        BatchId = 1
                    }
            };
        EtlBatchHistory[] batchHistories = { new EtlBatchHistory
                                             {
                                                 Status = new BatchStatus(),
                                                 TableHistories = tableHistories
                                             } };

        repositoryMock.Setup(repository => repository.GetBatchHistories(fromDate)).Returns((IEnumerable<EtlBatchHistory>)batchHistories);
        var controller = new EdwController(new Mock<IEdwSecurityService>().Object, repositoryMock.Object);

        // act
        ActionResult result = controller.BatchHistories(1);

        // assert
        Assert.IsInstanceOfType(result, typeof(JsonResult), "Result type was incorrect");
        var jsonResult = (JsonResult)result;
        var resultData = (dynamic)jsonResult.Data;
        var returnedHistories = resultData.GetType().GetProperty("batchHistories").GetValue(resultData, null);

        var returnedTableHistoriesType = returnedHistories.GetType();
        Assert.AreEqual(1, returnedTableHistoriesType.GetProperty("Count").GetValue(returnedHistories, null), "Wrong number of logs in result data");

A: Here's an example:
Controller:

    [HttpPost]
    public JsonResult AddNewImage(string buildingID, string desc)
    {
        ReturnArgs r = new ReturnArgs();

        if (Request.Files.Count == 0)
        {
            r.Status = 102;
            r.Message = "Oops! That image did not seem to make it!";
            return Json(r);
        }
        if (!repo.BuildingExists(buildingID))
        {
            r.Status = 101;
            r.Message = "Oops! That building can't be found!";
            return Json(r);
        }

        SaveImages(buildingID, desc);
        r.Status = 200;
        r.Message = repo.GetBuildingByID(buildingID).images.Last().ImageID;

        return Json(r);
    }

    public class ReturnArgs
    {
        public int Status { get; set; }
        public string Message { get; set; }
    }

Test:

    [TestMethod]
    public void AddNewImage_Returns_Error_On_No_File()
    {
        // Arrange
        ExtendedBuilding bld = repo.GetBuildings()[0];
        string ID = bld.Id;

        var fakeContext = new Mock<HttpContextBase>();
        var fakeRequest = new Mock<HttpRequestBase>();

        fakeContext.Setup(cont => cont.Request).Returns(fakeRequest.Object);
        fakeRequest.Setup(req => req.Files.Count).Returns(0);

        BuildingController noFileController = new BuildingController(repo);
        noFileController.ControllerContext = new ControllerContext(fakeContext.Object, new System.Web.Routing.RouteData(), noFileController);

        // Act
        var result = noFileController.AddNewImage(ID, "empty");

        ReturnArgs data = (ReturnArgs)(result as JsonResult).Data;

        // Assert
        Assert.IsTrue(data.Status == 102);
    }

In your example it looks to me that the problem is here:
var resultData = (dynamic)jsonResult.Data;
var returnedHistories = resultData.GetType().GetProperty("batchHistories").GetValue(resultData, null);

The resultData object would be the exact type of the object that you returned in your action. So if you did something like:
List<String> list = repo.GetList();
return Json(list);

Then your resultData would be of type:
List<String>

Try making sure that you are returning your Object using the Json(obj) function.

A: You can deserialize your Json into a dynamic object and then ask for the property you want
Example:
dynamic obj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);

var propertyValue = obj.MyProperty; //Ask for the right property

You can add Json serializer from Nuget Json.Net package.


text:
Q: ActiveRecord RoR - Saving only new associated objects How can I save (insert) only associated objects without saving (updating) the base object?
For example I just want to save the phone numbers, I don't wan to resave/update the person object.
def create_numbers
  #params =>   person_id => 41, person => {:phone_number => '12343445, 1234566, 234886'}
  @person = params[:person_id]
  nums = params[:person][:phone_numbers].split(',')
  nums.each do |num|
    @person.phone_numbers.build(:number => num)
  end
  @person.save    #here I just want to save the numbers, I don't want to save the person.  It has read only attributes
end

Models:
Person < ...
  # id, name
  belongs_to :school, :class_name => :facility
  has_many :phone_numbers
end

PhoneNumber < ...
  # id, number
  belongs_to :person
end

This is a bit of a dumb example, but it illustrates what I'm trying to accomplish

A: How about @person.phone_numbers.create(:number => num)
The downside is that you wont know whether it failed or not - you can handle that, but it depends on how exactly you want to handle it.

A: The simplest approach is to replace your build(:number => num) with create(:number => num), which will build and save the phone_number object immediately (assuming it passes validation).
If you need to save them all after creating the whole set (for some reason), you could just do something like
@person.phone_numbers.each{|num| num.save}