text:
Q: Install Filebeat locally or in the VM? I recently started learning ELK and I succeed to parse my XML files locally. But now I would like to have access to my server to get access to all of my XML files (upgrade every 30 seconds)
I have the ip-address of my server and my question is: should I install Filebeat locally and configure my filebeat.yml to get access to the server or I should install the Filebeat in the server and then indicate my locally address?

A: Filebeat is a shipper, which collects, aggregate and forward logs to your desired output (logstash, elasticsearch etc).
It works as an agent, so you need to install it in every node from which you want to collect logs from. For instance, if you want to collect logs from your local machine then install filebeat there, if you want to collect from logstash server itself, then install filebeat there. If you want to collect log from both, then filebeat needs to be installed in  both machines. and use logstash as an output,
have a look at this illustration,

A: But when I tried to install filebeat on my server using

curl -L -O elastic.co/downloads/beats/filebeat/filebeat-6.3.1-amd64.deb

I get this message:

Could not resolve host: www.elastic.co; Name or service not known

The OS version of the server is : Linux version 3.10.0-693.17.1.el7.x86_64


text:
Q: How to get Google Location API I request the current location when I initialize the app, but it is not working. The map starts and it has nothing requested. Can anyone please solve this?
Here is my code:
package com.example.leonardo.myapplicationmap;
import android.app.Dialog;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import java.io.IOException;
import java.util.List;

public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

    GoogleMap mGoogleMap;
    GoogleApiClient mGoogleApiCliente;

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

        if (googleServicesAvailable()) {
            Toast.makeText(this, "Play Services compativel", Toast.LENGTH_LONG).show();
            setContentView(R.layout.activity_main);

            initMap();

        } else {
           /* Toast.makeText(this, "Play Services incompativel", Toast.LENGTH_LONG).show();
            setContentView(layout.activity_main);*/
        }
    }

    private void initMap() {
        MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.mapFragment);
        mapFragment.getMapAsync(this);

    }

    public boolean googleServicesAvailable() {
        GoogleApiAvailability api = GoogleApiAvailability.getInstance();
        int isAvailable = api.isGooglePlayServicesAvailable(this);
        if (isAvailable == ConnectionResult.SUCCESS) {
            return true;
        } else if (api.isUserResolvableError(isAvailable)) {
            Dialog dialog = api.getErrorDialog(this, isAvailable, 0);
            dialog.show();
        } else {
            Toast.makeText(this, "Não foi possível conectar ao Play Services", Toast.LENGTH_LONG).show();
        }
        return false;

    }

    private void goToLocationZoom(double lat, double lng, float zoom) {
        LatLng ll = new LatLng(lat, lng);
        CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, zoom);
        mGoogleMap.addMarker(new MarkerOptions().position(ll).title("I am here!"));
        mGoogleMap.moveCamera(update);

    }

    public void geoLocate(View view) throws IOException {
        EditText et = (EditText) findViewById(R.id.et);
        String location = et.getText().toString();

        Geocoder gc = new Geocoder(this);

        List<Address> list = gc.getFromLocationName(location, 1);
        Address address = list.get(0);
        String locality = address.getLocality();

        Toast.makeText(this, locality, Toast.LENGTH_LONG).show();

        double lat = address.getLatitude();
        double lng = address.getLongitude();
        goToLocationZoom(lat, lng, 15);

    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mGoogleMap = googleMap;
        //goToLocationZoom(-23.6479053,-46.5756496,17);

  /*      if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
        }
        mGoogleMap.setMyLocationEnabled(true);*/
        mGoogleApiCliente = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();

        mGoogleApiCliente.connect();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.mapTypeNone:
                mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NONE);
                break;
            case R.id.mapTypeNormal:
                mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
                break;
            case R.id.mapTypeTerrain:
                mGoogleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
                break;
            case R.id.mapTypeSatellitee:
                mGoogleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
                break;
            case R.id.mapTypeHybrid:
                mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    LocationRequest mLocationRequest;

    @Override
    public void onConnected(Bundle bundle) {
        mLocationRequest = LocationRequest.create();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setInterval(1000);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                return;
            }
        }

        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiCliente, mLocationRequest, this);

    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Toast.makeText(this, "Sem coneção", Toast.LENGTH_LONG).show();
    }

    @Override
    public void onLocationChanged(Location location) {
        if(location == null){
            Toast.makeText(this, "Sem posição atual", Toast.LENGTH_LONG).show();
        } else {
            LatLng ll =new LatLng(location.getLatitude(), location.getLongitude());
            CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll,17);
            mGoogleMap.animateCamera(update);

        }

    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: rewrite file to wordpress I have in my plugin dir a endpoint.php and need to rewrite like this:
http://domain.com/API/endpoint.php

This is the code I've used:
add_rewrite_rule( 'API/endpoint.php', 'myplugin-path/endpoint.php', 'top' );

When I print the $wp_rewrite global I got this:
[non_wp_rules] => Array
    (
        [API/endpoint.php] => http://mydomain/myplugin-path/endpoint.php
    )

But still not work, any Ideas?

A: Wordpress rewrite mechanism works in a different way, not like .htaccess rewrite rules. More information about it you can find in codex (Rewrite API, WP_Rewrite, etc.). But fast work around could be the following:
First of all we need to register our query var and rewrite rule:
function myplugin_add_query_var( $vars ) {
    $vars[] = 'myplugin_api';
    return $vars;
}
add_filter( 'query_vars', 'myplugin_add_query_var' );

function myplugin_update_rewrite_rules( $rules ) {
    $newrules = array();
    $newrules['api\/endpoint\.php$'] = 'index.php?pagename=api&myplugin_api=1';
    return $newrules + $rules;
}
add_filter( 'rewrite_rules_array', 'myplugin_update_rewrite_rules' );

To complete registration of rewrite rule, we need to flush rules on activation/deactivation of you plugin:
function myplugin_activate() {
    flush_rewrite_rules();
}
register_activation_hook( __FILE__, 'myplugin_activate' );

function myplugin_deactivate() {
    flush_rewrite_rules();
}
register_deactivation_hook( __FILE__, 'myplugin_deactivate' );

A piece of magic to make rewrite rules working correctly :D
function myplugin_a_piece_of_magic_on_init() {
    global $wp_rewrite;
    $wp_rewrite->use_verbose_page_rules = !preg_match( "/api\/endpoint\.php$/i", $_SERVER['REQUEST_URI'] );
}
add_action( 'init', 'myplugin_a_piece_of_magic_on_init' );

And finally check if our query var presents on wp action:
function myplugin_check_query_var( $wp ) {
    if ( array_key_exists( 'myplugin_api', $wp->query_vars ) ) {
        // do api stuff here ...
        exit;
    }
}
add_action( 'wp', 'myplugin_check_query_var' );


text:
Q: output deeply nested json associations I've got a rails3 app with the following structure

Users
  has_many :tasks
  has_many :staff
  has_many :managers

Tasks
  has_one :location

Locations
  has_many :staff
  has_one :manager

Staff
  belongs_to :users
  belongs_to :location

Managers
  belongs_to :users
  belongs_to :location

Now in my json output, I'm trying to get a the User, their tasks, each task location, and the locations staff and manager.
I've got

 @User = User.find(params[:id], :include{:tasks=>:location})

This outputs the user and locations of the tasks, but not the tasks themselves.
And any further includes I attempt to add, result in an error for example

@User =  User.find(params[:id], :include{:tasks=>:location=>:staff})

I get an error of "unexpected tASSOC, expecting }.
What is the correct way to write this so I get all the associated data for this user?

A: You should be able to get the user and associated objects using this command:
@user = User.includes(:tasks => {:location => :staff}).find(params[:id])

You'll see a few queries execute. The first will retrieve the user, the second the related tasks, the third the related locations and the fourth the related staff. You'll notice that no queries execute when you type any of the following:
@user.tasks.first.location.staff
@user.tasks.first.location
@user.tasks.first


text:
Q: Why does Go think that this structure does not adhere to this interface? Let's say I set up two Go interfaces and implement them as follows:
type fooInterface interface {
    buildBar() barInterface
}

type barInterface interface {
    stuff()
}

type fooStruct struct{}
type barStruct struct{}

func (*fooStruct) buildBar() *barStruct {
    return &barStruct{}
}

func (*barStruct) stuff() {}

As soon as I try to assign fooStruct to a fooInterface variable, I get the following error:
cannot use fooStruct literal (type *fooStruct) as type fooInterface in assignment:
*fooStruct does not implement fooInterface (wrong type for buildBar method)
    have buildBar() *barStruct
    want buildBar() barInterface

Naturally, I can modify buildBar() in fooStruct to return a barInterface and it will work. However, I'm curious as to why Go does not notice that *barStruct adheres to barInterface in this case, especially since this would work in a language like Java (likely because Java interfaces are explicitly implemented).
Go playground example: https://play.golang.org/p/84zymo-YnM

A: Function type in go is not covariant, and not contravariant.
So to be assignable the signature must match exactly.
References:

*

*https://golang.org/ref/spec#Assignability


text:
Q: Can a forEach lambda result in a race condition? I am unsure of how lambdas work in practice, and I am concerned since under certain circumstances, lambdas can result in errors such as ConcurrentModificationExceptions if you use them incorrectly, which seems to be indicative of a race condition.
Consider the code below.
private class deltaCalculator{
    Double valueA;
    Double valueB;

    //Init delta
    volatile Double valueDelta = null;

    private void calculateMinimum(List<T> dataSource){
        dataSource.forEach((entry -> {
            valueA = entry.getA();
            valueB = entry.getB();
            Double dummyDelta;

            dummyDelta = Math.abs(valueA - valueB);

            if(valueDelta == null){
                setDelta(dummyDelta);
            }else {
                setDelta((valueDelta > dummyDelta) ? dummyDelta : valueDelta);
            }
        }));
    }

    private void setDelta(Double d){
        this.valueDelta = d;
    }
}

How does the forEach loop operate? Do different calls get passed to different threads where the JVM considers it appropriate, opening up the possibility of a race condition that could lead to incorrect minimum calculation?
If not, why can a forEach lambda throw a ConcurrentModificationException?

A: You'll get a ConcurrentModificationException if you try to modify the collection that you're iterating over while the for each loop runs. This could be done in a separate thread entirely, but much more commonly occurs when you try to modify the collection in the loop body.

Do different calls get passed to different threads where the JVM considers it appropriate, opening up the possibility of a race condition that could lead to incorrect minimum calculation?

No. No multithreading is taking place in your example above.


text:
Q: Akka HTTP Connection Pool Hangs After Couple of Hours I have an HTTP Connection Pool that hangs after a couple of hours of running:
private def createHttpPool(host: String): SourceQueue[(HttpRequest, Promise[HttpResponse])] = {
    val pool = Http().cachedHostConnectionPoolHttps[Promise[HttpResponse]](host)
    Source.queue[(HttpRequest, Promise[HttpResponse])](config.poolBuffer, OverflowStrategy.dropNew)
      .via(pool).toMat(Sink.foreach {
        case ((Success(res), p)) => p.success(res)
        case ((Failure(e), p)) => p.failure(e)
      })(Keep.left).run
  }

I enqueue items with:
private def enqueue(uri: Uri): Future[HttpResponse] = {
    val promise = Promise[HttpResponse]
    val request = HttpRequest(uri = uri) -> promise

    queue.offer(request).flatMap {
      case Enqueued => promise.future
      case _ => Future.failed(ConnectionPoolDroppedRequest)
    }
}

And resolve the response like this:
private def request(uri: Uri): Future[HttpResponse] = {
    def retry = {
      Thread.sleep(config.dispatcherRetryInterval)
      logger.info(s"retrying")
      request(uri)
    }

    logger.info("req-start")
    for {
      response <- enqueue(uri)

      _ = logger.info("req-end")

      finalResponse <- response.status match {
        case TooManyRequests => retry
        case OK => Future.successful(response)
        case _ => response.entity.toStrict(10.seconds).map(s => throw Error(s.toString, uri.toString))
      }
    } yield finalResponse
}

The result of this function is then always transformed if the Future is successful:
def get(uri: Uri): Future[Try[JValue]] = {
  for {
    response <- request(uri)
    json <- Unmarshal(response.entity).to[Try[JValue]]
  } yield json
}

Everything works fine for a while and then all I see in the logs are req-start and no req-end.
My akka configuration is like this:
akka {
  actor.deployment.default {
    dispatcher = "my-dispatcher"
  }
}

my-dispatcher {
  type = Dispatcher
  executor = "fork-join-executor"

  fork-join-executor {
    parallelism-min = 256
    parallelism-factor = 128.0
    parallelism-max = 1024
  }
}

akka.http {
  host-connection-pool {
    max-connections = 512
    max-retries = 5
    max-open-requests = 16384
    pipelining-limit = 1
  }
}

I'm not sure if this is a configuration problem or a code problem. I have my parallelism and connection numbers so high because without it I get very poor req/s rate (I want to request as fast possible - I have other rate limiting code to protect the server).

A: You are not consuming the entity of the responses you get back from the server. Citing the docs below:

Consuming (or discarding) the Entity of a request is mandatory! If
  accidentally left neither consumed or discarded Akka HTTP will assume
  the incoming data should remain back-pressured, and will stall the
  incoming data via TCP back-pressure mechanisms. A client should
  consume the Entity regardless of the status of the HttpResponse.

The entity comes in the form of a Source[ByteString, _] which needs to be run to avoid resource starvation.
If you don't need to read the entity, the simplest way to consume the entity bytes is to discard them, by using
res.discardEntityBytes()

(you can attach a callback by adding - e.g. - .future().map(...)).
This page in the docs describes all the alternatives to this, including how to read the bytes if needed.
--- EDIT
After more code/info was provided, it is clear that the resource consumption is not the problem. There is another big red flag in this implementation, namely the Thread.sleep in the retry method.
This is a blocking call that is very likely to starve the threading infrastructure of your underlying actor system.
A full blown explanation of why this is dangerous was provided in the docs.
Try changing that and using akka.pattern.after (docs). Example below:
def retry = akka.pattern.after(200 millis, using = system.scheduler)(request(uri))


text:
Q: How to get time change broadcast even if app closed i have an app and it's important for me to detect time changes. so far i have receiver with proper intent filters like this:
<receiver
  android:name=".MyReceiver"
  android:enabled="true"
  android:exported="true">
  <intent-filter>
    <action android:name="android.intent.action.TIME_SET" />
    <action android:name="android.intent.action.ACTION_TIME_CHANGED" />
    <action android:name="android.intent.action.DATE_CHANGED" />
  </intent-filter>
</receiver>

and this is my receiver :
public class MyReceiver extends BroadcastReceiver {
    public MyReceiver() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        SharedPreferences.Editor spe =PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext()).edit();
        spe.putLong("UFCount", 1));
        spe.putLong("FCount", 1));
        spe.commit();
        Toast.makeText(context.getApplicationContext(), "Your job is being done!!", Toast.LENGTH_LONG).show();
    }
}

this receiver only works when the app is open\in-the-background . how can i make this receiver to work even if the app is closed?

A: Since the application is closed, there is no UI (i.e. no Activity) to display the Toast. At this point, there should be an exception in Logcat. You might also add a logcat trace before displaying the Toast, like Log.d("MyReceiver", "in onCreate()"); and you should see it even when the app is closed.
Instead of displaying a Toast, you could for instance send a local notification, which is allowed because it does not require an Activity from your app.


text:
Q: Zorin OS on booting Displays Ubuntu Black Screen, how to get out of it? If I can't how to take a backup of my Data? I installed Zorin OS on my old laptop a few months back, but yesterday after boot it started showing a black screen and a basic command line to interact with - BusyBox built in shell ash. From what I could infer from searching the errors, I think it is some sort of memory fault which I don't completely understand. How do I recover my data? Data recovery is my first priority. Any thing that I can try?

Any help is appreciated.


text:
Q: What are the risks of changing the name of a SQL Server table, temporarily using an empty dummy table, and then changing it back? In order to solve an issue. I need to check what happens when a table has no rows. My plan:

*

*Take table 'Foo' --> script table as --> New Query Editor Window --> save as 'FooCopy'

*rename table 'Foo' to 'FooOriginal'

*rename the empty 'FooCopy' to 'Foo'

*Test what I need to test

*Rename 'Foo' to 'FooCopy'

*Rename 'FooOriginal' to 'Foo'

*drop 'FooCopy'

Can this influence a Microsoft Access application, stored procedures, or something along those lines, or would this be relatively safe? (assuming I am the only person using the DB)

A: Make sure that FooOriginal does not already exist or the rename table 'Foo' to 'FooOriginal' will fail as will the following rename and the test will be made on the original Foo Table.

A: Assuming you're the only one using the DB, it seems rather safe to test it like that. But it feels like a dirty fix. It might be better to copy the table first. Just to be sure.


text:
Q: spark parallelize(List(1,2,3,4),2) always partition the list in order? I've run the code below and the result is 37.
val z = sc.parallelize(List(1,2,7,4,30,6), 2)
z.aggregate(0)(math.max(_, _), _ + _)
res40: Int = 37

It seems that spark partitions the list into 2 lists:[1,2,7] , [4,30,6].
Then I changed the order of 7 and 4 in the list and I got 34.
scala> val z = sc.parallelize(List(1,2,4,7,30,6), 2)
z: org.apache.spark.rdd.RDD[Int] = ParallelCollectionRDD[18] at parallelize at <console>:24

scala> z.aggregate(0)(math.max(_, _), _ + _)
res11: Int = 34

What I want to know is if spark always keeps the order of the elements in the list when partitioning?
Thanks!

A: There are two different concepts here.

*

*Order of items which is persevered when using parallelize and applying transformations which don't require shuffling.

*Order of items during aggregation which is not preserved and is non deterministic. While each partition is aggregated sequentially order of merging partial result is arbitrary.

In general don't depend on the order of values and operations unless you enforce it explicitly (for example by sorting) or you know exactly what you're doing.


text:
Q: compilation fatal error boost/filesystem when running make

g++ -pedantic -Wall -W -g pkg-config --cflags --libs liblog4cxx
  dbus-c++-1 -DDOUANE_VERSION=\"0.9.0\" -o freedesktop/desktop_file.o
  -c freedesktop/desktop_file.cpp In file included from freedesktop/desktop_file.cpp:1:0: freedesktop/desktop_file.h:5:37:
  fatal error: boost/filesystem/path.hpp: No such file or directory
  compilation terminated. Makefile:36: recipe for target
  'freedesktop/desktop_file.o' failed make: ***
  [freedesktop/desktop_file.o] Error 1

getting this, Im on a distro with XFCE environment, as I searched the freedesktop/desktop_file.cpp has to do with the XFCE. But the main problem is line

boost/filesystem/path.hpp

A: the solution given by https://stackoverflow.com/a/25770596/1320686
sudo apt-get install libboost-dev


text:
Q: Specify Indexes on node properties during neo4j-import Is it possible in using the neo4j import tool to specify properties of nodes that will need an index created on them?  Currently, I import then run a set of Create Index on :somelable(someproperty) statements, but this isn't the fastest with large data sets.

A: The answer is no, as of v2.2.3.  When you use the super fast import tool (neo4j-import), you must setup Indexes once you've imported the nodes and relationships.


text:
Q: Disable auto sleep and monitor turning off from C++ code I develop [cross-platform C++ Qt-based] application which plays video using libVLC. When i watch video for a long time, my monitor is going to turn off according with power management settings. I want to disable auto turning off while video is playing as it is in Totem, VLC media player and other Ubuntu media players. But i can't find how to do this from C++ code using Ubuntu libraries.
For example, under Windows i can do that using:
SetThreadExecutionState( ES_DISPLAY_REQUIRED | ES_SYSTEM_REQUIRED | ES_CONTINUOUS );

Everything i found about Linux/Ubuntu is how to patch some config files. I can't do this from code:

*

*User that run app obiously may have no rights to edit configs

*Power settings must be restored anyway when video stops but if my app suddenly crashed it will not happen

*Different Ubuntu versions may have different config files and entries

So my questions:

*

*is there a some Ubuntu (or Qt and libVLC) library functions which suppress monitor turning off and system sleep?

*how popular Ubuntu video players implements such behaviour?

A: I would recommend you to have a look at the code of xset, a tool that's part of X.org, or any other program that can already do these things you want to do (you can disable the screen turning off with xset -dpms + xset s off).
In the case of xset, you'll find the source code here, or for when that link will be outdated:
http://www.x.org/releases/current/
-> Source Tar Files for X11RX.Y
-> app/
-> xset-x.y.z.tar.{bz2,gz}


text:
Q: org.apache.solr.common.SolrException: Document is missing mandatory uniqueKey field: id While indexing a MySQL database table with Apache Solr, I received the following error:
org.apache.solr.common.SolrException: Document is missing mandatory uniqueKey field: id

What does this mean?  How can I fix it?
Thank you.

A: This means that Solr is trying to index a document which doesn't have a field id specified. In your schema.xml you have defined an uniqueKey field, every document indexed by Solr needs such an id to be indexed.

A: One of the reason must be In Solr there should not be id field as int. It should always be string. I got same problem because I defined id field as integer instead of string.

A: I had this same error. My table name was voter and i used voterid as as a unique id . But after I changed the column name voterid as id it worked for me.
This is my data-config.xml
<dataConfig>
  <dataSource type="JdbcDataSource"
            driver="com.mysql.jdbc.Driver"
            url="jdbc:mysql://localhost/test"
            user="root"
            password="root" />
  <document name="voter">
    <entity name="voter" query="select *  from voter;" >
 <field column="id" name="id"/>
   <field column="voter_name" name="voter_name"/>
<field column="age" name="age"/>
</entity>
  </document>
</dataConfig>

Schema.xml File(I added 2 field , id was already present in the file)

<field name="voter_name" type="string" indexed="true" stored="true"/>
<field name="age" type="int" indexed="true" stored="true"/>
<field name="id" type="string" indexed="true" stored="true"/>


text:
Q: Using @casl/mongoose & mongoose-paginate-v2 together I am trying to use @casl/mongoose with mongoose-paginate-v2 in my express.js app, but the problem is that both libs must be used on the model object.
  // trying this
  const results = await Person
      .accessibleBy(req['ability'])
      .paginate({}, options);

  // or this, the same problem
  const results = await Person
      .paginate({}, options)
      .accessibleBy(req['ability']);

In both ways, I got either accessibleBy/paginate is not a function because as I said both libs must be used on the model (in my case Person) object.
Any help or suggestion is highly appreciated.

A: @casl/mongoose supports statics and query methods of mongoose. so, you can do this:
Person.findOne({ _id: id }).accessibleBy(ability).where({ createdAt: { $lt: new Date() } })

// or
Person.accessibleBy(ability).findOne({ _id: id }).where({ createdAt: { $lt: new Date() } })

At the same time pagination plugin supports only static method because it sends multiple queries to db, so it's (probably) impossible to achieve what you want. Either talk to the author of that package and ask him to do smth with that or just write own pagination plugin


text:
Q: click on add to list button get items added to list box from textbox and radio in javascript I have two forms,In form1 when user select radio button,enter value in text box and clicks on add to list button the (text of radio button+value of text box) should get added to a listbox in form2.
I wrote javascript function to add items and included the script in both forms i.e in form1 the function gets triggered for onclick event of add to list button and in form2 in body tag onload event.
But it is not working,can anyone help in this regard as i am new to javascript.
Form1:
<form name="orderform">
    Category:
 <input type="radio" name="category" id="category" value="0">Apple</input>
 <input type="radio" name="category" id="category" value="1">Orange</input>
 <input type="radio" name="category" id="category" value="2">Banana</input>
 <input type="radio" name="category" id="category" value="3">Guava</input>

 Item: <input type="text" length="30" name="item" id="item"/>

 <input type="button" name="add" value="Add to List" onClick="addItem_list()"/>
 </form>

Form2:

        <form name="items">
            Items <SELECT name="item_list" id="item_list">
                <option value="">Select item</option>
            </SELECT>

Javascript:
function addItem(selectbox,text,value )
{
    var item = document.createElement("OPTION");
    item.text = text;
    item.value = value;
    selectbox.options.add(item);
}

function addItem_list(){
    var it=document.orderform.item.value; //getting item value from textbox
    //To determine which radio button has been selected:
    for (var i=0; i<document.orderform.category.length; i++)
    {
        if (document.orderform.category[i].checked==true)
        {
            var y = orderform.category[i].value;
        }
    }
    var val=y+" "+it;
    addItem(document.items.item_list,val,val);
}

A: Your script does work as intended. However, your HTML is very invalid. This could break correct parsing in some browsers dependend on doctype and subsequently the correct execution of JavaScript. When use IDs then define them unique. <input> is a void tag, that means it must not have a closing tag! When you use an XHTML doctype, mark the open tag as self closing <input />. Use My Label to get a clickable label connected to the input element.
Don't rely on name mapping to document and form objects. Other scripts can overwrite this names, e.g. a JS-framework could define items as a document property/method. Use document.getElementById() or document.querySelector() / document.querySelectorAll() or some similar method instead.
I assume the  in the second code fragment appears in your code only once at the top of page.

A: Your not properly retrieving the 'orderForm' or the 'categories'. You need to grab those items correctly. You cannot navigate through the document just based on tag name, although that would be cool if you could. Here's the JS.
function addItem(selectbox,value )
{
    var item = document.createElement("OPTION");
    item.text = value;
    item.value = value;
    selectbox.options.add(item);
}

function addItem_list(){
    var item =document.getElementById('item');

    var it = item.value;

    if(!it)
        it = 'blank';

    var categories = document.getElementsByTagName('category');

    //To determine which radio button has been selected:
    for (var i=0; i<categories.length; i++)
    {
        if (categories[i].checked==true)
        {
            var y = categories[i].value;
        }
    }
    var val;

    if(y)
        val = y + ' ' + it;
    else
        val = it;

    var item_list = document.getElementById('item_list');

    addItem(item_list,val);
}

And now it works great! Hope that's what you were looking for!


text:
Q: How to setup UCMA Development environment locally for Lync 2010? I have created a chat bot in c#. But the requirement has changed to a bot that can be directly accessed through lync. Lync is present in our network, but the server is separate and my development environment is not at the server side. I have a few questions on the scenario :-

*

*I have to create an application endopoint. Is UCMA the best way to
go?

*Is UCMA free?

*How do I set up my development environment so that I can test my bot
without affecting the other lync users?

*Is it possible to make my local system the server, add it to the trusted server list in the actual lync server, add my application endpoint to the trusted application pool in the actual lync server.Would I need anything else if I follow this route?

*I have lync 2010. Will UCMA 4.0 SDK work for lync 2010?

A: *

*Skype / Lync offers UCMA & UCWA. However it depends on your application which might be the best one. Without having more details what you try to build its not easy to answer that. See this posting here for more infos.

*You need a Skype/Lync environment. This required a valid license.

*You might try an evaluation version from the Microsoft evalcenter here. You can have only one lync or Skype for Business environment in your active directory. But you can setup an additional pool. However to avoid that you break something I highly recommend to setup a separate developer environment

*Keep noted that Lync 2010 is quite very old. There is Lync 2013 already in place and got replaced with Skype for Business. Building something on Lync 2010 which is 6 years old didn´t sound a good idea. However UCMA 4.0 and UCMA 5.0 are supported (as written here) by Skype for Business, so your might wish to check if you will not build that for Skype for Business instead.


text:
Q: jQuery .is() not working Quick Question:
HTML:

Text

Text

Text

Text

jQuery:
$('.aaa').on('click', function(){
    var check = $(this).is('.aaa:last');
    alert(check);
});

How come it always alerts "false"? I'm expecting it to alert "true" when I click the last div?
Where am I doing wrong?
Edit --
I know why finally. My jQuery version is 1.9.1. It works fine when jQuery is 2.x –

A: It does work: http://jsfiddle.net/jef0nhmq/
Your code is fine.
$('.aaa').on('click', function(){
   var check = $(this).is('.aaa:last');
   alert(check);
});

A: For me, it works with :last-child


text:
Q: Mongoose change _id to id I would like to know how can i change the _id to id virtually or anyways so the direct json output from the database looks pretty. Additionally i see a __v generated in my documents and not sure how to hide those fields.

A: if you want to hide __v in mongodb collection use versionKey: false in schema definition of collection.
example:
'use strict';

const mongoose = require('mongoose');

export class DeviceID extends mongoose.Schema {

    constructor() {
        super({
            device_id: String
        },
        {
            versionKey: false
        });
    }

}


text:
Q: Organise android projects in eclipse and remove closed projects I want to know if there is anyway to organize the projects in Eclipse (In the package explorer) and remove closed ones.

A: You can delete the project, then don't select 'delete from harddisk'. This will remove it from your explorer while keeping it on your PC.


text:
Q: Finding the metric tensor from the Einstein field equation? I have have set my self a challenge to learn all the maths behind the Einstein field equation (EFE), and from reading it seems that the Metric tensor is the thing we are trying to find (from the 10 equations that forms the EFE). but since nearly all the terms in it are functions of this metric tensor, this seems very hard. What type of maths do we use to do this? (I have copied and pasted the EFE just for reference):
$$R_{\mu \nu}-\frac{1}{2}g_{\mu \nu}R+g_{\mu\nu}\Lambda=\frac{8 \pi G}{c^4}T_{\mu \nu}$$
Edit:
Thanks for your comments. Just as I have no one else to ask, is this the equation that we try to solve:
$$\left(\frac{\partial}{\partial x^{\lambda}}\Gamma^{\lambda}_{\mu \nu}- \frac{\partial}{\partial x^{\nu}}\Gamma^{\lambda}_{\lambda \mu}+\Gamma^{\lambda}_{\lambda \rho}\Gamma^{\rho}_{\nu \mu}-\Gamma^{\lambda}_{\nu \rho}\Gamma^{\rho}_{\lambda \mu}\right)-\frac{1}{2}g_{\mu \nu}g^{ab}\left(\Gamma^c_{\enspace ab,c}-\Gamma^c_{\enspace ac,b}+\Gamma^d_{\enspace ab}\Gamma^c_{\enspace cd}-\Gamma^d_{\enspace ac}\Gamma^c_{\enspace bd} \right)+g_{\mu \nu}\Lambda=\frac{8 \pi G}{c^4}T_{\mu \nu}$$
with the $R_{μν}$ and $R$ terms expanded and where $g_{μν}$ and $T_{μν}$ are the μν th components from the related tensors? (a yes or no answer will be fine, thanks).

A: This is really a comment, but it got a bit long for the comment field.
I'd guess that, like me, your experience in physics is from an area where solving differential equations is a routine part of the job. We're used to analysing a problem, writing down a differential equation that encapsulates the physics and solving it, analytically if we're lucky or in the worst case throwing it at a computer.
What struck me very forcefully when I started reading up on GR is that this is hardly ever the approach used. The equations are so hard that in almost every case the metric is obtained either by ingenious use of symmetry or just guessing answers until one fits. If you read the derivation of the Schwartzschild metric, which is probably the simplest one most of us meet, Schwarzschild obtained the answer by guessing at a basic form for the metric then using the high symmetry to eliminate all the possibilities but one. Kerr seems to have arrived as his result by inspired guesswork (though inspired by vast amounts of effort!!).
This all feels somehow unsatisfactory for us hedge physicists. It feels as if general relativists just cheat all the time and never do things methodically like we do. That's an unfair impression of course, and born out of ignorance, but nevertheless I'm willing to bet that's how you will feel as you start reading around the subject.
If you want to start learning GR in anger then I strongly recommend A first course in general relativity by Bernard Schutz. This will get you from a starting point of knowing basic calculus to the point where you're comfortable doing basic GR calculations. Note however that even after 376 pages you will still not have seen the Einstein equation written out in full.

A: If you have a metric, then you also have the manifold itself and all the points in it, and you can use the metric to compute the Einstein tensor at each point, and then multiply by a scalar constant to get the stress-energy tensor (assuming you know the value of your cosmological constant).
But the reverse direction is very different.  For instance, if you started with the manifold (but no one gave you the metric, only the topological space) and then you had a stress-energy tensor defined at every point on your manifold, you already have a lot since you have the manifold.  So this might be too much information, and be considered cheating.  But it can also be too little information.  The stress-energy tensor is the source term, it's like in electromagnetism if someone gave you the charge and current, that isn't actually enough to find the fields, you need boundary conditions too.
Let's look at a simple but troublesome example.  Your manifold is $\mathbb{R}^4$, your stress-energy tensor is $T_{\mu \nu}=0$.  There are many possible metrics.  You could have a metric corresponding to a gravitational wave travelling left, one travelling right, one up, one down, one forwards, one backwards.  Or just an empty flat space with no gravitational waves, the spacetime of special relativity.  This is entirely like the corresponding situation in electromagnetism when there is no charge and no current, you could have no fields, or you could have an electromagnetic wave going in any direction.  It's just not enough information.

A: The standard procedure to find the components of metric tensor has the following steps.

*

*Guess a trial formula for dynamic evolution of the metric tensor components ($g_{\mu\nu}$), considering the symmetries your given system possesses. The trial formula should include enough unknown parameters.

*Calculate the connection coefficients from your trial formula.

*Calculate the components of Riemann curvature tensor from the connection coefficients.

*Calculate the components of Einstein tensor from the Riemann tensor.

*Substitute the Einstein tensor in the Einstein Field Equation.

*By matching the boundary conditions (spacetime becomes flat at infinity), and find the unknown parameters that you had set in your metric tensor earlier.

*If you find a solution to the metric tensor that satisfies the Einstein equation and as well as the boundary condition, then the solution you got is the correct solution. If not, change the trial and repeat the steps above.

You can see, the procedure is heavily dependent on (educated) guessing. Therefore, it can not be applied to a situation where the spacetime lacks symmetry. For this reason, we do not have many analytic solutions to Einstein's equation.


text:
Q: Count all lines in the select statement, result value have column all the line number in select ![enter image description here][1]
I want in select  add a column "all line number" is all line was get(not use subquery).
Can use any data.
This my instance so everyone understands what are I need it.
select *, "all line number"
from SysUserInSubRoleRes
group by SubRoleId
having count(SubRoleId) > 2
order by SubRoleId desc
OFFSET 0 ROWS
FETCH NEXT 2  ROWS ONLY'

Value default:
SubRoleId
--------
  v1
  v2
  v3
  v1
  v2
  v2
  v1

Result Value
add column alllinenumber

SubRoleID  |  AllLineNumber
  v1       |      3
  v2       |      3

A: Your expected output cannot be the result of your query since subroleid 1 has a alllinenumber
= 1 and 2 as 2 neither of which pass the count test of > 2
You may be looking for something like
drop table t
go
create table t(subroleid int)
go
insert into t values (1),(2),(2),(2)

select subroleid, count(*) as "all line number"
from t
group by SubRoleId
having count(SubRoleId) > 2
order by SubRoleId desc

subroleid   all line number
----------- ---------------
2           3

but without sample data and expected output it's hard to be sure.
Edit 1.
drop table t
go
create table t(subroleid varchar(2))
go
insert into t values ('v1'),('v2'),('v3')

select t.subroleid,  cnt "all line number"
from t
cross join (select count(*) cnt from t) s
where cnt > 2
order by SubRoleId
OFFSET 0 ROWS
FETCH NEXT 2  ROWS ONLY

subroleid all line number
--------- ---------------
v1        3
v2        3

A: SELECT COUNT(SUBROLEID) AS [ALL LINE NUMBER]
FROM SYSUSERINSUBROLERES
GROUP BY SUBROLEID
HAVING COUNT(SUBROLEID) > 2
ORDER BY SUBROLEID DESC

Hope this Query Works for your case

A: If you want row number, then you can easily generate it
select SubRoleId, ROW_NUMBER() OVER(ORDER BY SubRoleId DESC) AS [all line number]
from SysUserInSubRoleRes
group by SubRoleId
having count(SubRoleId) > 2
order by [all line number]


text:
Q: ElasticBeanstalk Environment Variables not accessible using pm2 I have successfully been able to run my application on ElasticBeanstalk using the basic npm start script shown below.
"scripts": {
    "start": "NODE_ENV=production node ./bin/www"
}

On my server I have now installed pm2 globally and updated the start script in my package.json to use pm2.
"scripts": {
    "start": "pm2 start ./bin/www"
}

pm2 starts the process, I can see this from looking at my logs however it does not seem to have access to the environment variables I set for ElasticBeanstalk. I set the environment variables with the  aws:elasticbeanstalk:application:environment option in the file .ebextensions/options.config shown below.
option_settings:
  aws:elasticbeanstalk:application:environment:
    keyOne: foo
    keyTwo: bar
    keyThree: foo

pm2 complains about not being able to read a property of undefined for an environment variable.
0|www    | TypeError: Cannot read property 'keyOne' of undefined
0|www    |     at Object.<anonymous> (/var/app/current/app.js:26:38)
0|www    |     at Module._compile (internal/modules/cjs/loader.js:999:30)
0|www    |     at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
0|www    |     at Module.load (internal/modules/cjs/loader.js:863:32)
0|www    |     at Function.Module._load (internal/modules/cjs/loader.js:708:14)
0|www    |     at Module.require (internal/modules/cjs/loader.js:887:19)
0|www    |     at Module.Hook._require.Module.require (/var/app/current/node_modules/require-in-the-middle/index.js:80:39)
0|www    |     at require (internal/modules/cjs/helpers.js:74:18)
0|www    |     at Object.<anonymous> (/var/app/current/bin/www:7:11)
0|www    |     at Module._compile (internal/modules/cjs/loader.js:999:30)

Do I need to source a file first? I would like to avoid setting environment variables in a ecosystem.config.js file for pm2 as I can also manage the environment variables at the moment in a visual way from the AWS console using the approach currently implemented.

A: If you already created the PM2 process and then updated environment variables, you should delete the PM2 process and create it again using ecosystem file.
The delete and create actions consider newly created environment variables, but not the restart. I don't know why.


text:
Q: Data corruption in PGP encrypted environment I'm trying to determine what is causing, and how to prevent, data corruption that is occurring in a secure, PGP encrypted environment. I am one of the primary users of the system, and not an administrator. I have looked for solutions in the past, to no avail.
Background: I work for a commercial mailer, and one of our clients is a financial institute, so we are required to process their data in an encrypted environment, according to PCI (Payment Card Industry) regulations. We use PGP on Windows Server. I believe it's 2012, but I am not positive. We recently upgraded the system by doing a complete server replacement. We log onto the system from a handful of dedicated PCs, most of which run Vista, but at least one runs Windows 7 64-bit. The data is stored and manipulated on a mapped drive on the server. We use Visual Foxpro to access the data, and run counts and reports on it. The data is stored in .dbf files we create from text files.
Occasionally we would get corruption, usually in the .dbf files, but also in other, plain text files created by other software we use. Typically the corruption appears as nulls at the end of a file, or garbage replacing part or all of multiple records, located together in the .dbf. Sometimes the corruption in the text files only occurred when the file was copied to another directory.
Today, I had it happen again, for the first time since the server upgrade a few months ago. In both cases, the corruption occurred at the end of a .dbf. The first time, the data was replaced with random binary data when the file was closed. This was repeatable. Eventually, I copied and pasted the data from the original text file, which fixed it. The second time the corruption also happened repeatedly, even when the dbf in question was recreated and processed in a new directory. The data at the end of the file was replaced with users full names and binary data. The only thing that was done to the .dbf was that a temporary index was created for matching to another file, and then later deleted. The corruption happened either when the index was deleted, or when the file was closed. I have begun to suspect that it could be an issue with the file access table, reporting the wrong file size, but I'm not 100% certain, due to the corruption occasionally occurring in the middle of a .dbf.
My manager has been stumped. He said this occurred somewhat frequently, and more severely, a couple years ago, before I started working in the secure environment. He also  mentioned that when they did an upgrade on the PGP software, the issues went away, at least for awhile. It has happened about this time of year, for the last two years.
TL;DR:
I'm running into data corruption on a PGP encrypted system and I can't figure out what's causing it. Can anyone help me figure how to prevent it?


text:
Q: Unit Test fails after upgrading to angular8 I upgraded the project from Angular7 to Angular8. (for now, I haven't upgraded Nx, the current version used is "@nrwl/nx": "7.8.7",)
After upgrade, my application runs successfully (without any issues in build or deploy).
When I run the test cases by putting "codeCoverage": true in angular.json file it fails and throws below error.
script used
"test:appone": "ng test --project=app-one --no-watch",

Log
0 info it worked if it ends with ok
1 verbose cli [ 'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'run',
1 verbose cli   'test:one' ]
2 info using npm@6.4.1
3 info using node@v10.15.3
4 verbose run-script [ 'pretest:one', 'test:one', 'posttest:one' ]
5 info lifecycle proj-micro-apps@1.1.0~pretest:one: proj-micro-apps@1.1.0
6 info lifecycle proj-micro-apps@1.1.0~test:one: proj-micro-apps@1.1.0
7 verbose lifecycle proj-micro-apps@1.1.0~test:one: unsafe-perm in lifecycle true
8 verbose lifecycle proj-micro-apps@1.1.0~test:one: PATH: C:\Users\KBharambe\AppData\Roaming\nvm\v10.15.3\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin;D:\NX8New\proj-micro-apps\node_modules\.bin;C:\ProgramData\DockerDesktop\version-bin;C:\Program Files\Docker\Docker\Resources\bin;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files\1E\NomadBranch\;C:\Program Files\Git\cmd;C:\Program Files\Git\mingw64\bin;C:\Program Files\Git\usr\bin;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\WINDOWS\System32\OpenSSH\;C:\Users\KBharambe\AppData\Roaming\nvm;C:\Program Files\nodejs;C:\Users\KBharambe\scoop\apps\maven\current\bin;C:\Users\KBharambe\scoop\shims;C:\Users\KBharambe\.windows-build-tools\python27\;C:\Users\KBharambe\AppData\Local\Continuum\anaconda3;C:\Users\KBharambe\AppData\Local\Continuum\anaconda3\Library\mingw-w64\bin;C:\Users\KBharambe\AppData\Local\Continuum\anaconda3\Library\usr\bin;C:\Users\KBharambe\AppData\Local\Continuum\anaconda3\Library\bin;C:\Users\KBharambe\AppData\Local\Continuum\anaconda3\Scripts;C:\Users\KBharambe\AppData\Local\Microsoft\WindowsApps;C:\Program Files\Microsoft VS Code\bin;C:\Users\KBharambe\AppData\Local\Programs\Microsoft VS Code\bin;C:\Users\KBharambe\AppData\Roaming\npm;C:\Users\KBharambe\AppData\Roaming\nvm;C:\Program Files\nodejs
9 verbose lifecycle proj-micro-apps@1.1.0~test:one: CWD: D:\NX8New\proj-micro-apps
10 silly lifecycle proj-micro-apps@1.1.0~test:one: Args: [ '/d /s /c',
10 silly lifecycle   'ng test --project=app-one  --no-watch' ]
11 silly lifecycle proj-micro-apps@1.1.0~test:one: Returned: code: 1  signal: null
12 info lifecycle proj-micro-apps@1.1.0~test:one: Failed to exec test:one script
13 verbose stack Error: proj-micro-apps@1.1.0 test:one: `ng test --project=app-one  --no-watch`
13 verbose stack Exit status 1
13 verbose stack     at EventEmitter.<anonymous> (C:\Users\KBharambe\AppData\Roaming\nvm\v10.15.3\node_modules\npm\node_modules\npm-lifecycle\index.js:301:16)
13 verbose stack     at EventEmitter.emit (events.js:189:13)
13 verbose stack     at ChildProcess.<anonymous> (C:\Users\KBharambe\AppData\Roaming\nvm\v10.15.3\node_modules\npm\node_modules\npm-lifecycle\lib\spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:189:13)
13 verbose stack     at maybeClose (internal/child_process.js:970:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:259:5)
14 verbose pkgid proj-micro-apps@1.1.0
15 verbose cwd D:\NX8New\proj-micro-apps
16 verbose Windows_NT 10.0.17134
17 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "run" "test:one"
18 verbose node v10.15.3
19 verbose npm  v6.4.1
20 error code ELIFECYCLE
21 error errno 1
22 error proj-micro-apps@1.1.0 test:one: `ng test --project=app-one  --no-watch`
22 error Exit status 1
23 error Failed at the proj-micro-apps@1.1.0 test:one script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 1, true ]

If I remove "codeCoverage" flag the test cases executes without any errors but I won't get any coverage.
=============================== Coverage summary ===============================
Statements   : Unknown% ( 0/0 )
Branches     : Unknown% ( 0/0 )
Functions    : Unknown% ( 0/0 )
Lines        : Unknown% ( 0/0 )
================================================================================

I'm using karma jasmine for the same
    "karma": "4.4.1",
    "@types/jasmine": "3.5.0",
    "@types/jasminewd2": "2.0.8",
    "karma-jasmine": "2.0.1",
    "karma-jasmine-html-reporter": "1.4.2",
    "jasmine-core": "3.5.0",
    "jasmine-marbles": "0.6.0",
    "jasmine-reporters": "2.3.2",
    "jasmine-spec-reporter": "4.2.1",
    "karma-chrome-launcher": "3.1.0",
    "karma-cli": "2.0.0",
    "karma-coverage": "2.0.1",
    "karma-coverage-istanbul-reporter": "2.1.1",
    "karma-jasmine": "2.0.1",
    "karma-jasmine-html-reporter": "1.4.2",
    "karma-junit-reporter": "2.0.1",

ng --version
Angular CLI: 8.3.20
Node: 10.15.3
OS: win32 x64
Angular: 8.2.14
... animations, common, compiler, compiler-cli, core, forms
... language-service, platform-browser, platform-browser-dynamic
... router

Package                            Version
------------------------------------------------------------
@angular-devkit/architect          0.803.20
@angular-devkit/build-angular      0.803.21
@angular-devkit/build-ng-packagr   0.803.20
@angular-devkit/build-optimizer    0.803.21
@angular-devkit/build-webpack      0.803.21
@angular-devkit/core               8.3.20
@angular-devkit/schematics         8.3.20
@angular/cdk                       8.2.3
@angular/cli                       8.3.20
@angular/flex-layout               8.0.0-beta.27
@angular/material                  8.2.3
@angular/material-moment-adapter   8.2.3
@ngtools/json-schema               1.1.0
@ngtools/webpack                   8.3.21
@schematics/angular                8.3.20
@schematics/update                 0.803.20
ng-packagr                         5.0.0
rxjs                               6.5.3
typescript                         3.4.5
webpack                            4.39.2

I tried it with multiple node versions but still same.
Can you please let me know what can be the issue?
Thanks in advance.

A: You should consider migrating jest at least to upgrade unit test cases related dependencies
nx migrate @nrwl/jest@<new-version> --from=@nrwl/jest@<old-version>

You might have to run based on output of above command
npm install
nx migrate --run-migrations=migrations.json


text:
Q: Preparing Blob for chrome messaging: blob.text() and back again results in corrupted file I am trying to pass a Blob from a chrome extension to a javascript web application using the Chrome Message API. Inspired by a former Thread I want to convert the blob to text in order to send the content and filetype as an object via the messaging API to the website and eventually reassemble the Blob.
When executing the following snippet of code, however, I'm unable to reassemble the Blob. Basically the URL.createOjectURL() method should return valid blob:-URLs for both, blob and new_blob. While working on both objects, the new_blob URL results in a corrupted image (grey square) while the URL for blob shows the correct image. (On the receiving end the same problem occurs, of course).
fetch(request.url)
    .then(r => r.blob())
    .then(blob => {
    var filetype = blob.type
    blob.text().then(text => {
        var message = {
            blob: text,
            url: request.url,
            filetype: filetype
            }

        var new_blob = new Blob([message.blob], {type: message.filetype})

        console.log(URL.createObjectURL(blob))
        console.log(URL.createObjectURL(new_blob))

        ...
        sendResponse(message)
        })

    })

A: While the solution using blob is still not working, I found an alternative way to solve the problem: Using base64. There is example code available on GitHub:
const BlobToBase64 = function(blob){
... (see gist) ...
}

fetch(request.url)
    .then(r => r.blob())
    .then(blob => BlobToBase64(blob))
    .then(base => {
       sendResponse(base)
       })


text:
Q: Error when trying to update API in API Manager I started with a fresh install of the API Manager.  I can create an API just fine but I can not update it.
I am logged in as a 'creator'role as defined in the documentation of what roles to create.  The same user is logged in that is trying to modify it.  Even if i just create a new API then immediately try to update with ( with out any changes ) I get the following error.
TID: [0] [AM] [2014-01-30 13:16:41,059] ERROR {org.wso2.carbon.apimgt.hostobjects.APIProviderHostObject} -  Error while updating the API- ItemService-1.0 {org.wso2.carbon.apimgt.hostobjects.APIProviderHostObject}
org.wso2.carbon.apimgt.api.APIManagementException: Error while updating the API :ItemService
    at org.wso2.carbon.apimgt.impl.AbstractAPIManager.handleException(AbstractAPIManager.java:666)
    at org.wso2.carbon.apimgt.impl.APIProviderImpl.updateAPI(APIProviderImpl.java:496)
    at org.wso2.carbon.apimgt.impl.UserAwareAPIProvider.updateAPI(UserAwareAPIProvider.java:58)
    at org.wso2.carbon.apimgt.hostobjects.APIProviderHostObject.jsFunction_updateAPI(APIProviderHostObject.java:772)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.mozilla.javascript.MemberBox.invoke(MemberBox.java:126)
    at org.mozilla.javascript.FunctionObject.call(FunctionObject.java:386)
    at org.mozilla.javascript.optimizer.OptRuntime.call1(OptRuntime.java:32)
    at org.jaggeryjs.rhino.publisher.modules.api.c4._c_anonymous_1(/publisher/modules/api/update.jag:6)
    at org.jaggeryjs.rhino.publisher.modules.api.c4.call(/publisher/modules/api/update.jag)
    at org.mozilla.javascript.ScriptRuntime.applyOrCall(ScriptRuntime.java:2430)
    at org.mozilla.javascript.BaseFunction.execIdCall(BaseFunction.java:269)
    at org.mozilla.javascript.IdFunctionObject.call(IdFunctionObject.java:97)
    at org.mozilla.javascript.optimizer.OptRuntime.call2(OptRuntime.java:42)
    at org.jaggeryjs.rhino.publisher.modules.api.c0._c_anonymous_9(/publisher/modules/api/module.jag:35)
    at org.jaggeryjs.rhino.publisher.modules.api.c0.call(/publisher/modules/api/module.jag)
    at org.mozilla.javascript.optimizer.OptRuntime.call1(OptRuntime.java:32)
    at org.jaggeryjs.rhino.publisher.site.blocks.item_add.ajax.c0._c_anonymous_1(/publisher/site/blocks/item-add/ajax/add.jag:116)
    at org.jaggeryjs.rhino.publisher.site.blocks.item_add.ajax.c0.call(/publisher/site/blocks/item-add/ajax/add.jag)
    at org.mozilla.javascript.optimizer.OptRuntime.call0(OptRuntime.java:23)
    at org.jaggeryjs.rhino.publisher.site.blocks.item_add.ajax.c0._c_script_0(/publisher/site/blocks/item-add/ajax/add.jag:4)
    at org.jaggeryjs.rhino.publisher.site.blocks.item_add.ajax.c0.call(/publisher/site/blocks/item-add/ajax/add.jag)
    at org.mozilla.javascript.ContextFactory.doTopCall(ContextFactory.java:394)
    at org.mozilla.javascript.ScriptRuntime.doTopCall(ScriptRuntime.java:3091)
    at org.jaggeryjs.rhino.publisher.site.blocks.item_add.ajax.c0.call(/publisher/site/blocks/item-add/ajax/add.jag)
    at org.jaggeryjs.rhino.publisher.site.blocks.item_add.ajax.c0.exec(/publisher/site/blocks/item-add/ajax/add.jag)
    at org.jaggeryjs.scriptengine.engine.RhinoEngine.execScript(RhinoEngine.java:570)
    at org.jaggeryjs.scriptengine.engine.RhinoEngine.exec(RhinoEngine.java:273)
    at org.jaggeryjs.jaggery.core.manager.WebAppManager.execute(WebAppManager.java:432)
    at org.jaggeryjs.jaggery.core.JaggeryServlet.doPost(JaggeryServlet.java:29)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:755)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:749)
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:487)
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:379)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:339)
    at org.jaggeryjs.jaggery.core.JaggeryFilter.doFilter(JaggeryFilter.java:21)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.wso2.carbon.tomcat.ext.valves.CompositeValve.continueInvocation(CompositeValve.java:178)
    at org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve$1.invoke(CarbonTomcatValve.java:47)
    at org.wso2.carbon.webapp.mgt.TenantLazyLoaderValve.invoke(TenantLazyLoaderValve.java:56)
    at org.wso2.carbon.tomcat.ext.valves.TomcatValveContainer.invokeValves(TomcatValveContainer.java:47)
    at org.wso2.carbon.tomcat.ext.valves.CompositeValve.invoke(CompositeValve.java:141)
    at org.wso2.carbon.tomcat.ext.valves.CarbonStuckThreadDetectionValve.invoke(CarbonStuckThreadDetectionValve.java:156)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
    at org.wso2.carbon.tomcat.ext.valves.CarbonContextCreatorValve.invoke(CarbonContextCreatorValve.java:52)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1653)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:722)
Caused by: org.wso2.carbon.apimgt.api.APIManagementException: Error while performing registry transaction operation
    at org.wso2.carbon.apimgt.impl.AbstractAPIManager.handleException(AbstractAPIManager.java:666)
    at org.wso2.carbon.apimgt.impl.APIProviderImpl.updateApiArtifact(APIProviderImpl.java:579)
    at org.wso2.carbon.apimgt.impl.APIProviderImpl.updateAPI(APIProviderImpl.java:425)
    ... 63 more
Caused by: org.wso2.carbon.apimgt.api.APIManagementException: Failed to reset the WSDL : /registry/resource/_system/governance/apimgt/applicationdata/wsdls/creator--ItemService1.0.wsdl
    at org.wso2.carbon.apimgt.impl.utils.APIUtil.createWSDL(APIUtil.java:787)
    at org.wso2.carbon.apimgt.impl.APIProviderImpl.updateApiArtifact(APIProviderImpl.java:541)
    ... 64 more
Caused by: org.wso2.carbon.apimgt.api.APIManagementException:  Error occurs when change the addres URL of the WSDL
    at org.wso2.carbon.apimgt.impl.utils.APIMWSDLReader.readAndCleanWsdl(APIMWSDLReader.java:103)
    at org.wso2.carbon.apimgt.impl.utils.APIUtil.createWSDL(APIUtil.java:767)
    ... 65 more
Caused by: javax.wsdl.WSDLException: WSDLException: faultCode=OTHER_ERROR: Unable to resolve imported document at '/registry/resource/_system/governance/apimgt/applicationdata/wsdls/creator--ItemService1.0.wsdl'.: java.io.FileNotFoundException: This file was not found: file:/registry/resource/_system/governance/apimgt/applicationdata/wsdls/creator--ItemService1.0.wsdl
    at com.ibm.wsdl.xml.WSDLReaderImpl.readWSDL(WSDLReaderImpl.java:2259)
    at com.ibm.wsdl.xml.WSDLReaderImpl.readWSDL(WSDLReaderImpl.java:2207)
    at org.wso2.carbon.apimgt.impl.utils.APIMWSDLReader.readWSDLFile(APIMWSDLReader.java:128)
    at org.wso2.carbon.apimgt.impl.utils.APIMWSDLReader.readAndCleanWsdl(APIMWSDLReader.java:84)
    ... 66 more
Caused by: java.io.FileNotFoundException: This file was not found: file:/registry/resource/_system/governance/apimgt/applicationdata/wsdls/creator--ItemService1.0.wsdl
    at com.ibm.wsdl.util.StringUtils.getContentAsInputStream(StringUtils.java:173)
    at com.ibm.wsdl.xml.WSDLReaderImpl.readWSDL(WSDLReaderImpl.java:2238)
    ... 69 more

A: I have the exact same problem with WSO2 APIM 1.6.0.
I get around it by redefining the WSDL to the previous value.
For example when using the sample CDYNE API sample you originally used a WSDL path of:
http://ws.cdyne.com/phoneverify/phoneverify.asmx?WSDL
But when you later attempt to update that path is now:
/registry/resource/_system/governance/apimgt/applicationdata/wsdls/admin--NoAuthTNVerify1.0.0.wsdl
I upated that line back to:
http://ws.cdyne.com/phoneverify/phoneverify.asmx?WSDL
and was then able to save my edits.
Now...WHY does the path change?   or WHY doesn't WSO2 APIM deploy the wsdl to that location?  That I don't konw, maybe someone from WSO2 could explain.

A: I am seeing similar results running APIM 1.5.0 and trying to update an API through the API Publisher application. In fact, I cannot even save the API at all.
I initially created the API through the Publisher API endpoint as described in the docs:
https://docs.wso2.org/display/AM150/Publisher+APIs#PublisherAPIs-AddUpdateAPI
All seemed to work, as I got this response:
{"error" : false}
When I try to save the API in the Publisher web app, I see this error:
"Error while updating the API- testAPI-v1"
In the logs I see the following:
ERROR - APIProviderHostObject Error while updating the API- testAPI-v1
java.lang.NullPointerException
    at org.wso2.carbon.apimgt.impl.APIProviderImpl.updateAPI(APIProviderImpl.java:425)
    at org.wso2.carbon.apimgt.impl.UserAwareAPIProvider.updateAPI(UserAwareAPIProvider.java:58)
    at org.wso2.carbon.apimgt.hostobjects.APIProviderHostObject.jsFunction_updateAPI(APIProviderHostObject.java:716)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:622)
    at org.mozilla.javascript.MemberBox.invoke(MemberBox.java:126)
    at org.mozilla.javascript.FunctionObject.call(FunctionObject.java:386)
    at org.mozilla.javascript.optimizer.OptRuntime.call1(OptRuntime.java:32)
    at org.jaggeryjs.rhino.publisher.modules.api.c5._c_anonymous_1(/publisher/modules/api/update.jag:6)
    at org.jaggeryjs.rhino.publisher.modules.api.c5.call(/publisher/modules/api/update.jag)
    at org.mozilla.javascript.ScriptRuntime.applyOrCall(ScriptRuntime.java:2430)
    at org.mozilla.javascript.BaseFunction.execIdCall(BaseFunction.java:269)
    at org.mozilla.javascript.IdFunctionObject.call(IdFunctionObject.java:97)
    at org.mozilla.javascript.optimizer.OptRuntime.call2(OptRuntime.java:42)
    at org.jaggeryjs.rhino.publisher.modules.api.c0._c_anonymous_9(/publisher/modules/api/module.jag:35)
    at org.jaggeryjs.rhino.publisher.modules.api.c0.call(/publisher/modules/api/module.jag)
    at org.mozilla.javascript.optimizer.OptRuntime.call1(OptRuntime.java:32)
    at org.jaggeryjs.rhino.publisher.site.blocks.item_add.ajax.c0._c_anonymous_1(/publisher/site/blocks/item-add/ajax/add.jag:111)
    at org.jaggeryjs.rhino.publisher.site.blocks.item_add.ajax.c0.call(/publisher/site/blocks/item-add/ajax/add.jag)
    at org.mozilla.javascript.optimizer.OptRuntime.call0(OptRuntime.java:23)
    at org.jaggeryjs.rhino.publisher.site.blocks.item_add.ajax.c0._c_script_0(/publisher/site/blocks/item-add/ajax/add.jag:4)
    at org.jaggeryjs.rhino.publisher.site.blocks.item_add.ajax.c0.call(/publisher/site/blocks/item-add/ajax/add.jag)
    at org.mozilla.javascript.ContextFactory.doTopCall(ContextFactory.java:394)
    at org.mozilla.javascript.ScriptRuntime.doTopCall(ScriptRuntime.java:3091)
    at org.jaggeryjs.rhino.publisher.site.blocks.item_add.ajax.c0.call(/publisher/site/blocks/item-add/ajax/add.jag)
    at org.jaggeryjs.rhino.publisher.site.blocks.item_add.ajax.c0.exec(/publisher/site/blocks/item-add/ajax/add.jag)
    at org.jaggeryjs.scriptengine.engine.RhinoEngine.execScript(RhinoEngine.java:570)
    at org.jaggeryjs.scriptengine.engine.RhinoEngine.exec(RhinoEngine.java:273)
    at org.jaggeryjs.jaggery.core.manager.WebAppManager.execute(WebAppManager.java:432)
    at org.jaggeryjs.jaggery.core.JaggeryServlet.doPost(JaggeryServlet.java:29)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:755)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:749)
    at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:487)
    at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:379)
    at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:339)
    at org.jaggeryjs.jaggery.core.JaggeryFilter.doFilter(JaggeryFilter.java:21)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.wso2.carbon.tomcat.ext.valves.CompositeValve.continueInvocation(CompositeValve.java:178)
    at org.wso2.carbon.tomcat.ext.valves.CarbonTomcatValve$1.invoke(CarbonTomcatValve.java:47)
    at org.wso2.carbon.webapp.mgt.TenantLazyLoaderValve.invoke(TenantLazyLoaderValve.java:56)
    at org.wso2.carbon.tomcat.ext.valves.TomcatValveContainer.invokeValves(TomcatValveContainer.java:47)
    at org.wso2.carbon.tomcat.ext.valves.CompositeValve.invoke(CompositeValve.java:141)
    at org.wso2.carbon.tomcat.ext.valves.CarbonStuckThreadDetectionValve.invoke(CarbonStuckThreadDetectionValve.java:156)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
    at org.wso2.carbon.tomcat.ext.valves.CarbonContextCreatorValve.invoke(CarbonContextCreatorValve.java:52)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1653)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1146)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:701)

According to this Jira ticket, this bug was discovered in v1.3:
https://wso2.org/jira/browse/APIMANAGER-1024
It does appear to have been fixed.


text:
Q: delete multiple records from an object I want to delete multiple records of an object...How should I do it.
public class del_acc
{
   public List<String> sel_id{get;set;}
   set<id> sid = new set<id>();
   List<Account> accIdList = new List<Account>();
   public void deleteacc()
   {
      if(sel_id != '')
      {
        List<Account> acc = new List<Account>(id=sel_id);
        delete acc;
       }
   }
}

A: @Anzar to pass multiple ids in apex search about for each loop.
for (Account o : send your set of id's) {

    /* Code for account omitted */
}


text:
Q: GPU memory use with tiny YOLOv4 and Tensorflow I am creating a flask API which takes as input an image, width, height, and the threshold. It is then passed through a tiny YOLOv4 model to detect objects and then return the coordinates of the boxes. While it is running correctly and send the right points there is a problem, it is very slow because it is not using my GPU (GeForce MX230 2GB). When I run the code the model is loaded and the my GPU goes up to 30% usage which makes sense since the model is now in memory. but when the API receives an image I start getting CUDA out of memory errors like this
tensorflow/core/common_runtime/bfc_allocator.cc:272] Allocator (GPU_0_bfc) ran out of memory trying to allocate 1.08GiB with freed_by_count=0. The caller indicates that this is not a failure, but may mean that there could be performance gains if more memory were available

This does not seem to make sense since loading one (small) image is not supposed to demand that much GPU and the model has already been loaded. So my question is: Why is this happening and is their a way to fix it.
my code:
import cv2
import tensorflow as tf
import numpy as np
from tensorflow.python.saved_model import tag_constants
from flask import Flask , request
from flask_cors import CORS
import ast
physical_devices = tf.config.experimental.list_physical_devices('GPU')
if len(physical_devices) > 0:
    tf.config.experimental.set_memory_growth(physical_devices[0], True)
iou=0.4
saved_model_loaded = tf.saved_model.load('./yolov4-tiny-416', tags=[tag_constants.SERVING])
classe_names=["person","bicycle","car","motorbike","aeroplane","bus","train","truck","boat","traffic light","fire hydrant","stop sign","parking meter","bench","bird","cat","dog","horse","sheep","cow","elephant","bear","zebra","giraffe","backpack","umbrella","handbag","tie","suitcase","frisbee","skis","snowboard","sports ball","kite","baseball bat","baseball glove","skateboard","surfboard","tennis racket","bottle","wine glass","cup","fork","knife","spoon","bowl","banana","apple","sandwich","orange","broccoli","carrot","hot dog","pizza","donut","cake","chair","sofa","pottedplant","bed","diningtable","toilet","tvmonitor","laptop","mouse","remote","keyboard","cell phone","microwave","oven","toaster","sink","refrigerator","book","clock","vase","scissors","teddy bear","hair drier","toothbrush"]
app=Flask(__name__)
CORS(app)
cors=CORS(app,resources={r"/*":{"origins":"*"}})
@app.route('/' , methods=['POST'])
def index():
    d = ast.literal_eval(request.data.decode('utf-8'))
    h=d['height']
    w=d['width']
    score=d['threshold']/1000
    image=np.array(d['image']).reshape((h,w,3)).astype(np.uint8)
    image = image/255
    image=cv2.resize(image, (416, 416))
    infer = saved_model_loaded.signatures['serving_default']
    pred_bbox = infer(tf.constant(np.asarray([image]).astype(np.float32)))
    for key, value in pred_bbox.items():
        boxes = value[:, :, 0:4]
        pred_conf = value[:, :, 4:]
    boxes, scores, classes, valid_detections = tf.image.combined_non_max_suppression(
        boxes=tf.reshape(boxes, (tf.shape(boxes)[0], -1, 1, 4)),
        scores=tf.reshape(
            pred_conf, (tf.shape(pred_conf)[0], -1, tf.shape(pred_conf)[-1])),
        max_output_size_per_class=50,
        max_total_size=50,
        iou_threshold=iou,
        score_threshold=score)
    pred_bbox = [boxes.numpy(), scores.numpy(), classes.numpy(), valid_detections.numpy()]
    values=''
    for i in range(len(pred_bbox[0][0])):
        if np.all(pred_bbox[0][0][i]==0):
            break
        print(classe_names[int(pred_bbox[2][0][i])],pred_bbox[0][0][i],pred_bbox[1][0][i])
        values=values+str(int(pred_bbox[0][0][i][1]*w))+','
        values=values+str(int(pred_bbox[0][0][i][0]*h))+','
        values=values+str(int((pred_bbox[0][0][i][3]-pred_bbox[0][0][i][1])*w))+','
        values=values+str(int((pred_bbox[0][0][i][2]-pred_bbox[0][0][i][0])*h))+','
    return(values[:-1])
if __name__=='__main__':
    app.run(host='_._._._',port=5000,threaded=True,debug=True)

PS: the reshape at the beginning is needed because of the image source (an external software send it that way)


text:
Q: Windows Service Security I have a Windows Service (not a webservice) and I need to provide some security. ie. Only authorise users run methods of the service.
Is it possible to use certificates like you can do for webservices? Can anyone describe the process of how one would go about doing this?
Thanks!

A: Caveat : I have not done this before but it seems like one possible solution.
Create a WCF service and host it as a Windows Service.
There is a tutorial on MSDN as to how you can do that
You can use TCP / named Pipes to communicate and can configure security for either of these based on the security options options in WCF i.e.

*

*Transport

*Message

*Combination of Transport and Message

*TransportWithMessageCredential

*TransportCredentialOnly

For details on each of the security options above and how to use them you can also check out this article

A: You need windows service in a scenario where you want to do some continuous processing irrespective of user logged in. Your windows service would be running/processing even if no user is logged into system. To add on to this, windows service doesn't expose bunch of methods. It only gives you events like OnStart, OnStop so that you can control your service through Services.msc. In OnStart you merely fires off your business logic and keep doing it until you stop the windows service.
Probably windows service is not the right solution for your scenario.


text:
Q: centus 6 mysql 5.6 always automatically stop, restart mysqld will automatically stop after a while, the wireless cycle 1.Configuration environment:

*

*aliyun

*centos 6.3

*Apache 2.2.4

*mysql 5.6

*php 5.3.3

*WordPress

2.Problem Description:
mysql can start normal, but over a period (10 to 30 minutes) ranging from their own stop; SSH command line shown below
# /usr/bin/mysqld_safe: line 183:  9161 Killed                  nohup /usr/sbin/mysqld --basedir=/usr --datadir=/var/lib/mysql --plugin-dir=/usr/lib64/mysql/plugin --user=mysql --log-error=/var/log/mysqld.log --pid-file=/var/run/mysqld/mysqld.pid --socket=/var/lib/mysql/mysql.sock < /dev/null > /dev/null 2>&1

mysql stop and then directly start is not enough, will be reported as follows:
# service mysqld restart
Stopping mysqld:                                           [  OK  ]
MySQL Daemon failed to start.
Starting mysqld:                                           [FAILED]

But the first restart httpd, followed by the start mysqld will be able to normal up;
# service mysqld restart
Stopping mysqld:                                           [  OK  ]
MySQL Daemon failed to start.
Starting mysqld:                                           [FAILED]
[root@localhost ~]# service httpd restart
Stopping httpd:                                            [  OK  ]
Starting httpd:                                            [  OK  ]
[root@localhost ~]# service mysqld restart
Stopping mysqld:                                           [  OK  ]
Starting mysqld:                                           [  OK  ]

Mysqld.log :
2017-09-05 23:03:34 10926 [Note] InnoDB: Using atomics to ref count buffer pool pages
2017-09-05 23:03:34 10926 [Note] InnoDB: The InnoDB memory heap is disabled
2017-09-05 23:03:34 10926 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
2017-09-05 23:03:34 10926 [Note] InnoDB: Memory barrier is not used
2017-09-05 23:03:34 10926 [Note] InnoDB: Compressed tables use zlib 1.2.3
2017-09-05 23:03:34 10926 [Note] InnoDB: Using Linux native AIO
2017-09-05 23:03:34 10926 [Note] InnoDB: Using CPU crc32 instructions
2017-09-05 23:03:34 10926 [Note] InnoDB: Initializing buffer pool, size = 128.0M
InnoDB: mmap(137363456 bytes) failed; errno 12
2017-09-05 23:03:34 10926 [ERROR] InnoDB: Cannot allocate memory for the buffer pool
2017-09-05 23:03:34 10926 [ERROR] Plugin 'InnoDB' init function returned error.
2017-09-05 23:03:34 10926 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
2017-09-05 23:03:34 10926 [ERROR] Unknown/unsupported storage engine: InnoDB
2017-09-05 23:03:34 10926 [ERROR] Aborting

2017-09-05 23:03:34 10926 [Note] Binlog end
2017-09-05 23:03:34 10926 [Note] Shutting down plugin 'partition'
2017-09-05 23:03:34 10926 [Note] Shutting down plugin 'PERFORMANCE_SCHEMA'
2017-09-05 23:03:34 10926 [Note] Shutting down plugin 'FEDERATED'
2017-09-05 23:03:34 10926 [Note] Shutting down plugin 'INNODB_SYS_DATAFILES'
2017-09-05 23:03:34 10926 [Note] Shutting down plugin 'INNODB_SYS_TABLESPACES'
2017-09-05 23:03:34 10926 [Note] Shutting down plugin 'INNODB_SYS_FOREIGN_COLS'
2017-09-05 23:03:34 10926 [Note] Shutting down plugin 'INNODB_SYS_FOREIGN'
2017-09-05 23:03:34 10926 [Note] Shutting down plugin 'INNODB_SYS_FIELDS'
2017-09-05 23:03:34 10926 [Note] Shutting down plugin 'INNODB_SYS_COLUMNS'
2017-09-05 23:03:34 10926 [Note] Shutting down plugin 'INNODB_SYS_INDEXES'
2017-09-05 23:03:34 10926 [Note] Shutting down plugin 'INNODB_SYS_TABLESTATS'
2017-09-05 23:03:34 10926 [Note] Shutting down plugin 'INNODB_SYS_TABLES'
2017-09-05 23:03:34 10926 [Note] Shutting down plugin 'INNODB_FT_INDEX_TABLE'
2017-09-05 23:03:34 10926 [Note] Shutting down plugin 'INNODB_FT_INDEX_CACHE'
2017-09-05 23:03:34 10926 [Note] Shutting down plugin 'INNODB_FT_CONFIG'
2017-09-05 23:03:34 10926 [Note] Shutting down plugin 'INNODB_FT_BEING_DELETED'
2017-09-05 23:03:34 10926 [Note] Shutting down plugin 'INNODB_FT_DELETED'
2017-09-05 23:03:34 10926 [Note] Shutting down plugin 'INNODB_FT_DEFAULT_STOPWORD'
2017-09-05 23:03:34 10926 [Note] Shutting down plugin 'INNODB_METRICS'
2017-09-05 23:03:34 10926 [Note] Shutting down plugin 'INNODB_BUFFER_POOL_STATS'
2017-09-05 23:03:34 10926 [Note] Shutting down plugin 'INNODB_BUFFER_PAGE_LRU'
2017-09-05 23:03:34 10926 [Note] Shutting down plugin 'INNODB_BUFFER_PAGE'
2017-09-05 23:03:34 10926 [Note] Shutting down plugin 'INNODB_CMP_PER_INDEX_RESET'
2017-09-05 23:03:34 10926 [Note] Shutting down plugin 'INNODB_CMP_PER_INDEX'
2017-09-05 23:03:34 10926 [Note] Shutting down plugin 'INNODB_CMPMEM_RESET'
2017-09-05 23:03:34 10926 [Note] Shutting down plugin 'INNODB_CMPMEM'
2017-09-05 23:03:34 10926 [Note] Shutting down plugin 'INNODB_CMP_RESET'
2017-09-05 23:03:34 10926 [Note] Shutting down plugin 'INNODB_CMP'
2017-09-05 23:03:34 10926 [Note] Shutting down plugin 'INNODB_LOCK_WAITS'
2017-09-05 23:03:34 10926 [Note] Shutting down plugin 'INNODB_LOCKS'
2017-09-05 23:03:34 10926 [Note] Shutting down plugin 'INNODB_TRX'
2017-09-05 23:03:34 10926 [Note] Shutting down plugin 'ARCHIVE'
2017-09-05 23:03:34 10926 [Note] Shutting down plugin 'BLACKHOLE'
2017-09-05 23:03:34 10926 [Note] Shutting down plugin 'CSV'
2017-09-05 23:03:34 10926 [Note] Shutting down plugin 'MEMORY'
2017-09-05 23:03:34 10926 [Note] Shutting down plugin 'MRG_MYISAM'
2017-09-05 23:03:34 10926 [Note] Shutting down plugin 'MyISAM'
2017-09-05 23:03:34 10926 [Note] Shutting down plugin 'sha256_password'
2017-09-05 23:03:34 10926 [Note] Shutting down plugin 'mysql_old_password'
2017-09-05 23:03:34 10926 [Note] Shutting down plugin 'mysql_native_password'
2017-09-05 23:03:34 10926 [Note] Shutting down plugin 'binlog'
2017-09-05 23:03:34 10926 [Note] /usr/sbin/mysqld: Shutdown complete

2017-09-05 23:11:21 11670 [Note] InnoDB: Using atomics to ref count buffer pool pages
2017-09-05 23:11:21 11670 [Note] InnoDB: The InnoDB memory heap is disabled
2017-09-05 23:11:21 11670 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
2017-09-05 23:11:21 11670 [Note] InnoDB: Memory barrier is not used
2017-09-05 23:11:21 11670 [Note] InnoDB: Compressed tables use zlib 1.2.3
2017-09-05 23:11:21 11670 [Note] InnoDB: Using Linux native AIO
2017-09-05 23:11:21 11670 [Note] InnoDB: Using CPU crc32 instructions
2017-09-05 23:11:21 11670 [Note] InnoDB: Initializing buffer pool, size = 128.0M
2017-09-05 23:11:21 11670 [Note] InnoDB: Completed initialization of buffer pool
2017-09-05 23:11:21 11670 [Note] InnoDB: Highest supported file format is Barracuda.
2017-09-05 23:11:21 11670 [Note] InnoDB: The log sequence numbers 0 and 0 in ibdata files do not match the log sequence number 1600617 in the ib_logfiles!
2017-09-05 23:11:21 11670 [Note] InnoDB: Database was not shutdown normally!
2017-09-05 23:11:21 11670 [Note] InnoDB: Starting crash recovery.
2017-09-05 23:11:21 11670 [Note] InnoDB: Reading tablespace information from the .ibd files...
2017-09-05 23:11:21 11670 [Note] InnoDB: Restoring possible half-written data pages
2017-09-05 23:11:21 11670 [Note] InnoDB: from the doublewrite buffer...
2017-09-05 23:11:21 11670 [Note] InnoDB: 128 rollback segment(s) are active.
2017-09-05 23:11:21 11670 [Note] InnoDB: Waiting for purge to start
2017-09-05 23:11:21 11670 [Note] InnoDB: 5.6.37 started; log sequence number 1600617
2017-09-05 23:11:21 11670 [Note] Server hostname (bind-address): '*'; port: 3306
2017-09-05 23:11:21 11670 [Note] IPv6 is available.
2017-09-05 23:11:21 11670 [Note]   - '::' resolves to '::';
2017-09-05 23:11:21 11670 [Note] Server socket created on IP: '::'.
2017-09-05 23:11:21 11670 [Note] Event Scheduler: Loaded 0 events
2017-09-05 23:11:21 11670 [Note] /usr/sbin/mysqld: ready for connections.
Version: '5.6.37'  socket: '/var/lib/mysql/mysql.sock'  port: 3306  MySQL Community Server (GPL)

3.Have tried other ways:
Uninstall and reinstall mysqld, the problem still exists;


text:
Q: How to make infinite enumerator Suppose I have an array
array = [1,2,3]

I need to create such a enumerator that will return values in cyclic manner:
array.next #=> 1
array.next #=> 2
array.next #=> 3
array.next #=> 1
array.next #=> 2
...

I believe there's a neat solution for that

A: Array#cycle / Enumerable#cycle does what you are looking for:
e = [1,2,3].cycle  #=> #<Enumerator: [1, 2, 3]:cycle>

e.next             #=> 1
e.next             #=> 2
e.next             #=> 3
e.next             #=> 1
e.next             #=> 2

(1..3).cycle returns equivalent values.


text: Q: Conditional probability of two values I have a data set of two values, that can be true or false. Based on this I want to calculate what is the probability of happening B if A is true. I understand, that this should be calculated using Bayes' theorem, but I'm stuck with this.


text:
Q: Application appears in the menu without icon and in duplicate I have a problem with my deskop file, I suppose, for urxvt (rxvt-unicode).
When I open urxvt (from the menu with the favorite icon or for the "seach bar"), a new icon appears in the menu bar instead of add the little red dot near the rxvt icon.
The problem doesn't occur with other applications.
In the example below, I click on my terminal icon and it opens a new icon (with gears) at the bottom of the bar
enter image description here
If I put the mouse over the terminal icon (on top), this message appears : Rxvt Color Unicode Terminal, when I put it over the bottom icon, this message appears: URxvt.
My configuration
cat /usr/share/applications/rxvt-unicode.desktop
[Desktop Entry]
Version=1.1
Name=Rxvt Color Unicode Terminal
Comment=Terminal emulator
GenericName=Terminal
Exec=urxvt
Icon=/usr/local/share/icons/iterm3.png
Type=Application
Categories=Utility;TerminalEmulator;
StartupNotify=True
Keywords=shell;prompt;command;commandline;cmd;

uname -a
Linux cse-port 5.11.0-22-generic #23-Ubuntu SMP Thu Jun 17 00:34:23 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux

lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 21.04
Release:        21.04
Codename:       hirsute

Thanks

A: Problem solve with this configuration.
I don't know which parameter is important.
[Desktop Entry]
X-AppInstall-Package=rxvt-unicode
X-AppInstall-Popcon=71
X-AppInstall-Section=universe

Name=Rxvt Color Unicode Terminal
Comment=Use the command line
TryExec=urxvt
Exec=urxvt
Icon=/usr/local/share/icons/iterm3.png
Type=Application
Categories=Utility;TerminalEmulator;
StartupNotify=true
Keywords=Run;
Actions=New

[Desktop Action New]
Name=New Rxvt Color Unicode Terminal
Exec=urxvt
OnlyShowIn=Unity

X-Ubuntu-Gettext-Domain=app-install-data


text:
Q: Create 3 tables from 1 table in mssql I am creating a database of horse racing data. The data is scraped from the net, into excel and then into a single table Race_Master in a MS SQL database.
The columns include such data as:
date
pos
odds
btnby
going
horsename
trainername
jockeyname

Of course, the names of the horses, jockeys and trainers are stored in an inefficient and non-relational way, there are many duplicated entry's. So I have created 3 new tables:
horse_name
trainer_name
jockey_name

There are no duplicates in any of those tables.
How can I now create a new table which will take the data from Race_Master and instead of using the names of the horses trainers and jockeys, refer to those respective tables and use their id's as a reference?

A: If you already have created a table then.....
INSERT INTO NewTable (MasterID, JockeyID, TrainerID, HorseID)
SELECT M.MasterID, J.JockeyID, T.TrainerID , H.HorseID
FROM Race_Master M
INNER JOIN  Jockeys J   ON M.JockeyName = J.JockeyName
INNER JOIN  Trainer T   ON M.TrainerName = T.TrainerName
INNER JOIN  Horse   H   ON M.HorseName   = H.HorseName

If you want to create a table on the fly
SELECT M.MasterID, J.JockeyID, T.TrainerID , H.HorseID
  INTO New_Table
FROM Race_Master M
INNER JOIN  Jockeys J   ON M.JockeyName = J.JockeyName
INNER JOIN  Trainer T   ON M.TrainerName = T.TrainerName
INNER JOIN  Horse   H   ON M.HorseName   = H.HorseName

A: To create the table:
create table dbo.Race(
     ID    int identity not null primary key
    ,JockeyID  int references dbo.Jockey(ID)
    ,HorseID   int references dbo.Horse(ID)
    ,TrainerID int references dbo.Trainer(ID)
)
go

And to insert it's rows:
with
jockey as (
    select JockeyID
    from dbo.Jockey j
    join dbo.Race_Master
      on Race_Master.JockeyName = j.JockeyName
),
trainer as (
    select TrainerID
    from dbo.Trainer t
    join dbo.Race_Master
      on Race_Master.TrainerName = t.TrainerName
),
horse as (
    select HorseID
    from dbo.HOrse h
    join dbo.Race_Master
      on Race_Master.HorseName = h.HorseName
)
insert Race(JockeyID,HorseID,TrainerID)
select jockey.ID,horse.ID,trainer.ID;


text:
Q: Refresh template using templateUrl in angular I have web app that is very slow (there are few http connections that are very slow even on localhost) so reloading the page when template is change is painful, is there a way to refresh the directive's template file fetch using templateUrl from console?

A: I don't know which build do you use, but for example with gulp, you can use the gulp-angular-templatecache that will put in cache all your templates.
So each time your app requests a template, it will fetch in the cache first.
Here is a gist that can help you.


text:
Q: Dividing a deck among four people, multinomial coefficients
A deck of cards has 52 cards. We randomly divide the cards among 4 players, each getting 13 cards. What is the total number of ways the cards can be divided among the 4 players, assuming we don't make a distinction among the players?

We can use binomial or multinomial coefficients:
$${52 \choose 13 \space13 \space13 \space 13} = {52 \choose 13} {39 \choose 13} { 26 \choose 13} {13 \choose 13}$$
However, apparently we have to divide by $4!$ "because the order of the players doesn't matter". Intuitively, I'm having trouble grasping why we have to divide it by $4!$ (even though I know the reason). I don't grok it.
When I use multinomial coefficients, I use permutations of letters to provide intuition, e.g.:
${8 \choose 2 \space 2 \space 2 \space 2}$ is the number of unique letter sequences of $AABBCCDD$. By dividing by $4!$, what kind of different solutions are we "merging"? Things like $AABBCCDD$ and $BBCCDDAA$ would be considered as one, perhaps? Can anyone help provide me with intuition?


text:
Q: Console.WriteLine Method in c# is not writing its argument but the argument from another class I'm using Visual Studio 2013. I've created a blank solution in witch I have two different projects: "HelloCSharp" and "PrintMyName". In the first project there is a class with the following source code:
namespace HelloCSharp
{
class HelloCSharp
{
    static void Main(string[] args)
    {
        System.Console.WriteLine("Hello, C#!");
    }
}

}
In the "PrintMyName" project there is a class with the following source code:
namespace PrintMyName
{

class PrintMyName
{
    static void Main(string[] args)
    {
        System.Console.WriteLine("Rosen");
    }
}
}

When I try to run this program, the method doesn't write the argument "Rosen" but the argument from the another class "Hello, C#!".
I try with alternative code but the result is the same ("Hello, C#!"):
namespace PrintMyName
{
class PrintMyName
{

    static void Main(string[] args)
    {
        String myFirstName = "Rosen";
        System.Console.WriteLine(myFirstName);
    }
}
}

If someone have an idea what's the reason of this problem and how can I print my name, please send me an answer!
Thanks!

A: You're probably not running the program you think you're running. Check that the correct project is set as start-up project in Visual Studio.
To change it, right click the project you want to run, and look for Set Start Up Project (with a gear wheel symbol).


text:
Q: How can I theme Synaptic Manager? I use Lubuntu 12.04 and a gtk2 theme, Elegant Arch.
With such a theme, gtk2 applications like Thunar will be themed, while others like Nautilus, would be not (see this question ant the images there).
Because I wanted to theme gtk3 applications like Nautilus, Audacious etc., I have copied the "gtk-3" folder from the main folder of a gtk3 theme into the main folder of my Elegant arch theme, which is in home/username/themes. Using the gtk3 folder from this full flat theme I got a pretty similar look in gtk2 and gtk 3 apps.
Lubuntu Desktop Center, Ubuntu Desktop Center, Network Options and other such apps are now themed (before they were not). Even Update Manager is.

But why is Synaptic Manager not themed?

A: The application you are opening is one that needs root  privileges. You could also link the files to use them:
sudo ln -s ~/.themes /root/.themes
sudo ln -s ~/.icons /root/.icons
sudo ln -s ~/.fonts /root/.fonts

A: I'm using LXAppearance to change themes on i3wm. You have to open LXAppearance as root and apply a theme to change the theme of applications that run as root.
This will change that ugly Raleigh theme that the Synaptic Package Manager is using.

A: It looks like Synaptic Manager is a gtk2 application. So, all this has nothing to do with theming gtk3 apps.
But in order to use a theme for Synaptic, that theme has to be put in /usr/share/themes.
I figured where to put the theme by the fact that the lubuntu-default theme, which has gtk2+3 support and had themed Synaptic, was in /usr/share/themes, while Elegant Arch theme was in ~/.themes. Also, Synaptic uses gtk2: when I put Elegant Arch theme (with the gtk3 folder of the full flat theme inside) into /usr/share/themes, Synaptic takes the theming of Elegant Arch.