text:
Q: Error when calling camera.setMode(DJICameraMode.shootPhoto) The following situation occurs indeterminately, using Mobile SDK version 4.4 for iOS with a Phantom 4 Pro.  Most often the call to setMode() is successful.  Sometimes however it fails with the following error:
Setting parameters operation failed.(code:-1007)

There is no difference in the camera state between successful and failed requests.  The request is always made after the same event, which is after a DJIMediaFile download has completed (i.e. DJIMediaFile has called the update block from fetchDat() with isComplete = true.)
What does code -1007 mean and how does one avoid it?  Thanks!

A: Please update your iOS SDK to 4.6 and see if you continue to get the error


text:
Q: Control parquet filenames in spark output I am writing spark output to an external system that does not like file extensions (I know, I know, don't start).
Something like:
   df.write.partitionBy("date").parquet(some_path)

creates files like: some/path/date=2021-01-01/part-00000-77dd02e8-1a67-4f0d-9c07-b55b4f2e5efc-c000.snappy.parquet
And that makes that external system unhappy.
I am looking for a way to tell spark to write that file without extension.
I know I can just rename it afterwards, but that seems ... stupid (and there's a lot of files) :/
Is there some option I could use to tell spark to just write it the way I want?

A: df.write.partitionBy("date").parquet(some_path_ends_with_file_name)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Access a local directory to retrieve files from localhost and write back I currently have an Angular app (MEAN Stack) that I am running locally on my Windows machine. Being new to Node/Express, I would like to be able to access a local directory from http://localhost:3006 that I have setup within my main app directory, called /myfiles which I am unsure how to do.
What I am unsure is, how do I create an endpoint to access and read these files from localhost within the /myfiles directory and display them within an Angular Material dialog?
Just not sure what I need to do as part of Express side (setting up the route) and then the Angular side (using HttpClient) to display.
Further to the above, I will also need to write back to the /myfiles directory, where I will need to perform a copy command based on a file selection within Angular.

A: You'll want to create an endpoint in Express that your Angular app can call to be served the files.
I'll assume the files you want to read and send are JSON files. Here's a really simple example of an endpoint that you can visit that will return the file to your frontend.
In your Angular code you will make a get call to /myfile
var fs = require("fs");

app.get('/myFile', (req, res) => {
     var filepath = __dirname + '/myfiles/thefile.json';
     var file = fs.readFileSync(filepath, encoding);
     res.json(JSON.parse(file));
});

Then in Angular, you'll have something like
http.get('/myfile').subscribe( (data) => { console.log("The data is: ", data) });

ADDED
The example I provided above was just the basics to answer your question. Ideally, in production for file paths, you should the Node path library which 'knows' how to behave in different environments and file systems.


text:
Q: Why are we using interface to set onClick for View Holders for recycler view in the MainActivity I am going through a tutorial which is using the Recycler View to display a list of weather for each day for a week.
There are two classes which I am confused in:

ForecastAdapter and MainActivity

Here is the code for the above two classes:

ForecastAdapter.java

public class ForecastAdapter extends RecyclerView.Adapter<ForecastAdapter.ForecastAdapterViewHolder> {

    private String[] mWeatherData;
    final private ForecastAdapterOnClickListener mClickHandler;

    //Why do we need to create an interface here.
    public interface ForecastAdapterOnClickListener {
        void onClick(String weatherForDay);
    }

    public ForecastAdapter(ForecastAdapterOnClickListener forecastAdapterOnClickListener) {
        mClickHandler = forecastAdapterOnClickListener;
    }

    public class ForecastAdapterViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
        public final TextView mWeatherTextView;

        public ForecastAdapterViewHolder(View view) {
            super(view);
            mWeatherTextView = (TextView) view.findViewById(R.id.tv_weather_data);
            view.setOnClickListener(this);
        }

        @Override
        public void onClick(View v) {
            int adapterPosition = getAdapterPosition();
            String weatherForDay = mWeatherData[adapterPosition];

            //Why are we calling onClick from mClickHandler here. Why can't we just display Toast here.
            mClickHandler.onClick(weatherForDay);

            /*Why can't we just display the Toast from here like this:
              Toast.makeText(v.getContext(), weatherForDay, Toast.LENGTH_SHORT).show()
            */
        }

    }

    @Override
    public ForecastAdapterViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        Context context = viewGroup.getContext();
        int layoutIdForListItem = R.layout.forecast_list_item;
        LayoutInflater inflater = LayoutInflater.from(context);
        boolean shouldAttachToParentImmediately = false;

        View view = inflater.inflate(layoutIdForListItem, viewGroup, shouldAttachToParentImmediately);
        return new ForecastAdapterViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ForecastAdapterViewHolder forecastAdapterViewHolder, int position) {
        String weatherForThisDay = mWeatherData[position];
    forecastAdapterViewHolder.mWeatherTextView.setText(weatherForThisDay);
    }

    @Override
    public int getItemCount() {
        if (null == mWeatherData) return 0;
        return mWeatherData.length;
    }

    public void setWeatherData(String[] weatherData) {
        mWeatherData = weatherData;
        notifyDataSetChanged();
    }
}

MainActivity.java

//Why are implementing ForecastAdapterOnClickListener here?
public class MainActivity extends AppCompatActivity implements ForecastAdapter.ForecastAdapterOnClickListener{

private RecyclerView mRecyclerView;
private ForecastAdapter mForecastAdapter;

private TextView mErrorMessageDisplay;

private ProgressBar mLoadingIndicator;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_forecast);

    mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview_forecast);
    mErrorMessageDisplay = (TextView) findViewById(R.id.tv_error_message_display);

    LinearLayoutManager layoutManager
            = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);

    mRecyclerView.setLayoutManager(layoutManager);

    mRecyclerView.setHasFixedSize(true);

    mForecastAdapter = new ForecastAdapter(this);
    mRecyclerView.setAdapter(mForecastAdapter);

    mLoadingIndicator = (ProgressBar) findViewById(R.id.pb_loading_indicator);

    loadWeatherData();
}

private void loadWeatherData() {
    showWeatherDataView();

    String location = SunshinePreferences.getPreferredWeatherLocation(this);
    new FetchWeatherTask().execute(location);
}

@Override
public void onClick(String weatherForDay) {
    Context context = this;
    Toast.makeText(context, weatherForDay, Toast.LENGTH_SHORT)
            .show();
}

private void showWeatherDataView() {
    mErrorMessageDisplay.setVisibility(View.INVISIBLE);
    mRecyclerView.setVisibility(View.VISIBLE);
}

private void showErrorMessage() {
    mRecyclerView.setVisibility(View.INVISIBLE);
    mErrorMessageDisplay.setVisibility(View.VISIBLE);
}

public class FetchWeatherTask extends AsyncTask<String, Void, String[]> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        mLoadingIndicator.setVisibility(View.VISIBLE);
    }

    @Override
    protected String[] doInBackground(String... params) {
        if (params.length == 0) {
            return null;
        }

        String location = params[0];
        URL weatherRequestUrl = NetworkUtils.buildUrl(location);

        try {
            String jsonWeatherResponse = NetworkUtils
                    .getResponseFromHttpUrl(weatherRequestUrl);

            String[] simpleJsonWeatherData = OpenWeatherJsonUtils
                    .getSimpleWeatherStringsFromJson(MainActivity.this, jsonWeatherResponse);

            return simpleJsonWeatherData;

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

    @Override
    protected void onPostExecute(String[] weatherData) {
        mLoadingIndicator.setVisibility(View.INVISIBLE);
        if (weatherData != null) {
            showWeatherDataView();
            mForecastAdapter.setWeatherData(weatherData);
        } else {
            showErrorMessage();
        }
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.forecast, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == R.id.action_refresh) {
        mForecastAdapter.setWeatherData(null);
        loadWeatherData();
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}
The adapter, view holder and recycler view is working as expected. We are now supposed to implement Click Handling on the rows of the recycler view. Whenever a particular row is clicked, we are supposed to display a toast.
As you can see, we are implementing OnClickListener in the ForecastAdapterViewHolder and in the onClick function we are calling the onClick of the interface "ForecastAdapterOnClickListener".
In the MainActivity.java, we are implementing this "ForecastAdapterOnClickListener" and then displaying the toast.
Why can't we just display the toast in the onClick that is defined for the "ForecastAdapterViewHolder" class. I have tried it and it works. What is the point of doing what is being done in the code?
Is there some advantage in setting the click listener like that?

A: Because you'll have to display information afterwards and isn't role of ViewHolder neither Adapter. Activity/fragment must do that.
It's to keep your code organized.


text:
Q: The procedure entry point terminate could not be located in dynamic link library I wrote a program in Python 3.6.2 (32 bit), I converted it to an .exe file using cx_freeze.
When I run it in Windows 8 (64 bit), it needs the below DLLs inside the project:
api-ms-win-crt-runtime-l1-1-0.dll
api-ms-win-crt-time-l1-1-0.dll
api-ms-win-crt-string-l1-1-0.dll
api-ms-win-crt-stdio-l1-1-0.dll
api-ms-win-crt-process-l1-1-0.dll
api-ms-win-crt-math-l1-1-0.dll
api-ms-win-crt-locale-l1-1-0.dll
api-ms-win-crt-heap-l1-1-0.dll
api-ms-win-crt-environment-l1-1-0.dll
api-ms-win-crt-convert-l1-1-0.dll
api-ms-win-crt-conio-l1-1-0.dll

when I add api-ms-win-crt-filesystem-l1-1-0.dll and run the project, I get the error:
The procedure entry point terminate could not be located in dynamic link library.
C:\users\seyed_vahid\Desktop\exe.win32-3.6\MegaGram.exe

How to fix it?

A: See Pyinstaller onefile does not start on some Windows 7 machines .
The workaround seems to be to

*

*Install all Windows updates.

*Install the Microsoft Visual C runtime redistributable package.


text:
Q: Coding Style: Is it acceptable to make further queries from within model classes? I have a model class Alert with a one-to-many relationship with another model class Occurrence, as follows:
@Entity public class Alert extends Model
{
  public String name;

  @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="alert")
  public List<Occurrence> occurrences;
}

@Entity public class Occurrence extends Model
{
  @ManyToOne
  public Alert alert;

  @Column(nullable=false)
  public Date alertTime;
}

I have a view that lists Alerts in a simple table, which should have a column labelled "Occurrences today", with a count of how many occurrences of the alert have happened today (by alertTime).
I can't seem to find a way to do this using only JPA/Hibernate annotations in the Alert model class, and since I am listing Alerts, I don't know of a clean way to include the count in each Alert object.
So now I am wondering if it would be fine to simply query for the alert's occurrences from within the Alert model class itself, like so:
@Entity public class Alert extends Model
{
  public String name;

  @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="alert")
  public List<Occurrence> occurrences;

  @Transient
  public long getOccurrencesToday()
  {
    return Occurrence.count(
      "alert = ? and alertTime >= ?",
      this, new DateMidnight().toDate());
  }
}

My question is: Is it considered bad form to make queries to the DB from within a model class?
A secondary question is: Am I approaching this the wrong way? Is there a better way to achieve the end result that I've missed?

A: making queries from within domain model class should be the correct way to go giving those queries are relevant to that model. To this end, I don't see any problem with your code.
From Play's philosophy, domain object is not merely a data object. It should enclose certain business logic inside. In fact pure data object is not encouraged by play. Check more on http://www.playframework.org/documentation/1.2.4/model

A: While your approach is tempting, its dangerous because effectively you're putting logic into a "getter" (getOccurrencesToday()) which you'll probably access by ${alert.occurrencesToday}
A getter should always be side effect free.
I would change this to
@Entity public class Alert extends Model
{
  public String name;

  @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="alert")
  public List<Occurrence> occurrences;

  @Transient public Long occurrencesToday = null;

  public void populateOccurrencesToday()
  {
    occurrencesToday = Occurrence.count(
      "alert = ? and alertTime >= ?",
      this, new DateMidnight().toDate());
  }
}

then in your controller, iterate over all alerts that
you're going to render and execute the populateOccurrencesToday() method.
If you're now storing your object in a cache, its data will be consistent.


text:
Q: Knex & postgres connection error - error: role "admin" does not exist I am trying to connect to postgres db image using knex. But I am getting error:-
 error: role "admin" does not exist
My knexfile is ass below:
module.exports = {

  development: {
    debug: true,
    client: 'pg',
    connection: {
      database: process.env.POSTGRES_DB,
      user: process.env.POSTGRES_USER,
      password: process.env.POSTGRES_PASSWORD
    },

    migrations: {
      directory: __dirname + '/src/migrations'
    },
    seeds: {
      directory: __dirname + '/src/seeds'
    }
  }
};

And my docker-compose file is:-
version: '3.1'
services:
  db:
    image: postgres
    restart: always
    volumes:
      - ./docker-data/db-data:/var/lib/postgresql/data
    environment:
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
      POSTGRESS_USER: ${POSTGRES_USER}
      POSTGRESS_DB: ${POSTGRES_DB}
    ports:
      - 5432:5432
  pgadmin:
    depends_on:
      - db
    image: dpage/pgadmin4
    restart: always
    environment:
      PGADMIN_DEFAULT_EMAIL: ${PGADMIN_DEFAULT_EMAIL}
      PGADMIN_DEFAULT_PASSWORD: ${PGADMIN_DEFAULT_PASSWORD}
    volumes:
      - ./docker-data/pgadmin-data:/root/.pgadmin
    ports:
      - 8080:80

Environment variables are straight forward
POSTGRES_USER=admin
POSTGRES_PASSWORD=admin
POSTGRES_DB=configs
PGADMIN_DEFAULT_EMAIL=admin@admin.com
PGADMIN_DEFAULT_PASSWORD=admin

Packages details:
  "knex": "^0.21.1",
  "pg": "^8.3.0"

I ran command docker-compose up and on completion i created migrations and post that i ran npx knex migrate:latest. This is resulting in error
error: role "admin" does not exist
    at Parser.parseErrorMessage (/Users/test/packages/config-server/node_modules/pg-protocol/dist/parser.js:278:15)

I am not able to debug and fix. Please help.


text:
Q: Error to sync KSoap2 I am trying to synk my KSoap2 library but when I click on synchronize ksoap2 ... these tell me it was a successful synchronization but when I try to use this it does not show the tags and it marks in red the SoapObject
Does any body have the same problem? Or how can I fix it?

A: Problem solved i see these tutorial an works for me
https://code.tutsplus.com/tutorials/consuming-web-services-with-ksoap--mobile-21242


text:
Q: 3D Dicom Visualisation in Python I am new to 3D image processing . I would like to know how to view the dicom series in python. I tried using matplotlib and VTK. In matplot I am not able to view the volume like I view in matlab using volViewer. Regarding VTK I am not able to import VTKRAyCASt for viewing 3D. The version I am using is 8.2.0.
I am doing the processing using scipy.ndimages
Kindly suggest me some resources to my volume dicom files

A: You can try ipyvolume https://github.com/maartenbreddels/ipyvolume for interactive plotting, I found it quite useful.
Also, you can plot them with matplotlib by using marching cubes to obtain the surface mesh but it is quite slow though:
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import numpy as np
from skimage import measure

def plot_3d(image, threshold=-300):
    p = image.transpose(2,1,0)
    verts, faces, normals, values = measure.marching_cubes_lewiner(p, threshold)
    fig = plt.figure(figsize=(10, 10))
    ax = fig.add_subplot(111, projection='3d')
    mesh = Poly3DCollection(verts[faces], alpha=0.1)
    face_color = [0.5, 0.5, 1]
    mesh.set_facecolor(face_color)
    ax.add_collection3d(mesh)
    ax.set_xlim(0, p.shape[0])
    ax.set_ylim(0, p.shape[1])
    ax.set_zlim(0, p.shape[2])

    plt.show()

The threshold of -300 HU is fine for visualizing chest CT scans but change it if you going to use MRI (check your intensity values distribution) or binary volumes (threshold =0).
There is some example of visualization:

A: With vtkplotter you should be able to do this easily:
from vtkplotter import *

volume = load(mydicomdir) #returns a vtkVolume object
show(volume, bg='white')

To install:
pip install vtkplotter


text:
Q: scala Ide Not identifying my class as main method I have researched some answers in Stackoverflow but my error seems to be different. Having said that i am a newbie in scala hence please consider that as well.
I am trying to create multi class project in scala. Project Format is like this
Test Project
    |
    COM Package
    |
    |-->App.class
    |
    COM.Test Package
    |
    |-->App1.class
Code Snippet
App.scala
object App {

  def main(args : Array[String]): Unit = {
    var logger = Logger.getLogger(this.getClass())
     if (args.length < 3) {
      logger.error("=> wrong parameters number")
      System.err.println("Usage: MainExample <path-to-files> <srcCode> <tableName>")
      System.exit(1)
    }
      println("In Main Class")
}

App1.scala
object App1 {

      def main(args : Array[String]): Unit = {
         println("In Sub Class")
    }

Pom.xml
<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">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com</groupId>
  <artifactId>test</artifactId>
  <version>1.0.0</version>
  <name>${project.artifactId}</name>
  <description>My wonderfull scala app</description>
  <inceptionYear>2015</inceptionYear>
  <licenses>
    <license>
      <name>My License</name>
      <url>http://....</url>
      <distribution>repo</distribution>
    </license>
  </licenses>

  <properties>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
    <encoding>UTF-8</encoding>
    <scala.version>2.10.4</scala.version>
    <scala.compat.version>2.10.4</scala.compat.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.scala-lang</groupId>
      <artifactId>scala-library</artifactId>
      <version>${scala.version}</version>
    </dependency>
  </dependencies>

  <build>
    <sourceDirectory>src/main/scala</sourceDirectory>
    <!-- >testSourceDirectory>src/test/scala</testSourceDirectory -->
    <!-- plugins>
      <plugin>
        <see http://davidb.github.com/scala-maven-plugin >
        <groupId>net.alchim31.maven</groupId>
        <artifactId>scala-maven-plugin</artifactId>
        <version>3.2.0</version>
        <executions>
          <execution>
            <goals>
              <goal>compile</goal>

            </goals>
            <configuration>
              <args>
                <arg>-make:transitive</arg>
                <arg>-dependencyfile</arg>
                <arg>${project.build.directory}/.scala_dependencies</arg>
              </args>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins -->
  </build>
</project>

I am using SCALA IDE along with Scala Maven Plugin. I have commented out the build plugin but it doen=s not make a difference if that is turned on as well.
Two Issues i am facing
Issue 1) I am unable to Run App1.scala in Sub Package COM.Test. App.scala is run  without issue from Run As -->Scala Application. But when ever i try to run App1.scala the scala side is not able to find Main Class
Issue 2) I am unable to debug my code for App.scala in scala ide. Whenever i run Debug Command (Bug Operator) the breakpoints are skipped and code executes entirely. I use Scala JVM Launcher and checked The option Stop in Main. Please help
Using Eclipse Luna with Scala IDE and MAC OS

A: You need to add extends App to your main objects.
object App  extends App {

  def main(args : Array[String]): Unit = {
    var logger = Logger.getLogger(this.getClass())
     if (args.length < 3) {
      logger.error("=> wrong parameters number")
      System.err.println("Usage: MainExample <path-to-files> <srcCode> <tableName>")
      System.exit(1)
    }
      println("In Main Class")
}

A: Package structure must correspond to directory structure in the IDE. (This is unlike scalac.)
It's hard to tell from the info you present, but I can confirm that Scala IDE (on Eclipse Luna) will not offer "Run As > Scala application" if I remove the package declaration.
For example, if the class App in directory src/p/ (source file src/p/App.scala) is not in package p, then it won't offer to run it.
Uncommenting the correct package declaration gets the run as menu back.
I can also verify that a debug config with stop in main and Scala JVM launcher works as expected for App in the default package as well as in a named package. So I don't know how that could have broken for you.


text:
Q: Getting typescript compiler and live-server to play well together? I'm working with Angular2 and typescript but I'm running into frustrations in my dev process.
I'm using tsc -w to watch for file changes and immediately compile. This can take 2 or 3 seconds to complete as it compiles all files that reference a changed file.
I'm using live-server . --ignorePattern=.*\.ts so that live-server can watch for non-ts file changes and update the browser to reflect the changes. Ideally it should force the browser to update when tsc is done compiling.
What ends up happening is that tsc will immediately build a .ts file on change and emit it's .js and .js.map files. This will trigger live-server to update. Then tsc will recompile all files that import the changed .ts file and emit all of their .js and .js.map files. This takes nearly 2 seconds to do. After that live-server refreshes the browser again.
If I change my live-server line to live-server . --wait=3000 --ignore-pattern=.*\.ts then it waits 3 seconds after the second emission of js files which means it waits an entire 5 seconds (2 seconds of compiling files that reference the changed file + 3 extra seconds of waiting) which can be quite cumbersome if a bunch of small changes are made back to back. It'll compile all the way back to my boot.js file.
Are there any tsc options/flags I can use to only emit compiled files once? I do not want to emit just one .js file but I'm open to other solutions.


text:
Q: Gurobi/python formulating a constraint I have a parameter called f which has three values. I need to formulate a constraint with the right-hand side set to f. the f and constraints can be exemplified as follows:
f = 1  if i in P
f = -1 if i in D
f = O  otherwise
Xi + Yi = f  for i in P+D
I have formulated the constraint in Gurobi as next? is there another way instead of splitting the constraint into two parts?
m.addConstrs((quicksum(x[i])+quicksum(y[i]) == 1 for i in P)
m.addConstrs((quicksum(x[i])+quicksum(y[i]) == -1 for i in D)


text:
Q: How to Inject FacesContext in Arquillian Is it possible to inject FacesContext in Arquillian test? Or better approach is to mock it? I couldn't find any example from the last years on the web. FacesContext is null.
@Category(Arquillian.class)
@RunWith(Arquillian.class)
public class ControllerIT extends ArquillianDeployementsIT {

@Inject
private Controller controller;

@Test
public void shouldInitialize() {
    controller.getStatistics();
}

@ManagedBean
@ViewScoped
public class Controller {

public void getStatistcs(
    FacesContext context = FacesContext.getCurrentInstance();
      }

   }

Thanks and regards

A: Finally I solved the problem like this, maybe it helps someone.
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;
import javax.faces.application.Application;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.context.Flash;
import javax.servlet.http.HttpServletRequest;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public abstract class ContextMocker extends FacesContext {

private static final Release RELEASE = new Release();

private ContextMocker() {
}

public static FacesContext mockServletRequest() {
    FacesContext context = mock(FacesContext.class);
    setCurrentInstance(context);
    Mockito.doAnswer(RELEASE)
            .when(context)
            .release();
    Map<String, Object> session = new HashMap<>();
    ExternalContext ext = mock(ExternalContext.class);
    HttpServletRequest request = mock(HttpServletRequest.class);
    when(ext.getSessionMap()).thenReturn(session);
    when(context.getExternalContext()).thenReturn(ext);
    when(ext.getRequest()).thenReturn(request);
    when(ext.isUserInRole(anyString())).thenReturn(true);
    return context;
}
private static class Release implements Answer<Void> {

    @Override
    public Void answer(InvocationOnMock invocation) throws Throwable {
        setCurrentInstance(null);
        return null;
    }
}
}

and in the test:
@Category(Arquillian.class)
@RunWith(Arquillian.class)
public class LoginControllerIT extends ArquillianWebIT {

@Inject
private LoginController loginController;

private FacesContext facesContext;

@Before
public void init() {
    facesContext = ContextMocker.mockServletRequest();
}

@After
public void release() {
    facesContext.release();
}

 @Test...


text:
Q: How to quickly find the maximum-average interval? From an integer array A[N], I'd like to find an interval [i,j] that has a maximized average (A[i] + A[i + 1] + .. + A[j]) / (j - i + 1).
The length of the interval (j - i + 1) should be more than L.(L >= 1)
What I thought was to calculate an average for every i ~ j, but it is too slow to do like this.(N is too big)
Is there an algorithm faster than O(N^2)? Or I'd like to know whether there exists a randomized method for that.

A: There is an O(N*logC) algorithm, where C is proportional to the maximum element value of the array. Comparing with some more complicated algorithms in recent papers, this algorithm is easier to understand, and can be implemented in a short time, and still fast enough in practical.
For simplicity, We assume there is at least one non-negative integers in the array.
The algorithm is based on binary search. At first, we can find that the final answer must be in the range [0, max(A)], and we half this interval in each iteration, until it is small enough (10-6 for example). In each iteration, assume the available interval is [a,b], we need to check whether the maximum average is no less than (a+b)/2. If so, we get a smaller interval [(a+b)/2, b], or else we get [a, (a+b)/2].
Now the problem is: Given a number K, how to check that the final answer is at least K?
Assume the average is at least K, there exist some i, j such that (A[i] + A[i+1] + ... + A[j]) / (j - i + 1) >= K. We multiply both sides by (j-i+1), and move the right side to left, and we get (A[i] - K) + (A[i+1] - K) + ... + (A[j] - K) >= 0.
So, let B[i] = A[i] - K, we only need to find an interval [i, j] (j - i + 1 > L) such that B[i] + ... + B[j] >= 0. Now the problem is: Given array B and length L, we are to find an interval of maximum sum whose length is more than L. If the maximum sum is >= 0, the original average number K is possible.
The second problem can be solved by linear scan. Let sumB[0] = 0, sumB[i] = B[1] + B[2] + ... + B[i]. For each index i, the max-sum interval which ended at B[i] is sumB[i] - min(sumB[0], sumB[1], ..., sumB[i-L-1]). When scanning the array with increasing i, we can maintain the min(sumB[0], ..., sumB[i-L-1]) on the fly.
The time complexity of the sub-problem is O(N). And we need O(logC) iterations, so the total complexity is O(N*logC).
P.s. This kinds of "average problem" belongs to a family of problems called fractional programming. The similar problems are minimum average-weighted spanning tree, minimum average-weighted cycle, etc.
P.s. again. The O(logC) is a loose bound. I think we can reduce it by some careful analysis.


text:
Q: Clone remote site to local drive with SharePoint Designer 2013 I am a user (without Admin rights) of a remote SP site running SP 2013. My contact there wants me to clone the remote site to my local hard drive (where I have Admin rights).
SP Designer 2013 was suggested, which I have installed local. I am new to SP Designer and need a link/guidance.

A: "Clone" is an inaccurate term as your local Hard drive does not support anything beyond basic file storage.  All metadata, security, history and so forth would be lost.  Your local machine also cannot support lists of any type.
However, that said, why not just use Explorer view and drag and drop the files from the SharePoint site to your local machine?


text:
Q: Reclaiming space from one filesystem to give it to another without LVM I want to add one file system space to another file system.
/dev/cciss/c0d0p2    152358920 143606116    888588 100% /db2
/dev/cciss/c0d0p15   203899764  50767420 142607764  27% /db2/ade/sapdata1

From /db2/ade/sapdata1 to /db2 in this case. Our server is also not installed in LVM format.
How can I some of the free space to /db2?

A: The level of difficulty of doing this depends on the block layout of those two partitions: which one comes first on the disk in terms of start block and end block, whether there is any other partition of any empty space between them, etc...
It will also be necessary that the filesystem used on /db2/ade/sapdata1 supports shrinking. xfs, for example, does not.
I present an example for your information. It's quite a dangerous operation and I don't recommend that you do it. But it will give you an idea of what's involved. The example is the easiest case. Other cases are much more difficult because you might have to move data backwards (counting from the last block toward the first) from one location to another in a partition.
Let's say p15 is stored first on the disk followed by p2, they together occupy the whole disk, there are no other partitions, and no free blocks. This is what you would have to do:

*

*Shrink the filesystem on p15

*Shrink the p15 partition to the new size of the filesystem. This will create free space between the two partitions.

*Unmount p2 (/db2)

*Change the start block of the p2 partition to the first free block made available in step 2 (i.e. back up the start of the partition to be earlier on the disk)

*Move the data backwards on the disk with a command like this:
dd if=/dev/cciss/c0d0p2 of=/dev/cciss/c0d0p2 bs=xxx skip=yyy

xxx should be a large block size which divides without remainder the amount by which you are growing the partition and yyy should be the number of bytes by which you are growing the partition divided by xxx.

*Grow the /db2 filesystem.
As you can imagine, step 5 is an extremely dangerous operation. It will take a long time to execute and it may be very difficult to recover if it fails or is interrupted. You must understand what you are doing if you undertake this.
Another option if you are running under Linux would be to leave all of the existing data where it is and use the device mapper to stitch together an existing partition plus some non-adjacent empty space together into one larger virtual partition. This is basically something LVM would do, but without the nice LVM user interface and metadata that stitches block ranges together automatically and transparently.


text:
Q: Create a Window on a status bar app for macOS Warning: macOS dev beginner here.
I have a menu bar app (with no dock). Most of the app's functionality is in the menu (and implementation is in AppDelegate), but I need a separate window that will open once I click one of the menu items.
I want to use SwiftUI, Swift 5, Xcode 11.3.
I haven't found an appropriate way to do this. Which files and similar need to be created? How to open this window programatically?
@objc func openPreferences() {
  // open a new window here...
}

A: You have to create a window programatically. I have attached sample code of one of my apps:
private var windowController: NSWindowController?

fileprivate func createWindow()
{
    let storyboard = NSStoryboard(name: "Main", bundle: nil)

    self.windowController = storyboard.instantiateInitialController() as? NSWindowController

    // This is example code to show how to customize the hosted view controller. You can pass additional arguments here (may an important global variables that is declared in the AppDelegate).
    if let contentController = windowController?.contentViewController as? MyWindowViewController
    {
        // Do some assignments here
        // contentController.variable = ....
        // self.windowViewController = contentController // Maybe save for later use.
    }
}

@objc fileprivate func open()
{
    if self.windowViewController == nil
    {
        self.createWindow()
    }

    self.windowController?.showWindow(self)

    NSApp.activate(ignoringOtherApps: true) // Bring window to front.
}

I have linked the open() function to a button call (hence the @objc keyword). I think that you already did this, so my open() function would be your openPreferences function.


text:
Q: Measuring Django Command duration with NewRelic I have a set of Django commands that do some complex operations, and I'd like to begin tracking the duration of how long they take, in order to monitor their performance over time.
I've struggled to figure out how to instrument newrelic to capture the duration. I've tried everything from 'assuming' the standard django newrelic agent will magically capture it, to try to instrument them myself as a custom event, all with varying degrees of success.
What is the best way to do this, and does newrelic provide something to facilitate this? The docs were very lacking for this kind of scenario.
Additionally, I would consider these as background_tasks - what is the background_task field in newrelic used for?
Thanks

A: At New Relic we do have a prototype for some changes we are considering making to the Python agent which will add support for monitoring nominated Django admin commands. We are still working through some details of those changes but it is possible it will make it in to one of the upcoming releases over the next couple of months.
In the interim, what you can do is add something like the following to your agent configuration file:
[newrelic:django-manage]
app_name = Python Application (Django Management Commands)
startup_timeout = 10.0

[background-task:django-manage-syncdb]
enabled = true
function = django.core.management.commands.syncdb:Command.handle_noargs
name = syncdb
group = Django

You would then run the Django manage.py script as:
NEW_RELIC_CONFIG_FILE=newrelic.ini
NEW_RELIC_ENVIRONMENT=django-manage

export NEW_RELIC_CONFIG_FILE
export NEW_RELIC_ENVIRONMENT

newrelic-admin run-python manage.py syncdb

When the data is then reported into our UI, it will appear under 'Type -> Other transactions -> Django' in the 'Transactions' tab for the specified application.

The 'newrelic:django-manage' section is an environment section that allows you to override the 'app_name' setting defining which application in our UI the data should be reported to. The 'NEW_RELIC_ENVIRONMENT' variable says that the environment section should be used as overrides for the default 'newrelic' section'.
Even if you do not override 'app_name' and have it inherit the value from the default 'newrelic' section, you still must set the 'startup_timeout' setting. This is necessary as under normal circumstances the agent will only lazily register itself in the background when the first web request is being handled by a web application. Having registration being done lazily will though cause a problem when tracking Django management commands as a background task. This is because there is only the one function call to be monitored, and not waiting for agent registration to occur will result in no data being captured. Setting a non zero value for the startup timeout therefore says to wait for registration to occur.
If for some reason agent registration takes too long, the timeout will expire after the specified time and the management command allowed to proceed anyway. Either way, the need to wait means that there will be a delay in actually starting the management command. This should be kept in mind if the management command needs to be run as quickly as possible.
If necessary, a 'shutdown_timeout' can also be specified if the uploading of data captured by the agent is consistently taking longer than the default 2.5 seconds and therefore not always being reported.
As to the 'background-task' section, it defines the specific function which should be monitored and reported as a background task. In this case we are targeting the particular function implementing the Django 'syncdb' command.


text:
Q: Bootstrap navbar with collapsible search form I'm trying to fix a bug on the Linux Kamarada website regarding the search form. It is inspired on the one present on the Android's website, which is an expanding search bar:

It works very well on Mozilla Firefox, but not at all on Google Chrome.
Once, browsing through the web, I came across HPE's website and I found their search form awesome:

It works well on all browsers, so I thought it could be a solution to my problem.
I've tried to imitate it using Bootstrap's dropdown (see this example) and here is what I've got so far (I've used Bootstrap's Fixed navbar example as a starting point):

(source code available at Bootply)
According to tests made with Web Developer's View Responsive Layouts, it is working as expected on small, medium and large devices (768px wide and up), but not on extra small devices (e.g. mobile portrait, 320x480):

Does anyone know how to fix that?
Also, for the hamburguer menu to work the way I wanted, I ended up duplicating HTML code. Does anyone know how could I avoid that?
Last but not least, I'm not sure that code is accessible. I would appreciate very much advice about that.
Thank you in advance!

A: I was almost giving up and thinking about using a simple navbar-form with a search input (like this I found googling), that was when I found this, exactly what I was looking for: Bootsnipp Navbar with Search (that snippet is very close to the search actually used by the Bootsnipp website itself).
I liked it and adapted it to the Linux Kamarada website. The result can already be seen in production:

I tested it and it works on Mozilla Firefox, Google Chrome and Microsoft Edge.
Just in case anyone needs, I tried to catch the very basics of the idea and applied the navbar with collapsible search form to the Bootstrap's Sticky footer with navbar example. The result can be seen here: https://www.bootply.com/cf8Go56f4p

Also, just in case anyone is looking for a navbar with search and hits this page, I found this snippet interesting and recommend it: Simple Navbar Search


text:
Q: Why do I get a blank page when I click on links that point to '/' with my react router setup? This is essentially how I have it set up:
document.addEventListener('DOMContentLoaded', () => {
    ReactDOM.render(
        <Router>
            <Route path="/" component={App} />
        </Router>,
        document.body.appendChild(document.createElement('div')),
    )
})

const App = function(props) {
    return (
        <>
            <Navigation />
            <Switch>
                <Route exact path="/" component={Home} />
            </Switch>
        </>
    )
}

import React from "react";
import Layout from "../components/Layout"

const Home = function (props) {
    return (
        <Layout>
            The Home Component.
        </Layout>
    )
}

export default Home;

So here's what happens.
The site loads fine initially. I can see "This is the home component" appear on the page when I go to localhost:3000. But when I try to click on a link that points to just "/", the result is a completely blank page. If I refresh while the blank page is present, then a refresh will make the content appear again and appears as if it's loading properly. But once I click a link with the href="/" it's just a blank page.
This is my Navigation component (just a simple bootstrap nav, basic links with just href="/"...):
const Navigation = function (props) {
    return (

                Langsite

                <button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbar-content" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

                </button>

                        Home

    )
}

A: const Navigation = function (props) {
return (

            <Link className="navbar-brand" to="/">Langsite</Link>

            <button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbar-content" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

            </button>

                    Home

)

}
This can solve your problem


text:
Q: How to store rest client logging in a variable in Spring Boot(logging)? I am working on a rest client in Spring boot. And I have enabled logging in spring boot by putting the underlying lines in the property file.
logging.level.org.apache.http=DEBUG
logging.level.org.apache.http.wire=DEBUG

After this I am getting the request sent as well as the response in the xml format in Spring boot log console.
But now I want to log the request logged in the database. Does spring boot provides any configuration with which I can get these logs in some variable and store request and response separately in DB tables.


text:
Q: Data attr in second td is undefined Content comes from DB. I go foreach on array and insert rows into table. This is the structure of 1 row:

    <td data-name = '<?php echo $name ?>'><?php echo $name ?>
    <td data-email = '<?php echo $email ?>'><?php echo $email ?>
    <form method='post'><button class='delete' name='delete' ...>Remove</button></form>

I am trying to get the content of each data attribute in a row:
 $('.delete').click(function (e) {
        e.preventDefault();
        let name = $(this).parents('tr:first').find('td').data('name');
        let email = $(this).parents('tr:first').find('td').data('email'); // <--- undefined
        if (confirm(name + ' ' + email + ' delete?')) {
          ...code goes futher...

The question is:  I get name value, but email is undefined. What is wrong?
I also see the value of email variable in the table and in data attr in dev Console


text:
Q: Looping all values received in laravel $request My form has multiple check boxes where there names also change page to page. Something like below code.
 <input type="checkbox" name="name01" value="10">
 <input type="checkbox" name="name08" value="15"

Just imagine there are 20 check-boxes . If someone check 10 check-boxes I want them to be inserted in to DB using a foreach loop . So what I have done so far is
foreach($request as $singleItem){

        //Looping to check the name
        for($I=0 ;$I<25;$I++){

        //Making the name
            $name = 'item'.$I;

        if($singleItem[$name] ){

            $values[] = [
                'value' => $singleItem[$name]
            ];
        }
        }
    }
    dd($values);

But this gives me below error

Can anyone help me on this

A: You should fetch it like,
$arr = $request->all();
dd($arr);
foreach($arr as $key => $singleItem){
// $key is your name01, name02, etc
// here you will get padded name string if you want to check.
$name = str_pad($key, 2, "0", STR_PAD_LEFT);
    if(isset($arr[$name])){
        $values[] = [
                'value' => $singleItem
        ];
    }
}


text:
Q: BindParam not returning any values - PHP PDO I have a problem when i bind a variable to my sql query, i've tried without using params and it works fine, so it's not a connection issue.
This is my connection to my db, which is in another file:
<?php
$dbhost="localhost";  // localhost
$dbport ="";
$dbname="proyecto_final";

$usuario="root";
$contrasenia="38919650";

$strCnx = "mysql:dbname=$dbname;host=$dbhost";

$db ="";

try {
    $db = new PDO($strCnx, $usuario, $contrasenia);

    $db->setAttribute(PDO::ATTR_CASE,PDO::CASE_LOWER); # para referenciar en minúscula el nombre de las columnas
    $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC); # Relizar el FETCh ASSOC por defecto para ahorrar memoria

} catch (PDOException $e) {
    print "Error: " . $e->getMessage() . "<br/>";   # cambiar por un error personalizado
    die();
}
?>

And here is the file where i include the connection, and then use PDO FETCH to get the values:
      <?php
      require_once 'database/conn.php';
      $ciudad = (isset($_POST["valor_ciudad"]) && !empty($_POST["valor_ciudad"]))? $_POST["valor_ciudad"] : "";
      $oficio = (isset($_POST["valor_oficio"]) && !empty($_POST["valor_oficio"]))? $_POST["valor_oficio"] : "";
      echo $ciudad; //works fine
      echo $oficio; //works fine
      $query =
            "
              SELECT trabajador.nombre, trabajador.apellido, trabajador.telefono, oficios.categoria, oficios.experiencia, localidad.ciudad
              FROM trabajador
                      INNER JOIN oficios ON oficios.FK_IDtrabajador = trabajador.ID_trabajador
                      INNER JOIN localidad ON localidad.ID_localidad = trabajador.FK_IDlocalidad
              WHERE oficios.categoria = :oficio
              AND localidad.ciudad = :ciudad
            ";
      // prepare the query
      if(!empty($ciudad) && !empty($oficio)){
        try {
          //acá va la consulta
          $stmt = $db->prepare($query);
          $stmt->bindParam(':oficio', $oficio, PDO::PARAM_STR);
          $stmt->bindParam(':ciudad', $ciuddad, PDO::PARAM_STR); // PDO::PARAM_STR

          $stmt->execute();

          $num = $stmt->rowCount();
          echo $num; //returns 0, which means it doesnt get any value from the db
          if (!$stmt ) {
            print_r($db->errorInfo());      #mensaje en desarrollo
            echo "Error al ejecutar consulta.";
          }else{
            while ($fila = $stmt->fetch(PDO::FETCH_ASSOC)) {
              print_r($fila);
              $datos[] = $fila;
            }
            print_r($datos); //i get the error in this line "Undefined variable"
          }
          } catch (PDOException $e) {
          print "Error: " . $e->getMessage();
          die();
          }
      }
   ?>

As i marked above, i get the error "Undefined variable" when i try to print $datos, because it doesn't have any values inside.
I tried doing the query without params, and it works fine.


text:
Q: How to capture data from multiple form search fields in one variable I have an html search form with multiple fields like select, textarea and text inputs. I need the values from all the fields to be stored into $input in the php search form but I'm not sure how to store them into one variable called $input on the php page.
<form name="search" method="post" action="http://example.com/search/">
Seach for: <input type="text" name="find" /> <input type="submit"
name="search" value="Search" />
Search for movies by Type
<select name="find">
<option value="Sci-Fi" selected>Sci-Fi</option>
<option value="Comedy">Comedy</option>
<option value="Drama">Drama</option>
</select>
</form>

//on search.php need to 'find' to be data from several form inputs
$input = $_POST['find'];

A: Make your $input an array. For example:
$input = array(
    "user" => $_POST['username'],
    "find" => $_POST['find'],
);

Or simply add everything to $input by doing:
$input .= $_POST['username'];
$input .= $_POST['find'];

A: If you give multiple inputs the same name, $_POST['find'] will just contain the input from one of them (the last one, I think). You need to either give them different names, or you can end the name with []. When you do the latter, PHP will put all the inputs into an array.
<form name="search" method="post" action="http://example.com/search/">
Seach for: <input type="text" name="find[]" /> <input type="submit" name="search" value="Search" />
Search for movies by Type
<select name="find[]">
    <option value="Sci-Fi" selected>Sci-Fi</option>
    <option value="Comedy">Comedy</option>
    <option value="Drama">Drama</option>
</select>
</form>

With this, you can do:
$input = implode(' ', array_filter($_POST['find']));

array_filter will remove any empty values, then the rest will be concatenated together with space between them.

A: <?php
array_pop($_POST); // To delete Submit button from $_POST
foreach(array_filter($_POST) as $key=> $val)
{
    $input .= "$val";
}
?>


text:
Q: Can't get list of issues with multiple instances of the same parameter I'm trying to get list of issues from Bit Bucket via REST API with OAuth.js (http://oauth.googlecode.com/svn/code/javascript/). I'm signing every request with
OAuth.completeRequest(message, accessor);

where message is
message: {
  action: "https://api.bitbucket.org/1.0/repositories/owner/reponame/issues",
  method: "GET",
  parameters: p;
};

When p contains parameters with different names, everything is OK:
p = [['status','open'],['priority','high']]

but when p contains parameters with the same name
p = [['status','open'],['status','resolved']]

, server responds 401 UNAUTHORIZED.
Bitbucket API support mutliple instances of the same parameter:

You can query for multiple instances of the same parameter. The system treats multiple instances of the same parameter as an OR for the overall filter query. For example, the following filter looks for open and resolved bugs with the word for in the title:

status=open&kind=!bug&status=resolved&title=~for

I think that problem somewhere in signing methods of the OAuth.js library, but can't find it.

A: It was a bug on bitbucket side:
https://bitbucket.org/site/master/issue/7009/you-cannot-use-multiple-identical-query


text:
Q: Parent/owner of a Winforms component From a custom Winforms component that is embedded in a form, how to I get the parent/owner control?
I have an IContainer and the Site property is not null, but I have no idea how to get to the "real" parent.
(this is a followup to this question, atm I am trying to add a handler to the parents VisibleChanged, but that's not the first time I face this question)

A: Not Ideal, but try this...
Change the usercontrol to Component class (In the code editor), build the solution and remove all the code with errors (Related to usercontrols but not available in components so the debugger complains about it)
Change the usercontrol back to usercontrol class...
Now it recognises the name and parent property but shows the component as non-visual as it is no longer designable.


text:
Q: MYSQL: Creating a function with multiple returns Why is this function not working?
CREATE FUNCTION build_address(street VARCHAR(50), city VARCHAR(30), state CHAR(2), zipcode VARCHAR(10), country VARCHAR(10)) RETURNS VARCHAR(130)
    IF (street != '',
    IF (city != '',
    IF (state != '',
    IF (zipcode != '',
    IF (country != '',
    RETURN CONCAT(street, ', ', city, ', ', state, ' ', zipcode, ' ', country),
    RETURN CONCAT(street, ', ', city, ', ', state, ' ', zipcode)),
    RETURN CONCAT(street, ', ', city, ', ', state)),
    RETURN CONCAT(street, ', ', city)),
    RETURN CONCAT(street),
    IF (city != '',
    IF (state != '',
    IF (zipcode != '',
    IF (country != '',
    RETURN CONCAT(city, ', ', state, ' ', zipcode, ' ', country),
    RETURN CONCAT(city, ', ', state, ' ', zipcode)),
    RETURN CONCAT(city, ', ', state)),
    RETURN CONCAT(city),
    IF (state != '',
    IF (zipcode != '',
    IF (country != '',
    RETURN CONCAT(state, ' ', zipcode, ' ', country),
    RETURN CONCAT(state, ' ', zipcode)),
    RETURN CONCAT(state),
    IF (zipcode != '',
    IF (country != '',
    RETURN CONCAT(zipcode, ' ', country),
    RETURN CONCAT(zipcode),
    IF (country != '',
    RETURN CONCAT(country),
    RETURN '')))))))));

I'm about 99% certain that the parentheses are in the correct place. you can double check but I don't think that is the issue. I think the issue is that it is mad at me for having more than one return statement, but they are all within their own scope. From what I can tell this should work fine.
I don't know if this is important, but I am using phpMyAdmin and that is still on MySQL 5.6.21.
I am getting the following error:

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'RETURN CONCAT(street, ', ', city, ', ', state, ' ', zipcode, ' ', country),
      RE' at line 7

A: You're confusing the if function and if statement. You need the latter.
Also, this is way, way too much needlessly complicated. No sane human being will ever follow those crazy parenthesis. This can be written much simpler:
create function build_address(
    street varchar(50),
    city varchar(30),
    state char(2),
    zipcode varchar(10),
    country varchar(10)
)
returns varchar(130) deterministic
begin
  declare ret varchar(130);
  declare sep varchar(10);

  set ret = '';
  set sep = '';

  if street is not null and street != '' then
    set ret = concat(ret, sep, street);
    set sep = ', ';
  end if;

  if city is not null and city != '' then
    set ret = concat(ret, sep, city);
    set sep = ', ';
  end if;

  if state is not null and state != '' then
    set ret = concat(ret, sep, state);
    set sep = ' ';
  end if;

  if zipcode is not null and zipcode != '' then
    set ret = concat(ret, sep, zipcode);
    set sep = ' ';
  end if;

  if country is not null and country != '' then
    set ret = concat(ret, sep, country);
    set sep = ' ';
  end if;

  return ret;
end;

By the way - have you read falsehoods programmers believe about addresses? Trying to split address into components like this is mostly a doomed idea. There WILL be someone who cannot fit their address in that format. The best way is to simply provide a textarea where the user can fill out their address free-form.


text:
Q: Check for balanced parentheses in an expression in Swift I am trying to write this in swift as I could not find any solution written in swift but seem to have hit a roadblock with this implementation.
On the pop and push function, I am not sure if Character is the right return/argument.
class BalancedParam {
  struct stack {
    var top = -1
    var items = [Character]()

    mutating func push(_ x: Character) {
        items.append(x)
        if top == 99 {
            print("Stack full")
        } else {
            top += 1
            items[top] = x
        }
    }

    mutating func pop() -> Character {
        if top == -1 {
            print("Underflow error")
            return "0"
        } else {
            let element = items[top]
            top -= 1
            return element
        }
    }

    mutating func isEmpty() -> Bool {
        return (top == -1) ? true : false
    }
}

static func isMatchingPair(_ character1: Character, _ character2: Character) -> Bool {
    if character1 == "(" && character2 == ")"  {
        return true
    } else if character1 == "{" && character2 == "}" {
        return true
    } else if character1 == "[" && character2 == "]" {
        return true
    } else {
        return false
    }
}

static func areParenthesisBalanced(_ exp: [Character]) -> Bool {
    // Declare an empty character stack
    var st = stack()
    for i in 0..<exp.count {

        if exp[i] == "{" || exp[i] == "(" || exp[i] == "[" {
                st.push(exp[i])
        }

        if exp[i] == "}" || exp[i] == ")" || exp[i] == "]" {

            if st.isEmpty() {
                return false
            } else if !isMatchingPair(st.pop(), exp[i] ) {
                return false
            }

        }
    }
    if st.isEmpty() {
        return true //balanced
    } else {
        //not balanced
        return false
    }
  }
}

let exp: [Character] = ["{", "(", ")", "}", "[", "]"]
  if BalancedParam.areParenthesisBalanced(exp) {
    print("Balanced ")
  } else {
    print("Not Balanced ")
  }

I will appreciate any help in understanding what I am doing wrong. Thanks

A: You can not assign to an empty array, i.e items[top] = x, you can only use this syntax if the array is of size top+1 or larger
So this is not ok
var arr = [Int]()
arr[0] = 1

but this is
var arr = [Int]()
arr.append(0)
arr[0] = 1

Another option since you have a cap on your array size is to init an array of that size and then continue to use the original syntax
var arr = Array(repeating: 0, count: 99)
arr[0] = 1


text:
Q: Footprint finding algorithm I'm trying to come up with an algorithm to optimize the shape of a polygon (or multiple polygons) to maximize the value contained within that shape.
I have data with 3 columns:

*

*X: the location on the x axis

*Y: the location on the y axis

*Value: Value of the block which can have positive and negative values.

This data is from a regular grid so the spacing between each x and y value is consistent.
I want to create a bounding polygon that maximizes the contained value with the added condition.

*

*There needs to be a minimum radius maintained at all points of the polygon.  This means that we will either lose some positive value blocks or gain some negative value blocks.

The current algorithm I'm using does the following

*

*Finds the maximum block value as a starting point (or user defined)

*Finds all blocks within the minimum radius and determines if it is a viable point by checking the overall value is positive

*Removes all blocks in the minimum search radius from further value calculations and flags them as part of the final shape

*Moves onto the next point determined by a spiraling around the original point. (center is always a grid point so moves by deltaX or deltaY)

This appears to be picking up some cells that aren't needed.  I'm sure there are shape algorithms out there but I don't have any idea what to look up to find help.
Below is a picture that hopefully helps outline the question.  Positive cells are shown in red (negative cells are not shown).  The black outline shows the shape my current routine is returning.  I believe the left side should be brought in more.  The minimum radius is 100m the bottom left black circle is approximately this.

Right now the code is running in R but I will probably move to something else if I can get the algorithm correct.
In response to the unclear vote the problem I am trying to solve without the background or attempted solution is:
"Create a bounding polygon (or polygons) around a series of points to maximize the contained value, while maintaining a minimum radius of curvature along the polygon"
Edit:
Data
I should have included some data it can be found here.
The file is a csv. 4 columns (X,Y,Z [not used], Value), length is ~25k size is 800kb.

A: Graphical approach
I would approach this graphically. My intuition tells me that the inside points are fully inside the casted circles with min radius r from all of the footprint points nearby. That means if you cast circle from each footprint point with radius r then all points that are inside at least half of all neighboring circles are inside your polygon. To be less vague if you are deeply inside polygon then you got Pi*r^2 such overlapping circles at any pixel. if you are on edge that you got half of them. This is easily computable.
First I need the dataset. As you did provide just jpg file I do not have the vales just the plot. So I handle this problem like a binary image. First I needed to recolor the image to remove jpg color distortions. After that this is my input:

I choose black background to easily apply additive math on image and also I like it more then white and leave the footprint red (maximally saturated). Now the algorithm:

*

*create temp image
It should be the same size and cleared to black (color=0). Handle its pixels like integer counters of overlapping circles.

*cast circles
for each red pixel in source image add +1 to each pixel inside the circle with minimal radius r around the same pixel but in the temp image. The result is like this (Blue are the lower bits of my pixelformat):

As r I used r=24 as that is the bottom left circle radius in your example +/-pixel.

*select inside pixels only
so recolor temp image. All the pixels with color < 0.5*pi*r^2 recolor to black and the rest to red. The result is like this:

*select polygon circumference points only
Just recolor all red pixels near black pixels to some neutral color blue and the rest to black. Result:

Now just polygonize the result. To compare with the input image you can combine them both (I OR them together):

[Notes]
You can play with the min radius or the area treshold property to achieve different behavior. But I think this is pretty close match to your problem.
Here some C++ source code for this:
//picture pic0,pic1;
    // pic0 - source
    // pic1 - output/temp
int x,y,xx,yy;
const int r=24;                 // min radius
const int s=float(1.570796*float(r*r));     // half of min radius area
const DWORD c_foot=0x00FF0000;  // red
const DWORD c_poly=0x000000FF;  // blue
// resize and clear temp image
pic1=pic0;
pic1.clear(0);
// add min radius circle to temp around any footprint pixel found in input image
for (y=r;y<pic1.ys-r;y++)
 for (x=r;x<pic1.xs-r;x++)
  if (pic0.p[y][x].dd==c_foot)
   for (yy=-r;yy<=r;yy++)
    for (xx=-r;xx<=r;xx++)
     if ((xx*xx)+(yy*yy)<=r*r)
      pic1.p[y+yy][x+xx].dd++;
pic1.save("out0.png");
// select only pixels which are inside footprint with min radius (half of area circles are around)
for (y=0;y<pic1.ys;y++)
 for (x=0;x<pic1.xs;x++)
  if (pic1.p[y][x].dd>=s) pic1.p[y][x].dd=c_foot;
   else                   pic1.p[y][x].dd=0;
pic1.save("out1.png");
// slect only outside pixels
pic1.growfill(c_foot,0,c_poly);
for (y=0;y<pic1.ys;y++)
 for (x=0;x<pic1.xs;x++)
  if (pic1.p[y][x].dd==c_foot) pic1.p[y][x].dd=0;
pic1.save("out2.png");
pic1|=pic0; // combine in and out images to compare
pic1.save("out3.png");

I use my own picture class for images so some members are:

*

*xs,ys size of image in pixels

*p[y][x].dd is pixel at (x,y) position as 32 bit integer type

*clear(color) - clears entire image

*resize(xs,ys) - resizes image to new resolution

[Edit1] I got a small bug in source code
I noticed some edges were too sharp so I check the code and I forgot to add the circle condition while filling so it filled squares instead. I repaired the source code above. I really just added line if ((xx*xx)+(yy*yy)<=r*r). The results are slightly changed so I also updated the images with new results
I played with the inside area coefficient ratio and this one:
const int s=float(0.75*1.570796*float(r*r));

Leads to even better match for you. The smaller it is the more the polygon can overlap outside footprint. Result:

A: If the solution set must be a union of disks of given radius, I would try a greedy approach. (I suspect that the problem might be intractable - exponential running time - if you want an exact solution.)
For all pixels (your "blocks"), compute the sum of values in the disk around it and take the one with the highest sum. Mark this pixel and adjust the sums of all the pixels that are in its disk by deducing its value, because the marked pixel has been "consumed". Then scan all pixels in contact with it by an edge or a corner, and mark the pixel with the highest sum.
Continue this process until all sums are negative. Then the sum cannot increase anymore.
For an efficient implementation, you will need to keep a list of the border pixels, i.e. the unmarked pixels that are neighbors of a marked pixel. After you have picked the border pixel with the largest sum and marked it, you remove it from the list and recompute the sums for the unmarked pixels inside its disk; you also add the unmarked pixels that touch it.
On the picture, the pixels are marked in blue and the border pixels in green. The highlighted pixels are

*

*the one that gets marked,

*the ones for which the sum needs to be recomputed.

The computing time will be proportional to the area of the image times the area of a disk (for the initial computation of the sums), plus the area of the shape times the area of a disk (for the updates of the sums), plus the total of the lengths of the successive perimeters of the shape while it grows (to find the largest sum). [As the latter terms might be costly - on the order of the product of the area of the shape by its perimeter length -, it is advisable to use a heap data structure, which will reduce the sum of the lengths to the sum of their logarithm.]


text:
Q: Grouping PHP Array on 2 or more different values I'm creating a recent activity section and I am trying to group similar items. I want to be able to group activities based on type of activity and who did the activity. For instance:
Array
(
    [0] => Array
        (
            [user] => Bill
            [type] => photo
            [id] => 1
            [timestamp] => 12345678
        )

    [1] => Array
        (
            [user] => Joe
            [type] => photo
            [id] => 2
            [timestamp] => 12345678
        )

    [2] => Array
        (
            [user] => Bill
            [type] => comment
            [id] => 1
            [timestamp] => 12345678
        )

    [3] => Array
        (
            [user] => Bill
            [type] => photo
            [id] => 3
            [timestamp] => 12345678
        )

)

could turn into this:
Array
(
    [0] => Array
        (
            [user] => Bill
            [type] => photo
            [items] => Array
                (
                    [0] => Array
                        (
                            [id] => 1
                            [timestamp] => 12345678
                        )

                    [1] => Array
                        (
                            [id] => 3
                            [timestamp] => 12345678
                        )

                )

        )

    [1] => Array
        (
            [user] => Joe
            [type] => photo
            [items] => Array
                (
                    [0] => Array
                        (
                            [id] => 2
                            [timestamp] => 12345678
                        )

                )

        )

    [2] => Array
        (
            [user] => Bill
            [type] => comment
            [items] => Array
                (
                    [0] => Array
                        (
                            [id] => 1
                            [timestamp] => 12345678
                        )

                )

        )

)

This is almost what I am trying to do but not quite there: Grouping arrays in PHP
Anyone have an idea?

A: Your grouping doesn't exactly make sense (it makes a little more sense after your edit), try this:
foreach ($activity as $data) {
   $newdata[$data['user']][$data['type']]['id'][]=$data['id'];
   $newdata[$data['user']][$data['type']]['timestamp'][]=$data['timestamp'];
}

Edit to reflect your changes in desired output: (and a structure that is a bit more useful)
foreach ($activity as $data) {
    $newdata[$data['user']][$data['type']]['items'][]=array('id'=>$data['id'],'timestamp'=>$data['timestamp']);
}

Edit 2:
You have to have some sort of key, in this case its a combo of the username and the type.  Then you have to re-index it so its numeric if that actually matters. That should be quite close to exactly what you want:
foreach ($activity as $data) {
        $key=$data['user'].'-'.$data['type'];
        $newdata[$key]['items'][]=array('id'=>$data['id'],'timestamp'=>$data['timestamp']);
        $newdata[$key]['user']=$data['user'];
        $newdata[$key]['type']=$data['type'];
}
$newdata=array_values($newdata);

tested:
http://www.ideone.com/3uZdd
Edit 3:
separate dates...  this is the idea to get you started, you'll need to do a little more to the original array for this.
foreach ($activity as $data) {
        $key=$data['user'].'-'.$data['type'];
        $newdata[$key]['items'][$data['day']][]=array('id'=>$data['id'],'timestamp'=>$data['timestamp']);
        $newdata[$key]['user']=$data['user'];
        $newdata[$key]['type']=$data['type'];
}
$newdata=array_values($newdata);

A: Try using uasort with a custom function that sorts on the values of user and type.


text:
Q: Live connection between ArGIS Online and Google Docs Spreadsheet? I want to make a join in ArcGIS Online: From a spreadsheet with names (visitors to an exhibition) to polygons (containing that name).
I succeed to make that in ArcGIS Online: but there is no live connection.
Has anyone already done this?
Do I really need Zapier to make that connection?
We have an organisational account on ArcGIS Online
I have already tried several things:
add an item from cloud drive
within an item: add a layer from the web (.csv spreadsheet)
There is no need to change that spreadsheet from within ArcGIS Online.

A: For live update of data you can use Survey123, when all the entries are over or when you want spreadsheet you can export CVS and your data is updated real-time on the map.


text:
Q: Strange binding permanence between controllers I've got a project in which you write a note in a formulary. Then, you submit that note into an information container (now it's just an array for testing purposes, but it's intended to be a DB later).
The formulary has the following controller:
app.controller('controlFormulario', ['$scope', 'SubmitService', function($scope, submitService) {

  $scope.formData = {
    "titulo":"",
    "texto":"",
    "fecha": new Date()
  };

    $scope.submit = function() {
        var temp = $scope.formData;
        submitService.prepForBroadcast(temp);

    }
// more things we don't need now

... which is bound to this part of the DOM, which is added into it, via a directive:
<form ng-controller="controlFormulario as formCtrl">

 50 }">
            Título
            <input type="titulo" class="form-control"  id="inputTitulo" ng-model="formData.titulo">
             50" id="helpBlock" class="help-block">El título no puede exceder los 50 caracteres.

            Texto
            <textarea class="form-control" id="inputTexto" ng-model="formData.texto"></textarea>

            Fecha
            <input type="fecha" class="form-control" id="fecha" ng-model="formData.fecha" disabled>

            <button  class="btn btn-primary" style="height:35px;width:100px;float:right;"  id="submit"
            ng-disabled="isDisabled()" ng-click="submit()">
            Enviar
            </button>

 0">

{{formData.titulo | limitTo:50}}

{{formData.texto}}

{{formData.fecha | date}}

      </form>

This is my directive (I don't think it's really needed, but just in case):
app.directive('formulario', [function() {
  return {
    restrict: 'E', // C: class, E: element, M: comments, A: attributes
    templateUrl: 'modules/formulario.html',

  };
}]);

I use a service for passing the data between the previous controller, and the note controller (which controls the note objects of the array). This is the service:
app.factory('SubmitService', function($rootScope) {
    var data = {};

    data.prepForBroadcast = function(recvData) {
        data.data = recvData;
        this.broadcastItem();
    };

    data.broadcastItem = function() {
        $rootScope.$broadcast('handleBroadcast');
    };

    return data;
});

... and I receive it in this part of my note controller:
app.controller('noteController', ['$scope', 'SubmitService', function($scope, submitService) {

  var nc = this;

    $scope.$on('handleBroadcast', function() {
        nc.pruebaNota.push(submitService.data);
        $scope.formData.titulo = "";
        $scope.formData.texto= "";
        $scope.formData.fecha = new Date();
    });

// more things, the array, etc...

Ok. This should work, and it does, but something strange happens: as you can see, the preview note is binded with ng-model to the form. That works great, ok. But when I submit the form, the new note object keeps bound to the form (so if I delete the form text, the note appears in blank, and if I write something, it gets automatically updated both in the preview note, and the new note), when there isn't any relation between them. The new note, which appears dynamically on the screen, shouldn't be bound to anything.
Am I doing something wrong? Some help would be really nice!

A: You are forgetting something really important. Memory address. So, the rought idea is something like: imagine that $scope.formData is in the address 123123. You first create a temp var pointing to 123123 then you send it to the service and the service holds the same address 123123 into data.data.
Then in your second controller you say: hey, I want to work with that data.data (AKA your data in 123123) you have SubmitService.
Now when you modify $scope.formData again, you are updating what you have in that 123123 and everything that is "looking" into that address will be updated.
That is the rough idea. To point it simple, you're modifying the same piece of information everywhere.
See it here: http://plnkr.co/edit/zcEDQLHFWxYg4D7FqlmP?p=preview
As a AWolf suggested, to fix this issue, you can use angular.copy like this:
nc.pruebaNota.push(angular.copy(submitService.data));


text:
Q: Chaining Async Methods in WCF Service I'm having a bit of trouble with the Async pattern and chaining methods in a WCF service.  The client is calling up to the WCF asyncronously, then the service method needs to asynchronously open a SOAP proxy and call some methods.
The problem is the nature of the Soap service is sequential, meaning i need one result, before i can get the next and return it to the calling WCF service. I am trying to use the Async pattern, but failing miserably here, because the sequential calls are bottlenecking the other async calls until it completes.
Is there any way to chain these Async SOAP methods, to prevent a bottleneck?
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class DetailsService : IDetailService
{

    public DetailEntity GetDetails(DetailEntity entity)
    {

        TransactionUtilities.GetTransactionDetails(entity);

         // return modified entity with details
        return entity;

    }

}

public static class TransactionUtilities
{
    static SoapClient SoapProxy { get; set; }

    public static void GetTransactionDetails(DetailEntity entity)
    {
        IAsyncResult ar = SoapProxy.BeginExecuteTransaction(loginToken, new AsyncCallback(OnExecuteTransactionEnd), null);
        // will this block other async calls?
        ar.AsyncWaitHandle.WaitOne();
        string transactionId = SoapProxy.EndExecuteTransaction(ar);

        // another async call dependent on above transactionId
        IAsyncResult ar = SoapProxy.BeginGetTransactionResult(loginToken, processId, new AsyncCallback(OnTransactionResultEnd), null);
        ar.AsyncWaitHandle.WaitOne();
        Row[] TransactionResult = SoapProxy.EndGetTransactionResult(ar);

        // do work with result
    }

            // call back methods, just haning out doing nothing
    static void OnExecuteTransactionEnd(IAsyncResult result) { }
    static void OnTransactionResultEnd(IAsyncResult result) { }

}


text:
Q: How to fill a new data frame based on the value and the results of an calculus integrating this very value? For graphical purpose, I want to create a new data frame with two columns.
The first column is the dose of the treatment received (i; 10 grammes up to 200  grammes).
The second column must be filed with the result of a calculus corresponding to the value of the dose received, id est the percentage of patients developing the disease according the corresponding dose which is given by the formula  below:
The dose is extracted from a much larger dataset (data_fcpa) of more than 1 000 rows (patients).
percent_i <- round (prop.table (table (data_fcpa $ n_chir_act [data_fcpa $ cyproterone_dose > i] > 1))[2] * 100, 1)
I know how to create a new data (df) with the doses I want to explore:
df <- data.frame (dose <- seq (10, 200, by = 10))
names (df) <- c("cpa_dose")
> df
   cpa_dose
1        10
2        20
3        30
4        40
5        50
6        60
7        70
8        80
9        90
10      100
11      110
12      120
13      130
14      140
15      150
16      160
17      170
18      180
19      190
20      200

For example for a dose of 10 grammes the result is:
> round (prop.table (table (data_fcpa $ n_chir_act [data_fcpa $ cyproterone_dose > 10] > 1))[2] * 100, 1)
TRUE
11.7

I suspect that a loop is needed to produce an output alike the little example provided below but, I have no idea of how to do it.
 cpa_dose percentage
1      10       11.7
2      20
3      30
4      40

Any suggestion are welcomed.
Thank you in advance for your help.

A: It seems that you are describing a a situation where you want to show predicted effects from a statistical model? In that case, ggeffects is your best friend.
library(tidyverse)
library(ggeffects)

lm(mpg ~ hp,mtcars) %>%
  ggpredict() %>%
  as_tibble()

Btw, in order to answer your question it's required to provide some data and show what you have tried.


text:
Q: How can I set a compiler warning (GNU GCC) when overwriting a weak function Library functions have the weak attribute set by default (see [1]) and could be "overwritten" with functions having the same signature by accident.
For example printf internally calls fputc and I could easily declare one of my functions int fputc(int, FILE *).
If that happens, I would like to receive a compiler warning.
Is there a way to tell the compiler to warn me in case of overwriting a weak function?
[1] https://gcc.gnu.org/onlinedocs/gcc-3.2/gcc/Function-Attributes.html

A: (I am guessing you are on Linux, and compiling and linking your application as usual, in particular with the libc.so dynamically linked)

Library functions have the weak attribute set by default

This is not always true; on my system fputc is not a weak symbol:
% nm -D /lib/x86_64-linux-gnu/libc-2.21.so|grep fputc
000000000006fdf0 T fputc
0000000000071ea0 T fputc_unlocked

(if it was weak, the T would be a W, and indeed write is weak)
BTW, redefining your own fputc (or malloc) is legitimate (and could be useful, but is very tricky), provided it keeps a semantic conforming to the standard. More generally weak symbols are expected to be redefinable (but this is tricky).

Is there a way to tell the compiler to warn me in case of overwriting a weak function?

No (the compiler cannot warn you reliably).
Since the only thing which could give you some warning is not the compiler (which does not know which particular libc would be used at runtime, you might upgrade your libc.so after compilation) but the linker, and more precisely the dynamic linker, that is ld-linux(8). And the warnings could reliably only be given at runtime (because the libc.so might be different at build time and at run time). Perhaps you want LD_DYNAMIC_WEAK.
If you are ready to spend weeks working on a solution, you might consider using GCC MELT with your own MELT extension and customize a recent GCC to emit a warning when a weak symbol from the libc available at compile time (which might not be the same libc dynamically linked at runtime, so such a check has limited usefulness) is redefined.
Perhaps you might use some LD_PRELOAD trick.
Also, if you linked statically your application, the linker could give you diagnostics if you redefine a libc function.
Read also Drepper's How to Write a Shared Library & Levine's Linkers & loaders book.


text:
Q: Circular linked list going in infinite loop I am supposed to do a program which can do polynomial addition/subtraction/multiplication/evaluation using circular linked list.
My multiplication code is going in infinite loop, and I have marked a comment where it is happening (detected with printf statements, removed).
list* poly_mul(list *p1, list *p2) {
  term tmp;
  list *result = malloc(sizeof(list));
  memcpy(result, p1, sizeof(list));
  node *b = p2->head;
  node *r = result->head;
  do {
    do {
      tmp.exp = r->data.exp + b->data.exp;
      tmp.coeff = r->data.coeff * b->data.coeff;
      unsigned int add_term = 1;
      node *c = result->head;
      do {
        if(c->data.exp == tmp.exp) {
          c->data.coeff += tmp.coeff;
          add_term = 0;
          break;
        }
        c = c->next;
        //Here it goes in infinite loop
      } while(c != result->head);
      if(add_term)
        node_add(result, &tmp);
      b = b->next;
    } while(b != p2->head);
    r = r->next;
  } while(r != result->head);
  return result;
}

The structures used are here:
typedef struct {
  int exp;
  int coeff;
} term;

typedef struct node {
  term data;
  struct node *next;
} node;

typedef struct {
  node *head;
  node *tail;
  unsigned int count;
} list;

And this is the code in main:
void main() {
  list p1, p2, *p3;
  p1.count = p2.count = 0;
  poly_create(&p1);
  p3 = poly_mul(&p1, &p2);
  poly_print(p3);
}

void poly_create(list *l) {
  int i, n;
  printf("\nEnter number of terms in the polynomial: ");
  scanf("%d", &n);
  for(i = 1; i <= n; i++) {
    printf("\nEnter details for term %d: ", i);
    term_append(l);
}

void node_add(list *l, term *t) {
  node *tmp = malloc(sizeof(node));
  memcpy(&tmp->data, t, sizeof(term));
  if(l->count == 0) {
    l->head = tmp;
    l->tail = tmp;
    tmp->next = tmp;
  }
  else {
    l->tail->next = tmp;
    tmp->next = l->head;
    l->tail = tmp;
  }
  l->count++;
}

void term_append(list *l) {
  term t;
 enter:
  printf("\nEnter term as <coefficient>,<exponent>: ");
  scanf("%d,%d", &t.coeff, &t.exp);
  if(!t.coeff) {
    printf("\nCoefficient is zero, reenter term");
    goto enter;
  }
  if(l->count >= 1) {
    node *i = l->head;
    do {
      if(i->data.exp == t.exp) {
        printf("\nExponent %d was already entered, reenter term", t.exp);
        goto enter;
      }
      i = i->next;
    } while(i != l->head);
    node_add(l, &t);
  }
  else
    node_add(l, &t);
}

Please get me a solution for this problem, I've been trying to solve this for the past three hours.

A: Why is it going into an infinite loop?  You can find out by using a debugger and stepping through the code.  Just put a breakpoint at the appropriate place and you should be able to find it yourself. In all likelihood, you have a loop in your linked list.
You can check for loops in your linked list with two pointers.  The first one (tail) point to the start of your list.  The second (head) points to the second element of your list.  Loop till head is past the last element (I have those pointed to NULL, not head) by incrementing both head and tail by one.  If at any point tail > head, you have a loop.

A: What happens if you printf("%d",(int) c); at each iteration? I suspect that result->head is pointing to a node which is pointing to a member of the linked list, but is not in the linked list itself.
Potential test: Add a int seen to each member of the list and increment it on each member as you loop for a given number of nodes (something excessively high such as INT_MAX) and, when the loop stops, see if result->head->seen > 0:
typedef struct node {
  term data;
  struct node *next;
  // to be removed later
  int seen;
} node;

// place this before you get the infinite loop
unsigned int i = 1;
c->seen = 0;
do
{
    c = c->next;
    c->seen = i;
// replace INT_MAX with some number which is greater than the maximum list length
} while(++i <= INT_MAX);
// this should be roughly equal to i (might be off by 1).
// I'll bet it isn't though!
printf("result->head->seen = %d", result->head->seen);

A: One possible cause: you're never creating p2. Are you missing a line like this in your main function:
poly_create(&p2);

?


text:
Q: Unity3d AdMob rewarded ad not showing I am doing some simple app with two buttons... first button is sending request for Awarded (test) ad and then second shows the ad.
Here is my code:
using GoogleMobileAds.Api;
using UnityEngine;
using System;

public class adManager : MonoBehaviour
{
    RewardBasedVideoAd rewardedAd;

    public void Start()
    {
        rewardedAd = RewardBasedVideoAd.Instance;
        requestVideo();
    }

    public void requestVideo()
    {
        Debug.Log("Video Requested!");
        string adID = "My ad ID";
        AdRequest request = new AdRequest.Builder()
            .AddTestDevice(AdRequest.TestDeviceSimulator)       // Simulator.
            .AddTestDevice("BD6E7C35B6F8FA70")  // My test device.
            .Build();

        rewardedAd.LoadAd(request, adID);
    }

    public void showBannerAd()
    {
        if (rewardedAd.IsLoaded())
        {
            Debug.Log("AdAvailible!");
            rewardedAd.OnAdRewarded += HandleOnAdRewarded;
            rewardedAd.Show();
        }
        else
        {
            Debug.Log("AdNotAvailible!");
        }
    }

    public void HandleOnAdRewarded(object sender, EventArgs args)
    {
        Debug.Log("You are rewarded!");
    }

    public event EventHandler<Reward> OnAdRewarded;
}

Is something wrong with my code or something else?
I tried interstitial and banner ad and they WORKED.
Thanks for help.


text:
Q: How to do Database Execution while deploying War I don't know but Is this possible to do the following?
I have a situation, where I have to retrieve data from Ldap and put those in MySQL database using Hibernate.
This would be a one time execution. I don't need to get the data from Ldap periodically.
In this situation, is that possible to do the above mentioned procedure at the time of the deployment of the Application?
If possible? Can I have a simple Example of the solution?
Please Help.
Alternative Solution to the problem is also welcome.
Thanks in advance.

A: Hoping you are using a servlet container.
Use a ServletContextListener interface and plug this into the web.xml as a listener.
 public class MyClass implements ServletContextListener {
    .... Query LDAP
    .... Insert into DB
 }

Note that no exceptions must be thrown to MyClass because ContextListener architecture is not expecting it to happen, and application wont startup.


text:
Q: Unable to show multiple location on google map I'm trying to pass my address via intent.putExtra() from other activity to MapActivity  and inside the MapActivity i have done the Geocode. It has no error but when I run, it doesn't show the location. Can anyone tell me what am I missing or do wrong?
FYI: I have already pass the address from Listview Activity to DisplayItem activity (It works). Now i want to pass it to MapActivity
Bellow is my other activity (ListViewActivity)
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent = new Intent(ShoppingMall.this, Displayitem.class);
            if (adapter.getItem(position).length > 0) {

                intent.putExtra(Displayitem.EXTRA_ADDRESS, adapter.getItem(position)[4]);
                intent.putExtra(MapsActivity.EXTRA_ADDRESS, adapter.getItem(position)[4]);

            }

            startActivity(intent);
        }
    });

I want to put
intent.putExtra(MapsActivity.EXTRA_ADDRESS, adapter.getItem(position)[4]);

into this
    @Override
public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();
    //noinspection SimplifiableIfStatement
    if (id == R.id.myMap) {
        Intent intent = new Intent(ShoppingMall.this,MapsActivity.class);
        //Intent.putExtra

        startActivity(intent);
    }

    return super.onOptionsItemSelected(item);
}

This is my MapActivity
public static final String EXTRA_ADDRESS ="address";
private Bundle extras;
List<Address> location;
double lati, lon ;
.
.
.
.

private void getAddress(GoogleMap googleMap)  {

   try {
       mMap = googleMap;

       Intent intent = getIntent();
       extras = intent.getExtras();
       Geocoder geocoder = new Geocoder(this);
       String address = extras.getString(this.EXTRA_ADDRESS);
       location = geocoder.getFromLocationName(address, 1);
       if (location.size() > 0) {
           lati =location.get(0).getLatitude();
           lon =location.get(0).getLongitude();
           MarkerOptions options = new MarkerOptions()
                   .title("")
                   .position (new LatLng(lati, lon));
           mMap.addMarker(options);
       }

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

   }
}
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    getAddress(googleMap);
    setUpMap();

}

ps: Newbie in android

A: Try this....
Intent intent = new Intent(ShoppingMall.this, Mapactivity.class);
            if (adapter.getItem(position).length > 0) {

                intent.putExtra(Displayitem.EXTRA_ADDRESS, adapter.getItem(position)[4]);
                intent.putExtra(MapsActivity.EXTRA_ADDRESS, adapter.getItem(position)[4]);

            }

            startActivity(intent);

A: private void addMarkersToMap() {
    mMap.clear();
    for (int i = 0; i < private void addMarkersToMap() {
mMap.clear();
for (int i = 0; i < location.size(); i++) {
        LatLng ll = new LatLng(location.get(i).getPos().getLat(), location.get(i).getPos().getLon());
        BitmapDescriptor bitmapMarker;
        switch (location.get(i).getState()) {
        case 0:
            bitmapMarker = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED);
            Log.i(TAG, "RED");
            break;
        case 1:
            bitmapMarker = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN);
            Log.i(TAG, "GREEN");
            break;
        case 2:
            bitmapMarker = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE);
            Log.i(TAG, "ORANGE");
            break;
        default:
            bitmapMarker = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED);
            Log.i(TAG, "DEFAULT");
            break;
        }
        mMarkers.add(mMap.addMarker(new MarkerOptions().position(ll).title(location.get(i).getName())
                .snippet(getStateString(location.get(i).getState())).icon(bitmapMarker)));

        Log.i(TAG,"Car number "+i+"  was added " +mMarkers.get(mMarkers.size()-1).getId());
    }
}


text:
Q: How do I get a PHP file to automatically run itself? I have a PHP file, x.php, that outputs b.xml every time it is run. The way I do this is by using crontab to run the x.php file. The problem is that due to the server's settings, the new file has permissions of 400. So I also have another crontab line to change file b.xml permissions to 777 so that x.php can run over it next time.
I feel like I am making this too complicated. Is there any way to make this a bit simpler?

A: Quick Answer
You'll need to chmod the file to be 777 in the x.php script.
After b.xml has been created, run this line:
chmod('path/b.xml', 0777);

Note you should always specify octals when using chmod.
A better way?
When you run a cron job, you should take special note of the user that is running the cronjob.
Generally on a shared server you will have your own login and thus the cron job runs as that user. My question to you - is that user the same as your web server? often php runs as "apache" and cron might be running as "tanner". In that case, setting b.xml to be owned by tanner, and having a permissions 400 means that only tanner can change the file.
To solve this, if you don't have access to umask, one way would be to change your cron job to run as the webserver:
su -c "php /home/jonathan/public_html/b.php" apache
This may or may not work depending if you are allowed to switch to apache as the user. do not forget to switch apache to the actual web servers username.
Now, if that doesn't work, then the alternative is to go for the 777 permissions. Keep in mind on a shared server this means anyone on that server could potentially get to that file if they knew the path.
Another way as suggested by OP:
0,10,20,30,40,50 * * * * /usr/bin/wget http://example.com/user/x.php
This way will always run as the apache (or whatever) user that apache runs as, ensuring the next time it is accessed, the file will be useable.

A: This should work:
// set permission
chmod('path/to/b.xml', 777);

// do other stuff

A: Ask the server admin to create a new user who owns the folder where the script writes the xml file.
Run your php script through your cron job as such user. If you run your script as the folder's owner you might change the permissions through your php script.

A: To solve this issue, I ended up just creating a cronjob such as this:
0,10,20,30,40,50 * * * * /usr/bin/wget http://example.com/user/x.php

This executed the file which created b.xml and since the user who executed the script was public, the permissions remained public as well.


text:
Q: Finding limit supremum While  finding the limit supremum of $5x\cos(πx) - x^2$, the book says it is $-\infty$. But this function is bounded above. Shouldn't it's supremum be the lowest upper bound(which is 6). Why does it say it's supremum is $-\infty$ ?

A: Note that $f(x)=5x\cos(πx) - x^2$ is continuos and

*

*$\lim_{x\to \pm \infty} f(x)=-\infty$

then by EVT the function has maximum and is bounded from above.


text:
Q: Simplifying Expression in Mathematica How do I simplify this expression (a result i obtained from previous calculations)
Zin = (R1^2 + R1*RL + 2*L1*R1*s + L1*RL*s + L1^2*s^2 - M^2*s^2)/( R1 + RL + L1 s)

to
Zin = R1 + s*L1 - (s*M)^2/(R1 + RL + s*L1)

I've tried Apart, Cancel, Simplify, FullSimplify, and I can't figure out how to manipulate the equation to get it in the meaningful form I'm looking for.
Edit
Proof they are identical (after correction) -thank you @bill s
Zin = (R1^2 + R1*RL + 2*L1*R1*s + L1*RL*s + L1^2*s^2 - M^2*s^2)/(R1 + RL + L1 s);

Z2 = R1 + s*L1 - (s*M)^2/(R1 + RL + s*L1);

FullSimplify[Zin == Z2]

True

A: The reason it won't simplify to that expression is because they are not equal. Here are your two expressions:
z1 = (R1^2 + R1*RL + 2*L1*R1*s + L1*RL*s + L1^2*s^2 - M^2*s^2)/(R1 + RL + L1 s);
z2 = R1 + s*L1 + (s*M)^2/(R1 + RL + s*L1)
FullSimplify[z1 == z2]
(M s)/(R1 + RL + L1 s) == 0

They are only equal if M s = 0!

A: Collect[Zin, (s*M)^2, Simplify]

$$\text{R1}+ \text{L1} s -\frac{M^2 s^2}{\text{R1}+\text{RL}+\text{L1} s}$$


text:
Q: Does Realm automatically download all synced Realms? Let's say I have a Realm containing 50 custom objects on my server. If I sync to this Realm on a new client, will the entire Realm be downloaded from the server?
For some context, one feature of the app I'm developing is a chat platform, and I'm trying to figure out the best way to store the associated conversations and messages. Ideally I'd like to have one Realm for all conversations, where the only conversations that would be synced down to the user's device are ones that involve that user.

A: Realm won't download all synced Realms, only the ones you explicitly open. However, the contents of each synced Realm you open will be downloaded in their entirety.
The ability to retrieve only a subset of objects within a synced Realm is a feature we hope to build out in the future.