text:
Q: Data is not saving using Firebase I am using following code to save data on firebase . But it is giving permission denied error.Here is my code. I have followed all instruction given by firebase.
 buttonSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Firebase ref = new Firebase(Config.FIREBASE_URL);
                String name = editTextName.getText().toString().trim();
                String address = editTextAddress.getText().toString().trim();
                Person person = new Person();
                person.setName(name);
                person.setAddress(address);
                ref.child("Person").setValue(person);
                ref.addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot snapshot) {
                        for (DataSnapshot postSnapshot : snapshot.getChildren()) {
                            Person person = postSnapshot.getValue(Person.class);
                            String string = "Name: " + person.getName() + "\nAddress: " + person.getAddress() + "\n\n";
                            textViewPersons.setText(string);
                        }
                    }

                    @Override
                    public void onCancelled(FirebaseError firebaseError) {
                        Log.e("The read failed: ", firebaseError.getMessage());
                    }
                });

            }
        });

A: You might have following rule in your Rules Tab:
{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
  }
}

This rule means only authenticated users would be able to perform read and write operations.
Just change it to:
{
  "rules": {
    ".read": "true",
    ".write": "true"
  }
}

Caution: This rule means that anyone can read and write to your firebase database.
Steps: Go to Firebase Console -> Select Project -> Select Database from left handside menu -> Click on Rules tab -> Copy the rules over there.


text:
Q: Review changes in .tex files I have two files paper.tex and paper_suggested_changes.tex the latter is a modified version of the former with corrections.
I need to go through the two files and choose which changes to accept or reject, how would I go about this?

A: I have never used Meld but based on the screenshot posted by @Renan it looks pretty good for the purpose.
I use vim for this and it works perfectly if you don't mind to learn how to use the keystrokes to navigate and work with the differences. The advantage of learning this is that vim likely exists in most *NIX systems so you don't need to install additional software. Here's how to use it.

*

*Run either of:
gvimdiff paper.tex paper_suggested_changes.tex
gvim -d paper.tex paper_suggested_changes.tex
vimdiff paper.tex paper_suggested_changes.tex
vim -d paper.tex paper_suggested_changes.tex

gvimdiff is a shortcut to gvim -d. If you don't have gvimdiff then use gvim -d. Likewise for vimdiff. gvim is slightly easier to use than vim.

*You will see a vertically split window, with paper.txt in the left buffer and paper_suggested_changes.tex in the right buffer, with the differences highlighted with different colors depending on the type of the change, for example: line was added, line was deleted, lines are different.

*You can jump to the next difference with the key sequence ]c

*You can jump to the previous difference with the key sequence [c

*To accept a change from the other file and apply it in the current file where you have the cursor, move the cursor over the change and enter do.

*To switch between the left and right buffers, press ctrl+w w.

A: Install an utility like Meld (there are other utilities for doing this, too, but I like Meld since it doesn't have KDE/GNOME dependencies) and use it for visually diffing/merging the files.

Meld is a visual diff and merge tool targeted at developers. Meld helps you compare files, directories, and version controlled projects. It provides two- and three-way comparison of both files and directories, and has support for many popular version control systems.

A: I would certainly use vimdiff, simply because vim is my default editor. Check if your editor has a diff option first, as it makes things easier.
There are many graphical tools, the most user-friendly being Meld (as suggested by Renan).
Also consider using latexdiff to see the differences in a nice pdf format.
latexdiff paper.tex paper_suggested_changes.tex > changes.tex
pdflatex changes.tex

That will create a changes.pdf document with changes in different colours, and the old ones striked out.

A: As some of the other answers mentioned, use Vimdiff. Here's a short list of most useful key commands you might find useful:
https://stackoverflow.com/q/5288875/212942

A: You can use any of the above suggested solutions, vimdiff/gvimdiff are great if you are used to with vim. Meld is also good, but I personally like beyondcompare, It's another GUI tool like meld, meld sometimes mislead with big files, so I shifted from meld to bcompare.
beyond compare is available on ubuntu software centre, also you can download .deb file from http://www.scootersoftware.com/download.php this link.

A: I recommend using version control on the file. Tracking versions in a version control system will make your life a lot easier.
The simplest version control system to learn is CVS. It's basic, which means you can quickly learn its useful features, but you won't get the benefit of more complex systems' advanced features. Commit each successive version of the file, and use cvs diff paper.tex to see the differences between a new version and the last committed version, or cvs diff -r1.3 -r1.4 paper.tex to see the differences between version 1.3 and version 1.4.
With several people editing a document concurrently, you will benefit from a distributed version control system. Three common DVCS are Bazaar, Git and Mercurial. Commit each contributor's version on a branch (or better yet, set up a single repository for sharing and have each contributor commit their work to it). Periodically merge versions between branches. The DVCS keeps track of which changes you've already merged — this is a huge help to ensure you don't accidentally lose some work. The DVCS's merge command will also automatically merge parts that have only been changed by one person, so you'll only have to manually clean up the parts where there's a conflict.

A: You can use xxdiff for effective selection and combining of two or three files.
It can also compare directories (only 2).
It can be found here, but is also in many distros

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to setup a Java EE6 application structure So after reading about DDD and all it benefits and glory it seems like Java EE does not make it easy for you to do so. What I thought was to make a structure like this:
Domain
Repository
Application
View
However in the comment of this answer DDD and application layer it seems like the Application layer which I thought was going to be the layer with all the services annotated with @Stateful, @WebService etc is not the place it really should be in. It seems like the domain models should have these annotations.
So now the question is: How do people structure their applications? Where do you put the different annotations and how do they use each other. Could somebody please help me understand how I can structure an java ee 6 web application? Please help and say not how I do it in a specific tool or anything like that but where the actual classes goes and what the different layers are intended to do.
I am frustrated on where to start and how to organize.

A: There are no specific rules on how you should structure your application. Best would be to use common sense as well as observe how others are doing it.
You can generate a simple maven project provided by weld team to see how a basic Java EE application can be structured:
mvn archetype:generate -DarchetypeArtifactId=jboss-javaee6-webapp -DarchetypeGroupId=org.jboss.weld.archetypes -DarchetypeVersion=1.0.1.CR1 -DarchetypeRepository=central

For sure you will find many other examples on github or java.net

A: Here's an example that might be helpful -> EAR Testing
It's called "EAR Testing", but can just as easily apply to building war files.  For purposes of this answer I'll change the eartesting directory mentioned in the example to wartesting
EAR files and WAR files are nearly identical since at the Java EE spec level we decided to allow war files to contain EJBs, CDI beans, and more.
That example uses the Maven build system and has two modules, one for the "data obects" and one for "business logic".   Seems to fit with how you think of thinks and might be a helpful starting point.  It contains a tiny sample application with unit tests for the EJBs.
You might not have read yet, but often people refer to EJBs as hard to test.  There're not anymore and that example shows the latest spec compliant solution, so you can kill a few birds with one stone starting from that setup.
What that doesn't include is a module to create the final WAR file that you would deploy in production.  To create that you'd just add a third module

*

*wartesting/business-model

*wartesting/business-logic

*wartesting/business-war (added)
In the busines-war you'd have a pom.xml like the following:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <parent>
    <groupId>org.superbiz</groupId>
    <artifactId>myear</artifactId>
    <version>1.1-SNAPSHOT</version>
  </parent>

  <modelVersion>4.0.0</modelVersion>

  <artifactId>business-war</artifactId>
  <packaging>war</packaging>

  <dependencies>
    <dependency>
      <groupId>org.superbiz</groupId>
      <artifactId>business-model</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>org.superbiz</groupId>
      <artifactId>business-logic</artifactId>
      <version>${project.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.openejb</groupId>
      <artifactId>javaee-api</artifactId>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>

Then create the following directories:

*

*wartesting/business-war/src/main/java

*wartesting/business-war/src/main/webapp

And we'll say for example you add the following files to each:

*

*wartesting/business-war/src/main/java/org/superbiz/Foo.java

*wartesting/business-war/src/main/webapp/WEB-INF/web.xml

*wartesting/business-war/src/main/webapp/index.html

Once built, you should get a war file under wartesting/business-war/target/ containing:

*

*WEB-INF/web.xml

*WEB-INF/classes/org/superbiz/Foo.class

*WEB-INF/lib/business-model-1.1-SNAPSHOT.jar

*index.html


text:
Q: Cloud Run and Revel Container I have a simple site built using revel containerized in a docker image. I'm trying to run this image in Cloud Run. Unfortunately when I go to the URL for the site, I see a 502 in the browser and this log line
2020/10/30 17:27:07 http: proxy error: dial tcp 0.0.0.0:16166: connect: connection refused
I would assume it had something to do with the port, but I tried mapping the port originally to 9898 and I still saw a random port number in the log line. Currently I have the port in my revel application set to ${PORT} as recommended by the GCP documentation.
I should mention I can deploy the container locally with no issues.
Dockerfile:
FROM golang:1.15 AS build
ENV CGO_ENABLED 0
ADD . /go/src/app

# Install revel framework
RUN go get -u github.com/revel/revel
RUN go get -u github.com/revel/cmd/revel
# Run revel app
EXPOSE ${PORT}
ENTRYPOINT revel run -a /go/src/app -p ${PORT} -m dev

Revel app.conf snippet:
# The IP address on which to listen.
http.addr = 0.0.0.0

# The port on which to listen.
http.port = ${PORT}

UPDATE: It was suggested to use the hardcoded port of 8080 and see if that works. I still see the 502. I tried running it locally again and it looks like revel is trying to set up on one port and then listenining as a reverse proxy on another. So unless I'm thinking this may be a revel issue and not a Cloud Run issue
docker run --publish 8080:8080 app
Revel executing: run a Revel application
Changed detected, recompiling
Parsing packages, (may require download if not cached)... Completed
INFO  02:34:24    app     run.go:34: Running revel server
INFO  02:34:24    app   plugin.go:9: Go to /@tests to run the tests.
Revel engine is listening on.. 0.0.0.0:44795

Time to recompile 8.0340966s
Revel proxy is listening, point your browser to : 8080

Notice the last line Revel proxy is listening, point your browser to : 8080 but also Revel engine is listening on.. 0.0.0.0:44795

A: So after further investigation and discussion, it seems like when you run revel applications via revel run a proxy is set up on a random port and that connection was what was failing. Furthermore, the largest benefit of running via revel run is hot swapping of deployed code, which is unnecessary in a deployed context. So the solution here was to build the application via revel build and running that application that way so that only the application port is used for connections.


text:
Q: Making actions based on video audio codec Currently, I have a simple script that will detect video audio codec using ffmpeg and output a message specifing if the codec is mp4 or aac. Here is my code:
#!/bin/bash
for i in *.mp4; do
    OUTPUT=$(ffmpeg -i '$i' 2>&1 | grep -o 'Audio:.*' | cut -f2 -d' ' | awk '{print $0}' | tr -d ,)
    if [[ $OUTPUT == "mp3" ]]; then
        echo "${i} = audio codec mp3"
    fi
    if [[ $OUTPUT == "aac" ]]; then
        echo "${i} = audio codec aac"
    fi
done

But this script isn't working! There are no errors and I don't know what should I do to solve this. Also, ffmpeg -i <input.mp4> 2>&1 | grep -o 'Audio:.*' | cut -f2 -d' ' | awk '{print $0}' | tr -d , returns aac or mp3, this line is working perfeclty! I guess that the problem is related to if case, but as I've said, I'm unable to solve this alone, can you help me?
Thank you

A:

if [[ $OUTPUT == "mp3" ]]; then if [[ $OUTPUT == "aac" ]]; then

Replace this with
if [[ "$OUTPUT" = "mp3" ]]; then
if [[ "$OUTPUT" = "aac" ]]; then


text:
Q: how to check whether a user is logged in in django? I know about request.user.is_authenticated() but i created a custom user(model) and created login page for it
now how can we know if the user is logged in?

A: In views.py once the user logs in redirect to a url that calls a view
@login_required()
def login_success(request):

and render a welcome message


text:
Q: Draw the content of a textbox I have a textbox on top of an image overlay, which the user can interfere with. Now I want to draw the string onto that image via Graphics, but if I use the direct values of the box for drawing, the text isn't aligned correctly at all. Any tips on how to improve it, or any better way or doing it?
if (item is TextBox)
                {
                    var usedItem = item as TextBox;
                    var p1 = new System.Drawing.Point((int)Math.Round(usedItem.Margin.Left), (int)Math.Round(usedItem.Margin.Top));
                    var font = new System.Drawing.Font("Segoe UI", (float)(usedItem.FontSize) );
                    g.DrawString(usedItem.Text, font, new System.Drawing.SolidBrush((System.Drawing.Color)new System.Drawing.ColorConverter().ConvertFromString(new System.Windows.Media.BrushConverter().
                        ConvertToString(usedItem.Foreground))), p1);
                }

How it should look:

How it ends up looking:


text:
Q: Enforcing required function call I have a "Status" class in C#, used like this:
Status MyFunction()
{
   if(...) // something bad
     return new Status(false, "Something went wrong")
   else
     return new Status(true, "OK");
}

You get the idea.
All callers of MyFunction should check the returned Status:
Status myStatus = MyFunction();
if ( ! myStatus.IsOK() )
   // handle it, show a message,...

Lazy callers however can ignore the Status.
MyFunction(); // call function and ignore returned Status

or
{
  Status myStatus = MyFunction();
} // lose all references to myStatus, without calling IsOK() on it

Is it possible to make this impossible? e.g. an throw exception
In general: is it possible to write a C# class on which you have to call a certain function?
In the C++ version of the Status class, I can write a test on some private bool bIsChecked in the destructor and ring some bells when someone doesn't check this instance.
What is the equivalent option in C#?
I read somewhere that "You don't want a destructor in your C# class"
Is the Dispose method of the IDisposable interface an option?
In this case there are no unmanaged resources to free.
Additionally, it is not determined when the GC will dispose the object.
When it eventually gets disposed, is it still possible to know where and when you ignored that specific Status instance?
The "using" keyword does help, but again, it is not required for lazy callers.

A: If you really want to require the user to retrieve the result of MyFunction, you might want to void it instead and use an out or ref variable, e.g.,
void MyFunction(out Status status)
{
}

It might look ugly but at least it ensures that a variable is passed into the function that will pick up the result you need it to pick up.
@Ian,
The problem with exceptions is that if it's something that happens a little too often, you might be spending too much system resources for the exception. An exception really should be used for exceptional errors, not totally expected messages.

A: Even System.Net.WebRequest throws an exception when the returned HTTP status code is an error code. The typical way to handle it is to wrap a try/catch around it. You can still ignore the status code in the catch block.
You could, however, have a parameter of Action< Status> so that the caller is forced to pass a callback function that accepts a status and then checking to see if they called it.
void MyFunction(Action<Status> callback)
 { bool errorHappened = false;

   if (somethingBadHappend) errorHappened = true;

   Status status = (errorHappend)
                     ? new Status(false, "Something went wrong")
                     : new Status(true, "OK");
   callback(status)

   if (!status.isOkWasCalled)
     throw new Exception("Please call IsOK() on Status").
 }

MyFunction(status => if (!status.IsOK()) onerror());

If you're worried about them calling IsOK() without doing anything, use Expression< Func< Status,bool>> instead and then you can analyse the lambda to see what they do with the status:
void MyFunction(Expression<Func<Status,bool>> callback)
 { if (!visitCallbackExpressionTreeAndCheckForIsOKHandlingPattern(callback))
     throw new Exception
                ("Please handle any error statuses in your callback");

   bool errorHappened = false;

   if (somethingBadHappend) errorHappened = true;

   Status status = (errorHappend)
                     ? new Status(false, "Something went wrong")
                     : new Status(true, "OK");

   callback.Compile()(status);
 }

MyFunction(status => status.IsOK() ? true : onerror());

Or forego the status class altogether and make them pass in one delegate for success and another one for an error:
void MyFunction(Action success, Action error)
 { if (somethingBadHappened) error(); else success();
 }

MyFunction(()=>;,()=>handleError());

A: I am fairly certain you can't get the effect you want as a return value from a method. C# just can't do some of the things C++ can. However, a somewhat ugly way to get a similar effect is the following:
using System;

public class Example
{
    public class Toy
    {
        private bool inCupboard = false;
        public void Play() { Console.WriteLine("Playing."); }
        public void PutAway() { inCupboard = true; }
        public bool IsInCupboard { get { return inCupboard; } }
    }

    public delegate void ToyUseCallback(Toy toy);

    public class Parent
    {
        public static void RequestToy(ToyUseCallback callback)
        {
            Toy toy = new Toy();
            callback(toy);
            if (!toy.IsInCupboard)
            {
                throw new Exception("You didn't put your toy in the cupboard!");
            }
        }
    }

    public class Child
    {
        public static void Play()
        {
            Parent.RequestToy(delegate(Toy toy)
            {
                toy.Play();
                // Oops! Forgot to put the toy away!
            });
        }
    }

    public static void Main()
    {
        Child.Play();
        Console.ReadLine();
    }
}

In the very simple example, you get an instance of Toy by calling Parent.RequestToy, and passing it a delegate. Instead of returning the toy, the method immediately calls the delegate with the toy, which must call PutAway before it returns, or the RequestToy method will throw an exception. I make no claims as to the wisdom of using this technique -- indeed in all "something went wrong" examples an exception is almost certainly a better bet -- but I think it comes about as close as you can get to your original request.

A: I know this doesn't answer your question directly, but if "something went wrong" within your function (unexpected circumstances) I think you should be throwing an exception rather than using status return codes.
Then leave it up to the caller to catch and handle this exception if it can, or allow it to propogate if the caller is unable to handle the situation.
The exception thrown could be of a custom type if this is appropriate.
For expected alternative results, I agree with @Jon Limjap's suggestion.  I'm fond of a bool return type and prefixing the method name with "Try", a la:
bool TryMyFunction(out Status status)
{
}

A: Using Status as a return value remembers me of the "old days" of C programming, when you returned an integer below 0 if something didn't work.
Wouldn't it be better if you throw an exception when (as you put it) something went wrong? If some "lazy code" doesn't catch your exception, you'll know for sure.

A: Instead of forcing someone to check the status, I think you should assume the programmer is aware of this risks of not doing so and has a reason for taking that course of action.  You don't know how the function is going to be used in the future and placing a limitation like that only restricts the possibilities.

A: You can throw an exception by:
throw MyException;

[global::System.Serializable]
        public class MyException : Exception
        {
        //
        // For guidelines regarding the creation of new exception types, see
        //    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconerrorraisinghandlingguidelines.asp
        // and
        //    http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dncscol/html/csharp07192001.asp
        //

        public MyException () { }
        public MyException ( string message ) : base( message ) { }
        public MyException ( string message, Exception inner ) : base( message, inner ) { }
        protected MyException (
          System.Runtime.Serialization.SerializationInfo info,
          System.Runtime.Serialization.StreamingContext context )
            : base( info, context ) { }
    }

The above exception is fully customizable to your requirements.
One thing I would say is this, I would leave it to the caller to check the return code, it is their responsability you just provide the means and interface. Also, It is a lot more efficient to use return codes and check the status with an if statement rather than trhowing exceptions. If it really is an Exceptional circumstance, then by all means throw away... but say if you failed to open a device, then it might be more prudent to stick with the return code.

A: That would sure be nice to have the compiler check that rather than through an expression. :/
Don't see any way to do that though...

A: GCC has a warn_unused_result attribute which is ideal for this sort of thing.  Perhaps the Microsoft compilers have something similar.

A: @Paul you could do it at compile time with Extensible C#.

A: One pattern which may sometimes be helpful if the object to which code issues requests will only be used by a single thread(*) is to have the object keep an error state, and say that if an operation fails the object will be unusable until the error state is reset (future requests should fail immediately, preferably by throwing an immediate exception which includes information about both the previous failure and the new request).  In cases where calling code happens to anticipate a problem, this may allow the calling code to handle the problem more cleanly than if an exception were thrown; problems which are not ignored by the calling code will generally end up triggering an exception pretty soon after they occur.
(*) If a resource will be accessed by multiple threads, create a wrapper object for each thread, and have each thread's requests go through its own wrapper.
This pattern is usable even in contexts where exceptions aren't, and may sometimes be very practical in such cases.  In general, however, some variation of the try/do pattern is usually better.  Have methods throw exception on failure unless the caller explicitly indicates (by using a TryXX method) that failures are expected.  If callers say failures are expected but don't handle them, that's their problem.  One could combine the try/do with a second layer of protection using the scheme above, but I'm not sure whether it would be worth the cost.


text:
Q: how to append value in td I am getting dynamic values in table using Datatables. I am getting my desired value in alert, but I want to show that value in table. for that purpose I used .append, .html but no luck. How can I show = my value in . I also try to gave gave td an id e.g
here is my code:

function format(d) {
  var str = d.files;
  var myarr = str.split(",");
  for (var i = 0; i < myarr.length; i++) {
    alert(myarr[i]);
    $("#files").append("" + myarr[i] + "");
  }

  // `d` is the original data object for the row
  return '
' +
    '
' +
    'Contact Person:	' +
    '' + d.person + '	' +
    '
' +
    '
' +
    'Phone:	' +
    '' + d.phone + '	' +
    '
' +
    '
' +
    'Web:	' +
    '' + d.web + '	' +
    '
' +
    '
' +
    'Trade Type:	' +
    '' + d.ttype + '	' +
    '
' +
    '
' +
    'Files:	' + ''
  '	' +
  '
' +
  '
';
}

I hope it will be a easy fix.any help will be highly appreciable

A: Your issue is that the #files element doesn't exist at the point you attempt to select it. You need to first add that HTML string to the DOM, then append to it.
Alternatively, you could amend the logic which creates that HTML string to include the output of your for loop, like this:

function format(d) {
  var str = d.files;
  var filesHtml = str.split(",").map(function(file) {
    return '' + file + '';
  });

  return '
' +
    '
' +
      'Contact Person:	' +
      '' + d.person + '	' +
    '

' +
      'Phone:	' +
      '' + d.phone + '	' +
    '

' +
      'Web:	' +
      '' + d.web + '	' +
    '

' +
      'Trade Type:	' +
      '' + d.ttype + '	' +
    '

' +
      'Files:	' +
      '' + filesHtml + '	' +
    '
' +
  '
';
}

var html = format({
  person: 'John Smith',
  phone: '1234 567890',
  web: 'http://google.com',
  ttype: 'Foobar',
  files: 'a.jpg,b.jpg'
});
$('div').append(html);


text:
Q: disable old version of php-fpm after upgrade from 7.0 to 7.1 I upgraded from php-fpm 7.0 to 7.1 but the 7.0 is still running. How do I disable it?
This is the output from top;
 1251 ubuntu    20   0  464760  48424  40448 S  0.0  4.8   0:00.03 php
 1002 root      20   0  506216  47480  39856 S  0.0  4.7   0:00.03 php-fpm7.1
 1048 root      20   0  311664  29788  24032 S  0.3  2.9   0:00.03 php-fpm7.0
 1176 www-data  20   0  506216   9396   1772 S  0.0  0.9   0:00.00 php-fpm7.1
 1177 www-data  20   0  506216   9396   1772 S  0.0  0.9   0:00.00 php-fpm7.1
 1173 www-data  20   0  311664   7252   1496 S  0.0  0.7   0:00.00 php-fpm7.0
 1174 www-data  20   0  311664   7252   1496 S  0.0  0.7   0:00.00 php-fpm7.0

A: do this;
sudo systemctl disable php7.0-fpm.service
sudo reboot

A: the name of services can be different, in my case the name is without dot(.).  to check the right service name just use
systemctl | grep php

will return:
● php-fpm.service loaded failed failed    The PHP FastCGI Process Manager
  php72-php-fpm.service  loaded active running   The PHP FastCGI Process Manager

in above case, to disable just use:
systemctl disable php72-php-fpm.service

You dont need to reboot. It's work perfectly without reboot.


text:
Q: JSLint does not like .bind(this), but without it, this.obj cannot be accessed I am optimizing my code for user with JSlint, i came to a small issue that i am trying to find a solution to. In the code below which works, JSlint complains about .bind(this). If i remove .bind(this), then the code does not know what is "this.selectorCache.get()" nor "this.someFunc()".
Is there a way to get this code working by removing .bind(this)?
/*jslint this:true, devel: true */
/*global jQuery, $, window, SelectorCache */
"use strict";

$(function () {
    window.myApp = (function () {
        var _this = this;
        this.selectorCache = new SelectorCache();// selector cache function

        this.someFunc = function () {
            return 0;
        };

        this.selectorCache.get('#someID').click(function () {
            if (_this.this.selectorCache.get('#someOtherID').val() === 1){
                console.log(_this.someFunc());
            }
        }.bind(this));
    }.bind(this));
}.bind(this));

A: Store the this context to another variable and use it in the callback.
I'd recommend you to use the bind(this) though and to find out why exactly JSLint complains.
window.myApp = (function () {
    var _this = this;

    this.selectorCache = new selectorCache();// selector cache function

    this.someFunc = function () {
        return 0;
    }

    this.selectorCache.get('#someID').click(function () {
        if _this.selectorCache.get('#someOtherID').val() === 1{
            console.log(_this.someFunc());
        }
    });
}

A: The solution @Erazhihel proposed should fix the problem. Another minimal way to fix it is by using ES6's arrow function instead.
/* global jQuery, $, window */
"use strict";

$(function() {
  window.myApp = (function () {

    this.selectorCache = new selectorCache();// selector cache function

    this.someFunc = function (){
        return 0;
    }

    this.selectorCache.get('#someID').click(() => {
      if (this.selectorCache.get('#someOtherID').val() === 1){
        console.log(this.someFunc());
      }
    };
  });
});


text:
Q: EditText Control not showing in Android app I am following along with this tutorial and it says

The default weight for all views is 0, so if you specify any weight
  value greater than 0 to only one view, then that view fills whatever
  space remains after all views are given the space they require. So, to
  fill the remaining space in your layout with the EditText element,
  give it a weight of 1 and leave the button with no weight.

You achieve this by writing
<EditText
        android:layout_weight="1"
        ... />

which I have done. I have also set the layout_width to 0dp as the tutorial says.
Now, in Android Studio, everything appears fine in the Preview pane. But when I debug my app, the EditText control does not appear. But the Button appears further down the screen and to the very left as if the EditText control has actually filled the entire width of the screen and pushed it down (except the EditText does not appear so I cannot confirm this).
I have removed the weight property and set a fixed width on it, and that gets it to display, but obviously, that is not desirable.
Why won't the EditText control appear?
Here is my code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    tools:ignore="MergeRootFrame" android:orientation="horizontal">
    <EditText android:id="@+id/edit_message"
              android:layout_weight="1"
              android:layout_width="0dp"
              android:layout_height="wrap_content"
              android:hint="@string/edit_message" />

    <Button android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/button_send" />

</LinearLayout>

As you can see below, there is no EditText control.

A: Try this code: Your editText will cover appx. 70% and your button will cover remaining of total width...actually if you use 0dp width approach, you have to set it for all views afaik....
<EditText android:id="@+id/edit_message"
              android:layout_weight="3"
              android:layout_width="0dp"
              android:layout_height="wrap_content"
              android:hint="@string/edit_message" />

    <Button android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/button_send" />

A: The culprit is this in you editText:
android:layout_width="0dp"

Replace with this :
android:layout_width="107dip"


text:
Q: ssh with xterm can't get screen resources I am trying to launch a GUI of a program on my windows computer by ssh with putty.
I downloaded Xterm and have that running, and then in the putty options, I checked the box for X11 forwarding.
When I try to run my program, it comes up, but all greyed out. They terminal says:
failed to get the current screen resources
QXcbConnection: XCB error: 170 (Unknown), sequence: 170, resource id: 90, major code: 146 (Unknown), minor code: 20
Xlib:  extension "MIT-SHM" missing on display "localhost:24.0".
Xlib:  extension "MIT-SHM" missing on display "localhost:24.0".
Xlib:  extension "MIT-SHM" missing on display "localhost:24.0".
Xlib:  extension "MIT-SHM" missing on display "localhost:24.0".
Xlib:  extension "MIT-SHM" missing on display "localhost:24.0".
Xlib:  extension "MIT-SHM" missing on display "localhost:24.0".
Xlib:  extension "MIT-SHM" missing on display "localhost:24.0".

It keeps repeating this until I cntl+c out.
Any ideas what could be causing this?


text:
Q: I'm using axios and useEffect to do my get request but it doesn't work when my page is loaded When i refresh the page, my object is empty but when i go back in the code, change something and save it, the request is made again, with no refresh, successfuly and contain the expected result.
 const [specialities, setSpecialities] = useState([])
 const getData = async ()=> {

   await axios.get(getURL).then((response)=>{
     setSpecialities(response.data)
     console.log(specialities, "specialeties are displayed here")
   })
 }

 useEffect(()=>{
   getData()
 }, [])```

Here i remove the accolades in my useEffect and it works, my response is full when i reload but the request is made infinitely.
const [specialities, setSpecialities] = useState([])
const getData = async ()=> {

await axios.get(getURL).then((response)=>{
  setSpecialities(response.data)
  console.log(specialities, "specialesss")
})}

useEffect(()=>{
 getData()
})

A: For class component,
  this.setState(response.data)
     console.log(specialities, "specialeties are displayed here")

You cannot get the specialities data just after setting it. It takes some time to set the data.
The below code would work as we have a callback after setting the state.
  this.setState(response.data, function() {
    console.log(specialities, "specialeties are displayed here")   });

For functional component,
 useEffect(() => { console.log(specialities); },[specialities);


text:
Q: Get value from each cell of a Range.Areas I have this code which I got here
Sub QuickMap()

    Dim FormulaCells
    Dim TextCells
    Dim NumberCells
    Dim Area

    If TypeName(ActiveSheet) <> "Worksheet" Then Exit Sub

'   Create object variables for cell subsets
    On Error Resume Next
    Set FormulaCells = Range("A1").SpecialCells _
      (xlFormulas, xlNumbers + xlTextValues + xlLogical)
    Set TextCells = Range("A1").SpecialCells(xlConstants, xlTextValues)
    Set NumberCells = Range("A1").SpecialCells(xlConstants, xlNumbers)
    On Error GoTo 0

'   Add a new sheet and format it
    Sheets.Add
    With Cells
        .ColumnWidth = 2
        .Font.Size = 8
        .HorizontalAlignment = xlCenter
    End With

    Application.ScreenUpdating = False

'   Do the formula cells
    If Not IsEmpty(FormulaCells) Then
        For Each Area In FormulaCells.Areas
            With ActiveSheet.Range(Area.Address)
                .value = "F"
                .Interior.ColorIndex = 3
            End With
        Next Area
    End If

'   Do the text cells
    If Not IsEmpty(TextCells) Then
        For Each Area In TextCells.Areas
            With ActiveSheet.Range(Area.Address)
                .value = "T"
                .Interior.ColorIndex = 4
            End With
        Next Area
    End If

'   Do the numeric cells
    If Not IsEmpty(NumberCells) Then
        For Each Area In NumberCells.Areas
            With ActiveSheet.Range(Area.Address)
                .value = "N"
                .Interior.ColorIndex = 6
            End With
        End If
        Next Area
    End If
End Sub

What this code does is create a new worksheet with an map of other worksheet, for example, it place a N with background color yellow where is a numeric or constant on the other worksheet.
I want to set the background color to blue on cells on the map where the value on the other worksheet is a numeric and is greater than 130.
It seens to have a pretty simple solution but I have tried work with it like I work with Ranges but I am not getting any satisfactory results.
So, my question is,  how can I get the value of each cell to use a condition statement? Thanks in advance.

A: You can loop item on .area then if single item corresponding your text background cell will be blue otherwise yellow
Sub QuickMap()
        Dim FormulaCells
        Dim TextCells
        Dim NumberCells
        Dim Area

        If TypeName(ActiveSheet) <> "Worksheet" Then Exit Sub

    '   Create object variables for cell subsets
        On Error Resume Next
        Set FormulaCells = Range("A1").SpecialCells _
          (xlFormulas, xlNumbers + xlTextValues + xlLogical)
        Set TextCells = Range("A1").SpecialCells(xlConstants, xlTextValues)
        Set NumberCells = Range("A1").SpecialCells(xlConstants, xlNumbers)
        On Error GoTo 0

    '   Add a new sheet and format it
        Sheets.Add
        With Cells
            .ColumnWidth = 2
            .Font.Size = 8
            .HorizontalAlignment = xlCenter
        End With

        Application.ScreenUpdating = False

    '   Do the formula cells
        If Not IsEmpty(FormulaCells) Then
            For Each Area In FormulaCells.Areas
                With ActiveSheet.Range(Area.Address)
                    .Value = "F"
                    .Interior.ColorIndex = 3
                End With
            Next Area
        End If

    '   Do the text cells
        If Not IsEmpty(TextCells) Then
            For Each Area In TextCells.Areas
                With ActiveSheet.Range(Area.Address)
                    .Value = "T"
                    .Interior.ColorIndex = 4
                End With
            Next Area
        End If

    '   Do the numeric cells
        If Not IsEmpty(NumberCells) Then
            For Each Area In NumberCells.Areas
                For Each Item In Area
                    If Item > 130 Then
                        ActiveSheet.Range(Item.Address).Value = "N"
                        ActiveSheet.Range(Item.Address).Interior.ColorIndex = 5
                    Else
                        ActiveSheet.Range(Item.Address).Value = "N"
                        ActiveSheet.Range(Item.Address).Interior.ColorIndex = 6
                    End If
                Next Item
            Next Area
        End If
    End Sub


text:
Q: Como cambiar el tema a SweetAlert2 v9.x he intentado cambiar el tema de mi sweetAlert2, pero no he tenido éxito.
Los siguientes archivos fueron extraídos de la pagina oficial de SweetAlert2, pero no puedo lograr que se cambie el tema, se queda con el default, he buscado como hacerlo, pero sale que solo basta con declarar el css y se cambia el tema, pero desconozco si es que hay que cambiar algun otro archivo o alguna parte donde indique que estoy utilizando x tema
Este es mi css
<link rel="stylesheet" href="/sweetAlert2/css/borderless.css">

el cual es este css
https://cdn.jsdelivr.net/npm/@sweetalert2/theme-borderless/borderless.css
y mi js
<script src="/sweetAlert2/js/sweetalert2.js"></script>

el cual es este js
https://cdn.jsdelivr.net/npm/sweetalert2@9

A: SOLUCIONADO
Ya lo solucione, primero aclarar que el theme borderless no era lo que necesitaba ya que al abrir un mensaje de confirmacion, este se abre en pantalla completa (supongo que por ello el nombre), el punto es que logre cambiar al tema Dark, pero por alguna razon, al descargarlos desde jsDelivr no me carga el tema.
Por lo tanto lo que hice fue inspeccionar la pagina de sweetalert y sacar los archivos que necesitaba desde ahí (css del tema seleccionado y el js) y funciona perfectamente ahora


text:
Q: Duplicate Status Error when Tweeting using Twitter API I am new to JavaScript and I am using Node.js and the Twitter API as a way to learn how to code. I am also using the Twit NPM package.  I am trying to create a "game" where a specific phrase has to be tweeted in order to begin. I have a function where if the specific phrase is not tweeted to the account, the account also replies to try again.
Whether the phrase is met or not, this function works once. However, what if the same user tries to tweet a phrase again (matching the phrase or not)? How do I avoid getting a duplicate status error? I am not sure what the best approach is here as it is out of my knowledge scope. Here is a simplified version of the code that returns a duplicate status error after both if conditions have been met by the same user and then they try again to tweet:
var Twit          = require('twit');
var T             = new Twit(config);

// Start a stream for listening for @mentions
var stream = T.stream('statuses/filter', { track: ['@someusername'] });
stream.on('tweet', somePhrase);

function somePhrase(tweet) {

  var request = tweet.text;
  var trigger = /(?:[^"']|^)(\bsome phrase\b)(?!["'])/ig;
  var name    = tweet.user.screen_name;
  var nameID  = tweet.id_str;

  // check to see if the tweet does not meet the request trigger
  if (request != trigger) {

    var reply   = '@' + name + "try again";
    var params  = { status: reply };

  }
  // check to see if the request matches the request trigger
  if (request.match(trigger)) {

    var question = "what do you want to know?";
    var params = {
        status: question + ' @' + name,
        in_reply_to_status_id: nameID
    };
  }

  T.post('statuses/update', params, function(err, data, response) {
    if (err !== undefined) {
      console.log(err);
    } else {
      console.log('Tweeted: ' + params.status);
    }
  })
};

This is the error code that the API returns:
{ [Error: Status is a duplicate.]
  message: 'Status is a duplicate.',
  code: 187,
  allErrors: [ { code: 187, message: 'Status is a duplicate.' } ],
  twitterReply: { errors: [ [Object] ] },
  statusCode: 403 }

A: Twitter compares the post text against recent texts to determine whether or not it's a duplicate.  I don't know how strict this comparison is.  But, one possible way to get around this could be to append something unique to each status text.
A useful unique number could be a counter for the number of games that have been played.  Ex: "What do you want to know? @jaime #0001"
To create a counter like that, you could use a database, but if you don't want to use a database, you can use the Twit npm package to get the number you used in your last tweet and increment it.  That way, it's always a unique number.
You could also just generate a random string to append, but that's not a good practice.
Edit: If character length is not an issue (since Twitter is standing by the 140-character limit), you can just append the UNIX timestamp, which will always be a unique number.  This is very easy to include with the Date() object.


text:
Q: Add extension functions to a existing class without changing source code of class I have a big C++ application that uses the old version of a open source library. I want to upgrade to new library. In new libary a old function fnOldFunction() is removed and a new function fnNewFunction() is added.
Now I have two choices:

*

*Replace all the instances of fnOldFunction() with fnNewFunction(). I have many other functions like fnOldFunction(), I do not want deal with n functions with thousands of find and replacement.

*I have source code of library. I can add fnOldFunction() there and call the fnNewFunction from fnOldFunction(). But even I have source code of that libray, do not want to make any changes in libray's source code.
Can anybody give me another way to achieve the same. I know some languages like Ruby, Javascript, Objective C provides the way to extend/modify the existing class without changing the source code of that class. But C++ lacks this feature.

A: A simple way may be to derive your own class from the library class and re-add to it all the old version's functions. This does not require writing a full adapter and it does not touch the library code. You only need to bulk rename for class name, which is less error-prone and scales better.

A: You could use a macro for this porpuse.
class A {
public:
  void fnNewFunction() {}
};

int main(void) {
  A a;
  a.fnNewFunction();

#define fnOldFunction fnNewFunction

  a.fnOldFunction();
}

I do not advice to use this technique. This will screw the intellisense and might introduce bugs (what if there is a another class with both fnOldFunction and fnNewFunction defined?)
The reason I wrote this is because it answers your specific question.
Option 1 of yours is the preferred solution. You could easily use your editor's re-factoring facilities to perform this action in no-time.

A: I think that's a good fit for Policies.
You could define two interfaces:
class A {
    void fnOldFunction();
public:
    void fn() {
        fnOldFunction();
    }
};
class B {
    void fnNewFunction();
public:
    void fn() {
        fnFunction();
    }
};

A and B could inherit from classes of the old/new library.
Now, you just have to define your working class like this:
template <typename Policy>
class C : public Policy {
    /* Whatever you need */
public:
    /* Say doSomething need to call fn */
    void doSomething() {
        /* Whatever */
        fn();
        /* ... */
    }
};

Now depending on your usecase, you could either use C<A> or C<B>. Note that this could be cumbersome if many names have changed in the library (breaking the API like that isn't a good idea, you have my sympathy :( ).
With this solution, which in terms does almost the same thing as @Alexander's one, you can still link against the old library as well as the new version. You just have to switch from C<B> to C<A>.
You could even couple that with other metaprogramming techniques such as type traits to make the compiler deduce if you need C<A> or C<B> all by itself. If possible, you wouldn't even have to touch the code to compile with either version of the lib.


text:
Q: Mac 10.6 - unable to install PHP intl I'm trying to install the PHP intl extension on Mac 10.6 "Snow Leopard" using the following command:
sudo pecl install intl
...but getting the following errors:
running: phpize
grep: /usr/include/php/main/php.h: No such file or directory
grep: /usr/include/php/Zend/zend_modules.h: No such file or directory
grep: /usr/include/php/Zend/zend_extensions.h: No such file or directory
Configuring for:
PHP Api Version:
Zend Module Api No:
Zend Extension Api No:
Cannot find autoconf. Please check your autoconf installation and the
$PHP_AUTOCONF environment variable. Then, rerun this script.

ERROR: `phpize' failed

I am using the bundles Apache server with PHP 5.3.4.
Does anyone know how to install the intl extension?

A: Have you thought about using MAMP instead? It generally works better than Apple's bundled packages.

A: I've installed Zend Server CE and everything works 100%.
I removed Zend Server CE later on, and used this instead:
http://php-osx.liip.ch/ which is specifically built for Mac OSX 10.6, and Symfony2 in mind.
This worked better for me in the end, as I'm a Netbeans user, this means I can use xdebug bundled with the liip distribution.
I found it a bit cumbersome getting xdebug installed on Zend Server CE, and also, the liip PHP installation doesn't install an additional Apache and MySQL, it uses what is already included with the OS.

A: Try installing autoconf
brew install autoconf
Regards

A: This might be an old post, but for me, I found the easiest option was to install PHP using the liip service (http://php-osx.liip.ch/).  Using one simple command, it installed the latest version of PHP, configured it with the existing apache server installed on my mac all along with the intl extension.  A number of hours frustration solved in a couple of minutes!


text:
Q: Creating reusable function in Google AdWords I'm currently writing a script in Google AdWords, and I'm managing lots of campaigns that use the same function (which I have had to copy-paste around 90+ times). Whenever I want to edit this function it becomes incredibly hard as I need to manually to through every script individually.
Is there any way of creating a reusable function, store it as a separate script and call it from AdWords like how I can call Logger and DriveApp? I've tried to use the following resources, which has been pretty useless so far:

*

*Standalone Scripts - Google somehow allows you to create scripts but not execute them from within AdWords (at least that's as far as I've managed to come)

*Execution API - Gave up after getting constant 'Unauthenticated' errors (even when setting the permissions to 'Anyone, even anonymous')

*MCC Scripts - This allows me to update all accounts, but doesn't do what I need

If anyone knows any way of simply storing a function somewhere and calling it within Google AdWords, it would be greatly appreciated.

A: You can write your function a save it in a Google Drive file and the use it from there:
var scriptFile = getFile(location);
var scriptText = scriptFile.getBlob().getDataAsString();
eval(scriptText);


text:
Q: How to parse String and get certain value I should parse a string like this:
casale-monferrato/incomincia-oggi-roma-l-ultimo-atto-processo-eternit-davanti-corte-cassazione-74506.html

what I want to save the number at the end of the string, the one between "-" and ".html" (in this case 74506).
The parsing must be with the only condition that is considered the last number ONLY NO other number should be considered.
How can I do this in java ?
What is the correctly regexp that I must use ?

A: Use the below regex to match only the last number.
"(?<!\\d)\\d+(?=\\D*$)"

DEMO
String s = "casale-monferrato/incomincia-oggi-roma-l-ultimo-atto-processo-eternit-davanti-corte-cassazione-74506.html";
Pattern regex = Pattern.compile("(?<!\\d)\\d+(?=\\D*$)");
Matcher matcher = regex.matcher(s);
while(matcher.find()){
        System.out.println(matcher.group(0));
 }

Output:
74506

Regular Expression:
(?<!                     look behind to see if there is not:
  \d                       digits (0-9)
)                        end of look-behind
\d+                      digits (0-9) (1 or more times)
(?=                      look ahead to see if there is:
  \D*                      non-digits (all but 0-9) (0 or more
                           times)
  $                        before an optional \n, and the end of
                           the string
)                        end of look-ahead

A: You can use this simple regex to match:
\b\d+(?=\D*$)

RegEx Demo
(?=\D*$) will make sure there is no number after matched number hence matching the very last number.

A: There is no need for regexp. Try this instead:
public static void main(final String[] args) {
    final String url =
            "casale-monferrato/incomincia-oggi-roma-l-ultimo-"
                    + "atto-processo-eternit-davanti-corte-cassazione-74506.html";
    final String n = url.substring(url.lastIndexOf('-') + 1, url.lastIndexOf('.'));
    System.out.println(n);
}


text:
Q: Не срабатывает нажатие радио кнопок Не срабатывает скрыть / показать текст при выборе кнопок

jQuery('form.checkout').on('change', 'input[name^='shipping_method']', function() {
  var val = jQuery(this).val();
  if (val.match('^local_pickup')) {
    [
      jQuery('.address-field').fadeOut();
    } else {
      jQuery('.address-field').fadeIn();
    }
));

A: *

*Кавычки внутри кавычек.

*Со скобками полный бардак.

jQuery('form.checkout').on('change', 'input[name^=\'shipping_method\']', function() {
  var val = jQuery(this).val();
  if (val.match('^local_pickup')) {
    jQuery('.address-field').fadeOut();
  } else {
    jQuery('.address-field').fadeIn();
  }
});

<form class="checkout">
  <input type="radio" name="shipping_method" value="local_pickup:6"/>
  <input type="radio" name="shipping_method" value="free_shipping:6"/>

Address Field

</form>


text:
Q: Download manager in android? Hi have simple app in which data has been uploaded from the web server I am using .net web services. I need to replace the document on same location, so that duplicate document not place on same folder.
I am using:
request.setDestinationInExternalPublicDir(
                                  Environment.DIRECTORY_DOWNLOADS + "/Downloads",
                                  name );

is it right approach? can I delete document from physical place and then replace it with new one. if yes How this thing is possible.
this is my download manager and I am trying to delete name document and then trying to replace with new one. Please suggest. thanks
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setTitle(name);
// in order for this if to run, you must use the android 3.2 to compile your app
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
{
    request.allowScanningByMediaScanner();
    request.setNotificationVisibility(
                     DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
request.setDestinationInExternalPublicDir(
               Environment.DIRECTORY_DOWNLOADS + "/Downloads", name);
DownloadManager manager = (DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);


text:
Q: bar button in Xcode always goes to bottom Xcode 6.3 beta
when i drag the bar button item onto the view controller they will not stay at the top of the view they will automatically go to the bottom under the table view. Does anyone know what is wrong?

A: You can fix this by moving the bar button item under the navigation item, inside document outline windows.
Before

After

That should fix the issue. I verified the issue in Xcode 6.3.2

A: If you navigated to this view-controller via a push segue, it does not have an instance of the navigation bar in storyboard.
You need to drag in a "Navigation Item" object, and then you can add your Bar Button Item on to this.

A: indy and timbrah's fixes didn't work for me... but the below did.
To fix this, select Navigation Item in the Object Library and drag it onto the Root View. Note, it replaces the current one. Then you can drag a Bar Button Item onto as you like.  Hope this helps.

A: Actually, it seems as if the top bar isn't clearly designated as a navigation bar anymore. I had to select Root View Controller (first icon at the very top left of the screen) then chose the Show Attributes Inspector and at the Top Bar line item under Simulated Metrics chose Translucent Navigation Bar. That enabled it as a navigation bar and I was abled to drag a bar button item there. Weird!

A: I had same issue today with XCode 7. I have next stack: NC-(root)->VC1-(Show (e.g. Push))->VC2. After I've created VC2 there was no Navigation Item at all. To make it appear I changed segue type from Show (e.g. Push) to Deprecated Push and brought it back to Show (e.g. Push) and now I can use it correctly

A: You have to drag the Bar Button Item to one of the sides of the navigation controller's navigation bar. So, in your screenshot it would be all the way to the right or left of that bar that has "Root View Controller" in it.

A: From what I can tell this bug is still around in the 6.3 release. The only way I've been able to add items when this happens is to drag them under the navigation item in the left hand sidebar.

A: In my situation needed to select ViewControllerScene inside the document outline then forward attributes inspector then change Top Bar to Translucent Navigation Bar


text:
Q: Mismatch between reputation count at "/reputation" path and main site
Possible Duplicate:
Reputation report total slightly off from SO rep I see?

Sorry to add to all of the posts on rep cap, but I noticed a slight mismatch (1 point) between my calculated reputation at www.stackoverflow.com/reputation, and the reputation that shows up on the main site. Specifically, at the "/reputation", I get
** total rep 2044 :)

while the main site shows 2043. Is this a known issue? I'll admit that I haven't gone through every entry in the "/reputation" table, and summed them all up, but I assume that value is correct (if only because it's the higher one!).

A: The displayed reputation is usually slightly off if compared to the "real" reputation shown in the "reputation audit".
Votes on deleted questions/answers don't count to the "real" reputation, but the displayed reputation is not updated when a post is deleted.
In your case you probably downvoted a post (costing you one point) and that post later got deleted. In the "audit" report you got that point for the downvote back, but the displayed reputation was not updated.


text:
Q: Understanding Spark monitoring UI For a running Spark job here is part of the UI details for URL :  http://localhost:4040/stages/stage/?id=1&attempt=0

The doc at http://spark.apache.org/docs/1.2.0/monitoring.html does not detail each of these parameters. What do the columns "Input"  , "Write Time" & "Shuffle Write" indicate ?
As can see from this screenshot these 4 tasks have been running for 1.3 mins and I'm attempting to discover if there is a bottleneck then where it is occurring.
Spark is configured to use 4 cores, I think this is why there are 4 tasks displayed in UI, each task is running on a single core ?
What is determining the "Shuffle Write" sizes ?
On my console output there many log messages :
15/02/11 20:55:33 INFO rdd.HadoopRDD: Input split: file:/c:/data/example.txt:103306+103306
15/02/11 20:55:33 INFO rdd.HadoopRDD: Input split: file:/c:/data/example.txt:0+103306
15/02/11 20:55:33 INFO rdd.HadoopRDD: Input split: file:/c:/data/example.txt:0+103306
15/02/11 20:55:33 INFO rdd.HadoopRDD: Input split: file:/c:/data/example.txt:103306+103306
15/02/11 20:55:33 INFO rdd.HadoopRDD: Input split: file:/c:/data/example.txt:103306+103306
15/02/11 20:55:33 INFO rdd.HadoopRDD: Input split: file:/c:/data/example.txt:0+103306
15/02/11 20:55:33 INFO rdd.HadoopRDD: Input split: file:/c:/data/example.txt:0+103306
15/02/11 20:55:34 INFO rdd.HadoopRDD: Input split: file:/c:/data/example.txt:103306+103306
15/02/11 20:55:34 INFO rdd.HadoopRDD: Input split: file:/c:/data/example.txt:103306+103306
.....................
Are these the result of the files being split into multiple smaller sizes and each "Input" of size 100.9KB (specified in Spark UI screenshot) is mapping to one of these snippets ?

A: Input is the size of data that your spark job is ingesting. For example, it can be data that each map task you may defined is using.
Shuffle write is defined as bytes written to disk in order for future tasks. So it is the data that spark writes to disk to enable the transmission of your map output. For example, if you are trying a join and data need to be shuffled to other nodes, then this is the data which will be transferred to other nodes.
Task don't run on cores, tasks run on executors. This executor in turn use the cores.
Please also go through link for better understanding about the same.

A: Not everything is being printed in the logs, especially not any custom code (unless you print it yourself). When something is running for too long, you may want to do a thread dump on one of the executors and look at the stacks to see the progress in  your computation.


text:
Q: ASP:DropDownList vertical text alignment in Mozilla I have a selection of textboxes and dropdown lists on an ASP.net page, using the ASP:DropDownList control.
They all display fine in chrome, IE, opera, safari, but in FF I get:

Note "Please Select" is aligned Top in the dropdownlist.
code:
<asp:DropDownList runat="server" onclick="changeBorderColor(this.id)" forecolor="White"  style="border:none; Width:352px; font-size:15px; font-family:Arial, helvetica, Verdana; height:35px; color: rgb(0, 0, 0); border: 1px solid rgb(124, 201, 25); border-radius:4px 4px 4px 4px; box-shadow:0px 0px 9px rgb(191, 191, 191) inset; padding-left:10px; " ID="Country" Width="282px" >

I have tried assing some "padding-top:" but it causes other issues.
How can i get the text to display in the vertical center of the control?

A: instead of vertical-align use line-height 30 or something. try something between 20 and 30

A: The best solution i ever came with is to give padding-top and padding-bottom. Let's say now you have font-size: 15px; and height: 35px;, so this means 20px spare, so add padding-top: 10px and padding-bottom: 10px and text should be centered vertically in the middle of your input.


text:
Q: Error : sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: Base.html

<!DOCTYPE html>

 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>Todo App</title>

 <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.css">

To Do App

     <form class="ui form" action="/add" method="post">

             Todo Title
             <input type="text" name="title" placeholder="Enter Todo...">

         <button class="ui blue button" type="submit">Add</button>
     </form>

     {% for todo in todo_list %}

{{todo.id }} | {{ todo.title }}

         {% if todo.complete == False %}
         Not Complete
         {% else %}
         Completed
         {% endif %}

         Update
         Delete

     {% endfor %}

app.py

from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy

app = Flask(__name__)

# /// = relative path, //// = absolute path
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app)

class Todo(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    title = db.Column(db.String(100))
    complete = db.Column(db.Boolean)

@app.route("/")
def home():
    todo_list = Todo.query.all()
    return render_template("base.html", todo_list=todo_list)

@app.route("/add", methods=["POST"])
def add():
    title = request.form.get("title")
    new_todo = Todo(title=title, complete=False)
    db.session.add(new_todo)
    db.session.commit()
    return redirect(url_for("home"))

@app.route("/update/<int:todo_id>")
def update(todo_id):
    todo = Todo.query.filter_by(id=todo_id).first()
    todo.complete = not todo.complete
    db.session.commit()
    return redirect(url_for("home"))

@app.route("/delete/<int:todo_id>")
def delete(todo_id):
    todo = Todo.query.filter_by(id=todo_id).first()
    db.session.delete(todo)
    db.session.commit()
    return redirect(url_for("home"))

    @app.before_first_request
    def create_tables():
        db.create_all()

#if __name__ == "__main__":
    #db.create_all()
   # app.run(debug=True)

Steps followed:
$ mkdir myproject
$ cd myproject
$ python3 -m venv venv

Activate it
$ . venv/bin/activate

or on Windows
venv\Scripts\activate

Install Flask
$ pip install Flask
$ pip install Flask-SQLAlchemy

Set environment variables in terminal
$ export FLASK_APP=app.py
$ export FLASK_ENV=development

or on Windows
$ set FLASK_APP=app.py
$ set FLASK_ENV=development

Run the app
$ flask run

Error message:
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: todo [SQL: SELECT todo.id AS todo_id, todo.title AS todo_title, todo.complete AS todo_complete  FROM todo] (Background on this error at: https://sqlalche.me/e/14/e3q8)
The debugger caught an exception in your WSGI application. You can now look at the traceback which led to the error.

A: As mentioned in the docs, OperationalError occurs when the api is unable to resolve a driver. From your code, one possible troubleshoot might be to rename this line in app.py:
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite' # <--- remove this
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///db.sqlite3'# <--- add this
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

The reason:
The connection might not be well established and must have failed to create the required db. The above suggested edits might resolve this issue
EDIT: If the above answer doesn't work for you, checkout this answer.

A: It's possible, if this is the first time you are building this application, that you haven't ever created the databases in the first place.
I was following the Flask Mega Tutorial and got a similar error to what you have:
qlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: todo

In this tutorial there is a section about creation migration scripts that I could not get to work so I skipped that.  Apparently this creates the databases.  So the solution for me was from the Python Console I ran the following codes:
from app import db
from app.models import User, Posts
db.create_all()
u = User(username='admin', email='admin@email.com')
db.session.add(u)
db.session.commit()


text:
Q: java add text inside circle image I have that image:

And I need to add text to image, so I want to write method that recieved 2 strings and add them to image, for example:
addText(String str, String str2){...};

first string always be 3 chars lenth
second string can be from 1 to 20 chars length
addText("str", "secondstr");
And as result I want to recieve base64 png image string looking like that:

The main problem is how to write text in a 'circle format'? I need to change Y coordinate of each char what I write?
UPDATE1:
Explored link http://www.java2s.com/Code/Java/2D-Graphics-GUI/Drawtextalongacurve.htm, but text always draws from left side, how I can move them to center of my circle?

A: The important part is this one:
for (int i = 0; i < length; i++) {
      Point2D p = gv.getGlyphPosition(i);
      double theta = (double) i / (double) (length - 1) * Math.PI / 4;
      AffineTransform at = AffineTransform.getTranslateInstance(p.getX(),
          p.getY());
      at.rotate(theta);

here it defines an angle theta and makes it loop from 0 to length/length*Math.PI/4, so it's a rotation from 0° to 45°. What you need to do is to play with the value theta (using also negative numbers) to make it start and finish where you want.
From the image you posted, it seems that the first string has to go from -20° to 20° (or from 340° to 20°), and the second from 225° to 135°. Note that these degrees have to be transformed in radians to make it work.

A: Please find example how to write text along some curve here:
draw text along curve

A: The following sample program will print the string in a circular way. The degIncrement variable is the distance between characters in degrees.
import java.awt.*;
import java.awt.font.*;
import java.awt.geom.AffineTransform;
import javax.swing.*;

public class RoundTextSample extends JFrame{
    public RoundTextSample() {
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-400)/2, (screenSize.height-300)/2, 400, 300);

        add(new SamplePanel());
    }

    class SamplePanel extends JPanel{
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D) g;
            g2.setRenderingHint(
                    RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);

            addText(g2, "str", "secondstr");
        }
    }

    public void addText(Graphics2D g2, String string1, String string2) {
        int radius = 40;
        Point center = new Point(120, 120);

        double startDegAngle = 0, offsetAngle;
        double degIncrement = 15, strImageWidth, charWidth;
        boolean isInverted;

        Font font = new Font("Serif", Font.PLAIN, 18);
        FontRenderContext frc = g2.getFontRenderContext();

        charWidth = font.createGlyphVector(frc, "A").getGlyphOutline(0).getBounds2D().getWidth();

        // compute start deg for string1
        offsetAngle =  ((string1.length() * degIncrement) - (degIncrement)) / 2.0;
        startDegAngle = 0 - offsetAngle;

        isInverted = false; // for top text
        addText(g2, string1, font, radius, center, isInverted, startDegAngle, degIncrement);

        // compute start deg for string2
        offsetAngle =  ((string2.length() * degIncrement) - degIncrement) / 2.0;
        startDegAngle = 180 + offsetAngle;
        isInverted = true; // for bottom text
        addText(g2, string2, font, radius, center, isInverted, startDegAngle, degIncrement);

    }

    public void addText(Graphics2D g2, String text, Font font, int radius, Point center, boolean isInverted, double startDeg, double degIncrement) {
        AffineTransform at;
        double deg;

        deg = startDeg;

        FontRenderContext frc = g2.getFontRenderContext();
        if (!isInverted) {
            radius -= font.createGlyphVector(frc, "A").getGlyphOutline(0).getBounds2D().getHeight();
        } else {
            degIncrement = 0 - degIncrement;
        }

        for (int i=0; i<text.length(); i++) {
            String s = ""+text.charAt(i);
            GlyphVector gv = font.createGlyphVector(frc, s);
            Shape glyph = gv.getGlyphOutline(0);
            double charImageCenterX = glyph.getBounds2D().getCenterX();

            double theta = Math.toRadians(deg);

            int xp = (int)Math.round(Math.sin(theta) * radius);
            int yp = (int)Math.round(Math.cos(theta) * radius);
            yp = 0 - yp;

            if (isInverted)
                at = new AffineTransform( -1.0, 0.0, 0.0, -1.0, center.x + xp, center.y + yp );
            else
                at = new AffineTransform( 1.0, 0.0, 0.0, 1.0, center.x + xp, center.x + yp );

            at.rotate(theta);
            at.translate(0-charImageCenterX, 0);

            Shape transformedGlyph = at.createTransformedShape(glyph);
            g2.fill(transformedGlyph);

            deg += degIncrement;
        }
    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new RoundTextSample().setVisible(true);
            }
        });
    }

}

Sample output:

Output Notes:


text:
Q: Modern Opengl Line Stipple Issue I am trying to implement the Line Stipple in OpenGL because the Line stipple API is deprecated. It is working fine for lines and Polygons but It is not working for Circle. is there any problem with the below shaders? I see the pattern coming up fine for lines and polygons. But not working for circles. But when I zoom in case of circle I see the pattern. Don't know what is the issue. Please let me know .
Thanks in advance.
Below is my code for vertex and fragment shader.
Vertex Shader:
#version 420 core
layout (location = 0)in vec4 aPos;
flat out vec3 startPos;
out vec3 vertPos;
uniform mat4 mvp;
void main()
{
  vec4 pos  = mvp * vec4(aPos.x, aPos.y, 0.0, 1.0)
  gl_Position = pos;
  vertPos = pos.xyz/pos.w;
  startPos = vertPos;
}

Fragment Shader:
#version 420 core
flat in vec3 startPos;
in vec3 vertPos;
uniform vec4 my_color;
uniform vec2 u_resolution;
uniform uint u_pattern;
uniform float u_factor;
uniform int stipple;
out vec4 color;
void main()
{
  if (stipple == 1)
  {
  vec2 dir = (vertPos.xy-startPos.xy) * u_resolution/2.0;
  float dist = length(dir);
  uint bit = uint(round(dist/u_factor)) & 15U;
  if((u_pattern & (1U<<bit)) == 0U)
    discard;
  }
  color = my_color;
}

Below is the code where I am setting the uniform values.
if (vModel->getLineStipple() > 1 )
{
  glUniform1i(stip, 1);

  GLint loc_res = glGetUniformLocation(shaderProgram, "u_resolution");
  GLint loc_pattern = glGetUniformLocation(shaderProgram, "u_pattern");
  GLint loc_factor = glGetUniformLocation(shaderProgram, "u_factor");

  GLushort pattern = vModel->getLineStipple();
  GLfloat factor = vModel->getStippleFactor();

  glUniform1ui(loc_pattern, pattern);
  glUniform1f(loc_factor, factor);
  glUniform2f(loc_res, _scrWidth, _scrHeight);
}
...

then draw function
...
switch (vModel->getDrawMode())
{
case 0: //GL_POINTS
    //glPointSize(6.0);
  glDrawArrays(GL_POINTS, 0, vModel->getVertices().size());
  break;

case 1: //GL_LINES
    //glEnable(GL_LINE_SMOOTH);
    //GLint range[2];
    //glGetIntegerv(GL_ALIASED_LINE_WIDTH_RANGE,range);
  glDrawArrays(GL_LINES, 0, vModel->getVertices().size());
  break;

case 2: //GL_LINE_LOOP
  glDrawArrays(GL_LINE_LOOP, 0, vModel->getVertices().size());
  break;

case 3: //GL_LINE_STRIP
  glDrawArrays(GL_LINE_STRIP, 0, vModel->getVertices().size());
  break;
}


text:
Q: Reading data from Csv File How to find sequence of missing number from a CSV file using java Program?
I was using Arraylist taking some numbers into consideration.
I want to read entire CSV file Data And find the missing sequences on numbers.I have near about 1,00,000 records in the file.
Program:-
public class MissingNumber {

    public static long count = 0;
    public static int position = 0;
    public static boolean flag = false;

    public static void main(String[] args) {

        long a[] = {1054023,1054024,1054025,1054026,1054027,1054028,1054029,1054030,1054031,1054032,1054748,1054749,1054750,1054751,
            1054752,1054753,1054754,1054755,1054756,1054757,1054758,1055297,1055298,1055299,1055300,1055301,1055302,1055303,1055304,
            1055305,1055306,1055307,1055308,1055309,1056868,1057170,1057461,1057563,1057627,1057628,1057629,1057630,1057631,1057632,
            1057633,1057634,1057635,1057636,1057637,1057652,1057653,1057654,1057656,1057657,1057661,1057662,1057663,1057664,1057665,
            1057672,1057673,1057674,1057675,1057678,1057682,1057683,1057685,1057686,1057687,1057690,1057691,1057692,1057695,1057696,
            1057697,1057698,1057699,1057701,1057702,1057705,1057706,1057707,1057708,1057710,1057712,1057718,1057722,1057729,1057730,
            1057731,1057732,1057733,1057734,1057735,1057736,1057738,1057739,1057740,1057741,1057742,1057743,1057744,1057745,1057746,
            1057747,1057748,1057749,1057750,1057751,1057752,1057753,1057754,1057755,1057756,1057757,1057758,1057759,1057762,1057763,
            1057764,1057765,1057766,1057767,1057768,1057769,1057773,1057774,1057778,1057779,1057780,1057781,1057782,1057783,1057784,
            1057785,1057786,1057787,1057788,1057789,1057790,1057791,1057792,1057793,1057794,1057795,1057796,1057797,1057798,1057799,
            1057800,1057801,1057802,1057803,1057804,1057805,1057806,1057807,1057808,1057809,1057810,1057811,1057825,1057826,1057827,
            1057829,1057838,1057843,1057857,1057858,1057859,1057860,1057861,1057862,1057863,1057864,1057865,1057866,1057867,1057868,
            1057869,1057870,1057871,1057872,1057873,1057874,1057875,1057876,1057884,1057885,1057886,1057887,1057888,1057889,1057890,
            1057891,1057892,1057893,1057894,1057895,1057896,1057897,1057898,1057899,1057900,1057901,1057902,1057903,1057905,1057906,
            1057907,1057908,1057909,1057910,1057911,1057912,1057913,1057914,1057915,1057916,1057917,1057918,1057919,1057920,1057921};

        findMissingNumbers(a, position);

    }

    private static void findMissingNumbers(long a[], int position) {

        if (position == a.length - 1)
            return;

        for (; position < a[a.length - 1]; position++) {

            if ((a[position] - count) != position)
            {
                System.out.println("position"+position);
                System.out.println("Missing Number: " + (position + count));
                flag = true;
                count++;
                break;
            }
        }

        if (flag) {
            flag = false;
            findMissingNumbers(a, position);
        }
    }

}

A: I assume your array is already sorted. If so itreate through and find the missing nrs like you were doing it manually; compare two neighbors and if the difference is more than one print the numbers missing. something like this:
public class MissingNumber {

    public static void main(String[] args) {
       long a[] = {1,2,3,5,9,11,23,24,25,26,27,28,39}; //try first on small arrays
       findMissingNumbers(a);

    }

    private static void findMissingNumbers(long a[]) {
        for(int i = 0; i<a.length-1; i++){
           if(a[i+1]- a[i] > 1){
               System.out.println("missing nr at index: " + (i+1));
               System.out.println("missing nrs");
               for (int j = 1;j<a[i+1]-a[i];j++){ // for ex. if a[i] = 13 and a[i+1]= 17 difference is 4 and there are 3 missing nrs.
                  System.out.println(a[i]+j);
               }
            }
        }
    }
}

And to easily read from csv file i recomend opencsv


text:
Q: str_replace with a bunch of code php I have some content coming from database. And I want to replace the specific word of the content with a bunch of code.
Content coming from database is for example:

Thank you for interest on our web site.
  {FORMINSERT}
  You can
  also contact us by calling us to 1234567890

I want to replace the string {FORMINSERT} with a bunch of PHP code. If it is a normal text string I can simply replace it by using str_replace.
But the replacing content is not simple text it is form code.
want to replace this {FORMINSERT}
with example:
<form method="post" id="form1" action="<?php echo KT_escapeAttribute(KT_getFullUri()); ?>">

Contact Us

            Name:

                <input type="text" name="fullname" id="fullname" value="<?php echo KT_escapeAttribute($row_rsscotts_contact['fullname']); ?>" size="47" />
                <?php echo $tNGs->displayFieldHint("fullname");?> <?php echo $tNGs->displayFieldError("scotts_contact", "fullname"); ?>

            Phone:

                <input type="text" name="phone" id="phone" value="<?php echo KT_escapeAttribute($row_rsscotts_contact['phone']); ?>" size="47" />
                <?php echo $tNGs->displayFieldHint("phone");?> <?php echo $tNGs->displayFieldError("scotts_contact", "phone"); ?>

            Email:

                <input type="text" name="email" id="email" value="<?php echo KT_escapeAttribute($row_rsscotts_contact['email']); ?>" size="47" />
                <?php //echo $tNGs->displayFieldHint("email");?> <?php echo $tNGs->displayFieldError("scotts_contact", "email"); ?>

            Looking for:

                <textarea name="tellus" id="tellus" cols="37" rows="5"><?php echo KT_escapeAttribute($row_rsscotts_contact['tellus']); ?></textarea>
                <?php echo $tNGs->displayFieldHint("tellus");?> <?php echo $tNGs->displayFieldError("scotts_contact", "tellus"); ?>

                <input type="submit" name="KT_Insert1" id="KT_Insert1" value="Submit" class="button-blue" />
                <input name="Reset" type="reset" value="Reset" class="button-grey" />

</form>

A: You can use ob_start() if you want to have HTML and PHP code combined and save the output inside one variable:
ob_start();
?>
    <form action="contact.php" method="post">
    Few fields here
    and submit button
    </form>
<?php

$forminsert = ob_get_clean();

Then you can do your str_replace() as per normal.
However, if the {FORMINSERT} may or may not appear, you could use preg_replace_callback() to reduce the cost of generating the form data in the case there's no need for it:
$content = preg_replace_callback('/{(.*?)}/', function($match) {
    if ($match[1] == 'FORMINSERT') {
        // code to generate $forminsert
        return $forminsert;
    }
    return $match[0];
}, $content_from_db);

Btw, this function can also be used more generically to replace anything between curly braces.

A: test1.php:
$database_content = 'Thank you for interest on our web site.
{FORMINSERT}
You can also contact us by calling us to 1234567890';

if(stripos($database_content, '{FORMINSERT}') !== FALSE){
    ob_start();
    include 'test2.php';
    $result = ob_get_clean();
}

$database_content = str_replace("{FORMINSERT}", $result, $database_content);

echo $database_content;

test2.php (the code you're trying to insert in):
echo 'hello world';

The result:

Thank you for interest on our web site. hello world You can also
  contact us by calling us to 1234567890

So it is as if the code "echo 'hello world';" was sitting right where {FORMINSERT} was.  You can just create a bunch of PHP files to include like that, and make some if statements to handle the replacements.

A: Lets assume the content comining from database you have is stored in variable $db_content & php code that you need to replace is in custom_code.phpso
if(strpos($db_content, "{FORMINSERT}") === true){
    //remove the tag
    str_replace("{FORMINSERT}", '',$db_content)
    //load the php code
   require_once("custom_code.php")
}
//if need, you can add more conditions using else-if & replace more tags.

But its better to move towards MVC pattern where you can do such work easily via templates. Here is an example I use for simple scripts

A: just do this and your work is solved
       $forminser= " welcome to our website {FORMINSERT}";
       $form= "<form action='contact.php' method='post'>
                 Few fields here
                and submit button
              </form>" ;
       echo str_replace("{FORMINSERT}",$form,$forminser);

EDIT>
if you want the php code inside your form then here an exemple
     $var = "Few words here" ;
     $forminser= " welcome to our website {FORMINSERT}";
     $form= "<form action='contact.php' method='post'>";
     $form .= $var ;  // this php code here
     $form .= "  and submit button</form>" ;
         echo str_replace("{FORMINSERT}",$form,$forminser);

edit2
here comes the whole code zou can make it.
    <?php

 $forminser= " welcome to our website {FORMINSERT}";
 $form = "<form method='post' id='form1' action=' " ;
 $form .=  KT_escapeAttribute(KT_getFullUri());
 $form .= " '>

Contact Us

          Name:
          <input type='text' name='fullname' id='fullname' value=' " ;

$form .= KT_escapeAttribute($row_rsscotts_contact['fullname']);
$form .= " ' size='47' /> ";
$form .= $tNGs->displayFieldHint("fullname");
$form .= $tNGs->displayFieldError("scotts_contact", "fullname");
$form .= "

         Phone:
         <input type='text' name='phone' id='phone' value= ' " ;
$form .= KT_escapeAttribute($row_rsscotts_contact['phone']);
$form .= " ' size='47' /> ";
$form .= $tNGs->displayFieldHint("phone");
$form .= $tNGs->displayFieldError("scotts_contact", "phone");
$form .= '

        Email:
        <input type="text" name="email" id="email" value=" ' ;
$form .= KT_escapeAttribute($row_rsscotts_contact['email']);
$form .= '" size="47" />';
$form .=  $tNGs->displayFieldError("scotts_contact", "email");
$form .= '

         Looking for:
          <textarea name="tellus" id="tellus" cols="37" rows="5"> ';
$form .=  KT_escapeAttribute($row_rsscotts_contact['tellus']);
$form .= '</textarea> ';
$form .= $tNGs->displayFieldHint("tellus");
$form .=  $tNGs->displayFieldError("scotts_contact", "tellus");
$form .= '

         <input type="submit" name="KT_Insert1" id="KT_Insert1" value="Submit"  class="button-blue" /> <input name="Reset" type="reset" value="Reset" class="button-grey" />

    </form>
     ';

   echo str_replace("{FORMINSERT}",$form,$forminser);
 ?>

A: Ok, how about this one. The code below allows you to define custom {words} inside your content and they'll be replace with other content upon parsing.
$contentFromDB = "Etiam porta sem malesuada magna mollis euismod. Donec ullamcorper nulla non metus auctor fringilla. {FORMINSERT}";

echo matchTags($contentFromDB);

function matchTags($content) {
   $pattern = '/{(\w+)}/i';
   $content = preg_replace_callback($pattern,"transformTags",$content);
   return $content;
}

function transformTags($word) {

    if ($word[1] == "FORMINSERT") {

        ob_start();
        ?>
        <form action="contact.php" method="post">
        Few fields here
            and submit button
        </form>
        <?php
        $content = ob_get_clean();
        return $content;
    }

    if ($word[1] == "somethingelse") {

    }

}


text:
Q: Critical points when gradient doesn't exist Find and classify the critical points of: $f(x,y)=3x+4y^2$
I started off by working out the partial derivatives for the gradient, which leaves me with
$\nabla f(x,y) = (3, 8y)$, and set equal to 0 so 3=0 which means the gradient for x doesn't exist, and 8y=0. This still means I have a critical point right? If I do, how do I classify it if I can't take a second derivative of it?

A: The gradient exists everywhere, it's just never equal to $(0, 0)$. That is, your $f$ has no critical points.


text:
Q: How can I use geoserver's user management for my application I'm developing a gis application with java. My layers are in geoserver. Layers have different permissions, some layers have public permissions and some of them have private permissions. for private layers, Users must log in to my application that my application's users and geoserver's users are one.
In the other words, I want to use geoserver's user management in my application to log in users like geoexplorer.
How do I implement this issue? How do users login to my application and can read geoserver's layers directly?

A: Geoserver has CAS plugin , you should enable CAS for geoserver and implement CAS client in your application for SSO, then each application can use current user for authorization purpose, geoserver automatically do that.
Useful links:
http://www.geo-solutions.it/blog/geoserver-and-cas/
http://docs.geoserver.org/latest/en/user/security/tutorials/cas/index.html


text:
Q: Активация радиокнопок при анимации слайдера Доброго времени суток. Имеется слайдер сделанный на CSS3, 3 изображения, использую анимацию 15 сек, infinite. Каждая картинка стоит 3 сек и затем за 2 сек. уходит в лево, за ней встает другая, и т.д. Хочу сделать в низу под слайдером три кружка и например когда в главном экране первый слайд то закрашивался первый круг, когда второй слайд то закрашивается второй круг и т.д. Можно ли это реализовать с помощью css3? Если да, то подскажите пожалуйста.

#container {
 margin: 0 auto;
 overflow: visible;
 width: 960px;
}

#content-slider {
 width:100%;
 height:360px;
 margin:10px auto 0;
}

#slider {
 background: #000;
 border: 5px solid #eaeaea;
 box-shadow: 1px 1px 5px rgba(0,0,0,0.7);
 height: 320px;
 width: 680px;
 margin: 40px auto 0;
 overflow: hidden;
 position: relative;
}

#mask {
 overflow: hidden;
 height: 320px;
}

/*Стили для #active*/
#active {
 width: 680px;
 margin: 20px auto;
 text-align: center;
 outline: 1px solid red;
}

#active label {
 border: 2px solid red;
 cursor: pointer;
 border-radius: 5px;
 background-color: #bbb;
 display: inline-block;
 width: 10px;
 height: 10px;
 margin-right: 5px;
}

#active label:hover {
 background-color: #fff;
 border: 2px solid red;
}

/*Конец стили для #active*/

#slider article{
 right: -680px;
 position: absolute;
}

#slider .firstanimation {
 animation: cycle 15s linear infinite;
}

#slider .secondanimation {
 animation: cycletwo 15s linear infinite;
}

#slider .thirdanimation  {
 animation: cyclethree 15s linear infinite;
}

@keyframes cycle {
 /*Стоит 3 секунды*/
 0%{left: 0}
 20%{left: 0; opacity: 1} /*3сек = 20%*/
 /*уход 2 секунды*/
 34%{left: -680px;opacity: 1} /*2 сек = 13%*/
 54%{left: -680px;opacity: 1}
 /*уход в право 2сек и стоит 3 сек*/
 67%{left: 680px;opacity: 0; z-index: -1}
 87%{left: 680px;opacity: 0; z-index: 0}
 100%{left: 0px;opacity: 1; z-index: 1}
}

@keyframes cycletwo {
 /*Стоит 3 секунды*/
 0%{left: 680px; opacity: 1; z-index: 1}
 20%{left: 680px; opacity: 1; z-index: 1} /*3сек = 20%*/
 34%{left: 0; opacity: 1} /*3сек = 20%*/
 54%{left: 0;opacity: 1}
 67.001%{left: -680px;opacity: 1}
 87.002%{left: -680px; opacity: 0}
 /*96%{left: 680px; opacity: 0}*/
 100%{left: 680px;opacity: 0;}
 /*уход 2 секунды*/

}

@keyframes cyclethree {
 /*Стоит 3 секунды*/
 34%{left: 680px; opacity: 1; z-index: -1}
 54%{left: 680px; opacity: 1;z-index: 0} /*3сек = 20%*/
 67%{left: 0px;opacity: 1;z-index: 0}
 87%{left: 0px;opacity: 1; z-index: 0}
 100%{left: -680px;opacity: 1}

}
<input type="radio" name="slider" id="slide1" checked="">
 <input type="radio" name="slider" id="slide2">
 <input type="radio" name="slider" id="slide3">

Cougar

lions

Snowalker

A: Все с помощью '~':
#slide1:checked~.container #first,
#slide2:checked~.container #second,
#slide3:checked~.container #third{
  ...
}

#container {
 margin: 0 auto;
 overflow: visible;
 width: 960px;
}

#content-slider {
 width:100%;
 height:360px;
 margin:10px auto 0;
}

#slider {
 background: #000;
 border: 5px solid #eaeaea;
 box-shadow: 1px 1px 5px rgba(0,0,0,0.7);
 height: 320px;
 width: 680px;
 margin: 40px auto 0;
 overflow: hidden;
 position: relative;
}

#mask {
 overflow: hidden;
 height: 320px;
}

/*Стили для #active*/
#active {
 width: 680px;
 margin: 20px auto;
 text-align: center;
 outline: 1px solid red;
}

#active label {
 border: 2px solid red;
 cursor: pointer;
 border-radius: 5px;
 background-color: #bbb;
 display: inline-block;
 width: 10px;
 height: 10px;
 margin-right: 5px;
}

#active label:hover {
 background-color: #fff;
 border: 2px solid red;
}

/*Конец стили для #active*/

#slider article{
 right: -680px;
 position: absolute;
}

#slider .firstanimation {
 animation: cycle 15s linear infinite;
}

#slider .secondanimation {
 animation: cycletwo 15s linear infinite;
}

#slider .thirdanimation  {
 animation: cyclethree 15s linear infinite;
}

@keyframes cycle {
 /*Стоит 3 секунды*/
 0%{left: 0}
 20%{left: 0; opacity: 1} /*3сек = 20%*/
 /*уход 2 секунды*/
 34%{left: -680px;opacity: 1} /*2 сек = 13%*/
 54%{left: -680px;opacity: 1}
 /*уход в право 2сек и стоит 3 сек*/
 67%{left: 680px;opacity: 0; z-index: -1}
 87%{left: 680px;opacity: 0; z-index: 0}
 100%{left: 0px;opacity: 1; z-index: 1}
}

@keyframes cycletwo {
 /*Стоит 3 секунды*/
 0%{left: 680px; opacity: 1; z-index: 1}
 20%{left: 680px; opacity: 1; z-index: 1} /*3сек = 20%*/
 34%{left: 0; opacity: 1} /*3сек = 20%*/
 54%{left: 0;opacity: 1}
 67.001%{left: -680px;opacity: 1}
 87.002%{left: -680px; opacity: 0}
 /*96%{left: 680px; opacity: 0}*/
 100%{left: 680px;opacity: 0;}
 /*уход 2 секунды*/

}

@keyframes cyclethree {
 /*Стоит 3 секунды*/
 34%{left: 680px; opacity: 1; z-index: -1}
 54%{left: 680px; opacity: 1;z-index: 0} /*3сек = 20%*/
 67%{left: 0px;opacity: 1;z-index: 0}
 87%{left: 0px;opacity: 1; z-index: 0}
 100%{left: -680px;opacity: 1}
}

input[type="radio"]{
  display: none;
}

#slide1:checked~#active .radioFirst,
#slide2:checked~#active .radioSec,
#slide3:checked~#active .radioThree {
  background: #000;
}

/* Управление слайдами */
#slide1:checked~.container #first,
#slide2:checked~.container #second,
#slide3:checked~.container #third{
  animation: none;
  left: 0;
}
    <input type="radio" name="slider" id="slide1" checked="">
 <input type="radio" name="slider" id="slide2">
 <input type="radio" name="slider" id="slide3">

Cougar

lions

Snowalker


text:
Q: Function has unexpected behaviour (mutate function in dplyr) I expected cumulative sum in "n_rest"-column. But I get only the copy of "n_i"-column. My problem can be solved inserting "# as.data.frame() %>%" but I don't like this solution and I would like to understand the explanation of my mistake.
Thanks in advance!
library(dplyr)

t      <- c(42,57,63,98,104,105,132,132,132,133,133,133,139,140,161,180,180,195,195,233)
status <- c(1 ,1 ,1 ,1 ,0  ,1  ,1  ,1  ,1  ,1  ,1  ,1  ,1  ,1  ,1  ,1  ,1  ,1  ,1  ,  0)

KMP <- function(time,status){

  n_ges = length(t)

  df <- data.frame(t = t, status = status, n = 1)
  df <- df %>%  group_by(t,status) %>%
                summarise(n_i = sum(n)) %>%
                # as.data.frame() %>%
                mutate(n_rest = rev(cumsum(n_i)))

  df

}

A: The mutate is still working on the groups.
By passing into as.data.frame you are dropping the grouping. Alternatively reset the grouping by putting an empty group_by in the pipe:
> df %>% group_by(t,status) %>% summarise(n_i=sum(n)) %>% group_by() %>% mutate(n_rest=cumsum(n_i))
# A tibble: 14 x 4
       t status   n_i n_rest
   <dbl>  <dbl> <dbl>  <dbl>
 1    42      1     1      1
 2    57      1     1      2
 3    63      1     1      3
 4    98      1     1      4
 5   104      0     1      5
 6   105      1     1      6
 7   132      1     3      9
 8   133      1     3     12
 9   139      1     1     13
10   140      1     1     14
11   161      1     1     15
12   180      1     2     17
13   195      1     2     19
14   233      0     1     20

A: That is because your dataframe is still grouped by t. If you check output of
library(dplyr)
df %>%   group_by(t,status) %>%  summarise(n_i = sum(n))

# A tibble: 14 x 3
# Groups:   t [14]
#       t status   n_i
#   <dbl>  <dbl> <dbl>
# 1    42      1     1
# 2    57      1     1
# 3    63      1     1
# 4    98      1     1
# 5   104      0     1
# 6   105      1     1
# 7   132      1     3
# 8   133      1     3
# 9   139      1     1
#10   140      1     1
#11   161      1     1
#12   180      1     2
#13   195      1     2
#14   233      0     1

From ?summarise

An object of the same class as .data. One grouping level will be dropped.

As you are grouping for t and status, grouping of status is dropped keeping group_by t as it is, hence your cumsum result is grouped by t.
You can remove the effect of grouping by using ungroup after summarise
df %>%
  group_by(t,status) %>%
  summarise(n_i = sum(n)) %>%
  ungroup() %>%
  mutate(n_rest = rev(cumsum(n_i)))

The same effect was achieved using as.data.frame() in OP's code.


text:
Q: Why is the $\mathbb{Z}_p$-corank of $\operatorname{Sel}_{p^\infty}(E/\mathbb{Q})$ finite? I'm interested on the Mordell-Weil rank of an elliptic curve over $\mathbb{Q}$. I read that the $\mathbb{Z}_p$-corank of the $p^\infty$-Selmer group $\operatorname{Sel}_{p^\infty}(E)\doteq\displaystyle\varinjlim_{e\in\mathbb{N}}\operatorname{Sel}_{p^e}(E)$ is expected to be the Mordell-Weil rank of $E$. But I don't understand much about the structure of this group, other than that the sequence $$0\to E(\mathbb{Q})\otimes(\mathbb{Q}_p/\mathbb{Z}_p)\to\operatorname{Sel}_{p^\infty}(E)\to {\large Ш}(E)[p^\infty]\to 0$$splits, let alone about the finiteness of the $\mathbb{Z}_p$-corank. Can someone explain to me or give a reference for why this is true, please? If possible, I would like also some light on the torsion part of $\operatorname{Sel}_{p^\infty}(E)$, so I can understand better its structure as a whole. (I'm sorry if those are trivial questions, perhaps I'm missing something).
Thanks in advance.


text:
Q: Connection from many port(in different agents) to one export (in scoreboard) I have a many(port) to one(export) situation with my agents and the scoreboard. My doubt is how will I make sure that only one out of the many ports can write into the export at an instant of time so that I don't get any complications or lost transactions. any help/advice is appreciated. Thank you

A: As you mentioned, the ports are called 'serially' so you shouldn't have any lost transactions. Whenever the monitor in the agent is ready to broadcast, it'll call the port write function to which the scoreboard is a subscriber.
However, I don't think there's any guarantee in which order the port write functions are called, so you may still have complications depending on what you're trying to achieve.


text:
Q: Convert a String or a InputStreamReader into InputSource I just read some tutorials in order to parse a xml feed from the web and turn them into a Listview:
URL file = new URL("http://..../file.xml");
SAXParserFactory fabrique = SAXParserFactory.newInstance();
SAXParser parseur = fabrique.newSAXParser();
XMLReader xr = parseur.getXMLReader();
ReglageParseur gestionnaire = new ReglageParseur();
xr.setContentHandler(gestionnaire);
xr.parse(new InputSource(file.openStream()));

Everything is fine and I am able to parse xml.
My second step is to store the xml file from web into a xml file on the phone and only update it when user ask it. ( In fact, this xml file should not change or maybe once every 6 month, so I don't want to download it each time.)
So, what I did is to store the file on the phone and update it on user demand.
And I can read it by doing:
fIn = openFileInput("fichier.xml");
InputStreamReader isr = new InputStreamReader(fIn);
char[] inputBuffer = new char[255];
isr.read(inputBuffer);
String readString = new String(inputBuffer);

So, for now, everything seem fine and I am nearly happy.
The problem is now when I want to parse the new file on the phone:
xr.parse(InputSource);

I need an InputSource as parameter.
So my question is:
How can I turn my file in the phone into a InputSource?
I succeed to have a InputStreamReader or a String but would like to convert that into InputSource.
Thank a lot for any precious help

A: Well, I don't know what constructors are available on the Android version, but the J2SE InputSource class has a constructor with a Reader parameter. Have you tried that?
Alternatively, why not just construct an InputSource directly from the InputStream? I assume fIn is a FileInputStream? Why not just call:
InputSource input = new InputSource(fIn);

?

A: the best suitable line for me to convert string to InputSource is :
String myStringObject = "Hello this is string object to convert in InputSource";
InputSource inSource =  new InputSource(new StringReader(myStringObject));