text:
Q: Angular file not found after deploy to server for route specific url My angular app works perfectly on my localhost:4200. Now I have deploy it to the server. The homepage looks okay. It redirect to error page due to invalid URL. The valid url of the page is this.
I get valid page if the url has pass two route params in my local but for some reason it is not working on live server.
const routes: Routes = [
  {
    path:":restaurantId/:mobileNo",
    component: LandingComponent,
  },
  {
    path:"",
    component: LandingComponent,
    canActivate: [AuthGuard]

  },
  {
    path:"error",
    component: ErrorComponent,
  },
];

index.html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Freshii</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root></app-root>
</body>
</html>

A: This is because you are trying to access the url directly and you server does not have any information about this rout. This rout is only recognised by your angular app.
As i am not aware of your server configration now so i am not able to give you exact solution to fix it.
But if its an apache you can create an htaccess file and add the onfigration to first come at index.html before throwing an error

A: After this configuration made to this server ngix it is fix now.


text:
Q: Loop through object properties without reflection I have class MyModel and some object of MyModel.
I need for-loop or foreach properties of object without reflection. How implemented?
Class example:
public class MyModel
{
    public string Level1_TypeName { get; set; }
    public string Level1_AttrType { get; set; }
    public string Level1_AttrValue { get; set; }
    public string Level2_TypeName { get; set; }
    public string Level2_AttrType { get; set; }
    public string Level2_AttrValue { get; set; }
    public string Level3_TypeName { get; set; }
    public string Level3_AttrType { get; set; }
    public string Level3_AttrValue { get; set; }
    public string Level4_TypeName { get; set; }
    public string Level4_AttrType { get; set; }
    public string Level4_AttrValue { get; set; }
    public string Level5_TypeName { get; set; }
    public string Level5_AttrType { get; set; }
    public string Level5_AttrValue { get; set; }
    public string Level6_TypeName { get; set; }
}

A: You can use reflection to make a dictionary with all your values:
var obj = new MyModel();
var dictionary = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).ToDictionary(p => p.Name, p => p.GetGetMethod().Invoke(obj, null));
foreach (var kv in dictionary)
    Console.WriteLine(kv.Key + ": " + kv.Value ?? "null");

But I do recommend you read and use the answer of Jon Skeet
If you don't want to use reflection you can't loop through an objects properties.
You can use a bit of reflection in your model to implement an ienumerable:
public class MyModel : IEnumerable<KeyValuePair<string, object>>
{
    public string Level1_TypeName { get; set; }
    public string Level1_AttrType { get; set; }
    public string Level1_AttrValue { get; set; }
    public string Level2_TypeName { get; set; }
    public string Level2_AttrType { get; set; }
    public string Level2_AttrValue { get; set; }
    public string Level3_TypeName { get; set; }
    public string Level3_AttrType { get; set; }
    public string Level3_AttrValue { get; set; }
    public string Level4_TypeName { get; set; }
    public string Level4_AttrType { get; set; }
    public string Level4_AttrValue { get; set; }
    public string Level5_TypeName { get; set; }
    public string Level5_AttrType { get; set; }
    public string Level5_AttrValue { get; set; }
    public string Level6_TypeName { get; set; }

    public IEnumerator<KeyValuePair<string, object>> GetEnumerator()
    {
        return this.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).ToDictionary(p => p.Name, p => p.GetGetMethod().Invoke(this, null)).GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        throw new NotImplementedException();
    }
}

You can then use your class like this:
var obj = new MyModel();
foreach(var kv in obj)
    Console.WriteLine(kv.Key + ": " + kv.Value ?? "null");

A: I would strongly suggest that you take two actions:

*

*Create a new type to encapsulate the combination of TypeName, AttrType, AttrValue

*Change your model to contain a collection of that class rather than several separate properties.

At that point, it will be really easy to iterate over the properties without using reflection... and your code will be much clearer, too.

A: If you're looking to avoid reflection then you're going to have to write code by hand. You could add an method that returns an enumerator:
IEnumerable<Tuple<int,string,string,string>> GetLevels()
{
  yield return Tuple.Create(1, Level1_TypeName, Level1_AttrType, Level1_AttrValue);
  yield return Tuple.Create(2, Level2_TypeName, Level2_AttrType, Level2_AttrValue);
  yield return Tuple.Create(3, Level3_TypeName, Level3_AttrType, Level3_AttrValue);
  yield return Tuple.Create(4, Level4_TypeName, Level4_AttrType, Level4_AttrValue);
  yield return Tuple.Create(5, Level5_TypeName, Level5_AttrType, Level5_AttrValue);
  yield return Tuple.Create(6, Level6_TypeName, Level6_AttrType, Level6_AttrValue);
}

Now you can say:
foreach(var i in myModel.GetLevels())
{
  Console.WriteLine("{0},{1},{2},{3}",i.Item1,i.Item2,i.Item3,i.Item4);
}

A: Below code does not use reflections
using System.ComponentModel;

PropertyDescriptorCollection props = TypeDescriptor.GetProperties(instance);
foreach (PropertyDescriptor prop in props)
{
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Op Amp Oscillation BPW34 Radiation detection I have build the following circuit on a stripboard

Now the problem is, even if I do not have the BPW34 diode attached my output shows a nice sqaure wave as you can see here

But I have no idea where to start how to analyze where this comes from or why this happens. So I am very grateful for any ideas how to approach this problem. One addiational thing: I did not use the 330k Resisitors instead I used 300k resistors. Edit: The transistor is a BF245B.
Here you can see my stripboard.

This blue thing in the upper picture is a capacitor which is not connected. And remember: The BPW diode is missing but when it is soldered on the board and made lightproof it also starts oscillating with the same frequency and amplitude.

A: Look at the original PCB design from Elektor: -

It's a double sided board with a full coverage ground plane on the component side and a partial ground plane on the solder side. These ground planes are probably quite fundamental in achieving low noise and stability given that the circuit has an AC gain of 900.
You'd have to be at the top of your game to make this work consistently on strip board or just plain lucky.

A: It works. I only use a 10M\Omega Resistor from diode to ground instead of 20M\Omega so I think the Fet was biased wrong. I also put the whole stripboard into a metal case.

Look at this beautiful picture :-)
If someone could enlighten me why only using a 10M\Omega from diode to ground works but 20M\Omega does not work....this would be great.


text:
Q: Dom parser is not working- output shown is all null I want to parse this xml file called "Weather.xml" is shown below:
<?xml version ="1.0" encoding="UTF-8" ?>
   <weather>
       <forecast_information>
                                    <city data="Pittsford, NY" />
                                    <postal_code data="14534" />
                                    <forecast_date data="2015-03-12" />
                                    <unit_system data="US" />
                                  <condition data = "Mostly Cloudy" />
                                   <temp_f data ="42" />
                                   <wind_condition data="Wind: NW at 7 mph" />
                                    <day_of_week data="Sat" />
                                    <low data="32"/>
                                   <high data = "45" />
                                   <condition data="Rain and Snow" />
          </forecast_information>
         <forecast_information>
                                    <city data= "Rochester, NY" />
                                    <postal_code data="14623" />
                                   <forecast_date data= "2015-03-12" />
                                   <unit_system data="US" />
                                    <condition data="Partly Cloudy" />
                                    <temp_f data="40" />
                                    <wind_condition data="Wind: St at 3.5 mph"       />
                                     <day_of_week data="Mon" />
                                     <low data="30" />
                                     <high data="40" />
                                     <condition data="Bright and Sunny" />
            </forecast_information>
   </weather>

I have coded the DOM parser for it in the following way:
public class DomParserDemo {
 public static void main(String[] args){

  try {
     File inputFile = new File("Weather.xml");
     DocumentBuilderFactory dbFactory
        = DocumentBuilderFactory.newInstance();
     DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
     Document doc = dBuilder.parse(inputFile);
     doc.getDocumentElement().normalize();
     System.out.println("Root element :"
        + doc.getDocumentElement().getNodeName());
     NodeList nList = doc.getElementsByTagName("forecast_information");
     System.out.println("----------------------------");
     for (int temp = 0; temp < nList.getLength(); temp++) {
        Node nNode = nList.item(temp);
        System.out.println("\nCurrent Element :"
           + nNode.getNodeName());
        if (nNode.getNodeType() == Node.ELEMENT_NODE) {
           Element eElement = (Element) nNode;
           System.out.println("City : " + eElement.getAttribute("city"));

           System.out.println("Postal_Code : " + eElement.getElementsByTagName("postal_code").item(0).getTextContent());
           System.out.println("Forecast date : " + eElement.getElementsByTagName("forecast_date").item(0).getTextContent());
           System.out.println("Unit System : " + eElement .getElementsByTagName("unit_system") .item(0).getTextContent());
           System.out.println("Condition : " + eElement .getElementsByTagName("condition") .item(0).getTextContent());
           System.out.println("Wind Condition : " + eElement .getElementsByTagName("wind_condition") .item(0).getTextContent());
           System.out.println("Day of week : " + eElement .getElementsByTagName("day_of_week") .item(0).getTextContent());
           System.out.println("Low : " + eElement .getElementsByTagName("low") .item(0).getTextContent());
           System.out.println("High: " + eElement .getElementsByTagName("high") .item(0).getTextContent());

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

But the output shown is as follows, the information is not being extracted from the .xml file I provided:
   Root element :weather
   ----------------------------

   Current Element :forecast_information
   City :
   Postal_Code :
   Forecast date :
   Unit System :
   Condition :
   Wind Condition :
   Day of week :
   Low :
   High:

   Current Element :forecast_information
   City :
   Postal_Code :
   Forecast date :
   Unit System :
   Condition :
   Wind Condition :
   Day of week :
   Low :
   High:

A: In all your tags, there is no content. The data is an attribute, hence you need to get the value of the attribute using eElement.getAttribute("data");

A: First mistake:
System.out.println("City : " + eElement.getAttribute("city"));

You are asking for an attribute of your element named city, but the forecast_information element doesn't have any attributes. city is a child element of forecast_information, thus you should extract it either by traversing children or by using getElementsByTagName() as you do with the rest of the items.
Second mistake:
For all the other elements, you are doing getElementsByTagName, which works fine for retrieving the element itself. However, the data item which you want to retrieve is not their content - it's an attribute.
Using getTextContent() would be correct if the items looked like this:
<forecast_date>2015-03-12</forecast_date>
<unit_system>US</unit_system>

But this is not how your XML is formatted. In your XML, you need to retrieve the attribute data. So you should replace the calls like:
System.out.println("Postal_Code : " + eElement.getElementsByTagName("postal_code").item(0).getTextContent());

To:
System.out.println("Postal_Code : " + eElement.getElementsByTagName("postal_code").item(0).getAttribute("data"));


text:
Q: Python script stops running after running command using os.system() My python script freezes after running os.system(). The code looks like something below;
command_line = 'java -jar "backup.jar" test'
os.system(command_line)
# python script freezes at this point. Cannot move on to execute code below

For some reason, I suddenly encounter this problem today. No problem in the past. There was no error message. No hints on what's the problem. I did an update to latest Windows 10 package. Not sure if this is the cause.
If this problem can't be fixed, are there alternatives to os.system() to run a command such that python script doesn't freeze?
I am using python 3.8 on anaconda.

A: Change the command like below to see if there are any issues with command.
command_line = 'java -jar "backup.jar" test > /tmp/test.log'

You can verify /tmp/test.log to see if any issues with java command from the log.
os.system waits for response. Same can be achieved with subprocess.call() methods with return status (0 - if successful). To run command in background you can use subprocess.Popen() method.

A: I will answer my own question. It is based on the answer from rajendrau which I have marked as the correct answer. It works for me.
What I did was to use subprocess.Popen(). Script no longer "freezes" anymore.
subprocess.Popen(['java', '-jar', "backup.jar", 'test'])


text:
Q: ANTLR Plugin in eclipse sorry for my english! I install plagin in eclipse, but wen i run my little project i have this problem. Why its not work?

error(10):  internal error: Can't get property indirectDelegates using
  method get/isIndirectDelegates from org.antlr.tool.Grammar instance :
  java.lang.NullPointerException
  java.util.Objects.requireNonNull(Unknown Source)
  java.util.ArrayList.removeAll(Unknown Source)
  org.antlr.tool.CompositeGrammar.getIndirectDelegates(CompositeGrammar.java:222)
  org.antlr.tool.Grammar.getIndirectDelegates(Grammar.java:2620)
  sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
  sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
  java.lang.reflect.Method.invoke(Unknown Source)
  org.antlr.stringtemplate.language.ASTExpr.invokeMethod(ASTExpr.java:564)
  org.antlr.stringtemplate.language.ASTExpr.rawGetObjectProperty(ASTExpr.java:515)
  org.antlr.stringtemplate.language.ASTExpr.getObjectProperty(ASTExpr.java:417)
  org.antlr.stringtemplate.language.ActionEvaluator.attribute(ActionEvaluator.java:351)
  org.antlr.stringtemplate.language.ActionEvaluator.expr(ActionEvaluator.java:136)
  org.antlr.stringtemplate.language.ActionEvaluator.templateApplication(ActionEvaluator.java:216)
  org.antlr.stringtemplate.language.ActionEvaluator.expr(ActionEvaluator.java:126)
  org.antlr.stringtemplate.language.ActionEvaluator.action(ActionEvaluator.java:84)
  org.antlr.stringtemplate.language.ASTExpr.write(ASTExpr.java:149)
  org.antlr.stringtemplate.StringTemplate.write(StringTemplate.java:705)
  org.antlr.stringtemplate.language.ASTExpr.writeTemplate(ASTExpr.java:750)
  org.antlr.stringtemplate.language.ASTExpr.write(ASTExpr.java:680)
  org.antlr.stringtemplate.language.ASTExpr.writeAttribute(ASTExpr.java:660)
  org.antlr.stringtemplate.language.ActionEvaluator.action(ActionEvaluator.java:86)
  org.antlr.stringtemplate.language.ASTExpr.write(ASTExpr.java:149)
  org.antlr.stringtemplate.StringTemplate.write(StringTemplate.java:705)
  org.antlr.stringtemplate.language.ASTExpr.writeTemplate(ASTExpr.java:750)
  org.antlr.stringtemplate.language.ASTExpr.write(ASTExpr.java:680)
  org.antlr.stringtemplate.language.ASTExpr.writeAttribute(ASTExpr.java:660)
  org.antlr.stringtemplate.language.ActionEvaluator.action(ActionEvaluator.java:86)
  org.antlr.stringtemplate.language.ASTExpr.write(ASTExpr.java:149)
  org.antlr.stringtemplate.StringTemplate.write(StringTemplate.java:705)
  org.antlr.stringtemplate.language.ASTExpr.writeTemplate(ASTExpr.java:750)
  org.antlr.stringtemplate.language.ASTExpr.write(ASTExpr.java:680)
  org.antlr.stringtemplate.language.ASTExpr.writeAttribute(ASTExpr.java:660)
  org.antlr.stringtemplate.language.ActionEvaluator.action(ActionEvaluator.java:86)
  org.antlr.stringtemplate.language.ASTExpr.write(ASTExpr.java:149)
  org.antlr.stringtemplate.StringTemplate.write(StringTemplate.java:705)
  org.antlr.codegen.CodeGenerator.write(CodeGenerator.java:1281)
  org.antlr.codegen.Target.genRecognizerFile(Target.java:94)
  org.antlr.codegen.CodeGenerator.genRecognizer(CodeGenerator.java:466)
  org.antlr.Tool.generateRecognizer(Tool.java:641)
  org.antlr.Tool.process(Tool.java:454)

A: ANTLR 3 produces this message when used with Java 8. However, it doesn't seem to affect the actual output. Until the fix is released in a new version of ANTLR 3, you can either ignore the message, or use Java 7.
Related issue:
#151: NPE in CompositeGrammer.getIndirectDelegates in Java 8

A: I got a similar error running ANTLR 3.1.1 with Java 1.8. In my Ant Build file, I changed the attribute of the "java" task to "failonerror="false". I still got the error message, but my build stopped failing and produced the output that I wanted.

A: For java 8 and antlr 3, change the jar to "antlr-3.5.2-complete.jar" and the error will go away.

*

*update the ANTLR plugin to version 2.1.2

*Go to project properties-> ANTLR -> Building

*Uncheck "Enable project specific settings"

*Click "Configure Workspace Settings" -> ANTLR -> Builder -> Building

*Remove the installed 3.5.2 package

*Add installed packages and point it to the folder of "antlr-3.5.2-complete.jar"

*Save and come back to enable project specific settings.

*In the General-> ANTLR Runtime, select 3.5.2


text:
Q: How sum a field in a database I'm trying to group all fields with the same event name, and sum the participants of this fields.
{
    "_id": {
        "$oid": "54b6ae8aec17b5e905a5813a"
    },
    "person": {
        "name": "Something",
        "phone": "(011) 9468-1319",
        "email": "myemail@gmail.com",
        "obs": ""
    },
    "event": {
        "full": "20/11/01 Classic",
        "date": "20/11/01",
        "name": "Special",
        "participants": 10
    },
    "__v": 0
}
{
    "_id": {
        "$oid": "54b6aeaad7e410ec05dd1ca2"
    },
    "person": {
        "name": "Something",
        "phone": "(011) 9468-1319",
        "email": "myemail@gmail.com",
        "obs": ""
    },
    "event": {
        "full": "20/11/01 Classic",
        "date": "20/11/01",
        "name": "Special",
        "participants": 10
    },
    "__v": 0
}

I have just this two collections, and i am using the following code to a group by the event.full and them sum the participans (Number) field.
This is the code:
MyModel.aggregate(
    [
        { "$group":
            {
                _id: "$event.full",
                participants: { "$sum": "$participants" },
                count: { $sum: 1 }
            }
        },
        { "$skip": ( page-1 ) * 15 },
        { "$limit": 15 }
    ],
    function(err, obj) {
        res.send(obj);
    }
);

This is returning the following object:
[
 {
  _id: "20/11/01 Classic",
  participants: 0,
  count: 2
 }
]

Why the sum field is not working? How fix??

A: you missed the event use this:
[
        { "$group":
            {
                _id: "$event.full",
                participants: { "$sum": "$event.participants" },
                count: { $sum: 1 }
            }
        },
        { "$skip": ( page-1 ) * 15 },
        { "$limit": 15 }
 ]


text:
Q: Batch file for-loop with subrutine: Not forwarding parameter including spaces My problem is that the for-loop in my batch-script is reading pdf-file-paths from the "allepdfsnamen.txt" but is not forwarding these file-paths (which are including space-characters) correctly to the subroutine:

*

*%%X is the parameter (pdf-file-path) which can include spaces
e.g. "C:\Users\gruberw\Documents_OT_Tickets\20170320_I\Testpdfs\Scan Charge 31\0000000_134388_266737109_001.PDF"

*%1 the :body (subroutine) is only receiving file-path until first space-character-occurance

I have tried to put the paths which are provided to the for-loop in the "allepdfsnamen.txt" under double-quotes:

I have tried to put the parameter given to :body (%%X) under quotes.
Can anyone tell me how to correctly (complete file-path with space-characters) hand over a parameter to a subrutine (:body) ?

A: Better to cut-and-paste so it can be copied and run easily.
for /f "delims=" %%x

turns off the default tokenising using space-delimiter.
call :body "%%x"

quotes the string to be passed to the subroutine
echo %~1

strips the quotes from the first parameter


text:
Q: doFilter JSF User Authentication I am trying to use a doFilter and my web.xml page to force users to login to access any "secured" page.
I found an example here and I have implemented it. I am having a small issue though. When I put the filter definition into web.xml the entire website fails to load. I do believe this is because I do not have the proper class path to the java file which contains the filter.  I am showing you my web.xml page next to my project explorer.  I am hoping you can help me with the class path needed for the <filter-class>     </filter-class>
I am also showing my doFilter method
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    UserBean userBean = (UserBean)((HttpServletRequest)request).getSession().getAttribute("userBean");

    if(userBean == null || !userBean.isSuccessfullLogin()){
        String contextPath = ((HttpServletRequest)request).getContextPath();
        ((HttpServletResponse)response).sendRedirect(contextPath + "/index.xhtml");
    }
    chain.doFilter(request, response);
}

So far the rest of my server works, the website runs but I can not get the filter. Any suggestions are accepted!
Thank you!

A: I have not written any filters by now, but usually if you have to define a class in web.xml, it is named as
package.Class

So if your AuthenticationFilter class is in the package "my.filter.package" like so:
package my.filter.package;
public class AuthenticationFilter {...}

the filter class declaration should be
<filter-class>my.filter.package.AuthenticationFilter</filter-class>

A: I did get it to work last night. Filters.AuthenticationFilter works. It was my url pattern that was wrong.
Instead of having my url pattern as /secured/* I needed it to be /faces/secured/*


text:
Q: emacs F# mode REPL :: using Linq I am using mono in Ubuntu precise and have installed F# following the instructions found here.
I have also installed fsharp mode for emacs and so am able to test and compile simple F# programs (both on emacs F# mode REPL and also generate executables which I run under mono).
However, the statement:
open System.Xml.Linq

fails in both the emacs F# mode REPL and when invoking fsharpc from the bash shell with the same error:
error FS0039: The namespace 'Linq' is not defined

I found a similar post in SO for C#, and although the advise to use "-r: System.Xml.Linq" does works for the compilation from the shell:
fsharpc -r:System.Xml.Linq.dll parseemails.fs

... I still can't figure out how to make the Linq namespace available to emacs F# mode REPL so I can use it with C-c C-e evaluations.

A: As mentioned by John in a comment, if you want to reference an assembly in the F# interactive (the REPL running in emacs mode), you can do that using:
#r "System.Xml.Linq.dll"

When compiling code, this command is not valid and you have to add the command line argument -r:System.Xml.Linq.dll. If you want to combine both (run interactively and compile the same code), you can use conditional compilation:
#if INTERACTIVE
#r "System.Xml.Linq.dll"
#endif

The symbol INTERACTIVE is defined automatically in the REPL mode, so if you select and run these three lines, it should reference the assembly (but it will not break your code when compiling).


text:
Q: Configurar Spring Boot com Swagger para gerar documentação a partir de um json Bom dia pessoal.
Eu estou documentando as APIs de um projeto utilizando Swagger2.
Nessa documentação ao invés de utilizar anotações é utilizado um arquivo json.
Gostaria de saber se é possível criar um projeto Spring Boot com Swagger 2, que utilize o json para documentar as APIs.
Pesquisei na internet e só encontrei esse tutorial: https://dzone.com/articles/overcoming-swagger-annotation-overload-by-switchin?utm_content=bufferc0957&utm_medium=social&utm_source=twitter.com&utm_campaign=buffer
Segui os passos descritos, mas não funcionou.
A única forma que consegui foi baixando a pasta dist do projeto https://github.com/swagger-api/swagger-ui/tree/master/dist e apontando para o json, mas será que o Spring Boot não tem uma forma de configurar para que ele leia o json?

A: Existem duas formas de você trabalhar nesta situação.
API First: você possui o contrato desenhado primeiramente e deseja criar um scaffolding do projeto para Spring Boot. Para isso faça uso do swagger codegen.
Develop first: se você desenvolve a API e depois deseja criar um contrato para ela o framework SpringFox consegue te ajudar nesta situação.


text:
Q: Multithreading in Android - why doesn't my onCompleted callback get called? So I'm trying to add multithreading to my app and I'm running into a weird issue. I create a new runnable to handle parsing all the data so that the application doesn't freeze while it's doing so, and then create a new thread to run that runnable. However, when the thread starts and run() gets called, I noticed it never calls onCompleted(). This is weird to me because if I take that exact block of code out of the run() part, it works perfectly.
Can anybody let me know what I'm doing wrong? I'm a bit new to multithreading in Java, so I would really appreciate it.
    Runnable parseRunnable = new Runnable(){
        @Override
        public void run(){
            new Request(session, id + "/comments", null, HttpMethod.GET, new Request.Callback() {
                @Override
                public void onCompleted(Response response) {
                    try {
                        JSONArray msgs = response.getGraphObject().getInnerJSONObject().getJSONArray("data");
                        populateData(msgs);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    Request next = response.getRequestForPagedResults(Response.PagingDirection.NEXT);
                    retrieveMsgs(next);
                }
            }).executeAsync();
        }
    };

    Thread parseThread = new Thread(parseRunnable);
    parseThread.start();

I set a breakpoint at run() and at "new Request" which always gets hit, but when I set breakpoints for onCompleted(), those are never reached.

A: Your thread will finish when you reach the end of
public void run ()

I'm going to assume you don't get your callback because your thread has already finished since you call executeAsync (which will execute on a separate thread). Removing your thread altogether will probably fix your problem.


text:
Q: If $X \sim N(0,1)$, then $\varphi_{X}(t) = e^{-t^{2}/2}$ If $X \sim N(0,1)$, then
$\varphi_{X}(t) = e^{-t^{2}/2}$.
From the proof of the previous proposition, I have the following question: why is it enough to prove that $\max_{z\in I_2}|e^{-z^{2}/2}| \to 0 $ when $ n \to \infty$ and why is $0\leq s \leq t$ chosen? Also, at the end of the proof, when they take the maximum, I don't understand why $s$ is replaced by $t$.
I would appreciate some justification on this problem.
Proof.
\begin{align}
\varphi_{X}(t) &= \int{e^{itx}}dF_{X}(x)\\
&=\frac{1}{\sqrt{2\pi}}\int_{-\infty}^{\infty}{e^{itx-x^{2}/2}}dx \\
&=e^{-t^{2}/2}\cdot \frac{1}{\sqrt{2\pi}}\int_{-\infty}^{\infty}e^{-(x-it)^{2}/2}dx \hspace{0.4cm} \text{(completing squares)}\\
&=e^{-t^{2}/2}
\end{align}
where the last equation is verified as follows:
\begin{align}
\int_{-\infty}^{\infty}{e^{-(x-it)^{2}/2}}dx &= \lim_{n \to \infty}{\int_{-n}^{n}{e^{-(x-it)^{2}/2}}}dx\\
&=\lim_{n \to \infty}\int_{-n-it}^{n-it}{e^{-z^{2}/2}}dz \hspace{0.4cm} (\text{where} \hspace{0.3cm}z = x-it)
\end{align}
where the integration interval in this integral (for $n$ fixed and $t>0$) is $I_1$:

Since the function $f(z)= e^{-z^{2}/2}$ is analytic in the complex plane $\mathbb{C}$, Cauchy's theorem says that the integral of $f$ over any closed curve is zero. Then for $t>0$,
$$\int_{I_1}{e^{-z^{2}/2}}dz+\int_{I_2}{e^{-z^{2}/2}}dz+\int_{I_3}{e^{-z^{2}/2}}dz+\int_{I_4}{e^{-z^{2}/2}}dz=0$$
i.e.,
$$\int_{-n-it}^{n-it}{e^{-z^{2}/2}}dz = -\int_{I_2}{e^{-z^{2}/2}}dz + \int_{-n}^{n}{e^{-t^{2}/2}}dt - \int_{I_4}{e^{-z^{2}/2}}dz$$
Since $$\int_{-n}^{n}{e^{-t^{2}/2}}dt \to \int_{-\infty}^{\infty}{e^{-t^{2}/2}}dt = \sqrt{2\pi} \hspace{0.4cm} ( \text{when} \hspace{0.2cm} n \to \infty)$$
it is enough to prove that
$$\int_{I_2}{e^{-z^{2}/2}}dz \hspace{0.4cm} \text{and} \hspace{0.4cm} \int_{I_4}{e^{-z^{2}/2}}dz$$
tend to zero when $n \to \infty$ (thus it will be proven that $\varphi_{X} (t) = e^{-t^{2}/2}$, $t>0$. For $t<0$, the method is analogous, the only difference is that the intervals $I_2$ and $I_4$ invert the sense. Furthermore, it is enough to note that $X$ symmetric $\implies \varphi_{X}(t) = \varphi_{X}(-t)$ . For $t=0$, the result is obvious).
Let us prove that $$\int_{I_2}e^{-z^{2}/2}dz \to 0 $$ the proof that $$\int_{I_4}e^{-z^{2}/2}dz \to 0 $$is analogous.
Since the length of the interval $I_2$ is $t$, it suffices to prove that $$\max_{z\in I_2}|e^{-z^{2}/2}| \to 0 \hspace{0.4cm} \text{when} \hspace{0.2cm} n \to \infty$$ For $z=n-is$, where $0\leq s \leq t$, we have
$$z^2 = n^2 - s^2 -2nsi \hspace{0.5cm} \text{and} \hspace{0.5cm} e^{-z^{2}/2} = e^{(s^2 - n^2)/2}e^{nsi}$$
Since $|e^{it}| =1  \hspace{0.1cm} \forall t$, we have $|e^{-z^{2}/2}| = e^{(s^2 - n^2)/2}$. Therefore $$\max_{z \in I_2}{|e^{-z^{2}/2}|} = e^{(t^2 -  n^2)/2} \to 0 \hspace{0.4cm} \text{when} \hspace{0.3cm} n \to \infty$$
$\square$
Definition
Let $(\Omega, \mathcal{F}, P)$ be a probability space and $X$ be a random variable. The characteristic function of $X$, which we denote by $\varphi_{X}$, is:
$$\begin{array}{rccc}\varphi_X \colon&\mathbb{R}&\longrightarrow&\mathbb C\\&t&\mapsto&\displaystyle\varphi_{X}(t)\colon=\mathbb{E}[e^{itX}] = \int_{\mathbb{R}}e^{itx}dF_{X}(x)\end{array}$$

A: $|\int_{\gamma} f(z)dz| \leq Ml$ where $L$ is the length of $\gamma$ and $M$ is the maximum value of $|f(z)|$ on $\gamma$. In this case $t$ is fixed and $L=t$ so to show that the integral over $I_2$ tends to $0$ it is enough to show that $M \to 0$.
Points on the line segment  $I_21$ are of the type $n-is$ with $0 \leq s \leq t$. That is why they are taking $0 \leq s \leq t $ in estimating  $M$.


text:
Q: Ag-Grid, React, Redux Filters Issue - can not set setFilterModel() Here is my scenario,
I am making a onFetchEvents Redux Action call and getting all events and passing it as follows. rowData={this.props.events.data}
Everything works fine. Now I need to apply a filter, and this requires another call to the server.
I set enableServerSideFilter: true, so that when a filter applied, datagrid does not make a call on its own.
I monitor filter changes and call handleFilterChanged. I get the const filterModel = this.gridApi.getFilterModel(); and send it to rest endpoint.
Everything works fine but the datagrid does not remember the filter state.
I tried this.gridApi.setFilterModel(filterModel); but it gets me into infinite loop.
To make the long story short, how can I use filters with Redux so that I have full control also where should I use this.gridApi.setFilterModel()
Let me know if you need more clarification.
Thanks
    /* eslint-disable */
    import React, { Component, Fragment } from 'react';
    import { connect } from 'react-redux';
    import { AgGridReact } from 'ag-grid-react';
    import { fetchEvents } from '@mc/duck/actions/AppActions';
    import 'ag-grid-enterprise';
    import 'ag-grid-community/dist/styles/ag-grid.css';
    import 'ag-grid-community/dist/styles/ag-theme-balham-dark.css';
    // import './customTheme.scss';

    // col resizing pipe is not visibles
    class DatagridPage extends Component {
      constructor(props) {
        super(props);
        this.state = {
          params: {
            filterModel: {},
            page: 1,
            limit: 10,
          },
          gridOptions: {
            enableServerSideFilter: true,
            enableSorting: true,
            enableColResize: true,
            suppressMenuHide: true,
            pagination: true,
            animateRows: true,
            onFilterChanged: this.handleFilterChanged,
            onSortChanged: () => console.log('onSortChanged'),
            columnDefs: [
              {
                headerName: 'id',
                field: 'id',
                headerClass: 'test',
                checkboxSelection: true,
                filter: 'agTextColumnFilter',
              },
              {
                headerName: 'name',
                field: 'name',
                headerClass: 'test',
                filter: 'agTextColumnFilter',
              },
              {
                headerName: 'risk score',
                field: 'risk_score',
                headerClass: 'test',
                filter: 'agTextColumnFilter',
              },
              {
                headerName: 'urgency',
                field: 'urgency',
                headerClass: 'test',
                filter: 'agTextColumnFilter',
              },
              { headerName: 'type', field: 'type', headerClass: 'test', filter: 'agTextColumnFilter' },
              {
                headerName: 'artifacts',
                field: 'artifacts',
                headerClass: 'test',
                filter: 'agTextColumnFilter',
              },
              {
                headerName: 'created',
                field: 'created',
                headerClass: 'test',
                filter: 'agTextColumnFilter',
              },
              {
                headerName: 'updated',
                field: 'updated',
                headerClass: 'test',
                filter: 'agTextColumnFilter',
              },
              { headerName: 'due', field: 'due', headerClass: 'test', filter: 'agTextColumnFilter' },
              {
                headerName: 'owner',
                field: 'owner',
                headerClass: 'test',
                filter: 'agTextColumnFilter',
              },
              {
                headerName: 'status',
                field: 'status',
                headerClass: 'test',
                filter: 'agTextColumnFilter',
              },
              {
                headerName: 'description',
                field: 'description',
                headerClass: 'test',
                filter: 'agTextColumnFilter',
              },
            ],
          },
        };
      }

      componentDidMount() {
        console.log('componentDidMount');
        const { params } = this.state;
        this.props.onFetchEvents(params);
      }

      onGridReady = params => {
        this.gridApi = params.api;
        this.gridColumnApi = params.columnApi;
        this.gridApi.sizeColumnsToFit();
        console.log('onGridReady', this.gridApi.getFilterModel());
      };

      onPageSizeChanged(newPageSize) {
        var value = document.getElementById('page-size').value;
        const paramsCopy = { ...this.state.params };
        paramsCopy.limit = Number(value);
        paramsCopy.page = 1;
        this.setState({ params: paramsCopy }, () => this.props.onFetchEvents(paramsCopy));
        this.gridApi.paginationSetPageSize(Number(value));
      }

      handleFilterChanged = () => {
        console.log('handleFilterChanged');
        const filterModel = this.gridApi.getFilterModel();
        const paramsCopy = { ...this.state.params, filterModel };
        console.group('handleFilterChanged');
        console.log('filterModel', filterModel);
        console.log('state filterModel', this.state.params.filterModel);
        if (!areEqualShallow(filterModel, this.state.params.filterModel)) {
          this.gridApi.setFilterModel(filterModel);
          this.setState({ params: paramsCopy }, () => this.props.onFetchEvents(paramsCopy));
        }
        console.groupEnd();

        function areEqualShallow(a, b) {
          for (var key in a) {
            if (!(key in b) || a[key] !== b[key]) {
              return false;
            }
          }
          for (var key in b) {
            if (!(key in a) || a[key] !== b[key]) {
              return false;
            }
          }
          return true;
        }
        // this.gridApi.setFilterModel(filterModel);
      };

      render() {
        return (
          <Fragment>
            <div>
              Page Size:
              <select onChange={this.onPageSizeChanged.bind(this)} id="page-size">
                <option value="10">10</option>
                <option value="100">100</option>
                <option value="500">500</option>
                <option value="1000">1000</option>
              </select>
            </div>
            <div
              className="ag-theme-balham-dark"
              style={{
                height: '500px',
                width: '100%',
              }}
            >
              <AgGridReact
                rowSelection="multiple"
                gridOptions={this.state.gridOptions}
                columnDefs={this.state.columnDefs}
                rowData={this.props.events.data}
                defaultColDef={this.state.defaultColDef}
                onGridReady={this.onGridReady}
                rowHeight={49}
              />
            </div>
          </Fragment>
        );
      }
    }

    const mapStateToProps = state => ({
      events: state.app.events,
    });

    const mapDispatchToProps = {
      onFetchEvents: params => fetchEvents(params),
    };

    export default connect(
      mapStateToProps,
      mapDispatchToProps,
    )(DatagridPage);

A: In your column definition try setting the newRowsAction to "keep", e.g.
{
   headerName: 'name',
   field: 'name',
   headerClass: 'test',
   filter: 'agTextColumnFilter',
   filterParams: {
      newRowsAction: 'keep'
   }
}

Or set it for all via defaultColDef, e.g.
gridOptions: {
   defaultColDef: {
      filterParams: {
            newRowsAction: 'keep'
        }
    }
}


text:
Q: Is the anyway that I can plot bar and which I change the series? Is there anyway that I can plotbar with condition like this
plotbar(COND, Price1, price2), width -> plotbar(close>open, close, open), width
when the COND condition is satisfied, plot candle or bar line between the positions of PRICE1 and PRICE2, the width is WIDTH.
PLease help... I really need help on this... Please.

A: Yes.you can apply your condition on color transparency of the color you use in plotbar. for example :
c=(buy or sell)?color.rgb(255,255,0,0):color.rgb(255,255,0,100)
m=close*1.01
plotbar(m,m,m,m, color=c)


text:
Q: If 2 roots of the equation $(p-1)(x^2+x+1)^2-(p+1)(x^4+x^2+1)$ are real and distinct and $f(x)=\frac{1-x}{1+x}$... Question: If 2 roots of the equation $(p-1)(x^2+x+1)^2-(p+1)(x^4+x^2+1)$ are real and distinct and $f(x)=\frac{1-x}{1+x}$, then $f(f(x))+f(f(\frac{1}{x})) = ?$
(a)p
(b)2p
(c)-p
(d)-2p
Attempt: the give equation can be written as $(x^2+x+1)[(p-1)(x^2+x+1)-(p+1)(x^2-x+1)] = 2(x^2+x+1)(-x^2+px-1)$
$f(f(x))=x$ and $f(f(\frac{1}{x}))=-\frac{1}{x}$
So the required expression $x-\frac{1}{x}$
Now, $2(x^2+x+1)(x^2-px+1)=0$ (taking $-$ outside of second brackett) and $(x^2+x+1)\neq0$, so $(x^2-px+1)=0$. For this equation to have distinct real roots, $p^2-4>0$
But I am getting nowhere near the given options.

A: $\bf{My\; Solution::}$ Given
$$(p-1)(x^2+x+1)^2-(p+1)(x^4+x^2+1) = 0$$
$$\displaystyle (p-1)(x^2+x+1)^2=(p+1)(x^4+x^2+1)$$
We can write it as $$\displaystyle \frac{p+1}{p-1}=\frac{(x^2+x+1)^2}{(x^4+x^2+1)}=\frac{(x^2+x+1)^2}{(x^2-x+1)(x^2+x+1)}=\frac{x^2+x+1}{x^2-x+1}$$
Now We can Write it as $$\displaystyle \frac{\left(x+\frac{1}{x}+1\right)}{\left(x+\frac{1}{x}-1\right)}=\frac{p+1}{p-1}$$
Now Using Componendo-Dividendo, We get
$$\displaystyle \frac{\left(x+\frac{1}{x}+1\right)+\left(x+\frac{1}{x}-1\right)}{\left(x+\frac{1}{x}+1\right)-\left(x+\frac{1}{x}-1\right)}=\frac{(p+1)+(p-1)}{(p+1)-(p-1)}$$
So we get $$\displaystyle x+\frac{1}{x} = p..................(1)$$
Now Given $$\displaystyle f(x) = \frac{1-x}{1+x}$$. So $\displaystyle f(f(x)) = x$ and $\displaystyle f\left(f\left(\frac{1}{x}\right)\right)=\frac{1}{x}$
So $$\displaystyle f(x)+f\left(f\left(\frac{1}{x}\right)\right)=x+\frac{1}{x}=p$$ From $(1)$ equation.


text:
Q: При нажатии кнопки воспроизвести получаю ошибку E/MediaPlayer: Error (-38,0) При нажатии кнопки воспроизвести или остановить получаю ошибку, это на телефоне, на эмуляторе ошибки нету.
E/MediaPlayer: pause called in state 0, mPlayer(0x7f70e1e000)
               error (-38, 0)
E/MediaPlayer: Error (-38,0)
public class MainActivity extends AppCompatActivity {

Button  b_Play;

MediaPlayer mediaPlayer;
boolean prepareAsync = false;
boolean prepare = false;
boolean started = false;
boolean play = true;

String stream = "http://air.radiorecord.ru:8102/rus_320";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    b_Play = (Button) findViewById(R.id.b_play);

    mediaPlayer = new MediaPlayer();
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

    new PlayerTask().execute(stream);

    b_Play.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (started) {
              mediaPlayer.start();
                b_Play.setText("PLAY");
            } else {
                started = true;
                started = false;
                mediaPlayer.pause();
                b_Play.setText("PAUSE");
            }
         }
    });

}

@SuppressLint("StaticFieldLeak")
class PlayerTask extends AsyncTask<String, Void, Boolean> {

    @Override
    protected Boolean doInBackground(String... strings) {

        try {

            mediaPlayer.setDataSource(strings[0]);
            mediaPlayer.prepareAsync();
            mediaPlayer.setScreenOnWhilePlaying(true);
            prepareAsync = true;

        } catch (IOException e) {
            e.printStackTrace();
        }

          return prepareAsync;

    }

    @Override
    protected void onPostExecute(Boolean aBoolean) {
        super.onPostExecute(aBoolean);

            mediaPlayer.start();

    }

}

A: started = true;
started = false;

При повторном нажатии на паузу у вас эта ошибка, т.к. плейер уже в состоянии паузы.
Вообще, перед вызовом паузы проверяйте, играет ли у вас плейер:
if(mediaPlayer.isPlaying()) {
    mediaPlayer.pause();
}

Если переделать ваш код, то:
Во-первых, у вас неправильно написан PlayerTask, вы используете prepareAsync, но не задаёте обработчик. К моменту вызова onPostExecute у вас всё ещё может быть не готов плейер.
Во-вторых, AsyncTask не нужен.
Весь ваш код можно переделать так:
public class MainActivity extends AppCompatActivity {

    Button  b_Play;

    MediaPlayer mediaPlayer;
    boolean prepared = false;

    String stream = "http://air.radiorecord.ru:8102/rus_320";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        b_Play = (Button) findViewById(R.id.b_play);

        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

        b_Play.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if(!prepared) {
                    return;
                }

                if(mediaPlayer.isPlaying()) {
                    mediaPlayer.pause();
                    b_Play.setText("PLAY");
                }
                else {
                     mediaPlayer.start();
                     b_Play.setText("PAUSE");
                }
             }
        });

        mediaPlayer.setDataSource(strings[0]);
        mediaPlayer.prepareAsync();
        mediaPlayer.setScreenOnWhilePlaying(true);
        mediaPlayer.setOnPreparedListener(this);
    }

    public void onPrepared(MediaPlayer player) {
        prepared = true;
        player.start();
    }

}


text:
Q: How to call other module component function from app component My application has app module and dashboard module, dashboard module has lot of components. I have to trigger the dashboard component function(changedivStatus) from app component.
I hope this can be achieve by service  with EventEmitter by emit and subscribe.
Is there any other way without service.

app.module.ts

import { NgModule }                     from '@angular/core';
import { HashLocationStrategy, LocationStrategy } from '@angular/common';
import { BrowserModule }                from '@angular/platform-browser';
import {BrowserAnimationsModule,NoopAnimationsModule}       from '@angular/platform-browser/animations';
import { DashboardModule }              from './dashboard/dashboard.module';

dashboard.module.ts

import { NgModule }               from '@angular/core';
import { BrowserModule }          from '@angular/platform-browser';
import { RouterModule }         from '@angular/router';
import { WidgetsModule }          from '../widgets/widgets.module';
import { SharedModule }          from '../shared/shared.module';
import { DashboardComponent }     from './dashboard/dashboard.component';
import { AppSelectorComponent }   from './app-selector/app-selector.component';
import { AppReportsComponent }   from './app-reports/app-reports.component';
import {AppReportsService} from '../shared/services/app-reports.service';
import { BsDropdownModule }   from 'ngx-bootstrap/dropdown';
import {BrowserAnimationsModule} from '@angular/platform-browser/animations';
import {MatSidenavModule,MatDatepickerModule} from '@angular/material';
import {CheckboxModule} from 'primeng/primeng';
import { FormsModule } from '@angular/forms';

@NgModule({
    imports: [
        BrowserModule,
        SharedModule,
        WidgetsModule,
        BsDropdownModule,
        RouterModule,
        FormsModule,
        CheckboxModule,
        BrowserAnimationsModule,
        MatSidenavModule,
        MatDatepickerModule
    ],
    declarations: [
        DashboardComponent,
        AppSelectorComponent,
        AppReportsComponent
    ],
    providers: [
        AppReportsService
    ],
    exports: [
        DashboardComponent
    ]
})

export class DashboardModule {

}

app.component.html

    <input type="checkbox" (click)="changedivStatus()" class="md-primary" [checked]="showReport" />
    Hide Banner

dashborad.component.html

    <app-app-reports [items]="apps" *ngIf="loadReport"></app-app-reports>

dashboard.component.ts

changedivStatus() {
        this.showReport = !this.showReport;
        if(!this.showReport) {
            this.loadReport = true;
        } else {
            this.loadReport = false;
        }
    }

A: You can do it (and you should) using services, by putting your changeDivStatus() function in a dashboard.service, triggering it from your app.component, emitting the event from your dashboard.service and subscribing to this event in your dashboard.component ngOnInit function.
Here's the official angular guide for services : https://angular.io/tutorial/toh-pt4


text:
Q: Is it possible to restore files from a Windows Server 2016 Backup on a client PC? We create regular nightly backups of our physical server to (rotating) external hard drives. Our physical server is a Windows Server 2016 running two Server 2016 VM instances: the domain controller and the production server.
I am performing a disaster recovery test for the scenario where the server breaks, replacement hardware is not (immediately) available and the VMs need to be restored to a client machine to resume operation until replacement hardware is available.
Is it possible to restore files from a backup created with Windows Server Backup (Server 2016) on a Windows client machine (e.g. Windows 10)?
(What I tried so far: I attached the external HDD to a Windows 10 PC, stared "Backup and Restore (Windows 7)" and selected "Select another backup to restore files from", but no backup device was found.)

A: Great you are actually testing your disaster recovery! So many admins blindly rely on their backups.
Unlike Remote Server and Role Administration Tools that are available on Windows 10 (i.e. can be turned on from Windows Features), Windows Server Backup is only available on Windows Server operating systems in the Add Roles and Features Wizard in Server Manager.
However, in your scenario you are not restoring to the host operating system but to a VM. Some of the recovery options works within the newly installed server: Recover Files and Folders or Volumes.
Then, some of the options needs VSS writer running all the time, making them only available for restoring a previous state, like Recover Applications and Data; they are out of option here. Finally, Recover the Operating System or Full Server must be launched from the Windows Recovery Environment. I haven't personally tested, but this is something you could try: test if it is possible to use the Windows Recovery Environment within "Install an OS from a boot CD/DVD".
Then, outside the Windows Server Backup (& restoring to a client machine) used here, there's another option: you can use Azure Site Recovery and Replicate Hyper-V virtual machines to Azure. This way, you can skip the possibly long restoring phase and have up-to-date off-site backup of the whole servers in a cloud. Like in your situation here, it's also possible to run the fully functional server on Azure until you have the replacement hardware. You just need a temporary site-to-site VPN and possibly modify your network configuration. Naturally, it's wise to test this in advance, too.

A: I only have access to one Windows Server, but managed to rehearse the 'server won't boot but can only fully read user files from Server Backup via 'Windows Backup tool' on a server' conundrum by downloading an evaluation copy of Server 2019 Essentials from the Microsoft Evaluation Center and spinning up that 6-month trial copy in a Virtual Machine (in my case, on a mac - i know, right!). In the eval server, you may have to install the Bitlocker 'feature' in 'Roles and Features' in order to unlock the External backup drive (or you could disable bitlocker on that drive via Win10?). Thereafter, the full 'Windows Server Backup' tool functionality is available to navigate the source backup as if the original server was up. (Be sure the external drive is unlocked and mounted BEFORE running the Windows Backup tool' - so that it can autodetect the archive during RESTORE).

A: Since, in your case, you don't want to do a bare-metal recovery but only extract some files and folders (the VMs), you can do that by directly accessing the vhdx files created by Windows Server Backup:

*

*On your external drive, navigate to WindowsImageBackup\MyServer\Backup yyyy-mm-dd hhmmss.

*In there, you will see vhdx files corresponding to the physical hard drives that have been backed up.

*Copy those files to another location (to ensure that you don't accidentally modify your backup files).

*Mount those copied files (for example, by selecting the file in Windows Explorer and choosing Mount from the context menu).

*Assign drive letters in Disk Management.

*Copy all the files you need (for example, the VM disks and configuration files).


text:
Q: mail not sending from live server working on localhost I am sending mail from laravel its working fine on localhost but same code is not working on live server following is my mail configuration
MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
MAIL_USERNAME=pranav.bitware@gmail.com
MAIL_PASSWORD=******
MAIL_ENCRYPTION=ssl

i have allowed less secure apps in my account
i don't know why its generating error on live server
on some articles they are setting smtp to sendmail i tried that also but getting same error

A: Providing the error message you get will help with troubleshooting this issue. Since it works on your localhost, then you should look into the server configuration such as your php and Laravel setup, and firewall settings.


text:
Q: Failed to detect if this server is joined to a server farm Hi As I said in one of my previous question,
I have got a virtual Machine Image (VMWARE) for MS server 2003 with MOSS 2007 setup. Where they changed both IP and host name.
Following problems I face d so far,

*

*When I try accessing the central administration  , I got same old host name as url, instead of the new one.

*When I try accessing any of the sites deployed in this server, first I got an error service unavailable.

*I changed Identity login details to other user and added that credentials to IIS_WPG and WSS_WPG. So I got rid of the above problem.

*I tried running the site once again, got another error :

*So I run sharepoint configuration wizard, and again got the following error,

Failed to detect if this server is joined to a server farm. Possible reasons for this failure could be that you no longer have the appropriate permissions to the server farm, the database server hosting the server farm is unresponsive, the configuration database is inaccessible or this server has been removed from the server farm.
Can anyone please suggest me what am I missing here?
UPDATE : 15-Feb-2012
Reply to Deepu's and SBC's answer
Looks like all the services are running.

A: Try to disable the firewalls for both the database server and the sharepoint front end temporarily and try again. Make sure the account you are logged onto and running the SharePoint Config Wizard has proper database access.
Also, Are you bindings in IIS Manager linked to the old IP or hostname? Change that and try again.
Also view my blog about this:
http://mikessharepoint.wordpress.com/2011/11/22/cannot-connect-to-the-configuration-database-error-of-central-administration/

A: Use an utility like Windows Service Monitor to visually track which of the required services (including SQL Server) are up and running. Your error is frequently due to SQL Server (as mentioned by Deepu above).
Also make sure that the required SharePoint service accounts have the appropriate access to other installed resources. Good post about it here from Shane Young.

A: First, to have sharepoint connect to your SQL Server instance again, create a SQL alias by running the following command:
cliconfg

Create a SQL alias (2nd tab) that has the old server name as alias and the new name of the server as the alias's target:

Next, when you rename a server that has sharepoint running on it, you need to tell SharePoint about that change, because unlike SQL Server, SharePoint does not automatically pick this up and because SharePoint stores server names etc. in the config database. To do this, run the following command:
stsadm -o renameserver -newservername <NewName> -oldservername <OldName>

You should now be able to access Central Admin again

A: It seems like your database server services are not started. Go to Control Panel -> Admin tools -> Services, then find the SQL Server and SQL Server Agent services and start them for your particular SQL instance where SharePoint is installed. Refresh your central admin and it should be working.

UPDATED: Can you try logging into SQL Management Studio, using your credentials that you supply for the Central admin? If you are not able to login, then login to SQL with 'sa' user and give your account dbowner rights to the SharePoint config and content DBs.
If these don't work out, check the answer I had provided for another question here -
Central Administration cannot connect to configuration database

A: try to change the host file of your server name to pointing to the old servername and the current ip address of the server.
Browse the Central admin site  through iis website and check how it goes.
is it a prod environment??
Also is sql server DB is a separate server or on the same server??
How much customization you have done from the SharePoint side. Is there any Wsp installed on Sp farm?
How many web application you have and are there any host headers related to Web Apps if yes. Then change the Ip for that WEb app url to the new ip address and check uisng host file..
before you make any changes to host file make sure you back up the host file.

A: As far as I can see, you're missing a key config change which needs to be applied if you change the Sharepoint Admin site ports/site names etc.Sharepoint saves a Registry key on the server which tells it where the Central Admin site lives. This key is also used when running the products configuration wizard. The Key can be found in your Registry : HKLM > SOFTWARE > MICROSOFT > SHARED TOOLS > WEB SERVER EXTENTIONS > 14.0 > WSS
Change the URL in your CentralAdministrationURL Key to the correct URL with the correct port number
You can also search through the Registry for the old URL and replace with the new one.
Hope this helps.

A: If I understand you correctly, you took a Windows Server 2003 virtual machine running MOSS 2007, and renamed the computer (System Properties -> Computer Name) and changed the IP address.
Assuming this is correct, the unfortunate reality is that this is not supported and the fact that you can no longer access the farm is the expected behaviour.
If you wish to rename a MOSS server, you need to first run the Renameserver stsadm operation.
For example:
stsadm -o renameserver -oldservername SERVERNAME -newservername NEWSERVERNAME

Once run, you can then rename the server in System Properties, restart, (change the IP if necessary) and SharePoint should load as expected. The assumption here is you are not changing domain membership (though in theory changing to a domain with a two-way trust could still work)


text:
Q: .HTACCESS Apache Mod_Rewrite not working I have tried to manage my website's requests from http://example.com/index.php/register to http://example.com/register
But it always shows no input file specified.
Now all i want to do is to remove the /index.php and rewrite the requests.
here is my .HTACCESS file i have tried multiple things but no luck.
 <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>

Just let me know where the issue is.

A: No need to write RewriteBase /
Use below htaccess.
# Turn mod_rewrite on
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php/$1 [L]
# add / before index.php

Hope it will work :-)

A: There may be some reasons for not working this code
First - Allow override in apache config, You should know where is your apache config, usually it is in the /etc/apache2/sites-available/default
<Directory "/path/to/document/root/">
  AllowOverride All
  Allow from All
</Directory>

Second - mod_rewrite is not enable, so you should enter this command for enabling that.
sudo a2enmod rewrite
sudo service apache2 restart

Third - If still your rewrite mode doesn't work, or you don't have an access to change the config of the server
you can see your register page like this:
http://quepos.fishing/index.php/register

A: Can you try this:
RewriteEngine On
RewriteCond %{REQUEST_URI} !^/index.php
RewriteRule ^(.*)$ /index.php/$1 [L]


text:
Q: Getting eror " The type initializer for 'java.util.Locale' threw an exception." on Report.Init() method of windward I am looking for windward report with .net core.I found some sample on goggle which works fine with .net application but when I tried to create windward report through .net core it gives me error. any suggestion or
 public void ConfigureServices(IServiceCollection services)
        {
            // Initialize the engine. License and configuration settings in web.config.
            Configuration.GetSection("Windwardlicense");
            Report.Init();//getting error on this line
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));
            services.AddDefaultIdentity<IdentityUser>()
                .AddDefaultUI(UIFramework.Bootstrap4)
                .AddEntityFrameworkStores<ApplicationDbContext>();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }

enter image description here

A: Unfortunately, Windward products don't yet support .NET Core, but you can use our RESTful engine which has to be hosted on a Windows Server running IIS and it will answer POSTs and GETs from your .NET Core application.
If you have more questions, please contact Windward Support at support@windwardstudios.com.


text:
Q: How can I add a dependency to my sbt plugin? I would like to add a library that I am going to use within the code of my SBT-Plugin.
I did
...

sbtPlugin := true

libraryDependencies += "..." %% "..." % "..."

enablePlugins(SbtPlugin)

scriptedLaunchOpts := {
  scriptedLaunchOpts.value ++
    Seq("-Xmx1024M", "-Dplugin.version=" + version.value)
}

scriptedBufferLog := false

...

in build.sbt located in the root of my plugin project.
▶ tree -L 1
.
├── README.md
├── build.sbt <- this one
├── project
└── src

But when I run the test, following: https://www.scala-sbt.org/1.x/docs/Testing-sbt-plugins.html .
I run
sbt 'set isSnapshot := true' scripted

And I am getting
java.lang.NoClassDefFoundError

with some class coming from the library I added.

Am I doing something wrong ?


text:
Q: Does any asp.net data cache support background population of cache entries? We have a data driven ASP.NET website which has been written using the standard pattern for data caching (adapted here from MSDN):
public DataTable GetData()
{
   string key = "DataTable";
   object item = Cache[key] as DataTable;
   if((item == null)
   {
      item = GetDataFromSQL();
      Cache.Insert(key, item, null, DateTime.Now.AddSeconds(300), TimeSpan.Zero;
   }
   return (DataTable)item;
}

The trouble with this is that the call to GetDataFromSQL() is expensive and the use of the site is fairly high. So every five minutes, when the cache drops, the site becomes very 'sticky' while a lot of requests are waiting for the new data to be retrieved.
What we really want to happen is for the old data to remain current while new data is periodically reloaded in the background. (The fact that someone might therefore see data that is six minutes old isn't a big issue - the data isn't that time sensitive). This is something that I can write myself, but it would be useful to know if any alternative caching engines (I know names like Velocity, memcache) support this kind of scenario. Or am I missing some obvious trick with the standard ASP.NET data cache?

A: You should be able to use the CacheItemUpdateCallback delegate which is the 6th parameter which is the 4th overload for Insert using ASP.NET Cache:
Cache.Insert(key, value, dependancy, absoluteExpiration,
    slidingExpiration, onUpdateCallback);

The following should work:
Cache.Insert(key, item, null, DateTime.Now.AddSeconds(300),
    Cache.NoSlidingExpiration, itemUpdateCallback);

private void itemUpdateCallback(string key, CacheItemUpdateReason reason,
    out object value, out CacheDependency dependency, out DateTime expiriation,
    out TimeSpan slidingExpiration)
{
    // do your SQL call here and store it in 'value'
    expiriation = DateTime.Now.AddSeconds(300);
    value = FunctionToGetYourData();
}

From MSDN:

When an object expires in the cache,
  ASP.NET calls the
  CacheItemUpdateCallback method with
  the key for the cache item and the
  reason you might want to update the
  item. The remaining parameters of this
  method are out parameters. You supply
  the new cached item and optional
  expiration and dependency values to
  use when refreshing the cached item.
The update callback is not called if
  the cached item is explicitly removed
  by using a call to Remove().
If you want the cached item to be
  removed from the cache, you must
  return null in the expensiveObject
  parameter. Otherwise, you return a
  reference to the new cached data by
  using the expensiveObject parameter.
  If you do not specify expiration or
  dependency values, the item will be
  removed from the cache only when
  memory is needed.
If the callback method throws an
  exception, ASP.NET suppresses the
  exception and removes the cached
  value.

I haven't tested this so you might have to tinker with it a bit but it should give you the basic idea of what your trying to accomplish.

A: I can see that there's a potential solution to this using AppFabric (the cache formerly known as Velocity) in that it allows you to lock a cached item so it can be updated. While an item is locked, ordinary (non-locking) Get requests still work as normal and return the cache's current copy of the item.
Doing it this way would also allow you to separate out your GetDataFromSQL method to a different process, say a Windows Service, that runs every five minutes, which should alleviate your 'sticky' site.

Or...
Rather than just caching the data for five minutes at a time regardless, why not use a SqlCacheDependency object when you put the data into the cache, so that it'll only be refreshed when the data actually changes. That way you can cache the data for longer periods, so you get better performance, and you'll always be showing the up-to-date data.
(BTW, top tip for making your intention clearer when you're putting objects into the cache - the Cache has a NoSlidingExpiration (and a NoAbsoluteExpiration) constant available that's more readable than your Timespan.Zero)

A: First, put the date you actually need in a lean class (also known as POCO) instead of that DataTable hog.
Second, use cache and hash - so that when your time dependency expires you can spawn an async delegate to fetch new data but your old data is still safe in a separate hash table (not Dictionary - it's not safe for multi-reader single writer threading).
Depending on the kind of data and the time/budget to restructure SQL side you could potentially fetch only things that have LastWrite younger that your update window. you will need 2-step update (have to copy dats from the hash-kept opject into new object - stuff in hash is strictly read-only for any use or the hell will break loose).
Oh and SqlCacheDependency is notorious for being unreliable and can make your system break into mad updates.


text:
Q: Windows XP runs New Hardware Wizard for usb keyboard and mouse, can't find drivers I have a PC that up until a couple days ago was working fine.  I moved it from one site to another and now when I plug in the USB mouse or keyboard (the same ones that were working previously) XP brings up the New Hardware Wizard.  Going through it, the correct keyboard and mouse are identified, but XP can't find the drivers.
I've tried manually searching for the driver (using the Have Disk option) - the first file it's looking for is in the c:\i386 directory, but that installs a generic HID mouse device; the system then runs the hardware wizard for a new "unknown" device.
The system was SP2, I have installed SP3 in hopes that would help, and I've also downloaded and installed the mouse drivers from Dell's site (there are no specific drivers for the keyboard), with no change.
Before I completely reinstall XP, is there anything else I should try?

A: This often happens when the catalog cache is corrupted. Boot into safe mode and delete the %SystemRoot%\System32\catroot2 folder ( do not delete the "catroot" folder! only "catroot2"!).

A: Go to the device manager > choose on which device you are facing problem > go to update driver > and then click browse from the computer and choose any suitable driver.
if it doesn't works do the same with different driver .

A: If you have the drivers and utilities disc. Then install all the chipset drivers for this system, once this installation is complete, restart the system and connect the keyboard and mouse and check the functionality.

A: This happens when you connect one USB device to a different USB port on your machine. If you want, you can try to plug the keyboard and mouse into their original USB ports which would bypass all of this mess.


text:
Q: Why do I get "unfortunately myapp has stopped" in my Android app? When clicking on an image button in my app I always get the message: "unfortunately myapp has stopped". What is the problem???
Here is my code. The showImageDialog method is called on a click on an image button:
public class ReminderEditActivity extends Activity {

//
// Private instance variables
//
private Button mDateButton;
private Calendar mCalendar;
private Button mTimeButton;
private EditText mTitleText;
private EditText mBodyText;
private Button mConfirmButton;

private RemindersDbAdapter mDbHelper;
private ImageAdapter mImageHelper;

private Long mRowId;
private Long mImageRowId;

private ImageButton mImageButton;

private Uri mImageCaptureUri;

public String imageFilePath;

//
// Private constants
//
private static final int DATE_PICKER_DIALOG = 0;
private static final int TIME_PICKER_DIALOG = 1;
private static final String DATE_FORMAT = "dd-MM-yyyy";
private static final String TIME_FORMAT = "kk:mm";

public static final String DATE_TIME_FORMAT = "dd-MM-yyyy kk:mm:ss";

private static final int PICK_FROM_CAMERA = 1;
private static final int PICK_FROM_FILE = 2;

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

    // Instantiate mDbHelper and mImageHelper
    mDbHelper = new RemindersDbAdapter(this);
    mImageHelper = new ImageAdapter(this);

    setContentView(R.layout.reminder_edit);

    //
    // Instantiate instance variables
    //
    mTimeButton = (Button)findViewById(R.id.reminder_time);
    mCalendar = Calendar.getInstance();
    mDateButton = (Button)findViewById(R.id.reminder_date);
    mConfirmButton = (Button)findViewById(R.id.confirm);
    mTitleText = (EditText)findViewById(R.id.title);
    mBodyText = (EditText)findViewById(R.id.body);

    mImageButton =(ImageButton)findViewById(R.id.image);

    //Checks whether mRowId contains any values.
    mRowId = savedInstanceState != null ? savedInstanceState.getLong(RemindersDbAdapter.KEY_ROWID) : null;
    mImageRowId = savedInstanceState != null ? savedInstanceState.getLong(ImageAdapter.KEY_ROWID) : null;

    registerButtonListenerandSetDefaultText();
}

//
// Sets the row id from the intent. If mRowId is null its content is null.
//
private void setRowIdFromIntent() {
    if(mRowId == null) {
        Bundle extras = getIntent().getExtras();
        mRowId = extras != null ? extras.getLong(RemindersDbAdapter.KEY_ROWID) : null;
    }
}

//
// Executed on pause.
//
@Override
protected void onPause() {
    super.onPause();
    mDbHelper.close();
    mImageHelper.close();
}

//
// Executed on resume
//
@Override
protected void onResume() {
    super.onResume();
    mDbHelper.open();
    mImageHelper.open();
    setRowIdFromIntent();
    populateFields();
    populateImageField();
}

//
// Register the Date, Time and Save Button and set the default text
//
private void registerButtonListenerandSetDefaultText() {

    mDateButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            showDialog(DATE_PICKER_DIALOG);
        }
    });

    mTimeButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            showDialog(TIME_PICKER_DIALOG);
        }
    });

    mConfirmButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            saveState();
            setResult(RESULT_OK);
            Toast.makeText(ReminderEditActivity.this, getString(R.string.task_saved_message), Toast.LENGTH_SHORT).show();
            finish();
        }
    });

    mImageButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showImageDialog();
        }
    });

    updateDateButtonText();
    updateTimeButtonText();
}

private void showImageDialog() {
    final String [] items = new String [] {"From Camera", "From SD Card"};
    ArrayAdapter<String> adapter = new ArrayAdapter<String> (this, android.R.layout.select_dialog_item,items);
    AlertDialog.Builder builder = new AlertDialog.Builder(this);

    builder.setTitle("Select Image");
    builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
        public void onClick( DialogInterface dialog, int item ) {
            if (item == 0) {
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                File file = new File(Environment.getExternalStorageDirectory(),
                                    "tmp_avatar_" + String.valueOf(System.currentTimeMillis()) + ".jpg");
                mImageCaptureUri = Uri.fromFile(file);

                try {
                    intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
                    intent.putExtra("return-data", true);

                    startActivityForResult(intent, PICK_FROM_CAMERA);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                dialog.cancel();
            } else {
                Intent intent = new Intent();

                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);

                startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_FILE);
            }
        }
    } );

    final AlertDialog dialog = builder.create();
    dialog.show();
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
       if(requestCode == PICK_FROM_FILE && data != null && data.getData() != null) {
           Uri uri = data.getData();
           if(uri != null) {
              Cursor cursor = getContentResolver().query(uri, new String[] {
                                       android.provider.MediaStore.Images.ImageColumns.DATA},
                                       null, null, null);
                    cursor.moveToFirst();
                    String imageFilePath = cursor.getString(0);
                    cursor.close();

                    if(imageFilePath != null) {
                            // Do whatever you want like decode it into a Bitmap
                            Bitmap bitmap = BitmapFactory.decodeFile(imageFilePath);
                            mImageButton.setImageBitmap(bitmap);
                            // Or.. store it somewhere in your local db
                        }
           }
       }
    }

//
// If mRowId is not null (it contains value and we want to edit the task)
// this method is called.
//
private void populateFields() {
    if (mRowId != null) {
        Cursor reminder = mDbHelper.fetchReminder(mRowId);
        startManagingCursor(reminder);
        mTitleText.setText(reminder.getString(reminder.getColumnIndexOrThrow(RemindersDbAdapter.KEY_TITLE)));
        mBodyText.setText(reminder.getString(reminder.getColumnIndexOrThrow(RemindersDbAdapter.KEY_BODY)));

        SimpleDateFormat dateTimeFormat = new SimpleDateFormat(DATE_TIME_FORMAT);
        Date date = null;
        try {
            String dateString = reminder.getString(reminder.getColumnIndexOrThrow(RemindersDbAdapter.KEY_DATE_TIME));
            date = dateTimeFormat.parse(dateString);
            mCalendar.setTime(date);
        } catch (ParseException e) {
            Log.e("ReminderEditActivity", e.getMessage(), e);
        }
    }

    updateDateButtonText();
    updateTimeButtonText();
}

private void populateImageField() {
    if (mImageRowId != null) {
        Cursor reminderImage = mImageHelper.fetchReminder(mImageRowId);
        startManagingCursor(reminderImage);
        String imagePath = reminderImage.getString(reminderImage.getColumnIndexOrThrow(ImageAdapter.KEY_IMAGE));

        Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
        mImageButton.setImageBitmap(bitmap);

    }
}

//
// Saves the state so that it can be restored.
//
@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putLong(RemindersDbAdapter.KEY_ROWID, mRowId);

}

//
// Saves the content by communicating with the RemindersDbAdapter.
//
private void saveState() {
    String title = mTitleText.getText().toString();
    String body = mBodyText.getText().toString();

    SimpleDateFormat dateTimeFormat = new SimpleDateFormat(DATE_TIME_FORMAT);
    String reminderDateTime = dateTimeFormat.format(mCalendar.getTime());

    // Creates a new reminder if the value is null.
    if (mRowId == null) {
        long id = mDbHelper.createReminder(title, body, reminderDateTime);
        if (id > 0) {
            mRowId = id;

        }
    // Updates the reminder if the content is not null.
    } else {
        mDbHelper.updateReminder(mRowId, title, body, reminderDateTime);
    }
}

//
// Opens up an alert dialog box and asks the user if he wants to discard his task.
//
@Override
public void onBackPressed() {
    AlertDialog.Builder builder = new AlertDialog.Builder(ReminderEditActivity.this);
    builder.setMessage("Are you sure you want to discard your task?");
            builder.setTitle("Are you sure?");
            builder.setCancelable(false);
            builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int id) {
                    Intent j = new Intent(((Dialog)dialog).getContext(), ReminderListActivity.class);
                    startActivity(j);
                    return;

                }
            });

            builder.setNegativeButton("No", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();

                }
            });
            builder.create().show();
}

//
// When creating a dialog box, it either shows up a date or time picker.
//
@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
        case DATE_PICKER_DIALOG:
            return showDatePicker();
        case TIME_PICKER_DIALOG:
            return showTimePicker();
    }
    return super.onCreateDialog(id);
}

//
// Creates the date picker dialog box.
//
private DatePickerDialog showDatePicker() {
    DatePickerDialog datePicker = new DatePickerDialog(ReminderEditActivity.this, new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            mCalendar.set(Calendar.YEAR, year);
            mCalendar.set(Calendar.MONTH, monthOfYear);
            mCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
            updateDateButtonText();
        }
    }, mCalendar.get(Calendar.YEAR), mCalendar.get(Calendar.MONTH), mCalendar.get(Calendar.DAY_OF_MONTH));
    return datePicker;
}

//
// Creates the time picker dialog box.
//
private TimePickerDialog showTimePicker() {
    TimePickerDialog timePicker = new TimePickerDialog(ReminderEditActivity.this, new TimePickerDialog.OnTimeSetListener() {

        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            mCalendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
            mCalendar.set(Calendar.MINUTE, minute);
            updateTimeButtonText();
        }
    }, mCalendar.get(Calendar.HOUR_OF_DAY), mCalendar.get(Calendar.MINUTE), true);
    return timePicker;
}

//
// Updates the Date Button text.
//
private void updateDateButtonText() {
    SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
    String dateForButton = dateFormat.format(mCalendar.getTime());
    mDateButton.setText(dateForButton);
}

//
// Updates the Time Button text.
//
private void updateTimeButtonText() {
    SimpleDateFormat timeFormat = new SimpleDateFormat(TIME_FORMAT);
    String timeForButton = timeFormat.format(mCalendar.getTime());
    mTimeButton.setText(timeForButton);
}

}
Here is the LogCat:
05-30 22:09:06.726: E/AndroidRuntime(628): FATAL EXCEPTION: main
05-30 22:09:06.726: E/AndroidRuntime(628): java.lang.RuntimeException: Unable to pause activity {com.ndroidstudios.android.taskreminder/com.ndroidstudios.android.taskreminder.ReminderEditActivity}: java.lang.NullPointerException
05-30 22:09:06.726: E/AndroidRuntime(628):  at android.app.ActivityThread.performPauseActivity(ActivityThread.java:2706)
05-30 22:09:06.726: E/AndroidRuntime(628):  at android.app.ActivityThread.performPauseActivity(ActivityThread.java:2662)
05-30 22:09:06.726: E/AndroidRuntime(628):  at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:2640)
05-30 22:09:06.726: E/AndroidRuntime(628):  at android.app.ActivityThread.access$800(ActivityThread.java:123)
05-30 22:09:06.726: E/AndroidRuntime(628):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1154)
05-30 22:09:06.726: E/AndroidRuntime(628):  at android.os.Handler.dispatchMessage(Handler.java:99)
05-30 22:09:06.726: E/AndroidRuntime(628):  at android.os.Looper.loop(Looper.java:137)
05-30 22:09:06.726: E/AndroidRuntime(628):  at android.app.ActivityThread.main(ActivityThread.java:4424)
05-30 22:09:06.726: E/AndroidRuntime(628):  at java.lang.reflect.Method.invokeNative(Native Method)
05-30 22:09:06.726: E/AndroidRuntime(628):  at java.lang.reflect.Method.invoke(Method.java:511)
05-30 22:09:06.726: E/AndroidRuntime(628):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
05-30 22:09:06.726: E/AndroidRuntime(628):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
05-30 22:09:06.726: E/AndroidRuntime(628):  at dalvik.system.NativeStart.main(Native Method)
05-30 22:09:06.726: E/AndroidRuntime(628): Caused by: java.lang.NullPointerException
05-30 22:09:06.726: E/AndroidRuntime(628):  at com.ndroidstudios.android.taskreminder.ReminderEditActivity.onSaveInstanceState(ReminderEditActivity.java:345)
05-30 22:09:06.726: E/AndroidRuntime(628):  at android.app.Activity.performSaveInstanceState(Activity.java:1113)
05-30 22:09:06.726: E/AndroidRuntime(628):  at android.app.Instrumentation.callActivityOnSaveInstanceState(Instrumentation.java:1185)
05-30 22:09:06.726: E/AndroidRuntime(628):  at android.app.ActivityThread.performPauseActivity(ActivityThread.java:2688)
05-30 22:09:06.726: E/AndroidRuntime(628):  ... 12 more

And here is my manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ndroidstudios.android.taskreminder"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk android:minSdkVersion="4" android:targetSdkVersion="8" />

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <activity
        android:name=".ReminderListActivity"
        android:label="@string/app_name"
        android:configChanges="orientation|keyboardHidden" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".ReminderEditActivity"
        android:label="@string/app_name" />
    <activity
        android:name=".ImageAdapter"
        android:label="@string/app_name" />
</application>

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

A: ReminderEditActivity at line 345 has a null object. Im not sure which line it is in your code cause theres no line numbers

A: Try putting the super.onSaveInstanceState(outState); after you put your variables into the outState.
@Override
protected void onSaveInstanceState(Bundle outState) {

    outState.putLong(RemindersDbAdapter.KEY_ROWID, mRowId);
    super.onSaveInstanceState(outState);
}


text:
Q: Transform an array of arrays into an array of objects This is the (dynamic) input array:
[
 [1,"Node 1"],
 [2,"Node 2"],
 [3,"Node 3"],
 [4,"Node 4"]
//, Here the elements are going to appear
]

Can it be transformed to this?
[
 {id: 1, label: 'Node 1'},
 {id: 2, label: 'Node 2'},
 {id: 3, label: 'Node 3'},
 {id: 4, label: 'Node 4'},
 {id: 5, label: 'Node 5'}
//, Here the elements are going to be add
]

A: I think this is the code you are looking for
const a = [
   [1,"Node 1"],
   [2,"Node 2"],
   [3,"Node 3"],
   [4,"Node 4"]
]

let objArray = []

a.forEach(element => {
  let obj = {}

  obj.id = element[0]
  obj.label = element[1]

  objArray.push(obj)
  return element
})

console.log(objArray)

A: Here's a one-liner
const elements = [
 [1,"Node 1"],
 [2,"Node 2"],
 [3,"Node 3"],
 [4,"Node 4"],
 // Here the elements are going to appear
]

map(fork({ id: get(0), label: get(1) }))(elements) /*
=> [
 {id: 1, label: 'Node 1'},
 {id: 2, label: 'Node 2'},
 {id: 3, label: 'Node 3'},
 {id: 4, label: 'Node 4'},
 {id: 5, label: 'Node 5'},
]
*/

map, get, fork


text:
Q: No Activity found to handle Intent: ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS I'm trying to start an activity for whitelisting an app on the emulator (API 25), but I keep getting an error saying:
Caused by: android.content.ActivityNotFoundException:
No Activity found to handle Intent { act=android.settings.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS }

Here's my code:
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
    startActivity(intent);

  }

Anyone know why this error is thrown?

A: Take a look at the Android Developer Documentation:
https://developer.android.com/reference/android/provider/Settings#ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS
Looks like you are missing this part:

Input: The Intent's data URI must specify the application package name to be shown, with the "package" scheme. That is "package:com.my.app"

The following line should help:
intent.setData(Uri.parse("package:" + getApplicationContext().getPackageName()));

A: you should specify your package name !
intent.setData(Uri.parse("package:" + packageName));

here is document  :
https://developer.android.com/reference/android/provider/Settings.html#ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS


text:
Q: ADL(2,2) modelling in R with differenced variables and lags I'm new to time series analysis and I am trying to model this relationship based on a very simple dataset containing only two time series: percentual changes of sales - y, regressed on the percentual change in purchases - x and a deterministic trend.
'data.frame':   98 obs. of  3 variables:
 $ time         : int  1 2 3 4 5 6 7 8 9 10 ...
 $ sales        : num  3.18 4.59 5.41 5.68 4.62 ...
 $ comppurchases: num  1.675 0.246 0.333 0.969 0.147 ...

The dataset is based on an example from a book, so I am trying to figure out the regression formula according to the output presented in the book. The author presented coefficients for y_(t-1), ∆y_t-1, x_t, ∆x_t, ∆x_t-1 and time as explanatory variables.
This would then be my equation:

∆y_t = a + φy_(t-1) + λ∆y_t-1 + βx_t + β1∆x_t + β2*∆x_t-1 + + d*time + error

And the corresponding R syntax:
regr <- dynlm(d(sales) ~ L(sales,1)+L(d(sales))+ comppurchases +d(comppurchases)+L(d(comppurchases)) + time, data=df)
The problem is, whenever I run the syntax, I get this error:

Error: all(sapply(args, function(x) is.zoo(x) || !is.plain(x) ||
  (is.plain(x) &&  .... is not TRUE

Is there anything wrong with my syntax? What am I missing here? I'm not even sure if the problem is with the syntax or with my understanding of the regression formula.
Thanks in advance!

A: From documentation of dynlm package, it says that you need to have your columns in a time-series format to use the built-in dynlm functions "d" and "L".

All new formula functions require that their arguments are time series
  objects (i.e., "ts" or "zoo").

First, I assumed that sales and purchases were raw data and not percentage changes. If this is not true, then you can adapt this to your needs.
The function worked after creating new column the % change in sales, "sales_delta" and using that in the regression instead of the built in function "d(data, lag)". I couldn't get this function to work.
I tried replicating the results with the base "lm" function after creating the columns manually and the regression coefficients are the same. One difference was in the data argument. For lm, I had to specify to ignore the first 2 columns, which had NA values, while the dynlm package has the default method of omitting rows with NA values.
time = seq(1,11,1)
sales = c(3.18, 4.59, 5.41, 5.68, 4.62, 5.08, 6.02, 6.15, 5.99, 6.03, 6.05)
purch = c(1.675, 0.246, 0.333, 0.969, 0.147, 0.258, 0.65, 0.85, 0.25, 0.11, 0.25)
require(zoo)

df = data.frame(time = time, sales = sales, purch = purch)
df$sales = zoo(df$sales)
df$purch = zoo(df$purch)

df$sales_lag1 = NA
df$sales_lag1[2:nrow(df)] = df$sales[1:nrow(df)-1]
df$sales_delta = df$sales/df$sales_lag1 - 1
df$sales_delta_lag1 = NA
df$sales_delta_lag1[3:nrow(df)] = df$sales_delta[2:(nrow(df)-1)]

df$purch_lag1 = NA
df$purch_lag1[2:nrow(df)] = df$purch[1:nrow(df)-1]
df$purch_delta = df$purch/df$purch_lag1 - 1
df$purch_delta_lag1 = NA
df$purch_delta_lag1[3:nrow(df)] = df$purch_delta[2:(nrow(df)-1)]

mod_base = lm(sales_delta ~ sales_lag1 + sales_delta_lag1 + purch +      purch_delta + purch_delta_lag1 + time, data = df[-c(1:2),])
summary(mod_base)

require(dynlm)
mod_dynlm = dynlm(sales_delta ~ L(sales,1) + L(sales_delta,1) + purch +  purch_delta + L(purch_delta,1) + time, data = df)

#Check if results are similar
mod_base$coefficients == mod_dynlm$coefficients

Hope this helps. In general, I would recommend sticking to the base functions and using a package only when required.


text:
Q: Calculating growth rate in Mysql Hello I have this query to get rate based in previous row:
SELECT
  t.*,
  100 * (Volumen - Volumen_a) / (Volumen_a) Subida
FROM (
  SELECT
   *,
   (
     SELECT Volumen
     FROM ejemplo t_ant
     WHERE
       t_ant.Sujeto = t_act.Sujeto AND t_ant.Id < t_act.Id
     ORDER BY Id DESC
     LIMIT 1
   ) Volumen_a
  FROM ejemplo t_act
  WHERE Sujeto = 'HGT'
  ORDER BY Fecha DESC
  LIMIT 1
) t
WHERE Volumen_a IS NOT NULL;

It's just showing the last row... then I need it show me all rows.
Best regards

A: SELECT
  t.*,
  100 * (Volumen - Volumen_a) / (Volumen_a) Subida
FROM (
  SELECT
   *,
   (
     SELECT Volumen
     FROM ejemplo t_ant
     WHERE
       t_ant.Sujeto = t_act.Sujeto AND t_ant.Id < t_act.Id
     ORDER BY Id DESC
     LIMIT 1
   ) Volumen_a
  FROM ejemplo t_act
  ORDER BY Fecha DESC
  ) t
WHERE Volumen_a IS NOT NULL;

Resolved deleting last limit 1 and where name clausule.
Thank you


text:
Q: why java program is outputting the following Below is the code for implementing time server
Server class
public static void main(String args[])
    {
   try{
            ServerSocket ss=new ServerSocket(990);
             Socket s=ss.accept();
            while(true)
            {
                Calendar c=Calendar.getInstance();
                BufferedReader in=new BufferedReader(new InputStreamReader(s.getInputStream()));
                PrintWriter out =new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
                out.println("Hello This is server & My Time is :");
                out.println("Time :::  Hour="+c.HOUR +" Min="+c.MINUTE +" sec="+c.SECOND);
            out.flush();
              s.close();
            }
        }
        catch(Exception e)
        {
        }
    }

Client class
public static void main(String args[])
    {
   try{
            ServerSocket ss=new ServerSocket(990);
             Socket s=ss.accept();
            while(true)
            {
                Calendar c=Calendar.getInstance();
                BufferedReader in=new BufferedReader(new InputStreamReader(s.getInputStream()));
                PrintWriter out =new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
                out.println("Hello This is server & My Time is :");
                out.println("Time :::  Hour="+c.HOUR +" Min="+c.MINUTE +" sec="+c.SECOND);
            out.flush();
              s.close();
            }
        }
        catch(Exception e)
        {
        }
    }

the program is working but the output is always
time:: hour=10 min=12 sec=13

why it is outputting the above values

A: That's because you're printing the values of the static integer fields called HOUR, MINUTE, SECOND present in the Calendar class. You need to use the Calendar#get(field) method to get the HOUR, MINUTE, SECOND values from the Calendar.
out.println("Time :::  Hour="+c.get(Calendar.HOUR) +" Min="+c.get(Calendar.MINUTE)+" sec="+c.get(Calendar.SECOND));

Note that since HOUR, MINUTE, SECOND are static fields, you need to access them using the class name(Calendar.SECOND) and not using the instance(c.SECOND).


text:
Q: Java OCR algorithm I am looking to make an android app which allows a user to take a photo of a number plate of a car and then based the image, extract the letters in to a string.
I have really struggled to find a single open source app library for android thats simply lets you pass an image and it returns the text.
I was wondering if anyone knew of a library for doing just this, or if not if anyone knew of a particular algorithm that i could implement?
Kind regards

A: Ron Cemer has a really nice one.
http://www.roncemer.com/software-development/java-ocr
But the most popular is Tesseract(http://tesseract-ocr.googlecode.com/), but you'd have to use a JNI wrapper, like Tesjeract(http://code.google.com/p/tesjeract/).
Here's Mezzofanti (http://code.google.com/p/mezzofanti/) an open source app that uses Tesjeract with Tesseract.
There's also Abbyy's paid one:
http://www.abbyy.com/mobileocr/android/


text:
Q: How to set the frame's background using class ttk.Style? I'm making a tkinter interface and created a ttk.Style object to make it easy to change the design. However, when I try to change some characteristic of the frame or labelframe, I don't see changes in the widget.
import tkinter as tk
from tkinter import ttk

colors = [
    '#203864',
    '#ADB9CA'
]

myfont = ('calibri', 18)

root = tk.Tk()

style = ttk.Style()
style.theme_create('MyTheme', parent='alt', settings={
    'TFrame':{
        'configure':{'background':colors[0]}
    },
    'TLabel':{
        'configure':{'background':colors[0], 'font':myfont, 'foreground':colors[1]}
    }
})
style.theme_use('MyTheme')

frame = tk.Frame(root)
frame.pack()

tk.Label(frame, text='MyTheme').pack(padx=100, pady=20)

root.mainloop()

Sorry for my English, I'm learning.

A: The themes only work for ttk widgets, and your code is using a tk frame. You need to change your frame to this:
frame = ttk.Frame(root, width=100, height=100)
#       ^^^