text:
Q: Spring Cloud Vault picking up properties from wrong profile In my Spring Boot project I defined 4 profiles ide,dev,test and prod. When I ran the project using IntelliJ with profile ide, everything works fine and properties are retrieved from ide profile in the Vault. But during deployment in dev server when I select the dev profile using the argument -Dspring.profiles.active=dev dev profile is being selected and but ide profile properties are being retrieved
CustomVaultConfigurer.java
@Configuration
public class CustomVaultConfigurer  implements VaultConfigurer
{
    @Override
    public void addSecretBackends(SecretBackendConfigurer configurer)
    {
                configurer.add("secret/app/pres/ide");
        configurer.add("secret/app/pres/dev");
        configurer.add("secret/app/pres/test");
        configurer.add("secret/app/pres/prod");

        configurer.registerDefaultGenericSecretBackends(false);
        configurer.registerDefaultDiscoveredSecretBackends(true);
    }
}

Error Log:
2020-05-27 19:28:25.663  INFO 1 --- [           main] gov.cancer.ccr.oit.pres.PresApplication  : The following profiles are active: dev
2020-05-27 19:28:28.495  INFO 1 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data JPA repositories in DEFERRED mode.
2020-05-27 19:28:29.710  INFO 1 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 1203ms. Found 55 JPA repository interfaces.
2020-05-27 19:28:30.142  INFO 1 --- [           main] o.s.cloud.context.scope.GenericScope     : BeanFactory id=87545ee5-101d-3ebb-a79a-d12f99f15e9c
2020-05-27 19:28:31.002  INFO 1 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler@70c53dbe' of type [org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-05-27 19:28:31.011  INFO 1 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'methodSecurityConfig' of type [gov.cancer.ccr.oit.pres.security.MethodSecurityConfig$$EnhancerBySpringCGLIB$$8721baa3] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-05-27 19:28:31.033  INFO 1 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'methodSecurityMetadataSource' of type [org.springframework.security.access.method.DelegatingMethodSecurityMetadataSource] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-05-27 19:28:31.608  INFO 1 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2020-05-27 19:28:31.635  INFO 1 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2020-05-27 19:28:31.636  INFO 1 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.35]
2020-05-27 19:28:31.778  INFO 1 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2020-05-27 19:28:31.778  INFO 1 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 6069 ms
2020-05-27 19:28:32.616  INFO 1 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2020-05-27 19:28:32.909  INFO 1 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2020-05-27 19:29:03.630 ERROR 1 --- [           main] com.zaxxer.hikari.pool.HikariPool        : HikariPool-1 - Exception during pool initialization.

com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host localhost, port 1433 has failed. Error: "Connection refused (Connection refused). Verify the connection properties. Make sure that an instance of SQL Server is running on the host and accepting TCP/IP connections at the port. Make sure that TCP connections to the port are not blocked by a firewall.".

but when I place ide profile at the end(shown below) of the list, it works
configurer.add("secret/app/pres/dev");
configurer.add("secret/app/pres/test");
configurer.add("secret/app/pres/prod");
configurer.add("secret/app/pres/ide");

A: Okay. Dumb part on my end. As per Marks comment When you're using configurer.add(…) in combination with configurer.registerDefaultGenericSecretBackends(false) then Spring Cloud Vault does not look at spring.profiles.active at all but rather uses what your VaultConfigurer specifies.
The updated VaultConfigurer looks like below, and active profile is retrieved from
VaultConfigurer.java
@Configuration
public class CustomVaultConfigurer  implements VaultConfigurer
{
    @Autowired
    private Environment environment;

    @Override
    public void addSecretBackends(SecretBackendConfigurer configurer)
    {
        //Get active profile from environment, if none exist select DEV profile
        if(environment.getActiveProfiles().length > 0)
            configurer.add("secret/app/pres/"+environment.getActiveProfiles()[0]);
        else
            configurer.add("secret/app/pres/dev");

        configurer.registerDefaultGenericSecretBackends(false);
        configurer.registerDefaultDiscoveredSecretBackends(true);
    }
}


text:
Q: Checking if a string contais substrings in correct positions So what I am tasked to do is check if an email has a specific form.It has to be itxxxxxx@uom.edu.gr, where the x's can be whatever but the rest is a must.
If the rest is slightly different, I must print that this user is not accepted. I have no idea how to do that. I have written no code because I do not know how to tackle this problem.

A: You can use a regular expression.
A pattern that matches your input is: ^it\w*@uom.edu.gr. the \w* means

Zero or more of any word character (letter, number, underscore)

If you want to include more symbols e.g. "." but to exclude the "@" for obvious reasons you can change the pattern to use [^@]* which means

Zero or more of any single character excluding the "@".

So the pattern becomes: ^it[^@]*@uom.edu.gr
Use any of the two suits your needs.
Example code:
Pattern p = Pattern.compile("^it\\w*@uom.edu.gr");
Matcher m = p.matcher("itxxxxxx@uom.edu.gr");
boolean b = m.matches();

The above can be expanded as per you have been requested, e.g.:
public static void main(String[] args)throws Exception{

    String email = "itxxxxxx@uom.edu.gr";

    Pattern p = Pattern.compile("^it\\w*@uom.edu.gr");
    Matcher m = p.matcher(email);
    boolean b = m.matches();
    if(b) {
        System.out.println("Valid email");
    } else {
        System.out.println("Invalid email.");
    }

}

A: Use startsWith and endsWith
String var = "itxxxxxx@end.com";
if(var.startsWith("it") && var.endsWith("end.com")){
    // your code
}
else {
   // String do not start with it or it does not end end.com
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Retrieving all POST data parameters into map with Java Jersey I'm trying to gather all parameters of an HTTP POST request into a map, however it's not working.
With a GET, I used:
@Context
private HttpServletRequest request;

and
@GET
@Path("/{uuid}/invoke/{method}")
public Response invokeMethod (
    @PathParam("uuid") String uuid,
    @PathParam("method") String methodz
) {
    Map<String, String[]> params = request.getParameterMap();

and it returned the map. However, when sending form data via a POST instead of inline with the URL, the map is being returned as NULL.
Is there a similar way to retrieve all the parameters at once using a POST?
EDIT:
My data is being submitted as a serialized JSON, so using a cURL statement as an example:
curl --data "firstname=john&lastname=smith" http://localhost:8080/uuid1/apitest/method1

Ideally, I'd want to get a hashmap of something like:
ParamMap["firstname"] = "john"
ParamMap["lastname"] = "smith"

Also, the parameters won't be static, so this cURL:
curl --data "job=construction" http://localhost:8080/uuid2/apitest/method2

would result in:
ParamMap["job"] = "construction"

A: Finally got this resolved using this thread:
Jersey: Consume all POST data into one object
My new function is:
@POST
@Path("/{uuid}/invoke/{method}")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response invokeMethod (
    MultivaluedMap<String,String> params,
    @PathParam("uuid") String uuid,
    @PathParam("method") String method
) {

Variable 'params' is now a map containing form data key/value pairs.

A: You can try following code
@POST
@Path("/{uuid}/invoke/{method}")
public Response invokeMethod (
    @Context UriInfo request
) {
    Map<String, List<String>> params = request.getPathParameters();
  }

You no need to write
 @Context
 private HttpServletRequest request;

Now You can get idea...


text:
Q: What is "good" single-block read latency? Is there a reference anywhere that I can go and see what kind of single-block read latency I can expect from Oracle given a certain hardware configuration?
I can run a query to show the current performance (select * from V$SYSMETRIC_HISTORY where metric_id=2144 order by 1) but what I don't understand is how to evaluate the result - what is "good" or "bad" given a certain set of hardware?  And how would load impact that?


text:
Q: top left image not aline with the menu In my page, the top left image which is logo2.jpg shifts to right, and I want it to be at the same line of menu that is below it. How can I do that?
The page is here, if it helps:
http://www.dilyurdu.com
#logo {
margin:0 auto; width: 975px; position:relative;
}
#top {
position:relative; top:0px; left:0px; width:100%; height:95px;background:url("vocab_dosyalar/back2.jpg") top repeat-x;
}
#logoicerik {
position:absolute; top:2px;
}
#logoicerik2 {
position:absolute; top:2px; left:357px;
}

A: your container class has width: 960px but your wraper(sic) class has width: 990px
so you need to make sure they both have the same width: I'd recommend making both 990px by changing the width of container
.container {
  WIDTH: 990px;
}


text: Q: Azure SQL Server Database We use SQL Sever as a Service in Azure cloud. Created WEB API and hosted on Azure Cloud under WEB APP. we are able to read from the DB using our WEB API, but unable to Write into DB using WEB API.  any clue ? thanks


text:
Q: Methods can only be called from within the same library Im using third party library.I Just want to replicate the same functionality.Im getting a warning saying that
Method can only be called from within the same library
Im still able to use the application perfectly without any issues.
What are the consequences of ignoring the warning from the complier and decides to go live with that?

A: If your app always uses a fixed version of the library, there should be no issues whatsoever. It's just a linter warning, and can be safely ignored.
However, that API may change in future versions and break your application if your app uses those new versions.
So, the decision is yours, depending on how your app uses that library.


text:
Q: adding labels on bottom of barchart I'm quite new to lattice so for me its a trial and error run here.
It seems to customize lattice graphics cannot be done with the typical r-understanding.
I would like to add something like count(percentage) beneath each bar which is supposed to look like this when its done:

As you can see my code does not label the bars right. Not all of them and wrong. The first is supposed to be 20(0.1%).
Here my code:

grp1<-rep("grp1",20)
grp2<-rep("grp2",40)
grp3<-rep("grp3",60)
grp4<-rep("grp4",80)
grp <- c(grp1,grp2,grp3,grp4)

barchart(grp,horizontal=F,
    par.settings = list(
    plot.polygon = list(col = c("#1E4150","#28556E","#32698C","#3C7DAA")) ),
        panel = function(x, y, subscripts, ...){
            X <- table(x)
            panel.barchart(x,y,...)
            percentages <- paste(round(table(X)/length(X),2),"%",sep="")
            lab1 <- paste( "(",percentages, sep="")
            lab1 <- paste( lab1,")", sep="")
            abs <- table(X)
            panel.text(1,-3, label = paste(abs,lab1), cex=0.8)
        }
)

A: I think maybe you wanted to do something more like this:
barchart(grp,horizontal=F,
    par.settings = list(
    plot.polygon = list(col = c("#1E4150","#28556E","#32698C","#3C7DAA")) ),
        panel = function(x, y, subscripts, ...){
            panel.barchart(x,y,...)
            percentages <- paste(round(y/sum(y),2),"%",sep="")
            lab1 <- paste( "(",percentages,")", sep="")
            panel.text(x,-3, labels = paste(y,lab1), cex=0.8)
        }
)


text:
Q: The text recognition of MLkIT does not recognize non-english text I implemented the text recognition of MLkit on IOS but it could not recognize non-English text (e.x Arabic text).
It works in English only.
Here are the docs
https://developers.google.com/ml-kit/vision/text-recognition/ios
My code:
        let textRecognizer = TextRecognizer.textRecognizer()
        let visionImage = VisionImage(image: image)

        textRecognizer.process(visionImage) { result, error in
            guard error == nil, let result = result else { return }
            let resultText = result.text
            print("MLKit : " + resultText)
        }

A: Update: If it does not need to be completely local (on-device without network), you can try MLKit for cloud, which supports "100+ different languages and scripts.". Firebase Text Recognition
For local inference:
Googles 'MLKit text recognition' is based on 'TensorFlow Lite' which uses local models in order to recognize the text.
From my researches Google does not state that the predefined model is exclusively working for Latin alphabet. But it seems like that.
So you have three options now:

*

*Look for a custom "TensorFlow Lite" model which is trained for arabic alphabet.

*Train your own "TensorFlow Lite" model: TensorFlow Lite Model Maker

*Find/Train a "Tensor Flow" model (not lite!) and convert it to a "TensorFlow Lite" Model


text:
Q: Error Loading JSON from configuration file using ConfigParser I have this configuration file
[section1]
namespace = {'pro1':'http://pro1/go','pro2':'http://pro2/go','pro3':'http://pro3/go'}

Reading the file with ConfigParser I got:
>>> from ConfigParser import ConfigParser
>>> Config = ConfigParser()
>>> Config.read("myfile.ini")
>>> name = Config.get("section1", "namespace")
>>> name
"{'pro1':'http://pro1/go','pro2':'http://pro2/go','pro3':'http://pro3/go'}"

To convert the string to dict/json:
>>> import json
>>> namespace = json.loads(name)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\json\__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "C:\Python27\lib\json\decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Python27\lib\json\decoder.py", line 382, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 1 column 2 (char 1)
>>>

Any ideas?

A: That's not valid JSON; unlike Python dicts, JSON is very strict - you always need to use double quotes.
namespace = {"pro1":"http://pro1/go","pro2":"http://pro2/go","pro3":"http://pro3/go"}


text:
Q: Android Wear automatic layout This is my first try with Android Studio, i have used Eclipse for my previous applications.
I am create an application for Google Wear and i want to include the function to automatic change the layout depending on square or round watch.
And this is actually the default code but i cant get it to work, maybe someone could point me in the right direction.
It always uses the square layout, i have tried it on actual round watch (Moto 360) and also in the layout windows in Android Studio and even if i pick the Wear Round option it still uses the square layout.
Activity.java
private TextView mTextView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_wear_activity);
    final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
    stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
        @Override
        public void onLayoutInflated(WatchViewStub stub) {
            mTextView = (TextView) stub.findViewById(R.id.text);
        }
    });
}

rect_main_wear_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainWearActivity"
tools:deviceIds="wear_square">

<TextView
    android:id="@+id/text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello_square" />
</LinearLayout>

round_main_wear_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainWearActivity"
tools:deviceIds="wear_round">

<TextView
    android:id="@+id/text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:text="@string/hello_round" />
</RelativeLayout>

main_wear_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.wearable.view.WatchViewStub
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/watch_view_stub"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:rectLayout="@layout/rect_main_wear_activity"
app:roundLayout="@layout/round_main_wear_activity"
tools:context=".MainWearActivity"
tools:deviceIds="wear">
</android.support.wearable.view.WatchViewStub>

A: In terms of the AndroidWear Round emulator this was clearly a bug. Today Google released the SDK Tools 23.0.4 as well as a new ARM EABI v7a system image (rev2) which should fix the bug you've described in your post.
Here's the "official" statement by Wayne Piekarski:

The Android Developer Tools team has just released SDK Tools 23.0.4.
  This version contains an update for the AndroidWearRound emulator, so
  that there is now one correct profile instead of the three different
  profiles that existed before. So go to the Android SDK Manager and
  download the update to SDK Tools 23.0.4, as well as Android Wear ARM
  EABI v7a System Image rev. 2, and then recreate your AndroidWearRound
  AVD in the AVD Manager.

I've just tested this and I can confirm that this bug is solved. However it's still not possible to use the Host GPU. (Problem is described here)


text:
Q: DNS configuration causing some confusion across platforms I'm pretty sure this is down to the DNS configuration for the domain that has houses the 192.168.0.0 PTR records (which belongs to a company we bought). Is this clear enough to someone that they can explain what was done incorrectly?
The problem presents itself on Windows as IP addresses that are in our network being transformed to IP addresses outside of our network.
On *NIX like systems including OSX:
$ host 192.168.0.1
1.0.168.192.in-addr.arpa is an alias for 1.128-27.0.168.192.in-addr.arpa.
1.128-27.0.168.192.in-addr.arpa domain name pointer foo.bar.

The IP address 192.168.0.1 is a load balancer for foo.bar
$ host foo.bar
foo.bar is an alias for foo.baz.
foo.baz has address 10.0.0.1

foo.baz is a monitoring and analytics service we subscribe to that forwards to 192.168.0.1
That configuration seems kinda' screwy, it's what we inherited.
Here's where it gets more confusing, in Windows when we resolve the load balancer IP and get this:
PS C:\> [System.Net.Dns]::GetHostEntry("192.168.0.1")

HostName                                Aliases                                 AddressList
--------                                -------                                 -----------
foo.baz                                 {}                                      {10.0.0.1}

What is Windows doing to seemingly make extra lookups, and why?


text:
Q: which snap command is eqivalent to `apt depends ` in apt If I get it right, then snap installs the application package which contains a binary and the libraries the application depends on, if they're not installed already.
But I wonder how I can view these libraries the application depends on like I can do with apt depends <application> in apt.

A: As far as I can tell, the closest you can get is via
snap connections

It will list the connections that various snaps provide and have to each other and the system.
Kudos to this answer for pointing me in the right direction.

A: tl;dr: there's no such thing, because snaps don't have dependencies.
Snaps don't install dependencies if they're not already installed. They literally bundle them along with the rest of the snap. For example, if you have PHP 7.1 installed as a Debian package, and you install the Nextcloud snap, the Nextcloud snap will be using PHP 7.3 because it includes it inside the snap. In fact, it's confined to the point of not even being able to find out if you have PHP already installed or not, much less have the ability to install more stuff on your host.
Why do they work this way? One of the reasons is so that snap developers can rest assured that you're using exactly what they tested. To re-use the Nextcloud snap example, those maintainers can rest a lot easier releasing updates knowing that it's impossible for any of their users to be using anything other than PHP 7.3. If they had to make sure they tested it against every possible PHP version, releases would be a lot slower and a lot more risky.
Now, time for a little caveat. While snaps don't have traditional dependencies, it's possible for snaps to share content between each other using a special content interface. In that sense it's possible to create snap A that doesn't work properly unless a snap that's providing the content it requires is also installed. However, that doesn't imply that snap A depends on snap B, it implies that snap A depends on something providing it with a particular set of content; that might be snap B, but could also be snap C. For the most part, you can completely ignore this caveat and say "snaps bundle their dependencies."

A: The objective of Snaps is to hide that from you.
However, you can look up the pre-Snap package which is the equivalent for the app and find your dependencies that way by opening a browser and going to "ubuntu man ".


text:
Q: ¿Por qué JS permite declarar dos constantes con el mismo nombre? Estoy siguiendo un tutorial sobre el framework Express en NodeJs y empieza:

const { Router } = require('express');
const router = Router();

Imagino que es porque la primera no es una constante, pero entonces que "estado" tiene esa primera linea antes de declarar la segunda? Por lo que he leído la primera es sólo una forma de sacar el método Router prefabricado que tiene Express. Pero y si luego por casualidad pongo una variable con nombre "Router" daría error? La primera línea es realmente una constante o no?

A: JavaScript no permite declarar dos constantes con el mismo nombre, hay que recordar que JavaScript es case sensitive lo que quiere decir que null === null es verdadero, mientras que null === NULL dara un error ya que NULL no está declarado.
En tu primera linea, Router si es una constante que estás asignando por Object destructuring, pongo un ejemplo:

const person = {
  name: 'Carlos',
  lastname: 'Proaño',
}
const { name, lastname } = person;

console.log(`${name} ${lastname}`);

Que es lo mismo que hacer esto:

const person = {
  name: 'Carlos',
  lastname: 'Proaño',
}
const name = person.name;
const lastname = person.lastname;

console.log(`${name} ${lastname}`);

En tu caso en particular estás obteniendo la función Router de la librería express, mientras que en la segunda linea estás asignando lo que sea que la función Router retorne, otro ejemplo:

const acciones = {
  Hola: () => 'Hola',
  Adios: () => 'Adios',
};

const { Hola } = acciones;
const hola = Hola();
console.log(hola);

A: El utilizar el identificador const ayuda a determinar que tipo de datos es, veamos lo siguiente ejemplo
"use strict";

const Router = "Soy el Router 1";
const Router = "Soy el router 2";

console.log(Router)

Que como resultado me va a dar

"SyntaxError: Identifier 'Router' has already been declared

Entonces como puedes notar identifica que ambas constantes son la misma por que el nombre así lo determina, para corregir ese punto revisa este ejemplo
"use strict";

const Router = "Soy el Router 1";
const router = "Soy el router 2";

console.log(Router)
console.log(router)

Me devuelve
"Soy el Router 1"
"Soy el router 2"

Porque JS es sensible a mayúsculas y minúsculas; entonces vas a evitar la colisión de nombres en este caso específico haciendo uso del identificador para saber si lo que declaras es const o no


text:
Q: Solr indexing HTML entities I am indexing documents by Solr, which were scraped from the web. The documents contain HTML entities (such as £ or £). Mostly the documents contain central european characters. Is there any charfilter for this task? I know solr.MappingCharFilterFactory, but using this would mean, that I have to define the mappings myself. I would be happier with a shared solution maintained by a community. Thanks for your help!

A: There is solr.HTMLStripCharFilterFactory, which converts HTML entities, but it also strips HTML tags.


text:
Q: How get step count from background app using JobScheduler The Android docs for the STEP_COUNTER sensor are a bit confusing.
According to this: Android Sensor doc I should always register the STEP_COUNTER sensor because otherwise the step counter sensor will not count at all. That is all fine and works as expected up until I think Android 10 when sensor events are no longer sent to background apps.
So then I tried to take the advice from this other step counter doc recommending using a JobScheduler to read the last value periodically. Now, afaik there is no way to get the latest value from a sensor, I must register a SensorEventListener as always.
So, now I tried to combine the two advices, always register the step counter sensor so the hardware sensor is counting then since I always get a fresh event when I register my listener, I tried to unregister and re-register this listener when the JobScheduler executed but I have not been able to get the latest step count when in background on my Pixel running Android 11 no matter what method I have tried.
I know we have Google Fit but for this specific scenario, using the basic step counter would be good enough if I could read out the latest value also when the JobScheduler runs as indicated in the documentation.
Anyone knows if this should still be possible or is it just that the docs are not updated?

A: Your app should be in foreground mode to get sensors data. Works for me with attaching foreground notification to worker (workmanager + setForegroundAsync). I think you solution will also work if foreground service  will be active.


text:
Q: Java 11: why "The import xxx cannot be resolved" even with module-info informing it is required I have read about modularity since Java 9. I am aware I have to create a module-info and infor which package is exposed and required. I can see I do have Java 11 on my classpath. But I am getting the error mentioned on topic. More precisely, while building, I get this error log
INFO] --- maven-compiler-plugin:3.8.0:compile (default-compile) @ zuul ---
[WARNING] Can't extract module name from xpp3_min-1.1.4c.jar: Provider class org.xmlpull.mxp1.MXParser,org.xmlpull.mxp1_serializer.MXSerializer not in module
[WARNING] ********************************************************************************************************************
[WARNING] * Required filename-based automodules detected. Please don't publish this project to a public artifact repository! *
[WARNING] ********************************************************************************************************************
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 3 source files to C:\_d\WSs\soteste\zuul\target\classes
[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] /C:/_d/WSs/soteste/zuul/src/main/java/module-info.java:[24,18] module not found: common
[INFO] 1 error

I am missing some extra setup in order to make the class from common project visible to other project?
PS1: I followed Import XXX cannot be resolved for Java SE standard classes and setup to alternative JRE.
PS2.: I don't think this has something related to Eclipse. BTW, I am using this version:
Eclipse IDE for Enterprise Java Developers.
Version: 2018-12 (4.10.0)
Build id: 20181214-0600
OS: Windows 10, v.10.0, x86_64 / win32
Java version: 11.0.2
In my zuul project:
import com.test.common.security.JwtConfig;

@EnableWebSecurity
public class SecurityTokenConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private JwtConfig jwtConfig;

...
module-info.java
module zuul {
...
    requires common;

}

In my common project
@Getter
@ToString
public class JwtConfig {

...
module-info.java
module common {
    exports com.test.common.security;
    exports com.test.common;
...
}

A: I found the issue. Probably it will seem very silly for others more experienced with Java9+ but for me took a while to find the root cause. Hopefully it can be usefull for future readers.
The problem: common project was in classpath instead of module-path

The solution: just move to module-path as sugested by Eclipse when I handed over requires common; in module-info.java When I handovered import com.test.common.security.JwtConfig; on SecurityTokenConfig.java the solution proposed is completed diferent from the one when I handed over module-info.java (maybe a modest suggestion to Eclipse team would be revview it from now on but it is beyond the purpose of this question).

Credits to https://www.eclipse.org/community/eclipse_newsletter/2018/june/java9andbeyond.php
*** edited
Although I still consider the above solution as the answer to my question I must admit that after fixed this issue I stumbled on a new issue and I realize that, at least for my case, even using Java 11 I must avoid modularity (Jigsaw). Future readers may get interested on this thread also
Java 11 without modularity: package does not exist while it is added as maven dependency


text:
Q: What is the syntax for adding multiple strings to one variable in Java? Okay the thing i want to do is make a variable like Line = "hey","you",Mom".
Then later I want to be able to call Line 0 and get the string "hey".
I have something like this:
String[] history = new String "hey","you","Mom";

public String getLine(int index)
{
   if (index < 0 || index >= this.history.length)
       return null;
}

But this is not working..
How do i make this list?  I'm new with the syntax in java.

A: It's
String[] history = new String[] { "hey", "you", "Mom" };

A: String[] history = new String[] {"hey","you","Mom"};
String hey = history[0];

This creates a String array with size 3 initialized with the strings hey, you and Mom.
Another option is to use a List:
List<String> history = Arrays.asList("hey","you","Mom");
String hey = history.get(0);

A: You didn't return anything when the index was in range:
And array initialization works like this:
String[] history = new String[] { "hey","you","Mom" };

public String getLine(int index)
{
  if (index < 0 || index >= this.history.length)
    return null;
  else
    return history[index];
}

A: String[] history = new String[] {"hey", "you", "Mom"};

Alternatives:

*

*List<String> words = Arrays.asList("hey", "you", "Mom");

*String str = "Hey you Mom"; String[] words = str.split(" ")


text:
Q: Windows Forms - no C# source code? I'm new to Windows Forms.
I'm not fully understanding why can't I see methods definitions? Am I only allowed to look at declarations?
For example, there is
public class ListBox : ListControl

I want to see how its method is working(source code, not Microsoft comments):
public override string ToString();

I only see this definition and when I'm pressing "Go to definition", it transfers me to this declaration.
Can someone please explain is System.Windows.Forms code is "hidden" ? Can someone describe what's the idea?

A: .net is closed source so you cant see exact codes, not only winforms you cant see any class definition of framework. If you want you can use reflector.

A: Yes, there is the official source code released by Microsoft since December 2018 and can be seen on Github. There is an alternative (buggy) implementation from Mono.


text:
Q: Paste a HTML table into Excel, how to keep the line break in cell I have a simple html table, for example, just one cell, but when I copy the dom node, and paste it into excel, it will be recognize as two rows, How to make Excel get the correct paste data.

1
2

I tried to add css style
br {mso-data-placement:same-cell;},

But it only works in IE.
Note, copy a plain text out is not OK, i need to add color, font information on cells.

A: It looks like Firefox entirely ignores the mso-data-placement directive; it doesn't appear in the Firebug style panel. Perhaps that's why it won't paste as you expect?

A: As many of you probably know, you can output data (a report, for example) as an Excel file, simply by adding right content-type and content-disposition header:
Response.ContentType = "application/vnd.ms-excel";

Response.AppendHeader("content-disposition", "inline; filename=report.xls");

If client has MS Excel installed, your output HTML page will be opened in it instead of web browser. Excel will interpret all formating (borders, fonts etc.) and TABLE tags, which can result a nice, formated worksheet, without using heavyweight server-side controls.
The problem I was struggling for some time was with multi-line cells. I needed to wrap text in cell, but when I put
 tag into HTML output, Excel interpreted it as a new row, not a line-break in existing cell.
add into a stylesheet:
br {mso-data-placement:same-cell;}

Then it works like a charm. I hope it useful :)
Tip: You can make ContentType and header conditional, providing alternate HTML/XLS reports with one file.

A: What about using a macro with e.g. the following code?
• TransformingPaste1(): however, this fails on my machine (still multiple cells)

*

*gets the clipboard text

*pastes a transformed version using mso-data-placement:same-cell

*restores the original clipboard text

• TransformingPaste2(): pastes in single cell on my machine, keeping the formatting etc., but results in a space rather than a newline because you're still pasting HTML

*

*gets the clipboard text

*pastes a transformed version using vbCrLf

*restores the original clipboard text

• TransformingPaste3(): pastes in single cell on my machine, with a newline, but loses the formatting etc. (current implementation) – see note with link!

*

*gets the clipboard text

*pastes a transformed version using a self-defined token

*restores the original clipboard text

*post-processes the cells, replacing the token by newlines – might be improved…

Modify to what best suits your needs, e.g. using regex to perform the replacements, but I hope this gets you on your way :]
Function GetClipboardText() As String
    Dim BufObj As MSForms.DataObject
    Set BufObj = New MSForms.DataObject
    BufObj.GetFromClipboard
    GetClipboardText = BufObj.GetText
End Function

Function SetClipboardText(ByRef text As String)
    Dim BufObj As MSForms.DataObject
    Set BufObj = New MSForms.DataObject
    BufObj.SetText text
    BufObj.PutInClipboard
End Function

Function PreProcess(ByRef text As String, ByRef find As String, ByRef replace As String) As String
    PreProcess = Application.WorksheetFunction.Substitute(text, find, replace)
End Function

Function PostProcess(ByRef find As String, ByRef replace As String)
    Dim rCell As range
    For Each rCell In Selection
        'TODO: e.g. combine with answers from http://stackoverflow.com/questions/2192730/merge-contents-of-2-excel-cells-keeping-character-format-intact-using-vba
        rCell.Formula = Application.WorksheetFunction.Substitute(rCell.Formula, find, replace)
    Next
End Function

Sub TransformingPaste1()
    Dim OrigText As String
    Dim TempToken As String
    Dim PasteText As String
    Dim sSelAdd As String
    OrigText = GetClipboardText
    PasteText = PreProcess(OrigText, "", "")
    SetClipboardText PasteText
    'Selection.PasteSpecial "Unicode Text"
    ActiveSheet.Paste
    SetClipboardText OrigText
    Application.CutCopyMode = False
End Sub

Sub TransformingPaste2()
    Dim OrigText As String
    Dim TempToken As String
    Dim PasteText As String
    Dim sSelAdd As String
    OrigText = GetClipboardText
    PasteText = PreProcess(OrigText, "
", vbCrLf)
    SetClipboardText PasteText
    ActiveSheet.Paste
    SetClipboardText OrigText
    Application.CutCopyMode = False
End Sub

Sub TransformingPaste3()
    Dim OrigText As String
    Dim TempToken As String
    Dim PasteText As String
    Dim sSelAdd As String
    OrigText = GetClipboardText
    TempToken = "#mybr#"
    PasteText = PreProcess(OrigText, "
", TempToken)
    SetClipboardText PasteText
    ActiveSheet.Paste
    SetClipboardText OrigText
    PostProcess TempToken, vbLf
    Application.CutCopyMode = False
End Sub

A: I usually face this issue as i have to download excel files from a site which are actually html files wrapped in table tag with xls extension
Wherever br tag is in cell, a new row is created.
So, i created one small vbscript which replaces br tag with comma and then i open the file in excel. It works for me well.

A: If you really need to do a copy-paste, it would be better to edit the 'Cell properties' in the excel sheet before copying the data. Right-Click on the column name in the excel and select cell properties. Make the changes as applicable for your data and save. Now you can copy your data and hope that it is interpreted correctly in MS-Excel.
I haven't used it for HTML content, though.


text:
Q: xctool ...ERROR: build-tests: '' is not a testing target in this scheme i try to run my Xcode UI Tests and just a specific method. It isn't possible with the default xcodebuild command line from apple. I found the xctool but the tool didn't found my UITestsTarget.
Here my command line:
/path/to/xctool -workspace APP.xcworkspace -scheme "APPScheme" test -only UITestsTarget:UITestsClass/UITestsMethod

and i got this error: ...ERROR: build-tests: 'UITestsTarget' is not a testing target in this scheme.
with xcodebuild list i can see all the informations about project and i see my UITestsTarget.
has someone any ideas?
Cheers

A: xctool doesn`t support Xcode UI testing now. https://github.com/facebook/xctool/issues/534. They told: " At Facebook we are using our own infrastructure (see https://github.com/facebook/webdriveragent) to run E2E tests and as a result we aren't going to work on this feature in the nearest future."


text:
Q: Does partial commit happen when TransactionInDoubtException is encountered? Does partial commit happen when TransactionInDoubtException is encountered? If so how to roll back the commits/ properly handle TransactionInDoubtException
var option = new TransactionOptions();
option.IsolationLevel = IsolationLevel.ReadCommitted
using (var scope = new TransactionScope(TransactionScopeOption.Required, option))
{
    try
    {
         Context.SaveEmail(_emailInfoList);
         context.SaveSyncState(syncState);
         scope.Complete();
         return true;
    }
    catch (TransactionInDoubtException ex)
    {
         // Looks like commit has already taken place
         // How to roll back the changes ??
         // sth like scope.Rollback()
    }
}

A: According to MSDN:

This exception is thrown when an action is attempted on a transaction
  that is in doubt. A transaction is in doubt when the state of the
  transaction cannot be determined. Specifically, the final outcome of
  the transaction, whether it commits or aborts, is never known for this
  transaction.
This exception is also thrown when an attempt is made to commit the
  transaction and the transaction becomes InDoubt.
This is a recoverable error.

EDIT:
For recovery:
You have to catch TransactionInDoubtException& write compensate logic with apt checks.
using (var scope = new TransactionScope(TransactionScopeOption.Required, option))
    {
        try
        {
            Context.SaveEmail(_emailInfoList);
            context.SaveSyncState(syncState);
            scope.Complete();
            return true;
        }
        catch (TransactionInDoubtException ex)
        {
            //check whether any one record from the batch has been partially committed . If committed then no need to reprocess this batch.

            // transaction scope should be disposed first .

            scope.Dispose();

            if (IsReprocessingNeeded(syncState))
                throw;

            return true;
        }
    }

        /// <returns></returns>
        private bool IsReprocessingNeeded(SyncStateDataModal syncState)
        {
            while (true)
            {
                try
                {
                    var id = _emailInfoList[0].ID;
                    bool isEmailsCommitted = Context.GetJournalEmail().FirstOrDefault(a => a.ID == id) != null;
                    if (!isEmailsCommitted)
                        return true;
                    if (context.EmailSynch(syncState.Id) == null)
                    {
                        context.SaveSyncState(syncState);
                    }
                    return false;
                }
                catch (Exception ex)
                {

                    Thread.Sleep(TimeSpan.FromMinutes(AppConfiguration.RetryConnectionIntervalInMin));
                }
            }
        }

SOURCE What is the recovery path for TransactionInDoubtException ?


text:
Q: put ruby code into html string? Sinatra, Ruby I'm using Sinatra.
I have a deck: in main.rb
session[:deck] = []
suit  = ['Clubs', 'Spades', 'Hearts', 'Diamonds']
values = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen','King', 'Ace']
session[:deck] = suit.product(values).shuffle!

In my game.erb I want to display the images associated with each of these arrays. I have all the images in my public/images/cards. In the game.erb I can get any card to display statically like so:
Here are your cards:

Is there a way I can do something like:

I want to make a helper method, but I can't seem to get started.

A: The definition of which card image applies to a particular card needs to be done in the controller, not in the view. I'd structure things differently:
SUITS  = %w[Clubs Spades Hearts Diamonds]
VALUES = %w[2 3 4 5 6 7 8 9 10 Jack Queen King Ace]
CARDS = SUITS.product(VALUES)
IMAGES = Hash[ CARDS.map{ |suit, value| [[suit, value], File.join('/images/cards', suit, "#{ value }.jpg") ] } ]
session = {deck:[]}
session[:deck] = CARDS.shuffle

Here's what is defined at this point:
CARDS
# => [["Clubs", "2"], ["Clubs", "3"], ["Clubs", "4"], ["Clubs", "5"], ["Clubs", "6"], ["Clubs", "7"], ["Clubs", "8"], ["Clubs", "9"], ["Clubs", "10"], ["Clubs", "Jack"], ["Clubs", "Queen"], ["Clubs", "King"], ["Clubs", "Ace"], ["Spades", "2"], ["Spades", "3"], ["Spades", "4"], ["Spades", "5"], ["Spades", "6"], ["Spades", "7"], ["Spades", "8"], ["Spades", "9"], ["Spades", "10"], ["Spades", "Jack"], ["Spades", "Queen"], ["Spades", "King"], ["Spades", "Ace"], ["Hearts", "2"], ["Hearts", "3"]...

IMAGES
# => {["Clubs", "2"]=>"/images/cards/Clubs/2.jpg", ["Clubs", "3"]=>"/images/cards/Clubs/3.jpg", ["Clubs", "4"]=>"/images/cards/Clubs/4.jpg", ["Clubs", "5"]=>"/images/cards/Clubs/5.jpg", ["Clubs", "6"]=>"/images/cards/Clubs/6.jpg", ["Clubs", "7"]=>"/images/cards/Clubs/7.jpg", ["Clubs", "8"]=>"/images/cards/Clubs/8.jpg", ["Clubs", "9"]=>"/images/cards/Clubs/9.jpg", ["Clubs", "10"]=>"/images/cards/Clubs/10.jpg", ["Clubs", "Jack"]=>"/images/cards/Clubs/Jack.jpg", ["Clubs", "Queen"]=>"/images/...

session
# => {:deck=>[["Hearts", "10"], ["Hearts", "King"], ["Hearts", "2"], ["Hearts", "Jack"], ["Spades", "5"], ["Spades", "Queen"], ["Clubs", "Jack"], ["Spades", "King"], ["Spades", "Ace"], ["Hearts", "5"], ["Hearts", "Queen"], ["Clubs", "9"], ["Clubs", "3"], ["Diamonds", "3"], ["Clubs", "4"], ["Diamonds", "King"], ["Clubs", "8"], ["Hearts", "4"], ["Spades", "2"], ["Clubs", "5"], ["Clubs", "7"], ["Diamonds", "8"], ["Clubs", "2"], ["Hearts", "Ace"], ["Clubs", "King"], ["Spades", "10"], ["Diamon...

In your view, you can easily figure out which image to present for a particular card by looking up the card in the IMAGES hash:
session[:deck].each do |card|
  puts IMAGES[card]
end

# >> /images/cards/Hearts/10.jpg
# >> /images/cards/Hearts/King.jpg
# >> /images/cards/Hearts/2.jpg
# >> /images/cards/Hearts/Jack.jpg
# >> /images/cards/Spades/5.jpg
# >> /images/cards/Spades/Queen.jpg
# >> /images/cards/Clubs/Jack.jpg
# >> /images/cards/Spades/King.jpg
# >> /images/cards/Spades/Ace.jpg
# >> /images/cards/Hearts/5.jpg
# >> /images/cards/Hearts/Queen.jpg
# >> /images/cards/Clubs/9.jpg
# >> /images/cards/Clubs/3.jpg
# >> /images/cards/Diamonds/3.jpg
# >> /images/cards/Clubs/4.jpg
# >> /images/cards/Diamonds/King.jpg
# >> /images/cards/Clubs/8.jpg
# >> /images/cards/Hearts/4.jpg
# >> /images/cards/Spades/2.jpg
# >> /images/cards/Clubs/5.jpg
# >> /images/cards/Clubs/7.jpg
# >> /images/cards/Diamonds/8.jpg
# >> /images/cards/Clubs/2.jpg
# >> /images/cards/Hearts/Ace.jpg
# >> /images/cards/Clubs/King.jpg
# >> /images/cards/Spades/10.jpg
# >> /images/cards/Diamonds/4.jpg
# >> /images/cards/Spades/9.jpg
# >> /images/cards/Spades/7.jpg
# >> /images/cards/Spades/8.jpg
# >> /images/cards/Clubs/10.jpg
# >> /images/cards/Hearts/8.jpg
# >> /images/cards/Diamonds/Jack.jpg
# >> /images/cards/Diamonds/6.jpg
# >> /images/cards/Hearts/7.jpg
# >> /images/cards/Hearts/9.jpg
# >> /images/cards/Hearts/6.jpg
# >> /images/cards/Diamonds/Ace.jpg
# >> /images/cards/Hearts/3.jpg
# >> /images/cards/Diamonds/Queen.jpg
# >> /images/cards/Diamonds/10.jpg
# >> /images/cards/Spades/4.jpg
# >> /images/cards/Spades/6.jpg
# >> /images/cards/Clubs/Queen.jpg
# >> /images/cards/Diamonds/7.jpg
# >> /images/cards/Diamonds/5.jpg
# >> /images/cards/Spades/3.jpg
# >> /images/cards/Diamonds/9.jpg
# >> /images/cards/Spades/Jack.jpg
# >> /images/cards/Diamonds/2.jpg
# >> /images/cards/Clubs/6.jpg
# >> /images/cards/Clubs/Ace.jpg

Ruby Hashes can have an array for a key, which makes it very easy to find the image that matches a particular card.

A: <img src='/images/cards/<%= "#{session[:deck].first}_#{session[:deck].last} %>.jpg' height="120" width="120>

But probably it's better to do:
<%= image_tag "cards/#{session[:deck].first}_#{session[:deck].last}.jpg", size: '120' %>

A: You can create a method in your helpers:
def display_image(card)

""
end

Then you would call your method like so:
<%= display_image(card) %>


text:
Q: Can I get the domain of a request with silex I want to create one silex application that listens to requests to routes to two domains. Depending on the domain the response should be different.
I know I can simply inject a Request object and use that to get the host from, but I'd like to use a nicer way like this, but using Silex.
Is this possible and if so: how?

A: It should be as easy as calling the host() method for each route (you can also do that on an entire ControllerCollection instance for all its routes) like so:
<?php

// initialization, etc.

$app->get('/', function() {
  return new Response("Only from my.host.com!");
})
->host('my.host.com')
;

A: This is not a bad question - I ended up here looking for a quick answer myself.
It turns out to be rather easy - you just need your instance of the Symfony Request which provides access to the following method:
$base_url = $request->getHost();
$app['monolog']->notice('Base path result', ['base_url' => $base_url])

My result:
[2016-02-19 10:04:15] api.INFO: Base path result [] {"base_url":"api-test.xonadu.com"}
I hope that's useful :)


text:
Q: Включение визуализации win10 Для виртуальной машины потребовалось включить визуализацию,
не могу найти её включение в BIOSе. Везде читал оно там, но такая настройка отсутствует.
ОС: Windows 10.
Материнская плата:
Gigabyte GA-78LMT-S2 R2.
BIOS:
1 x 32 Мбит ПЗУ
Лицензионный BIOS компании AWARD
Поддержка спецификаций PnP 1.0a, DMI 2.0, SM BIOS 2.4, ACPI 1.0b.
Процессор: amd fx-4300.


text:
Q: Hide platform fee with PayPal Adaptive payments Our platform using PayPal Adaptive Payments with Chained Payment especially.
Default payment will look like this:
buyer make a transaction - money goes to a seller - platform takes fees
But in our application can be more than just one seller in a transaction.
In transaction can be more than one seller.
The problem here is that chained payment required only one Primary receiver and only this user will be responsible for pay fee to PayPal. How can we share this between our sellers and make sellers emails visible in receipt page without showing our platform?
Maybe we need another type of payments? Additional options?

A: I'm not sure I fully understand your question, but it sounds like you want to split the fees across each receiver instead of the primary receiver paying the entire fee..??
If I understand correctly, you could leave the Chained payment in place and add the FeesPayer=EACHRECEIVER to your Pay request.  So it would be something like this:
<?xml version="1.0" encoding="UTF-8"?>
<PayRequest xmlns="http://svcs.paypal.com/types/ap">
   <requestEnvelope xmlns="">
      <detailLevel>ReturnAll</detailLevel>
      <errorLanguage>en_US</errorLanguage>
   </requestEnvelope>
   <actionType xmlns="">PAY_PRIMARY</actionType>
   <cancelUrl xmlns="">http://paypal.angelleye.com/paypal-php-library/cancel.php</cancelUrl>
   <clientDetails xmlns="">
      <applicationId>APP-80W284485P519543T</applicationId>
      <ipAddress>192.168.1.254</ipAddress>
   </clientDetails>
   <currencyCode xmlns="">USD</currencyCode>
   <feesPayer xmlns="">EACHRECEIVER</feesPayer>
   <receiverList xmlns="">
      <receiver>
         <amount>500.00</amount>
         <email>usb_1329725429_biz@angelleye.com</email>
         <primary>true</primary>
      </receiver>
      <receiver>
         <amount>50.00</amount>
         <email>sandbo_1215254764_biz@angelleye.com</email>
         <primary>false</primary>
      </receiver>
      <receiver>
         <amount>20.00</amount>
         <email>bogus@angelleye.com</email>
         <primary>false</primary>
      </receiver>
   </receiverList>
   <sender>
      <useCredentials xmlns="" />
   </sender>
   <account xmlns="">
      <phone />
   </account>
   <returnUrl xmlns="">http://paypal.angelleye.com/paypal-php-library/return.php</returnUrl>
</PayRequest>


text:
Q: Ubuntu Boot Disk have wrong name I recently installed Ubuntu on my desktop. My PC has three hard disks: one SSD and two HDDs. The SSD has Windows and one of the HDDs is used as storage for it.
I got a new HDD for Ubuntu, and I installed onto that HDD. However, when I'm on the booting screen of the motherboard, Ubuntu seems to be on the SSD where I have Windows. Is that a poblem and how can I fix it?

A: No, that is not a problem. Ubuntu, like Windows, has a boot manager and that boot manager is installed by default onto the first hard drive1. The image you show just suggests that Ubuntu's boot manager (GRUB) and Windows' are both installed on the same drive. It doesn't mean that the operating systems are on the same drive, only that the BIOS sees two boot managers there.
Unless you can no longer boot Windows, in which case this is a different problem, everything should be fine.

1OK, strictly speaking, in modern systems it is installed in the EFI partition which is usually in the first physical drive.

A: The disk that Ubuntu installed the grub bootloader to is separate from where Ubuntu is actually installed. Your motherboard can boot from the SSD and find grub there, which then points to where Ubuntu was installed onto your disk. If you want to change where grub is installed, you can run:
sudo grub-install /dev/sdX
With 'X' being the disk where you want it instead, presumably on the same one Ubuntu is installed onto. You can use sudo fdisk -l if you're not sure. You then have to change your motherboard's BIOS settings to boot from that disk instead of your SSD by default.


text:
Q: Rails - Find all instances of all models with a certain attribute set to true So lets say that I have a rails app with 3 models:
Posts
Products
Services
All of the above models have an attribute called featured, which is a boolean.
Is it possible to get all featured ( where featured is set to true ) posts, products, and services in 1 query?

A: Try:
[Post,Product,Service].each do |model|
  model.where(feature: true)
end


text:
Q: Can I delete a logical E: drive, which popped up after installing dual boot ubuntu? I installed Ubuntu dual-boot in my PC alongside Windows 10. Before installing, i had shrunk my 1TB hard drive and left 200 GB for Ubuntu installation. The installation went fine, but after booting up Windows, I see in disk management, that a new logical drive had appeared, which i did not create, having 512 MB size...Can i safely delete the new drive?

A: Do not delete! It contains grub config files! Deleting will cause grub bootloader to fail to start!


text:
Q: Google Apps Script creates duplicate tasks Using labels and filters I set up a label for all incoming mail.This code 1. Generates an email receipt, generates, sends it
// 2. Generates a task with the Username as the title, date, html link to the email, and email as the notesI am working from the dashboard, and have created the following script.  However, it doesn't seem to refresh.  I keep getting tasks and emails generated off of emails I received and removed the label from.

function EmailReceiptFunction(){
let receiptsub = "Email Receipt";
let receiptbody ="I've received your email!";
let lbltxt = 'zzCogEmail'; // cog= zzCogEmail intro=zzIntroEmail
let tlid_txt = 'tasklistid'; //
var rpljunk = ['Listerservecrap','othercrap','reply@aplace.com','"','"','>'];  //things I need to remove from the sender

var label = GmailApp.getUserLabelByName(lbltxt);  // Log the subject lines of the threads labeled with MyLabel
var threads = label.getThreads();

  For (var i = 0; i < threads.length; i++) {
    var message = threads[i].getMessages()[i];  //get the message at index i of label array
    var mydate = message.getDate();
    let a_name = message.getFrom();
    let mysub = message.getSubject();
    var mybody = message.getPlainBody();
    let myid = message.getHeader("Message-ID"); //this gets the messages id

    if (mysub.includes('TODAYS EMAIL CHECK')){  //This is supposed to eliminate the email that prints out my daily agenda of how to check my email
      message.removeLabel(label);
      }else if(mysub.includes(receiptsub)){
      message.removeLabel(label);
      }else{

        for (var s = 0; s < 10; s++){  //myAgenda.length, replaces double spaces and carriage returns in email body
          var mybody = mybody.replace(/\n|
          myid = myid.replace('\>','');
          myid = myid.replace('\<','');
          myid = 'https://mail.google.com/mail/u/0/?tab=wm#search/rfc822msgid:' + myid; //this creates a link in tasks to the email
          let tasknotes = mydate + '\n\n' + myid + '\n\n' + mybody;
            for (var r = 0; r < rpljunk.length; r++){
              a_name = a_name.replace(rpljunk[r],'');
               }
          a_name = a_name.replace('<',' - ');
          let indexaname = a_name.split('-');
         var  j = indexaname.length - 1;
          let mysender = indexaname[j]; //sets the last line of the array to string variable mysender
          var pos = mysender.lastIndexOf('@');
            if (mysender.includes('dontacceptemailfromme@gmail.com')){
              message.markRead();
              } else if(mysender.includes('dontacceptemailfromme@sc.edu')) {
              message.markRead();
             } else if(mysender.includes('dontaccepteemailfromotherme')) {
             message.markRead();
             }else if(pos < 4) {
            message.markRead();
             } else {
    GmailApp.createDraft(mysender, receiptsub, receiptbody);
    var draft = GmailApp.getDrafts()[0]; // The first draft message in the drafts folder
    var msg = draft.send(); // Send it
   // Logger.log(tasknotes);
      var taskListId = tlid_txt; //tasklist id for CogRec
      var task = {
         title: mysender,
         notes: tasknotes,
         };
          //Adds a task with the email in this code created in IntroRec
         var taskListId = tlid_txt;
         task = Tasks.Tasks.insert(task, taskListId);
         Logger.log(task);

      }
 threads[i].removeLabel(label);
 threads[i].refresh();
  }
  }
 }


text:
Q: How to add comment in apache httpd.conf not as a complete line? In an apache conf file, if a line is start with #, that line is counted as comment. For example,
#This is a comment line
#And then the following is some real settings:
AllowOverride None

However, this is not allowed.
#And then the following is some real settings:
AllowOverride None #A comment that starts in the middle of line

Is it possible to starts a comment in the middle of the line? And if yes, how?

A: The documentation states that it is not possible:

... Lines that begin with the hash character "#" are considered comments,
  and are ignored. Comments may not be included on the same line as a
  configuration directive ...

A: I believe only # is parsed as there is no real need for it. But if you really need you can use IfDefine block, which will be ignored unless a matching variable has a definition.
<IfDefine myexisterenceIsForJustAComment>
...
</IfDefine>

Look at discussion at : https://bugzilla.redhat.com/show_bug.cgi?id=1349546
Not sure if these are supported in latest versions (< httpd-2.2.15-53) but you can try below which was supported in earlier versions. You may be in luck if you are on older version.
In earlier/older versions of Apache, I remember it was okay to include a comment at the end of a line (wrapped in double quotation marks), like so:
<Limit GET >
    Order Allow,Deny
    Allow from all
    Deny from xxx.xxx.xxx "# I am in inline comment"
</Limit>

A: Apache interprets its conf files line by line. And it considers a line starting with # as a blank line (or line break) and skips the line.
Also it doesn't have a symbol to indicate comments because conf files have many special symbols, which might let them to disable middle-line comment.


text:
Q: PHP - If in string without leaving the string on str_replace() $str = '

        Present Room Type
        <select class="form-control" name="form-present-room-type" required>
            <option value=""></option>
            <option value="PREMIUM" '.( ("@form-present-room-type@" == "PREMIUM") ? "selected" : "").'>PREMIUM</option>
            <option value="SINGLE" '.( ("@form-present-room-type@" == "SINGLE") ? "selected" : "").'>SINGLE</option>
            <option value="DOUBLE" '.( ("@form-present-room-type@" == "DOUBLE") ? "selected" : "").'>DOUBLE</option>
            <option value="TRIPLE" '.( ("@form-present-room-type@" == "TRIPLE") ? "selected" : "").'>TRIPLE</option>
        </select>

';

I questioned it the last time, and I figured out that when I make the if outside the option tag like the above code, the @form-present-room-type@ value was not changed that means @form-present-room-type is not equal with PREMIUM or any of the option values. But when I put it inside the option tag. Like this <option value="PREMIUM" (@form-present-room-type@ == PREMIUM ? selected : "")>PREMIUM</option> he will get the @form-present-room-type@ value, BUT it just returns string like this <option value="PREMIUM" (premium="=" premium="" ?="" selected="" :="" "")="">PREMIUM</option>. Cause I want it to be replaced with certain string like: str_replace('@form-present-room-type@','PREMIUM',$str);

A: Simply use a cycle:
$options = ['', 'PREMIUM', 'SINGLE', 'DOUBLE', 'TRIPLE'];
$form_present_room_type = 'SINGLE';

$str = '';
foreach($options as $opt)
{
  $str.= '<option value="'.$opt.'"'.($form_present_room_type === $opt ? ' selected' : '').'>'.$opt.'</option>';
}
$str = '

        Present Room Type
        <select class="form-control" name="form-present-room-type" required>'
.$str.'</select>

';


text:
Q: Convert string to number while sending data When I am submitting a data without any edit I am able to submit it, but when I am editing a value I am not able to submit the data because I am sending the value in string, during edit I have to convert the value to number, so I want to know how can I do this as I am not able to solve the issue, please let me now how can I solve this issue

A: you can do something like this:
Note : you must be sure the string actually contain the number(I mean it should be convert-able value)
let stringData = "2020";

const num = Number(stringData);
console.log(num);


text:
Q: Loop over rows matching conditions from another table Please, find below a simplified version of my (very much huge) data set:
data <- data.frame(PRODUCT= c('TOMATO','APPLE','TOMATO','BANANA','BANANA','TOMATO','APPLE','BANANA'),UNIT = c('BOX','BIG BOX','BIG BAG','BIG BOX','BIG BAG','BOX','BOX','BIG BAG'), QUANTITY = c(20,1,5,7,9,1,5,100))

conversion <-matrix(c(300,150,100,50,222,420,350,60,120),3,3)
colnames(conversion) <- c('BOX', 'BIG BOX', 'BIG BAG')
rownames(conversion) <- c('TOMATO','APPLE','BANANA')

My question is how to obtain a new column ('ESTIMATED') in data as the result of the multiplication between data$QUANTITY and the matching value from conversion.
This may be a pretty basic question, but I'm unsuccessfully trying to code for and if loops using UNIT and PRODUCT as indices.
The desired result would look like this:
RESULT <- data.frame(PRODUCT= c('TOMATO','APPLE','TOMATO','BANANA','BANANA','TOMATO','APPLE','BANANA'),UNIT = c('BOX','BIG BOX','BIG BAG','BIG BOX','BIG BAG','BOX','BOX','BIG BAG'), QUANTITY = c(20,1,5,7,9,1,5,100),ESTIMATED = c(6000,222,1750,2940,1080,300,750,12000))

I would highly appreciate any suggestion.
Thank you very much.

A: Though there already is an accepted answer, here is a base R way.
i <- match(data$PRODUCT, row.names(conversion))
j <- match(data$UNIT, colnames(conversion))

RESULT <- data
RESULT$ESTIMATED <- data$QUANTITY * conversion[cbind(i, j)]

A: tidyverse
data <-
  data.frame(
    PRODUCT = c(
      'TOMATO',
      'APPLE',
      'TOMATO',
      'BANANA',
      'BANANA',
      'TOMATO',
      'APPLE',
      'BANANA'
    ),
    UNIT = c(
      'BOX',
      'BIG BOX',
      'BIG BAG',
      'BIG BOX',
      'BIG BAG',
      'BOX',
      'BOX',
      'BIG BAG'
    ),
    QUANTITY = c(20, 1, 5, 7, 9, 1, 5, 100)
  )

conversion <- matrix(c(300, 150, 100, 50, 222, 420, 350, 60, 120), 3, 3)
colnames(conversion) <- c('BOX', 'BIG BOX', 'BIG BAG')
rownames(conversion) <- c('TOMATO', 'APPLE', 'BANANA')

library(tidyverse)
conversion_melt <-
  rownames_to_column(.data = as.data.frame(conversion), var = "PRODUCT") %>%
  pivot_longer(-PRODUCT, names_to = "UNIT", values_to = "AMOUNT")

left_join(data, conversion_melt, by = c("PRODUCT", "UNIT")) %>%
  mutate(ESTIMATED = QUANTITY * AMOUNT)
#>   PRODUCT    UNIT QUANTITY AMOUNT ESTIMATED
#> 1  TOMATO     BOX       20    300      6000
#> 2   APPLE BIG BOX        1    222       222
#> 3  TOMATO BIG BAG        5    350      1750
#> 4  BANANA BIG BOX        7    420      2940
#> 5  BANANA BIG BAG        9    120      1080
#> 6  TOMATO     BOX        1    300       300
#> 7   APPLE     BOX        5    150       750
#> 8  BANANA BIG BAG      100    120     12000

Created on 2021-06-30 by the reprex package (v2.0.0)
data.table
library(data.table)
setDT(data)
conversion <- as.data.frame(conversion)
conversion$PRODUCT <- c('TOMATO', 'APPLE', 'BANANA')
setDT(conversion)

conversion_melt <-
  melt(
    data = conversion,
    measure.vars = names(conversion)[-ncol(conversion)],
    id.vars = "PRODUCT",
    variable.name = "UNIT",
    value.name = "AMOUNT"
    )

merge(data, conversion_melt, all.x = TRUE, by = c("PRODUCT", "UNIT"))[, ESTIMATED := QUANTITY * AMOUNT][]
#>    PRODUCT    UNIT QUANTITY AMOUNT ESTIMATED
#> 1:   APPLE BIG BOX        1    222       222
#> 2:   APPLE     BOX        5    150       750
#> 3:  BANANA BIG BAG        9    120      1080
#> 4:  BANANA BIG BAG      100    120     12000
#> 5:  BANANA BIG BOX        7    420      2940
#> 6:  TOMATO BIG BAG        5    350      1750
#> 7:  TOMATO     BOX       20    300      6000
#> 8:  TOMATO     BOX        1    300       300

Created on 2021-06-30 by the reprex package (v2.0.0)

A: Simple tidyverse strategy
library(tidyverse)

data %>% mutate(ESTIMATED = pmap_dbl(data, ~ ..3 * conversion[..1, ..2]))

#>   PRODUCT    UNIT QUANTITY ESTIMATED
#> 1  TOMATO     BOX       20      6000
#> 2   APPLE BIG BOX        1       222
#> 3  TOMATO BIG BAG        5      1750
#> 4  BANANA BIG BOX        7      2940
#> 5  BANANA BIG BAG        9      1080
#> 6  TOMATO     BOX        1       300
#> 7   APPLE     BOX        5       750
#> 8  BANANA BIG BAG      100     12000

Or with apply in baseR
data$ESTIMATE <- apply(data, 1,  \(.x) as.numeric(.x[3])*conversion[.x[1], .x[2]] )


text:
Q: Setting up a linked list in c I'm trying to set up a linked list but just get the same element in every location -
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>

#define LENGTH 45

typedef struct node
{
    char* word;
    struct node* next;
}
node;

int main(void)
{

    node* head = NULL;  //start of list
    // open input file
    FILE* inptr = fopen("smalllocal", "r");
    if (inptr == NULL)
    {
        printf("Could not open %s.\n", "smalllocal");
        return 2;
    }
    printf("Opened file\n");

    //Get a word from dictionary
    char str1[LENGTH +1];
    while (fscanf(inptr, "%s", str1) != EOF)
    {
        node* new_node = malloc(sizeof(node));  //malloc space for a new node
        if (new_node == NULL)
        {
            return 3;
        }
        new_node->word = str1;
        // is it the first insertion at this index?
        if (head == NULL)
        {
              new_node->next = head;
              head = new_node;
        }
        else
        // collision so insert at front of list
        {
            new_node->next = head;
            head = new_node;
        }
    }
    fclose(inptr);
    printf("Closed file\n");
    node* pointer = head;
    while (pointer != NULL)
    {
        printf("%s\n", pointer->word);
        pointer = pointer->next;
    }

    return 0;
}

The file 'smalllocal' contains about 15 different words but the print routine at the end just prints out the last element in the file for every location.  Can anybody help please??

A: This isn't the correct way to copy strings in C (you can't assign them using =).
Instead, you need to allocate a character array long enough to hold the string, and use strcpy().
new_node->word = malloc(strlen(str1) + 1);
strcpy(new_node->word, str1);

Don't forget to free() them later to avoid a memory leak.
The reason your program prints the same value over and over is that every node's word pointer points to the str1 array, but that array is reused for each word. So at any given time, no matter how many nodes you have, you only really have one string: inside str1, and naturally its value will be the last string read in your loop.

A: You are allocating memory for your strcut, but you also need to allocate memory for your string. Change your
new_node->word = str1;

for
new_node->word = malloc(strlen(str1)+1);
strcpy(new_node->word, str1);

so that you allocate the necessary memory to hold the string and then copy it to this allocated memory. Otherwise, all of your nodes word pointer will be pointing to the same string, str1.

A: Your new_node->word is a pointer, it doesn't contain any characters. All nodes points to the same block of memory. When you insert a new node, you changed the content of str1 so it just prints out the last string.
Use new_node->word = strdup(str1); instead. You need to include string.h header.

A: You cannot simply do
new_node->word = str1;

You need to allocate memory first and copy the string into memory ...
new_node -> word = (char *) malloc( sizeof(char)*(LENGTH +1) );
strcpy(new_node -> word, str1);

That should do it. Otherwise, all the pointers in the linked list are pointing to the same memory location.


text:
Q: Not able to print Google+ response in tableview I am getting Google+ post response but I am not understand how to print response of an array ito object in Swift here is my response
Response
{
    access={
      description=Public;items=({
        type=public;
      });
      kind="plus#acl";
    };
    actor={
      displayName="David Cortex";
    id=109312437164671299520;
    image={
        url="https://lh4.googleusercontent.com/-ThgEmnPFYYk/AAAAAAAAAAI/AAAAAAAAACQ/WPsSVrwV2QU/photo.jpg?sz=50";
      };
      url="https://plus.google.com/109312437164671299520";
      verification={
        adHocVerified="UNKNOWN_VERIFICATION_STATUS";
      };
    };
    etag="\"jb1Xzanox6i8Zyse4DcYD8sZqy0/xVZBlUo9r9epJ_89TXvxLKINDpQ\"";
    id=z12wxpaqqu2rhrse523wthozexffxnhke;
    kind="plus#activity";

    object={   **i want to print attachments data like image reshares and replies but not able to understand how to do that**
      actor={
        verification={
          adHocVerified="UNKNOWN_VERIFICATION_STATUS";
        };
      };

      attachments=({
        content="gplus-2128611415.jpg";
        displayName="Test Post";
        fullImage={
          height=480;
          type="image/jpeg";
          url="https://lh3.googleusercontent.com/-CPumbzy2aCw/W2gUJhHp8eI/AAAAAAAAALk/nHPiSw2M8vkCSMbcsH9Mjq26ZLhQYrGggCJoC/w480-h480/gplus-2128611415.jpg";
          width=480;
        };
        id="109312437164671299520.6586536608771207650";
        image={
          type="image/jpeg";
          url="https://lh3.googleusercontent.com/-CPumbzy2aCw/W2gUJhHp8eI/AAAAAAAAALk/nHPiSw2M8vkCSMbcsH9Mjq26ZLhQYrGggCJoC/w506-h750/gplus-2128611415.jpg";
        };
        objectType=photo;url="https://plus.google.com/photos/109312437164671299520/albums/6586536610238804449/6586536608771207650";
      });
      content="Test Post";
      objectType=note;plusoners={
        selfLink="https://www.googleapis.com/plus/v1/activities/z12wxpaqqu2rhrse523wthozexffxnhke/people/plusoners";
        totalItems=0;
      };
      replies={
        selfLink="https://www.googleapis.com/plus/v1/activities/z12wxpaqqu2rhrse523wthozexffxnhke/comments";
        totalItems=0;
      };
      resharers={
        selfLink="https://www.googleapis.com/plus/v1/activities/z12wxpaqqu2rhrse523wthozexffxnhke/people/resharers";
        totalItems=0;
      };
      url="https://plus.google.com/109312437164671299520/posts/CfnxAnsjzxp";
    };
    provider={
      title="Google+";
    };
    published="2018-08-06T09:25:58.775Z";
    title="Test Post";updated="2018-08-06T09:25:58.775Z";
    url="https://plus.google.com/109312437164671299520/posts/CfnxAnsjzxp";
    verb=post;
  }

now here i show my code which i have tried
Code
   func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! GooglePostListTableViewCell
        let instaResponse = serviceData[indexPath.row]["actor"] as! [String:Any]
        let fName = instaResponse["displayName"] as! String
        cell.lblUserName.text = fName

        let object = serviceData[indexPath.row]["object"] as! [String : Any]
        let content = object["content"] as! String
        cell.lblPostDesc2.text = content
//        let object = serviceData[indexPath.row]["attachments"] as! [String:Any]
//        let content = object["content"] as! String
//        cell.lblPostDesc2.text = content
        let gplus = serviceData[indexPath.row]["object"] as! [String:Any]
        let plusoners = gplus["attachments"]!["plusoners"] as! String
        cell.lbl2.text = plusoners
        return cell
    }

So I mean I want to print data of object and attachment inside data so please any one help me to solve this.
So I mean to say that how to print attachments inside data which is in object so please help.


text:
Q: How to keep the shortcuts of a hidden widget in PyQt5? I have a menu bar with a shortcut associated to it. I want to hide the menu bar but in that case the associated shortcut will be disabled. Here is an example:
import sys

from PyQt5.QtWidgets import QApplication, QMainWindow, QAction

class Window(QMainWindow):
    def __init__(self):
        super().__init__()
        self.InitWindow()

    def InitWindow(self):
        mainMenu = self.menuBar()
        fileMenu = mainMenu.addMenu("&File")

        mainMenu.hide()    # comment it and the shortcut 'q' will work

        quitItem = QAction("Quit", self)
        quitItem.setShortcut("Q")
        quitItem.triggered.connect(self.close)

        fileMenu.addAction(quitItem)

if __name__ == "__main__":
    App = QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(App.exec())

If you put the line mainMenu.hide() in a comment, i.e. if the menu bar is shown, then the app. will quit with the shortcut 'q'. How could I keep the shortcuts of a hidden widget?
In the app. I want to add full-screen support, and in that case I want to hide the menu bar, but also, I want to keep the shortcuts in full-screen mode.

A: I found a working solution. The idea is the following: the main window has a shortcut ('q' in the example), and the menu bar also has this shortcut. To avoid conflict, disable the window's shortcut if the menu bar is present. If the menu bar is hidden, enable the window's shortcut.
import sys

from PyQt5.QtCore import Qt
from PyQt5.QtGui import QKeySequence
from PyQt5.QtWidgets import QApplication, QMainWindow, QAction, QShortcut

class Window(QMainWindow):
    def __init__(self):
        super().__init__()

        self.shortcutQuit = QShortcut(QKeySequence("q"), self)
        self.shortcutQuit.activated.connect(self.close)
        self.shortcutQuit.setEnabled(False)    # disable it if the menu bar is visible

        self.InitWindow()

    def InitWindow(self):
        self.mainMenu = self.menuBar()
        fileMenu = self.mainMenu.addMenu("&File")

        hideItem = QAction("Hide Menu Bar", self)
        hideItem.setShortcut("h")
        hideItem.triggered.connect(self.my_hide)

        quitItem = QAction("Quit", self)
        quitItem.setShortcut("Q")
        quitItem.triggered.connect(self.close)

        fileMenu.addAction(hideItem)
        fileMenu.addAction(quitItem)

    def my_hide(self):
        self.mainMenu.hide()
        self.shortcutQuit.setEnabled(True)

if __name__ == "__main__":
    App = QApplication(sys.argv)
    window = Window()
    window.show()
    sys.exit(App.exec())


text:
Q: PHPexcel generated CSV for values not set (each row with diff. no. of col's) Generated CSV file using below code
$objPHPExcel->setActiveSheetIndex( 0 )
                ->setCellValue( 'A1', 'one' )
                ->setCellValue( 'B1', 'two' )
                ->setCellValue( 'C1', 'three' );
 $objPHPExcel->setActiveSheetIndex( 0 )
                    ->setCellValue( 'A2', 'mon' )
                    ->setCellValue( 'B2', 'tue' )
                    ->setCellValue( 'C2', 'wed' )
                    ->setCellValue( 'D2', 'thu' )
                    ->setCellValue( 'E2', 'fri' );
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'CSV')->setUseBOM(TRUE)
                                                                ->setDelimiter(',')
                                                                ->setEnclosure('')
                                                                ->setSheetIndex(0)
                                                                ->save('php://output');

So the above code generating results. But i don't want comma to generate for D1 & E1 cells.

Would like to get result as :

one,two,three

mon,tue,wed,thu,fri

is there a way for define PHPExcel to read on each rows?

A: Finally ended up by writing my own class github


text:
Q: Unity3d FirebaseApp initialization unsuccessful I'm trying to integrate Firebase on Unity3d in order to receive push notifications.
I get the following error when the app launching:
I/dalvikvm( 7881): Could not find method android.content.Context.isDeviceProtectedStorage, referenced from method com.google.firebase.FirebaseApp.zza
I/FirebaseInitProvider( 7881): FirebaseApp initialization unsuccessful

The firebase-messaging sample work fine with my google-services.json. So I suppose that the console configuration is correct.
1. I created a library project on Android Studio.
I followed a web site to build a .jar from Android Studio and the official documentation to add firebase.
http://www.thegamecontriver.com/2015/04/android-plugin-unity-android-studio.html
project gradle file:
buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.2.1'
        classpath 'com.google.gms:google-services:3.0.0'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

app gradle file:
apply plugin: 'com.android.library'

android {
    compileSdkVersion 24
    buildToolsVersion "24.0.3"
    sourceSets {
        main {
            java {
                srcDir 'src/main/java'
            }
        }
    }
    defaultConfig {
        minSdkVersion 15
        targetSdkVersion 24
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    lintOptions {
        abortOnError false
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:appcompat-v7:24.2.1'
    compile 'com.google.firebase:firebase-core:9.6.1'
    compile 'com.google.firebase:firebase-messaging:9.6.1'
    compile files('libs/classes.jar')
}

task deleteOldJar(type: Delete) {
    delete 'release/NotificationPlugin.jar'
}

task exportJar(type: Copy) {
    from('build/intermediates/bundles/release/')
    into('release/')
    include('classes.jar')
    rename('classes.jar', 'NotificationPlugin.jar')
}

exportJar.dependsOn(deleteOldJar, build)

apply plugin: 'com.google.gms.google-services'

At this point a .jar is successfully generated.
2. I created a JarResolver dependencies in Unity.
I use the PlayServicesResolver v1.1 found into other google unity package (Google analytics for exemple, other plugins upgrade it)
https://github.com/googleanalytics/google-analytics-plugin-for-unity
FirebaseDependencies.cs
using Google.JarResolver;
using UnityEditor;

[InitializeOnLoad]
public static class FirebaseDependencies
{
    private static readonly string PluginName = "Firebase";

    static FirebaseDependencies()
    {
        PlayServicesSupport svcSupport = PlayServicesSupport.CreateInstance(
                                         PluginName,
                                         EditorPrefs.GetString("AndroidSdkRoot"),
                                         "ProjectSettings");

        svcSupport.DependOn("com.google.firebase",
            "firebase-core",
            PluginVersion.PlayServicesVersionConstraint);

        svcSupport.DependOn("com.google.firebase",
            "firebase-messaging",
            PluginVersion.PlayServicesVersionConstraint);
    }
}

PluginVersion.cs
public class PluginVersion
{
    public const string PlayServicesVersionConstraint = "9.6+";
}

After the ResolveClientJars command, all dependencies are copy into the Plugins/Android folder.
AndroidManifest.xml
firebase-analytics-9.6.1
firebase-analytics-impl-9.6.1
firebase-common-9.6.1
firebase-core-9.6.1
firebase-iid-9.6.1
firebase-messaging-9.6.1
google-services.json
play-services-basement-9.6.1
play-services-tasks-9.6.1
support-annotations-24.0.0.jar
support-v4-24.0.0

Everything seems to work perfectly at this point and there are no error during the build process.
What I'm doing wrong?

A: You could use Firebase Push Notifications without creation additional plugin. But the flow is a little bit tricky. Here are quick steps:

*

*In the Unity Editor. In the Build Settings select Google Android
Project flag and Export your project. Make sure that your bundle id
correspond to the bundle id  at the Firebase Console.

*In the Android Studio. Import your Unity project. IMPORTANT: Don't
    Open, Import!

*Setup .gradle scripts and add google-services.json file as described here.

*Build project from Android Studio.


text:
Q: Correlation bound proof Disclaimer: I am not talking about the correlation coefficient $\rho \in [-1,1]$
The correlation, according to a textbook I have, is defined as $m_{11} = E[XY]$ given the Model $(X,Y,f(x,y))$ of $2$ random variables $X$, $Y$.
I want to prove that $$\frac{m_{11}^2}{E[X^2] - E[Y^2]} \leq 1.$$
I tried $E[(aX \pm Y)^2] \geq 0$, which led me to the Cauchy-Schwarz inequality $$(E[XY])^2 \leq E[X^2]E[Y^2].$$ I don't know if the textbook is wrong, however if it holds, then by symmetry this should also hold:
$$\frac{m_{11}^2}{E[Y^2] - E[X^2]} \leq 1.$$
Any help is appreciated. Thank you in advance!
Correction: I had misread the denominator previously. Now it is fixed.

A: This is not always true. Let's take $X$, $Y$ such that $P (X = 2) = 1$ and $P (Y = 1) = 1$. Then it becomes false ($4/3\leq 1$).


text:
Q: How would you effectively override a parent's computed iVar? I'm trying to convert an existing Objective-C code into its Swift 3.0 equivalent.
I'm having trouble converting an Objective-C paradigm of defining the parent's declared getter (assessor) within its descendant; into its equivalent Swift 3.0's  computed iVar paradigm.

Objective-C
Parent property:
@property(nonatomic, readonly) CGRect frameOfPresentedViewInContainerView;

Defining property within its descendant:

- (CGRect)frameOfPresentedViewInContainerView
{
    CGRect containerViewBounds = self.containerView.bounds;
    CGSize presentedViewContentSize = [self sizeForChildContentContainer:self.presentedViewController withParentContainerSize:containerViewBounds.size];

    // The presented view extends presentedViewContentSize.height points from
    // the bottom edge of the screen.
    CGRect presentedViewControllerFrame = containerViewBounds;
    presentedViewControllerFrame.size.height = presentedViewContentSize.height;
    presentedViewControllerFrame.origin.y = CGRectGetMaxY(containerViewBounds) - presentedViewContentSize.height;
    return presentedViewControllerFrame;
}

Swift 3.0
Parent property:
var frameOfPresentedViewInContainerView: CGRect { get }

When I attempt to define the value of 'frameOfPresentedViewInContainerView' via:
func frameOfPresentedViewInContainerView() -> CGRect {
        let containerViewBounds = self.containerView?.bounds;   // ...UIPresentationController  - iOS 10

}

I get the following compiler error:

Method 'frameOfPresentedViewInContainerView()' with Objective-C
  selector 'frameOfPresentedViewInContainerView' conflicts with getter
  for 'frameOfPresentedViewInContainerView' from superclass
  'UIPresentationController' with the same Objective-C selector

Which makes sense and is obvious.

So what's the best way to override a parent's computed (getter) variable?

Note: the parent class is Apple's canned UIPresentationController.

A: You override the var, just as given in the Swift interface:
override var frameOfPresentedViewInContainerView: CGRect {


text:
Q: label orientation after dxf to shp conversion I'm writing a script with python in QGIS that allows me to convert a dxf file to shp. In the dxf file I have oriented text but after the conversion I lose this information. Is it possible to keep it?
this is my script :
import os
from PyQt4.QtCore import *
import datetime
print datetime.datetime.now().minute
uri="C:/Users/Lenovo/Desktop/stage_brome/restitution.dxf|layername=entities"
vlayer = QgsVectorLayer(uri, 'layer', 'ogr')
##For each sublayer, diferent type of geometry, load a layer to map.
subLayers = vlayer.dataProvider().subLayers()
types=["LineString","Point","Polygon"]
for sublayer in subLayers:
    #Extract the geometry type
    geom_type = sublayer.split(':')[-1]
    #Set the path
    url = str(uri)+"|layername=entities|geometrytype="+str(geom_type)
    #Name for sub layer
    dxf_file_name = os.path.splitext(os.path.basename(url))[0]
    layer_name =str(dxf_file_name)+" - "+str(geom_type)
    #Create layer
    sub_vlayer = QgsVectorLayer(url, layer_name, 'ogr')
    #Add layer to map
    QgsMapLayerRegistry.instance().addMapLayer(sub_vlayer)
    if geom_type in types:
        #list of string that contains the name of each layer
        layer_types=[]
        #list of vector layers
        vlayers_by_type=[]
        #list of providers for each vector layer
        vlayers_providers=[]
        geom_types=[]

        for feature in sub_vlayer.getFeatures():
            #fill the lists (vector layer and it's provider and attributes of each layer)
            if (feature.attributes())[0] not in layer_types:
                name=(feature.attributes())[0]
                layer_types.append(name)
                # create vlayer
                vl=QgsVectorLayer(geom_type, "temporary_points", "memory")
                geom_types.append(geom_type)
                pr = vl.dataProvider()
                # add fields
                fields=[field for field in sub_vlayer.pendingFields()]
                pr.addAttributes(fields)
                # tell the vector layer to fetch changes from the provider
                vl.updateFields()
                vlayers_by_type.append(vl)
                vlayers_providers.append(pr)
                error = QgsVectorFileWriter.writeAsVectorFormat(vl, "C:/Users/Lenovo/Desktop/stage_brome/output/layers/"+name+"-"+str(geom_type)+".shp", "CP1250", None, "ESRI Shapefile")
#                if error != QgsVectorFileWriter.NoError:
#                    print "failed  "------------------------------------

        for feature in sub_vlayer.getFeatures():
            name=(feature.attributes())[0]
            if name in layer_types:
                # add features
                vl=vlayers_by_type[layer_types.index(name)]
                pr=vlayers_providers[layer_types.index(name)]
                pr.addFeatures([feature])
                # update layer's extent when new features have been added
                # because change of extent in provider is not propagated to the layer
                geom_type=geom_types[layer_types.index(name)]
                vl.updateExtents()
                error = QgsVectorFileWriter.writeAsVectorFormat(vl, "C:/Users/Lenovo/Desktop/stage_brome/output/layers/"+str(name)+"-"+str(geom_type)+".shp", "CP1250", None, "ESRI Shapefile")
                if error != QgsVectorFileWriter.NoError:
                    print "failed  "+str(layer_types[vlayers_by_type.index(vl)])

print datetime.datetime.now().minute

A: Yes it is possible. The plugin "AnotherDXF2Shape" makes that.
[edit]
You must use the appropriate SQL code with OGR.
import processing
dxfdat="d:/.../test.dxf"
shpdat="d:/.../dxf2.shp"

opt="-skipfailure  --config DXF_MERGE_BLOCK_GEOMETRIES FALSE --config DXF_INLINE_BLOCKS TRUE  -nlt POINT "
sql= "-sql \"select *, ogr_style from entities where OGR_GEOMETRY LIKE '%POINT%'\""

print processing.runalg('gdalogr:convertformat',dxfdat , 0,opt + sql, shpdat)

Then you find the angle in the DBF column ogr_style Param a:<win>:
LABEL(f:"Arial",t:"mytext",p:1,s:0.603g,c:#000000,a:143.25)

1) In Plugin "AnotherDXF2Shape" there is a Option: "Group layer".

2) My Code produce a shape with a DBF. In the DBF exist a field "Layer".
import processing
dxfdat="d:/test.dxf"
shpdat="d:/point.shp"
savedir="d:/output/layers/"

# Step 1: Create a Shape with POINT's
opt="-skipfailure  --config DXF_MERGE_BLOCK_GEOMETRIES FALSE --config DXF_INLINE_BLOCKS TRUE  -nlt POINT "
sql= "-sql \"select *, ogr_style from entities where OGR_GEOMETRY LIKE '%POINT%'\""

print processing.runalg('gdalogr:convertformat',dxfdat , 0,opt + sql, shpdat)
DBFedit (shpdat) ###!!!!!!!!!!!!!###
# Step 2: Group the Shape by Layer
Layer = QgsVectorLayer(shpdat, "points","ogr")

fni = Layer.fieldNameIndex('Layer')
unique_values = Layer.dataProvider().uniqueValues(fni)
for AktLayerNam in unique_values:
        Layer = QgsVectorLayer(shpdat, AktLayerNam,"ogr")
        Layer.setSubsetString( "Layer = '" + AktLayerNam + "'" )
        QgsMapLayerRegistry.instance().addMapLayer(Layer, True)
        # Step 3:  save Shape by Layer
        QgsVectorFileWriter.writeAsVectorFormat(Layer, savedir+ AktLayerNam+ ".shp", "CP1250", None, "ESRI Shapefile")

This function edits the point shape.
Quick&dirty:
# -*- coding: utf-8 -*-
import ogr
def DBFedit (shpdat):
    def trennArtDaten(ArtDaten):
        #BRUSH(fc:#dcdcdc)
        #LABEL(f:"Arial",t:"{\fArial|b1|i0|c0|p34;VZOG}",s:3.5g,p:8,c:#ff7f7f)
        sDaten = ""
        sArt = ""
        inDaten = False
        for c in ArtDaten[:-1]:
            if c == '(' and not inDaten:
                inDaten = True
                c = ''
            if inDaten:
                sDaten = sDaten + c
            else:
                sArt = sArt + c
        return sArt, sDaten

    def csvSplit(csvZeile, trenn=',', tKenn='"', tKennDel = True):
        inString = False
        mask = ""
        s = ''
        sb = False
        for c in csvZeile:

            if c == tKenn and not sb:
                inString = not inString
            if c == trenn and inString  and not sb:
                if mask == "":
                    mask = "$$"
                    while mask in csvZeile:
                        mask = mask + '$'
                s=s+mask
            else:
                if not (tKennDel and (not sb) and c == tKenn):
                    s=s+c
            if c == "\\":
                sb = True
            else:
                sb = False

        arr = s.split(trenn)
        if mask != "":
            for i in range(0,len(arr)):
                arr[i] = arr[i].replace(mask,trenn)

        return arr

    source = ogr.Open(shpdat, update=True)
    if source is None:
        print('ogr: can not open: ' + shpdat)
        return

    layer = source.GetLayer()
    laydef = layer.GetLayerDefn()

    Found = False
    for i in range(laydef.GetFieldCount()):
        if laydef.GetFieldDefn(i).GetName() == 'ogr_style':
            Found = True

    if not Found:
        print("missing field 'ogr_style': " + shpdat)
        return
    # add a new field for angle
    layer.CreateField(ogr.FieldDefn('angle', ogr.OFTReal))

    feature = layer.GetNextFeature()
    while feature:
            att=feature.GetField('ogr_style')
            if att is None:
                print("missing field 'ogr_style' in: "  + shpdat)
            else:
                sArt,sDaten = trennArtDaten(att)
                params = csvSplit (sDaten)
                for param in params:
                    arr=csvSplit(param,":")
                    if len(arr) == 2:
                        f = arr[0]
                        w = arr[1]
                        if f == "a":
                            dWin = float(w)
                            if dWin >=360:
                                dWin = dWin - 360
                            feature.SetField('angle', dWin)
                    else:
                        print ("incomplete field 'ogr_style': " + param)

            layer.SetFeature(feature)
            feature = layer.GetNextFeature()
    source.Destroy()


text:
Q: Handling Multiple read and Single writes I am very new to this topic. Its confusing whenever I try to get one process done after another, The next process kicks in before executing the first process.
For example : I am reading from the shared memory , I want the next write process wait until the read is over. But after reading some portion the write process comes in and changes the values.
I have tried to code using mutex and cond_wait. Maybe there are some errors or I  dont know really how cond_wait works properly. Need help
my code snippet:
void create_reader()
{
    pthread_mutex_lock(&mutex);
    if (0 == fork()) {
        reader();
        exit(0);
    }
    readerID++;
    r+=1;

    pthread_cond_signal(&condition);
    pthread_mutex_unlock(&mutex);
}

void create_writer()
{
    pthread_mutex_lock(&mutex);

    while (!r)
    {
        cout<<"waiting"<<endl;
        pthread_cond_wait(&condition,&mutex);
    }

    if (0 == fork()) {
        writer();
        exit(0);
    }

    pthread_mutex_unlock(&mutex);
    writerID++;
}

A: As fork() will create a copy of the running process, if the writer change the memory in the second process, the reader will never see the memory modification in its own:

*

*threads share memory

*processes don't (unless you share memory with mmap)

That said, your other pthread functions calls seem correct.
See http://www.linuxprogrammingblog.com/threads-and-fork-think-twice-before-using-them


text:
Q: List of AWS lambda functions deployed from my IAM How is it possible to get a list of AWS functions deployed by my IAM. The problem here is that our organization has over 4000 lambda functions so I don't need list of lambda functions in our account, rather ones I've created.

A: You're using a wrong concept to group your lambdas.... I suggest you use a tag and then list all the lambdas, query the tags and filter by that:
How To Filter Out Lambdas with the AWS Cli with tags?


text:
Q: Overflow with CSS positioning http://jsfiddle.net/myxzh/6/
ul {
display: table;
table-layout: fixed;
width: 100%;
padding:0;
position: absolute;
top: -10px;
}

li {
display: table-cell;
height: 150px;
border: 1px solid black;
text-align: center;
vertical-align: bottom;
}

#con {
width: 100%;
border: 1px solid red;
height: 200px;
overflow: hidden;
}

#logo {
width: 80%;
height: 100px;
margin: 10px auto;
border: 1px solid yellow;
z-index: 1;
}

Hello

Hello

Hello

I have this code and I am trying to make it where the list elements take up 100% of the red div box. Right now, the list goes outside of the red div which is not what I am trying to do. How do i make the black div(list items) fill up 100% of the red div and not go outside the red div?

A: If you want the black div to take up 100% of the height and width of the red div, change your CSS to:
ul {
    display: table;
    table-layout: fixed;
    width: 100%;
    padding:0;
    position: absolute;
    margin:0;
    bottom:0;
    height:100%;
}
li {
    display: table-cell;
    height: 150px;
    border: 1px solid black;
    text-align: center;
    vertical-align: bottom;
}
#con {
    width: 100%;
    border: 1px solid red;
    height: 200px;
    overflow: hidden;
    position:relative;
}
#logo {
    width: 80%;
    height: 100px;
    margin: 10px auto;
    border: 1px solid yellow;
    z-index: 1;
}

jsFiddle example
I added position:relative; to your #con div since your absolute positioned ul element is positioned relative to it's first positioned ancestor, which in your example was the body, but you needed it to be #con. Then I made a few small changes to your ul's CSS rules so that it would take up all the space of the red div.

A: I changed your mark up a bit, there is no need for the div #list, that why ul exists.
This is the css
#con {
width: 100%;
border: 1px solid red;
height: 200px;
overflow: hidden;
position: relative;
}

#logo {
width: 80%;
height: 100px;
margin: 10px auto;
border: 1px solid yellow;
z-index: 1;
}

#list {
width: 100%;
list-style: none;
position: absolute;
top: 0px;
margin: 0;
padding: 0;
}

li {
float: left;
width: 33.1%;
height: 200px;
border: 1px solid black;
text-align: center;
vertical-align: bottom;
}

Is this good enough?
http://jsfiddle.net/myxzh/11/

A: A working fiddle --> http://jsfiddle.net/2VvTu/
You needed to set your container element to position: relative; and float your table cells left.
the box sizing property calculates borders and margins as part of the width (rather than default of adding them on on top of the width) --> you'll need to vendor prefix this as appropriate. More about that here --> http://paulirish.com/2012/box-sizing-border-box-ftw/
li {
-webkit-box-sizing: border-box;
display: inline-block;
height: 150px;
margin: 0;
padding: 0;
text-align: center;
width: 33.33%;
float: left;
border: thin purple dashed;
}


text:
Q: Is there anyway to get categorical label of a Photo by iOS public API? In case some of you don't know this: If you open Photos app in iOS device and search a keyword like "beach", you get all the photos related to the keyword. iOS seems to included a pre-trained model of photo labeling system.
My question is, can I, as an app developer, use this model to get the labels for photo taken with iOS camera? (something like: User takes a photo in my app, I call a public API to retrieve the labels)
I searched the documentation but didn't find anything. Maybe someone has used such an API?
Ignore this since CommonsWare already answer this part:
And how about Android?


text:
Q: Soa Suite domain performance degradation The story:
We have SOA Suite domain, 3 nodes. OEL Linux 6.8, CPU 32 cores.
We have cleaned tmp folders, soainfta database tables truncated. Right after the domain start(SOA Platform is running...) we observe the domain degradation:
1) High CPU utilization (50-70%) on all nodes by jvm processes. Usual utilization was 10-15%. GC is G1, it is working OK, not taking CPU time.
2) In Enterprise manager of domain we observe that processes stuck on BPEL activation.
3) After 600 seconds we observe stuck threads in weblogic console, we observe transactions rollback in logs.
4) We observe growth of Runnable and Blocked JVM threads
5) If we stop the load , then after few hours stucked instances go further the BPEL processes and they end with transaction timeouts, JVM threads are released.
6) We observe no problems on Database, nor we have JMS queues growth nor memory problems.
Probably, someone had the same issues and knows how to solve them.
Please point to the right direction. Thanks.

A: I recommend to check the entropy, you need at least 500 for the Integrated WebLogic Server to start up in a timely manner. See also Oracle SOA Suite docs, section 2.4.3 Checking entropy for Oracle Linux. The recommended steps from Oracle documentation are following.
To check for entropy, run the following command:
cat /proc/sys/kernel/random/entropy_avail

If you have less than 500, use the following command to replenish bytes to /dev/random using /dev/urandom as the source:
rngd -r /dev/urandom -o /dev/random -b

You can configure this command by editing /etc/sysconfig/rngd and add the following line:
EXTRAOPTIONS="-i -r /dev/urandom -o /dev/random -b -t 60 -W 2048"