text:
Q: Counting occurrences in several columns I'm making an app that shows people movies to rate, a-la hot-or-not. I'd like to write a query that gets me the number of times a movie has been rated. The table for ratings looks like this:
| id | winner | loser |
| 1  |   1    |   2   |
| 2  |   2    |   3   |
| 3  |   1    |   3   |

I can get the number of times a movie has "won" by running a query like this:
SELECT winner, count(winner) AS number_of_wins
  FROM movie_results
  GROUP BY winner
  ORDER BY number_of_wins DESC;

But I'd like to get another query that shows the total number of times a movie was pitched against other movies, i.e. the number of times a movie has appeared to be rated, whether it was rated above or below the other movie. What is the easiest way to achieve this, using only SQL queries?

A: Here is one method, using union all:
select movie, count(*) as nummatches, sum(win) as numwins
from ((select winner as movie, 1 as win from match_results) union all
      (select loser, 0 from match_results)
     ) wl
group by movie;

A: You can do a full join between two derived tables where each table contains the number of losses and wins for each player.
select
    coalesce(winner,loser) player,
    coalesce(number_of_wins,0) number_of_wins,
    coalesce(number_of_losses,0) number_of_losses,
    coalesce(number_of_wins,0) + coalesce(number_of_losses,0) number_of_matches
from (
    select winner, count(*) number_of_wins
    from movie_results
    group by winner
) winners full join (
    select loser, count(*) number_of_losses
    from movie_results
    group by loser
) losers on losers.loser = winners.winner

http://sqlfiddle.com/#!15/980d6/3


text:
Q: ¿Mis sentencias preparadas estan bien formuladas o hay algun fallo donde puedan hacer inyeccion SQL? static public function CrearNotaModel($tablaBD, $datosController) {
    $pdo = ConexionBD::cBD()->prepare("INSERT INTO $tablaBD(id_paciente, fecha, nota, imc, glucosa, peso)
    VALUES (:id_paciente, :fecha, :nota, :imc, :glucosa, :peso)");

    $pdo -> bindParam(":id_paciente", $datosController["id_paciente"], PDO::PARAM_INT);
    $pdo -> bindParam(":fecha", $datosController["fecha"], PDO::PARAM_STR);
    $pdo -> bindParam(":nota", $datosController["nota"], PDO::PARAM_STR);
    $pdo -> bindParam(":imc", $datosController["imc"], PDO::PARAM_STR);
    $pdo -> bindParam(":glucosa", $datosController["glucosa"], PDO::PARAM_STR);
    $pdo -> bindParam(":peso", $datosController["peso"], PDO::PARAM_STR);

    if($pdo -> execute()) {
      return true;
    }

    $pdo -> close();
    $pdo = null;

  }

A: Las sentencias preparadas son seguras en general si estan contienen interpolaciones de valores directos con bindParam() como en el ejemplo de la pregunta.
Esto significa que la consulta ejecutaria correctamente en la mayoria de los casos, excepto por errores de programacion que podrian inducir errores (pero no inyeccion) tales como:

*

*Strings mas largos de lo que permite el esquema de base de datos (por ejemplo en un varchar(50) no se guardaran mas de 50 caracteres.

*Uso del tipo incorrecto o un valor no esperado en bindParam() (por ejemplo, usar PARAM_STR donde el campo es de tipo entero y el valor no es numerico)

Los problemas de inyeccion pueden venir despues a nivel de despliegue en HTML, si los datos que entran en la base de datos se muestran sin escape (ejemplo, sin usar htmlentities() o htmlspecialchars()) lo que podria producir inyeccion de codigo externo (XSS) al incrustarlo en el sitio ya sea en contenido HTML como en atributos.
https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html#xss-prevention-rules-summary

redpajama_set_name: RedPajamaStackExchange


text:
Q: Network adapter state [Wireless] What does a wireless network adapter "disassociated state" mean?
Please help.
I cannot seem to find an explanation anywhere.
T

A: It means that even though you can see a Wireless network SSID being broadcast on the client interface's spectrum/wireless range, you are not talking to it directly.  Once you associate (meaning: choose to talk to this network), then the next step would be to authenticate if there is the need to do that via security measures implemented by the network administrator.
https://www.rfc-editor.org/rfc/rfc5418.  Check out the "Forming an association (joining)" part for a more technical overview of this phase of the connection process.


text:
Q: Redirecting to two different welcome-pages depending on the users role in Java EE 6/Glassfish I have implemented FORM based authetication with Glassfish 3.1 + JDBCRealm + MySQL (MD5). I've got only two roles, user and admin. Everything is going great, I can see from the log that authentication is working in both cases as an uset and as an admin (Watch log below)
Q1: Is it possible to make two different index-files so that when user is admin, he/she goes to /admin/index.xhtml and when user is in role user he goes direct to faces/user/index.xhtml?
Q2: Now when I logged in as an user, I can still go to "admin side" with just writting the whole link straight to address field in a browser, why ja how to avoid that?
Q3: When I logged in as a user and I have ONLY faces/admin/index.xhtml in welcome file list, it redirects me to that file even if xml file tells something else, why?
<welcome-file-list>
        <welcome-file>faces/admin/index.xhtml</welcome-file> *?? ----> it goes always here, cause it is the first one I think?*
       <welcome-file>faces/user/index.xhtml</welcome-file>
    </welcome-file-list>

    <security-constraint>
        <display-name>Admin Pages</display-name>
        <web-resource-collection>
            <web-resource-name>Protected Admin Area</web-resource-name>
            <description/>
            <url-pattern>/faces/admin/*</url-pattern>
            <http-method>GET</http-method>
            <http-method>POST</http-method>
            <http-method>HEAD</http-method>
            <http-method>PUT</http-method>
            <http-method>OPTIONS</http-method>
            <http-method>TRACE</http-method>
            <http-method>DELETE</http-method>
        </web-resource-collection>
        <auth-constraint>
            <description/>
            <role-name>admin</role-name>
        </auth-constraint>
    </security-constraint>
    <security-constraint>
        <display-name>User Pages</display-name>
        <web-resource-collection>
            <web-resource-name>Protected Users Area</web-resource-name>
            <description/>
            <url-pattern>/faces/users/*</url-pattern>

            <http-method>GET</http-method>
            <http-method>POST</http-method>
            <http-method>HEAD</http-method>
            <http-method>PUT</http-method>
            <http-method>OPTIONS</http-method>
            <http-method>TRACE</http-method>
            <http-method>DELETE</http-method>
        </web-resource-collection>
        <auth-constraint>
            <description/>
            <role-name>user</role-name>
        </auth-constraint>
    </security-constraint>

    <login-config>
        <auth-method>FORM</auth-method>
        <realm-name>JDBCRealm</realm-name>
        <form-login-config>
            <form-login-page>/faces/loginForm.xhtml</form-login-page>
            <form-error-page>/faces/loginError.xhtml</form-error-page>
        </form-login-config>

    </login-config>
</web-app>

LOG:
FINE: Login module initialized: class com.sun.enterprise.security.auth.login.JDBCLoginModule
FINEST: JDBC login succeeded for: admin groups:[admin, user]
FINE: JAAS login complete.
FINE: JAAS authentication committed.
FINE: Password login succeeded for : admin
FINE: Set security context as user: admin
FINE: [Web-Security] Setting Policy Context ID: old = null ctxID = jdbcrealm/jdbcrealm
FINE: [Web-Security] hasUserDataPermission perm: (javax.security.jacc.WebUserDataPermission  GET)
FINE: [Web-Security] hasUserDataPermission isGranted: true
FINE: [Web-Security] Policy Context ID was: jdbcrealm/jdbcrealm
FINE: [Web-Security] Codesource with Web URL: file:/jdbcrealm/jdbcrealm
FINE: [Web-Security] Checking Web Permission with Principals : null

(Edit after myfear's answer)
-----In glassfish-web.xml I have roles like that. If I understood it correctly it means that admin belongs to groups: admin, customer and user. Customer belongs to groups: customer and user and User belongs to group user. Did I understand it correctly?
    <security-role-mapping>
    <role-name>admin</role-name>
    <group-name>admin</group-name>
    <group-name>customer</group-name>
    <group-name>user</group-name>
  </security-role-mapping>
  <security-role-mapping>
    <role-name>customer</role-name>
    <group-name>customer</group-name>
    <group-name>user</group-name>
  </security-role-mapping>
  <security-role-mapping>
    <role-name>user</role-name>
    <group-name>user</group-name>
  </security-role-mapping>

</glassfish-web-app>

Thank you!
Sami

A: I've just attempted this as part of a University class and here's how I got the functionality I think you're after.
I'm using Netbeans with a Glassfish 4.1.1 server and have already configured the user roles in the servers  file realm.
My project has 3 files:
index.xhtml
users/mainmenu.xhtml
admin/mainmenu.xhtml
The welcome page is set to index.xhtml with the following hyperlinks:

         Admin Login

           User Login

In my web.xml security section I have the following roles configured
Now because access to each of these is restricted via the user groups, when you click on the hyperlinks on index you'll be prompted to login. If you enter a valid admin login for the admin link you'll be redirected to admin/mainmenu.xhtml, and vice versa for a user login.

A: A1) Welcome files aren't related to roles. If you need to do any kind of logic for dispatching users, you need to think about using boolean HttpServletRequest.isUserInRole(String role) or something similar to find out in which role the user is in.
A2) That shouldn't happen. You need to check the roles you have in your JDBCRealm. To what I see here, everything is configured the right way.
A3) I am not sure if I understand your remark "XML" file the right way. But welcome-files aren't bound to roles and .. see A1)
Thanks,
M

A: For your question 1: use the filter from where you can redirect the user to the specific page either userlogin.xhtml or adminlogin.xhtml
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    String userName = SecurityAssociation.getPrincipal().getName();
    String userNameSubject = SecurityAssociation.getSubject().toString();

    System.out.println("Yeeey! Get me here and find me in the database: " + userName+ " Subject : "+userNameSubject);

    filterChain.doFilter(servletRequest, servletResponse);
}


text:
Q: How can I use higher cost support abilities? I'm getting to a point in the game where my characters have several support abilities. I've even gotten one that costs 2 ..."cost"(?). The problem is that I only have one "cost" to use. I might have accidentally skipped a tutorial, but I have no idea how to get more "cost". How does one aquire more "cost"?

A: You start the game with one support ability slot and automatically get a new one at the end of each chapter after awakening the crystal, for a total of 5 support slots by the end of Chapter 4. The cost you're referring to corresponds to how many slots the ability takes up.


text:
Q: Create a two color circle I'm trying to create two half circles (each with a different color) which together form one circle. Something like this

DEMO
I created this using 2 elements and a bit of css:

and
$size: 100px;
$border: 20px;

...

.half-right-circle {
    border-top-right-radius: $size + $border;
    border-bottom-right-radius: $size + $border;
    border: $border solid green;
    border-left: 0;
}

.half-left-circle {
    border-top-left-radius: $size + $border;
    border-bottom-left-radius: $size + $border;
    border: $border solid red;
    border-right: 0;
}

Although this is exactly what I need, I was wondering if this can be achieved with just one html element (without pseudo elements of course :) ?

A: Here is a working snippet of what I'll do, using border:

*

*% values instead of px for border-radius, it simplifies a lot!

*border-color to add the correct color for each side.

*transform: rotate(45deg); to turn it like you want.

body{
  background: #ccc;
}

.halves-circle{
  background: #fff;
  height: 200px;
  width: 200px;
  border: 20px solid;
  border-radius: 50%;
  border-color: green green red red;
  transform: rotate(45deg);
}

⋅
⋅
⋅
We could use some CSS variables too, if you want to make many of them:

body{
  background: #ccc;
}

.halves-circle{
  background: #fff;
  height: var(--size);
  width: var(--size);
  border: var(--border) solid;
  border-radius: 50%;
  border-color: green green red red;
  transform: rotate(45deg);
}

#hc1{
  --size: 100px;
  --border: 20px;
}

#hc2{
  --size: 60px;
  --border: 30px;
}

#dot{ /* We can even do this! */
  --size: 0px;
  --border: 20px;
}

Hope it helps.

A: Here is a more simple solution with only 2 gradient and less of code:

.circle {
  margin:20px;
  border-radius:50%;
  width:200px;
  height:200px;
  background:
      radial-gradient(circle at center,white 60%,transparent 60.5%),
      linear-gradient(to right,red 50%,green 0);
}

body {
 background-color:pink;
}

A: Please try this code

body {
  background: #ccc;
}
.circle {
 margin: 25px 0;
  width: 200px;
  height: 200px;
  border-radius: 50%;
  border: 12px solid transparent;
  background-size: 100% 100%, 100% 50%,100% 100%, 100% 50%;
  background-repeat: no-repeat;
  background-image: linear-gradient(white, white),
                    linear-gradient(360deg, green 100%, lightgrey 100%),
                    linear-gradient(360deg, red 100%, lightgrey 100%);
  background-position: center center, left top, right top, left bottom, right bottom;
  background-origin: content-box, border-box, border-box, border-box, border-box;
  background-clip: content-box, border-box, border-box, border-box, border-box;
  transform: rotate(90deg);
}

Fiddle: http://jsfiddle.net/66r7nj4x/


text:
Q: How can I import XML data into Hadoop Am quite new to Hadoop and I wanted to import the semi-structured data - XML into HDFS. What are the ways to import XML data from a remote location to HDFS and any open source tools used for it? Can Flume import XML data into HDFS? Thanks in advance

A: You could try writing use HDFS Java API to create files in HDFS and write the whole content of the XML in each files.
Yes you could also go with flume, if there would be a large number of XML files getting generated from the source and will want to be sinked into HDFS.
You can have a look at these links :
http://www.dummies.com/how-to/content/log-data-with-flume-in-hdfs.html


text:
Q: mongodb calculate cumulative data i want to calculate my electricity usage.
we are using 3 period for each day
22:00 - 06:00 is T1
06:00 - 17:00 is T2
17:00 - 22:00 is T3

i can calculate from php but i am switched my database couchdb to mongodb.
i'm receiving data every minute and i need to make group usages example like this.
T1 = 06:00 max(s) value - prevday 22:00 max(s) value

....
i understand how $project using but i cant make it.
My example data is this and for calculation i use S value from the data.(raw watt)
/* 1 */
{
    "_id" : ObjectId("586e77658ce7580929392122"),
    "act" : 7613313,
    "rct" : 0.0,
    "cos" : 1.0,
    "hz" : 50.01,
    "s" : 988940600.0,
    "type" : "electric",
    "t" : 1483645333,
    "utc_date" : ISODate("2017-01-05T16:42:13.000Z")
}

/* 2 */
{
    "_id" : ObjectId("586e779f0ce3797b684845f6"),
    "act" : 7613652,
    "rct" : 0.0,
    "cos" : 1.0,
    "hz" : 50.01,
    "s" : 988984700.0,
    "type" : "electric",
    "t" : 1483645391,
    "utc_date" : ISODate("2017-01-05T16:43:11.000Z")
}


text:
Q: Defining [(ngModel)] for checkbox array to get output in different JSON format using forms I am trying to define [(ngModel)] for check boxes and convert them in some different format using forms like below:
In component file:
...
public roleList = [{"role":"ROLE_ADMIN","privileges":null},{"role":"ROLE_USER","privileges":null},{"role":"ROLE_READONLY","privileges":null}];
public privilegeList = [{"name":"ADMIN_READ_WRITE"},{"name":"ADMIN_READ"},{"name":"USER_READ_WRITE"},{"name":"READONLY"}];
public roleFormData = {"privileges":[{"name":null}],"role":null};

public populateRoleForm(roleForm: NgForm) {
    console.log(roleForm.value);
    this.roleFormData = roleForm.value;
}
...

In HTML file:
...
<form #roleForm="ngForm" (ngSubmit)="populateRoleForm(roleForm);" *ngIf="roleFormData">
    <select name="role" [(ngModel)]="roleFormData.role">
        <option *ngFor="let role of roleList" value="role.role">{{role.role}}</option>
    </select>
    <ng-container *ngFor="let privilege of privilegeList; let in=index">
        <input type="checkbox" name="privilegeName" value="privilege.name" [(ngModel)]="roleFormData.privileges[in].name" />{{privilege.name}}
    </ng-container>
    <button type="submit" class="btn btn-primary">ADD</button>
</form>
...

Error in console:
ERROR TypeError: Cannot read property 'name' of undefined
    at Object.eval [as updateDirectives] (UsersComponent.html:65)
    at Object.debugUpdateDirectives [as updateDirectives]

line 65 in html is: <input type="checkbox" name="privilegeName" value="privilege.name" [(ngModel)]="roleFormData.privileges[in].name" />{{privilege.name}}
Not sure how to define [(ngModel)] for checkboxes in this case. How I can get my desired roleFormData?
EDIT:
I changed my HTML as:
<form #roleForm="ngForm" (ngSubmit)="populateRoleForm(roleForm);roleModal=false;" *ngIf="roleFormData">
    <select name="roleName" [(ngModel)]="roleFormData.role">
        <option *ngFor="let role of roleList">{{role.role}}</option>
    </select>
    <ng-container *ngFor="let privilege of privilegeList; let i=index">
        <input type="checkbox" name="privilegeNames" value="{{privilege}}" [(ngModel)]="roleFormData.privileges[i].name" />{{privilege.name}}
    </ng-container>
    <button type="button" class="btn btn-outline" (click)="roleModal=false">CANCEL</button>
    <button type="submit" class="btn btn-primary">ADD</button>
</form>

and component as:
public roleFormData = {"privileges":[{"name":null},{"name":null},{"name":null},{"name":null}],"role":null};

But the console for roleForm.value in populateRoleForm method is giving me {roleName: "ROLE_USER", privilegeNames: true} but I wanted to get privilegeNames as [{"name":"ADMIN_READ_WRITE"},{"name":"ADMIN_READ"}] ie. all selected values. How I can get this?

A: Your roleFormData.privileges don't have the same number of objects as that in the privilegeList. Due to that, you're getting the error as for the value of index 1 or more, you're not going to have objects in the roleFormData.privileges array.
To fix that, you might want to either add equal number of Objects as you have in privilegeList or change [(ngModel)]="roleFormData.privileges[in].name" to [(ngModel)]="roleFormData.privileges[0].name", whatever suits your purpose.

Here's a Working Sample StackBlitz for your ref.


text:
Q: Is there a way to scan JPA entities not to declare persistent classes in a persistence.xml file? I would like to take advantage of JPA @Entity annotations not to declare class entities a J2SE persistence.xml file. What I'd like to avoid :
<persistence-unit name="test" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <class>com.mycompany.entities.Class1</class>
    <class>com.mycompany.entities.Class2</class>
    <class>com.mycompany.entities.Class3</class>
</persistence-unit>

and here is what my actual persistence.xml look alike
    <persistence-unit name="test" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <properties>
        <!-- Scan for annotated classes and Hibernate mapping XML files -->
        <property name="hibernate.archive.autodetection" value="class, hbm" />
        <property name="hibernate.cache.use_second_level_cache" value="false" />
        <property name="hibernate.cache.use_query_cache" value="false" />
        <property name="hibernate.hbm2ddl.auto" value="create-drop" />
    </properties>
</persistence-unit>

Is there a standard way to scan JPA entities in a persistence.xml file from within a JAR module?
Is there a unstandard Hibernate way to scan JPA entities in a persistence.xml file from within a JAR module?

A: -Make sure your entities and persistence.xml end up in the same classpath when you build your jar.
The entities cannot be scanned if they are sitting in another classpath. If you need to have them sitting in different classpaths, heres one trick I've seen to make it work: No autodetection of JPA Entities in maven-verify.
If you are unsure where things are ending, you can unzip the .jar file and peak. This is an unpacked persistence web project:

Notice my classes are down the com directory, and my persistence.xml is in the META-INF directory. Both are in the same 'classes' classpath, so autoscan will work.
-Set hibernate.archive.autodetection property.
<!-- Scan for annotated classes and Hibernate mapping XML files -->
<property name="hibernate.archive.autodetection" value="class, hbm" />

-Add false to the persistence-unit
<persistence-unit name=...>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
    ...

Hopefully one of those will work for you.


text:
Q: How do I install Big Sur on a machine running Mavericks? I just erased an MBP 2014 that had been running the latest Big Sur to factory settings in preparation for migrating from another MPB running Big Sur, following the instructions provided by Apple. But the process has installed Mavericks and provides no way to install Big Sur.
How do I install Big Sur on a Mavericks machine? Can I just run Migration Assistant on the Big Sur (source) - Mavericks (destination) combo and end up with Big Sur on the destination? Is there some way to download a disk image to the Mavericks Mac that will work as an installer there?

A: If using the various macOS Recovery options doesn't get you there, you should be able to upgrade to a more recent version of macOS from Mavericks.
Once you're up to El Capitan (or later) you then have the option of creating a bootable installer for macOS.


text:
Q: What's the difference between PROC EXPORT, LIBNAME and ODS in exporting file? Basically, I understood I can export files and data from SAS in three ways (PROC EXPORT, LIBNAME statement and ODS statement), but I really can't see the differences between them.
From what I understood, the PROC EXPORT let me export only data sets created using a DATA step, but not the results of the procedures.
Differently, LIBNAME and ODS statements allow this, but it seems there isn't a significant difference between them.
Is this correct? And if it's so, what's the main difference between the two statements?

A: ODS redirects output from the procs directly to a different output format, such as PDF, Excel, Word or PowerPoint. This is more for generating automated reports that have styles and formatting which differentiates it from PROC EXPORT or LIBNAME.
PROC EXPORT exports raw data - no formatting or commenting - best used for data transfers.
LIBNAME is closer to export - you get more raw data extracted but not formatting in the data. I don't think there's a significant difference between PROC EXPORT and LIBNAME methods.


text:
Q: Azure expressjs web apps I have created an express application in Visual Studio. I am having problems running it in azure once I've hosted.
It does not seem to find my node_modules folder.
Whenever I deploy and visit the site, on Kudu under the /logStream url I receive the error

cannot find module 'debug'

I found out that the debug module was required in the www folder. I then removed it from there and redeployed.
After redeployment I get

cannot find module 'express'

When I run my app in production (locally), I do not experience these problems.
One suggestion was removing the node_modules folder and then publish to Azure, with that you then use npm install on Kudu powershell or cmd. I have tried this and the same errors still come back. Could you please direct me on how I can resolve this?
package.json:
   {
   "name":"app-name",
   "version":"0.0.0",
   "private":true,
   "scripts":{
      "start":"node ./bin/www"
   },
   "description":"descrt",
   "author":{
      "name":"myname",
      "email":"myemail@smtpserver.com"
   },
   "dependencies":{
      "body-parser":"~1.8.1",
      "cookie-parser":"~1.3.3",
      "debug":"~2.0.0",
      "express":"~4.9.0",
      "jade":"~1.6.0",
      "morgan":"~1.3.0",
      "request":"^2.72.0",
      "serve-favicon":"~2.1.3",
      "stylus":"0.42.3"
   }
}


text:
Q: Class Packing and Alignment What is the alignment for calling #pragma pack() with no argument in GCC compiler?
Also, I often see that when we use placement new in creating object, the class is often being packed. What is the reason for that? Is it necessary to do so?

A: for the first part, you could have recklessly used google: http://gcc.gnu.org/onlinedocs/gcc/Structure_002dPacking-Pragmas.html
secondly there may be times when you need to control the binary format of your class. you may need to manage the amount of memory and the real binary offsets of data structures:
struct
{
  char c;
  int i;
};

may use 8 bytes of memory or 5 bytes of memory, according to machine type and pragma pack used.


text:
Q: AsyncStorage.removeItem('my_token'); returns null Below is my code, whenever I try to logout by clicking onButtonPress it returns err : null, and my token is not removed from local storage. Please help me solve this.
onButtonPress = async () => {
    try {
        await AsyncStorage.removeItem('id_token', err =>
            console.log('error : ' + err)
        );
        console.log('logged out!');
        this.props.navigation.navigate('main');
    } catch (err) {
        console.log('AsyncStorage error: ' + error.message);
    }
};

A: try this:
async removeKey() {
    try {
      await AsyncStorage.removeItem('id_token');
      this.props.navigation.navigate('main');
        } catch (error) {
      console.log("Error resetting data" + error);
    }
  }


text:
Q: Program written with asyncio takes same time to run as the synchronous version I started learning python asyncio module. I was writing a basic program which basically waits for some time an prints the result.
async def say_helloworld(wait:int)->None:
    print(f"starting say_helloworld({wait})")
    await asyncio.sleep(wait)
    print(f"say_helloworld({wait}) says hello world!")

I wrote my coroutine as given above and created some tasks.
tasks = (asyncio.create_task(say_helloworld(i)) for i in range(10))

I then wrapped the tasks in another coroutine.
async def main(tasks):
    for task in tasks:
        await task

Finally, I ran the wrapper coroutine
asyncio.run(main(tasks))

My expectation was that the program will finish in around 10 seconds, since each task will wait concurrently, and not in a synchronous fashion. But, the program nearly took 45 seconds (synchronous?).
What am I missing? Why is it running like a synchronous program?

A:
I wrote my coroutine as given above and created some tasks.

The problem is that your code, as written, doesn't actually create tasks in advance, it just provides a recipe how to create them when needed. tasks is initialized to:
tasks = (asyncio.create_task(say_helloworld(i)) for i in range(10))

The above is a generator expression that will only create tasks as you iterate over it. So, while the intention was to create tasks in advance and then await them while they run in parallel, the actual implementation creates a single task in each iteration, and then awaits it immediately. This of leads to the undesirable result of the tasks being executed sequentially.
The fix is to build an actual list by switching from (asyncio.create_task... ) to [asyncio.create_task... ]. You will also need to do so inside a coroutine so there is an event loop running for the tasks. For example:
# ... say_helloworld defined as before ...

async def main():
    tasks = [asyncio.create_task(say_helloworld(i)) for i in range(10)]
    for task in tasks:
        await task

asyncio.run(main())

This results in ten "starting ..." messages followed a single pause and ten "says hello..." messages, which was the initial goal.


text:
Q: How does the change of variable formula hold for random variables w/o pdfs or discrete random variables? Given a random variable $X$ on $(\Omega, \mathscr{F}, \mathbb{P})$ and its law $\mathcal{L}_X$,
$$E[X] = \int_{\Omega} X d\mathbb{P} = \int_{\Omega} X(\omega) d\mathbb{P}(\omega)$$
Change of variable theorem allows us to compute as follows:
$$E[X] = \int_{\mathbb{R}} t d\mathcal{L}_X(t)$$
From Wiki:

What is $$\int_{\mathbb{R}} t d\mathcal{L}_X(t)$$ when, say, $X$ is Binomial or has the Cantor distribution?

Guess:
$$\int_{\mathbb{R}} t d\mathcal{L}_X(t)$$
$$= \int_{Range \ of \ X} t dF_X(t)$$
$$= \lim_{||P|| \to 0} \sum_{i=0}^{n-1} c_i [F(x_{i+1}) - F(x_{i})]$$ where $P = (\min(Range \ of \ X) = x_0 < x_1 < ... < x_n = \max(Range \ of \ X))$
And that holds for the F being the distribution function of either Cantor distribution or binomial distribution?

A: It is a standard result in measure theory that for nonnegative functions $f$
$$\int_A f d \mu = \lim_{n \to \infty} n \mu(f^{-1}([n,\infty)) + \sum_{k=1}^{n^2-1} \frac{k}{n} \mu(f^{-1}([k/n,(k+1)/n)).$$
(The details of the partitioning are not so important; the important matter is that the mesh size goes to zero and the upper bound goes to infinity.) For general measurable functions $f$, introduce $f^+=\max \{ 0,f \}$ and $f^-=-\min \{ 0,f \}$, then $\int_A f d \mu = \int_A f^+ d \mu - \int_A f^- d \mu$, provided at least one of these numbers is finite. Translated to the probability context, this is what you're trying to say.


text:
Q: Odd Angular/Bootstrap Dropdown Behavior I've got an application requiring a series of dropdowns.  The functionality requires me to be able to switch between normal dropdown behavior and multi-select behavior.
I have made slight modifications to the ui.boostrap.dropdown from the Angular Directives for Bootstrap (see Dropdown).  Everything works well, except for a gray bar after clicking (looks like the :hover css stays active after clicking) when in Multiselect mode.
When I toggle off then back on, the highlight goes away, as if the hover event has somehow completed.
Process:

*

*Open the dropdown

*Click Multiselect

*Move the mouse and Multiselect stays highlighted, as if the ":focus" tag is not removed.

Visually:
The mouse is over 345 in this image, Multiselect should not be highlighted.

Angular HTML for dropdown:

        <button type="button" class="btn btn-default dropdown-toggle" dropdown-toggle>
            {{ vm.selected }}
        </button>

                {{ company.name }}

                Multiselect
                <button
                    ng-hide="!vm.multi.select"
                    ng-class="{ multi_button: vm.multi.select }"
                    ng-click="vm.event.close_dropdown($event)">Close</button>

Here's the event where the click on an element is handled:
vm.event = {};
vm.event.select = function(company) {
    if (!vm.multi.select) {
        clearCompanies(false);
        company.selected = true;
        vm.selected = company.name;
        vm.isopen = false;
    } else {
        if (company.name !== vm.defaultCompany) {
            company.selected = !company.selected;
            vm.selected = vm.multi.title + countCompanies();
        }
    }
};

Link to Plunker.
I have had no luck tracking this down and my instinct is that the issue is in the CSS, but it's standard bootstrap CSS.  Any assistance would be appreciated.

A: If you just dont want any item to have the highlight then in your own custom app.css file override the focus state with white:
.dropdown-menu > li > a:focus {
  background-color: white;
}

Without doing a custom bootstrap build just add the hover following the focus to to keep the grey highlight:
 .dropdown-menu > li > a:hover {
      background-color: lightgray;
    }


text:
Q: Can FirebaseAuth 5.0.x be used in an iOS app extension? FirebaseAuth uses [UIApplication sharedApplication] in FIRAuth.m. Since that API is not available to App Extensions, it appears that FirebaseAuth (and anything that depends on it, such as Firestore) can not be used in an App Extension.
Is there any way around this limitation?

A: Update:
Firebase confirms that a fix is targeted for 5.2.x version. Track the Github issue for latest updates.

It seems as Firebase is not officially supporting extensions in iOS. I have got that info from this GitHub issue (see paulb777's answer). Maybe someone from Firebase can also confirm this here. I am very surprised that we can't use Firebase SDK when creating extensions such as a Today widget.
The only workaround I had was reverting back to an earlier version of Firebase via:
pod 'Firebase', '4.9.0'
This uses the 4.9.0 version of the Firebase SDK and doesn't create compiler errors.


text:
Q: Assign Ids dynamically to Apex:inputField I'm trying to assign Id to my inputField dynamically, those input fields are coming from field sets.
These Ids needs to be assigned to those fields which are required in database.
On giving Id dynamically I'm getting Literal value is required for attribute id in  error.
Based on those ids I need to perform some check in javascript, before saving the record.
<apex:outputPanel id="mySalesforceFields">
  <apex:repeat value="{!fieldSetMemberList}" var="field">
    <apex:inputField value="{!sObject[field]}" required="{!if((field.dbRequired || field.required), true,false)}"
    id="{!if((field.dbRequired || field.required), field.label,'')}" />

  </apex:repeat>
</apex:outputPanel>

A: You can't dynamically assign the Visualforce id attribute. You can, however, assign data- attributes or pass through html- attributes. See, for example, Setting Custom HTML Attributes on Visualforce Components
. Make sure you use a unique value such as the field's API Name rather than its Label if you decide to pass through an html-id.
Probably better to use data- attributes. You can still select on them.
<apex:inputField ... html-data-id="{!field}"
    html-data-required="{!OR(field.required, field.dbRequired)}" />


text:
Q: Packet Tracer 7.3.0 cannot be installed on Ubuntu I noticed that Ubuntu 20 Release, comes with many unmet dependencies with some of them already deprecated and almost impossible to install. I see this when I try to install Packet Tracer and it outputs that requires many dependencies that at the same time need to install other dependencies.
Note: If you have a solution, I hope it worked out for you on a VM with Ubuntu 20 before suggesting it.
m@m:~/Desktop$ sudo dpkg -i PacketTracer_730_amd64.deb
Selecting previously unselected package packettracer.
(Reading database ... 207479 files and directories currently installed.)
Preparing to unpack PacketTracer_730_amd64.deb ...
Unpacking packettracer (7.3.0) ...
dpkg: dependency problems prevent configuration of packettracer:
 packettracer depends on libdouble-conversion1; however:
  Package libdouble-conversion1 is not installed.
 packettracer depends on qt-at-spi; however:
  Package qt-at-spi is not installed.

dpkg: error processing package packettracer (--install):
 dependency problems - leaving unconfigured
Processing triggers for gnome-menus (3.36.0-1ubuntu1) ...
Processing triggers for desktop-file-utils (0.24-1ubuntu2) ...
Processing triggers for mime-support (3.64ubuntu1) ...
Processing triggers for shared-mime-info (1.15-1) ...
Errors were encountered while processing:
 packettracer
EDIT: The main problem, is with qt-at-spi, libdouble-conversion1 I was able to install manually.
The following packages have unmet dependencies:
 qt-at-spi : Depends: libqt4-dbus (>= 4:4.8.0) but it is not installable
             Depends: libqtcore4 (>= 4:4.8~) but it is not installable
             Depends: libqtgui4 (>= 4:4.8~) but it is not installable

A: I had the same difficulty. After spending a few days googling and trying various suggestions, the following solved most of the problems.

*

*Downloaded and installed libdoule-conversion1 from this link:
https://packages.ubuntu.com/bionic/libdouble-conversion1

*Downloaded PacketTracer_730_amd64.deb from
https://www.netacad.com/portal/resources/packet-tracer

*Unpacked the .deb file and edited the file named control in the DEBIAN folder. I simply opened with text editor and deleted qt-at-spi from the "Depends: libdouble-conversion1, qt-at-spi" line, and saved, repacked as fixed.deb.
Find detailed instructions here.

*Installed the fixed .deb.

*Rebooted.
Now Packet Tracer can only be launched from the terminal, the shortcut icon is not working. I remember seeing a solution for that somewhere, but I don't really mind.


text:
Q: Recognizing instances placed on the stage I'm working with Flash Builder 4.6 as an IDE and Flash CS5.5 to create library items.
The problem is - when I put an instance of a library item on the stage or inside of another item, Flash Builder fails to detect the instance name that was declared in Flash CS.
This doesn't prevent the code from compiling just fine though.
I understand that the IDE only sees the fields that I have declared directly in the .as file, but it really hinders me that I the IDE goes crazy when I do this.
Is there any way to circumvent this - other than dynamically creating and placing the instances?
Thanks in advance.

A: You can proceed with using the name you have given as instance name. Flash Builder will not identify or list it with others when you press CTRL + SPACE. You need to worry only when it shows compile errors.
One thing usually done is creating proxy variables for the library items on stage.
Suppose you have a library item Car which you dragged and dropped on stage in Flash CS 5 and gave it instance name car1. In your .as file you can create a proxy variable in the constructor and use that proxy variable everywhere else in the code.
var car1Proxy:MovieClip = MovieClip(car1);

A: A pretty old question, I've since found an answer a long time ago.
The way to do this is to set "Automatically Declare stage instances" to false in Flash CS, and use the following syntax:
public var instanceName:Type;

The variable name and type must correspond to the object placed on the stage and it will be populated automatically on constructor call. (like a normal field.)


text:
Q: Playing a random animation every time an object passed I am currently in the process of making a game and I am trying to have a mirror play a random animation as the player walks past it. I managed to get it working, sort-of, and am having some troubles with it.
So first I created an idle animation along with three random animations to be activated as the player walks by and from the idle animation. I then created a simple transition to each of the three states leaving the standard exit time and transition duration on. I than created this script to try to activate the animations:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class mirrorActivate : MonoBehaviour
{
    private GameObject FSSecurity;
    public GameObject mirrorblank;
    public List<AnimationClip> anim = new List<AnimationClip>();
    // Start is called before the first frame update
    private void Awake()
    {

    }
    void Start()
    {
        FSSecurity = GameObject.Find("Female Security");
    }

    // Update is called once per frame
    void Update()
    {
        if (FSSecurity.transform.position.x == 10)
        {
            StartAnimation();
        }
    }
    public void StartAnimation()
    {
        int random = Random.Range(0, anim.Count);
        mirrorblank.GetComponent<Animator>().Play(anim[random].name);
    }
}

What's working: It is seemingly playing a random animation every time the player walks to this location.
What's not working?:
1. Upon entering scene idle animation immediately triggers one of the three animations without the if statement being activated. ((It should be in idle and only switch to one of the three randomly if if() is true))
2. Due to floating point precision using == is not practical, this theoretically could be solved if I use a range with <= and >= rather than ==. But if there is a better solution to activate the player passing an object I am open to suggestions. 3. Animations when played randomly are not fully playing the full time the animation should last. 4. Final issue after activated they are not returning to idle state until next activation.
What I am looking for: Random animation to play each time user walks passed object and as it finishes return to idle. And as a side note is there a more effective way to know when player passes object (I am using 2D)
(for some reason not letting me put unity2d tag on the post)

Simple transitions between, no triggers set or anything

A: Finally! After some more long and twisted turns I have finally come up with a reasonable solution that I think works well.
Problem 1 solution:
In order to prevent any animation from triggering before if() statement is tripped, remove transition from Idle to random states.
Problem 2 solution:
Simply used a range to solve issue with comparing floating point precision using ==. Please comment on any other better way to go about this.
Problem 3 solution:
Animations were not fully running their course of the desired animation time because of constant triggering. If the player is >= 10 was the only parameter causing it to activate so to solve use a simple solution of a boolean. If the player.transform is >= 10 and the boolean is true start animation. If the player is outside of the range boolean is false. In StartAnimation() set boolean too true.
Problem 4 solution:
Now with transitions from idle to random animations removed instead create transition from random states to exit. No transitions interacting between idle and random animations are required.
Full code for better details:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class mirrorActivate : MonoBehaviour
{
    private GameObject FSSecurity;
    public GameObject mirrorblank;
    public List<AnimationClip> anim = new List<AnimationClip>();
    bool isPlayingAlready = false;
    // Start is called before the first frame update
    private void Awake()
    {

    }
    void Start()
    {
        FSSecurity = GameObject.Find("Female Security");
    }

    // Update is called once per frame
    void Update()
    {
        if (FSSecurity.transform.position.x >= 10 && isPlayingAlready == false)
        {
            StartAnimation();
        }
        if (FSSecurity.transform.position.x <= 10 && isPlayingAlready == true)
        {
            isPlayingAlready = false;
        }
    }
    public void StartAnimation()
    {
        int random = Random.Range(0, anim.Count);
        mirrorblank.GetComponent<Animator>().Play(anim[random].name);
        isPlayingAlready = true;
    }
}

Animation Controller View:

Animation Transition View (This may change depending on your needs but for this purpose..):

I hope this helps anyone who may suffer from these same issues, this can be done with anything that you with to activate random animations whether it be collision or something else.


text:
Q: Legend is not aligning correctly I want to use legend like the image below.

So a square is on the left, the title is on the right.
My code is:
<Grid>
                <TextBlock Text="{Binding Title}" Foreground="White" Margin="15 0 0 0" HorizontalAlignment="Left"/>
                <Path Width="12"
                      Height="12"
                      Fill="{Binding MarkerFill}"
                      HorizontalAlignment="Left" >
                      <Path.Data>
                        <Binding Path="ActualMarkerGeometry"
                             RelativeSource="{RelativeSource AncestorType=telerik:LegendItemControl}">
                        </Binding>
                      </Path.Data>
                </Path>
            </Grid>

My question is that the text is not aligning correctly. It align the text to the right rather than the left. See the image below.

Update code
<telerik:RadLegend.ItemTemplate>
  <DataTemplate>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition></ColumnDefinition>
            <ColumnDefinition></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <Path Width="15" Height="15" Fill="{Binding MarkerFill}"
                      HorizontalAlignment="Left" Grid.Column="0">
           <Path.Data>
                        <Binding Path="ActualMarkerGeometry"
                             RelativeSource="{RelativeSource AncestorType=telerik:LegendItemControl}">
                        </Binding>
                      </Path.Data>
            </Path>
             <TextBlock Text="{Binding Title}" Foreground="White" Margin="15 0 0 0" HorizontalAlignment="Left" Grid.Column="1" />
             </Grid>
           </DataTemplate>
   </telerik:RadLegend.ItemTemplate>

A: I added the width of the first column to enforce the width same as the square. It seems work. But not sure why?
      <ColumnDefinition Width="15"></ColumnDefinition>


text: Q: How to move a button from its a layout parent to another on android java? I'm trying to make a simple game for practice on android, but I need a generic function which can help me to move a button from its layout parent to another, so the user should be able to look the animation of that, please can you help me?


text:
Q: Assigning unique path name in spring webflow while using for each loop I was using spring textarea to retrieve list of item. The problem doing so is I am getting commas due to repeatition of the path name. How can I make the name of the path name unique? As per my understanding the name of the path should match the variable in the modal.
<c:forEach var="note" items="${model.modelname}">
//create a click button for each items
//each click opens up a modal and

            <form:textarea path="textPath" />

</c:forEach>

I tried using specifying index  <form:textarea path="note[0].textPath" /> but I could not do anything to list the whole item.
I tried giving index to the for each loop and assign unique name to the path as shown below but this just displays the first item on the list
<c:forEach var="note" items="${model.modelname}" varStatus="status">
//create a click button for each items
//each click opens up a modal and

            <form:textarea path="textPath[${status.index}]" />

</c:forEach>


text:
Q: Error with Geocode, Rails and Mongoid I'm using Rails 3.2.16, mongoid and geocode.
I've set up the model for my profile to convert the street and city address into long/lat. This is working well. I also have a search that's based on geocode - which also works. It searches for profiles with in certain distances etc.
Even when I misspell a city in the search it's intelligent enough to figure out what I actually mean.
However, when I search for something that really stumps geocode, like "sgervwsewerw", it throws the "We're sorry, but something went wrong" error. How can I prevent this error and just have it send back no results? Here is the error information:
Processing by ProfilesController#index as HTML
  Parameters: {"utf8"=>"✓", "profile_search"=>"sgervwsewerw"}
  Rendered profiles/index.html.erb within layouts/application (137.3ms)
Completed 500 Internal Server Error in 489.6ms

ActionView::Template::Error (The operation: #<Moped::Protocol::Query
  @length=208
  @request_id=2
  @response_to=0
  @op_code=2004
  @flags=[]
  @full_collection_name="tango_production.profiles"
  @skip=0
  @limit=0
  @selector={"$query"=>{"coordinates"=>{"$nearSphere"=>[NaN, NaN], "$maxDistance"=>0.0063151153689165445}}
  @fields=nil>
failed with error 16433: "point not in interval of [ -180, 180 ] :: caused by :: { 0: nan.0, 1: nan.0 }"

See https://github.com/mongodb/mongo/blob/master/docs/errors.md
for details about this error.):

Here is the code from my profile controller:
def index
 if params[:profile_search].present?
    @profiles = Profile.near(params[:profile_search], 25, :order => :distance).desc("position_order")
  else
    @profiles = Profile.desc("position_order")
  end
end

A: Your problem seems to be in the NaN argument in the $nearSphere for coordinates.
Make sure, you provide correct values for the comparison (e.g. if using the users location, make sure it is available).
Hope that helps.

A: In your mongoid.yml initializer file you will find a line like:
# Raise an error when performing a #find and the document is not found.
# (default: true)
raise_not_found_error: false

default it's true, if you set it to false you will not get this error anymore.


text:
Q: In Angular: How to Check the Previous route that is sending the Id, then apply the if else condition So what I am trying to do is. I have three components in angular2+ Application
1 Home with (/home) route
2 Products with (/product) route
3 ViewProducts with (/view product) route.
HomeComponent has Feature products.
ProductComponent has only products.
They both have a method that routes them to viewProduct Component with their feature/product _id.
Now ViewCompnenet should check that from which component the _id is coming by checking the previous
route and then do some actions according to the route.
Here is my snippet.
   for example
   in FeatureProductComponent / ProductComponet both have this method

      SendProductId(_ProductId){
        this._MessengerService.SendFeatureProductId(_ProductId);//I am using rxjs to send data to viewComponent
        this._Router.navigate(['viewProduct']);
      }

     Now at ViewProduct Component.ts
     ngOnInit(): void {
       if(_Id is coming from /home (route or slug){

        //run some block of code here

       }else if(_id is coming from /product (route or slug)){

                     ///run some block of code here

          }
     }

A: I have implemented and solved this using the logic given below. And it's working fine Just want to know is it a good way of solving this particular problem.
  viewProductComponent.ts

 Here docs are coming from the home/product component and it is an object
 {id:someId,Component:someComponent} and on this object i am checking form which
  component the data is coming.

 this._MessengerService.GetMessageWithData().subscribe((docs: any) => {

   if (docs.Component === "FeatureProductComponent") {
         console.log('Data Coming From Feature Product Component');
       } else if (docs.Component === "ProductComponent") {
         console.log('Data Coming From Feature Product Component');
       }
     });

  }

A: Here's a StackBlitz with what you want:
https://stackblitz.com/edit/angular-ivy-xceqqt?embed=1&file=src/index.html

*

*In the home.component.html and the list.component.html, I've specified query parameters on the a elements, which will be appended on navigation to the show.component.
<a ... [routerLink]='["/product", i]' [queryParams]="{from: 'home'}"><!-- or 'list' -->
    Go to product {{ i }}
</a>

*In the show.component.ts I'm reading the value of the query parameter
constructor(private route: ActivatedRoute) {
  this.route.queryParams.subscribe((params) => {
    this.from = <string>params.from;
  });
}

*Here you can put your if clause to decide what actions need to be taken.


text:
Q: if $f(x+3\pi)=f(x)$ where $f(x)=\cos{(nx)}\sin{(\frac{4}{n}x)}$ Let $n$ be integer number,if $$f(x)=\cos{(nx)}\sin{(\dfrac{4}{n}x)}$$
such $f(x+3\pi)=f(x),\forall x\in R$
Find $n$
since
$$2f(x)=\sin{\left(\left(\dfrac{4}{n}+n\right)x\right)}+\sin{\left(\left(\dfrac{4}{n}-n\right)x\right)}$$

A: We notice almost immediately that if $n=2$, then $f(x)=\cos2x\sin2x=\frac{1}{2}\sin4x$, and so $f(x+3\pi)=f(x)$. But, although we are not specifically asked for all possible values of $n$, we may as well look for them. Indeed, if $n=-2$, then $f(x)=-\cos2x\sin2x$, which also works.
For any $n$ we have $f(x+6\pi)=\cos(nx)\sin(\frac{4x}{n}+\frac{12\pi}{n})$, so for the condition to hold we require $\sin\frac{4x}{n}=\sin(\frac{4x}{n}+\frac{12\pi}{n})$ to hold for all $x$, which it clearly cannot for $|n|>3$.
$f$ is undefined for $n=0$, so we rule out that value. For $n=1$ we have $f(x)=\cos x\sin4x$ and $f(x+3\pi)=\cos(x+\pi)\sin4x=-f(x)$, which fails. Similarly, for $n=-1$ we have $f(x)=-\cos x\sin4x$ and again $f(x+3\pi)=-f(x)$. For $n=3$ we have $f(x)=\cos3x\sin(\frac{4x}{3})$, and $f(x+3\pi)=\cos(3x+\pi)\sin(\frac{4x}{3}+\pi)=f(x)$, which works. Finally for $n=-3$ we have $f(x)=-\cos3x\sin(\frac{4x}{3})$ and $f(x+3\pi)=-\cos(3x+\pi)\sin(\frac{4x}{3}+\pi)=f(x)$.
So $n$ can be any of $\pm2,\pm3$.


text:
Q: How to set a title if URL contains exactly URL, and nothing after it? I am currently using:
 if (strpos($_SERVER['REQUEST_URI'], "/administrator/index.php?option=com_ohanah&view=event") !== false){
            $this->getCommand('title')->title = $translator->translate('test');
        }

but this sets the title for all URLs even if it contains something after the &view=event. How can I do this only on the exactly URL?


text:
Q: maven module referencing itself during install command When I run maven install I get following  message -

Failed to execute goal on project Ret: Could not resolve dependencies
  for project com.software.org:Ret:jar:1.0-SNAPSHOT: Could not find
  artifact com.software.org:Ret:jar:1.0

Here's my pom.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.software.nagibator</groupId>
    <artifactId>Ret</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <properties>
        <compiler>1.8</compiler>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.nag.software</groupId>
            <artifactId>SpringContainer</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.4</version>
        </dependency>

        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-all</artifactId>
            <version>1.10.19</version>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <version>1.4.187</version>
        </dependency>

        <dependency>
            <groupId>com.software</groupId>
            <artifactId>nag</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

        <dependency>
            <groupId>com.software.org</groupId>
            <artifactId>SpringProxyProvider</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.2</version>
                <configuration>
                    <source>${compiler}</source>
                    <target>${compiler}</target>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.12.4</version>
                <configuration>
                    <skipTests>true</skipTests>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


text:
Q: The while..do loops in C I've just studied C programming recently. In fact, I'm a beginner in programming. Currently, I'm reading the book called: C programming, Absolute beginner's guide.
I don't quite understand this, they use the do...while loop:
if (choice == 'n')
    {
        choice = 'N';
    }
} while (choice != 'N');

This is used in case user types 'n' instead of N. But I retyped like this:
while ((choice != 'N')||(choice!='n'));

The while loop still continues
Sorry guys, dude to tha lack of time (I nearly missed my school buss)
Here is the complete original code from the book:
float num1, num2, result;
char choice;
do {
    printf("Enter your first number to multiply: ");
    scanf(" %f", &num1);
    printf("Enter your second number to multiply: ");
    scanf(" %f", &num2);
    result = num1 * num2;
    printf("%.2f times %.2f equals %.2f\n\n",
        num1, num2, result);
    printf("Do you want to enter another pair of numbers ");
    printf("to multiply (Y/N): ");
    scanf(" %c", &choice);
    // If the user enters a lowercase n, this if statement will
    // convert it to an N
    if (choice == 'n')
    {
        choice = 'N';
    }
} while (choice != 'N');
return 0;

A: You're boolean logic is incorrect, what you are looking for is...
while ((choice != 'N')&&(choice!='n'));

In the case of using OR if either case is true it continues and as such it always will
| Choice |  choice!='N' | choice !='n' | OR | AND |
| X | true | true | true | true |
| n | true | false | true | false |
| N | false | true | true | false |


text:
Q: Ranking Posts with Ruby Okay so I am using the punching bag gem to track the number of hits for my posts. What im trying to do is have a ranking system. So the most viewed post would be 1st and say the 10th viewed post would say 10th. Has anyone done this before or can give me a push in the right direction.
Right now on the posts I am showing the hit count with

      VIEWS
<%= @post.hits %>

and I am ranking them by just overall views and this is in my posts controller
def index
 if params[:sort_param] == "views"
  @posts = Post.sort_by_popularity('DESC')

  elsif params[:sort_param] == "likes"
  @posts = Post.all.order(:cached_votes_up => :desc)

  else
    @posts = Post.all.order("created_at DESC")
end

end
I dont know what else code would be helpful for anyone. I will gladly add anymore code that would help.  Im just trying to figure out how to have a ranking on the show for the posts. So when you click on the post you see where that posts ranks on views. So for example you will see 450 views (I have this already) and Ranked 5th. I want people to be able to see where the posts ranks on view count. I just dont know where to begin for this

A: Let's say that @post has the post you are trying to figure out the ranking for. Next step is to search the array you got with
  @posts = Post.sort_by_popularity('DESC')

to find where @post appears. You can try to do it like this:
@ranking = @posts.find_index(@post) + 1

Now you have the postion of your post relative to others with respect to hits. Plus one is because arrays start with zero


text:
Q: How to I create an adjacency matrix out of this? try to turn in this information into adjacency matrix but confused on how
import java.util.*;

public class graph {

  public static void main(String[] args) {
    Scanner stdin = new Scanner(System.in);
    int adjMatrix[][];
    ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
    while(stdin.hasNext()) {
      String[] str = stdin.nextLine().split("[\\s,]+");
      ArrayList<Integer> inner = new ArrayList<Integer>();
      for(int i = 0; i < str.length; i++) {
        inner.add(Integer.parseInt(str[i]));
      }
      list.add(inner);
    }
  }
}

storing the information in an arraylist of arraylist. help on how to make this an adjacency matrix would be appreciated.

A: If the data you are extracting from stdin are valid you should be able to construct adjacency matrix like this :
public static void main(String[] args) {
    String[] input = "1 2 5 \n3 4 2 \n".split("\n");
    int adjMatrix[][];
    int max = 0;
    ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
    for(int i=0; i<input.length; i++) {
      String[] str = input[i].split("[\\s,]+");
      ArrayList<Integer> inner = new ArrayList<Integer>();
      for(int j = 0; j < str.length; j++) {
        inner.add(Integer.parseInt(str[j]));
      }
      max = Math.max(Math.max(max, inner.get(0)), inner.get(1));
      list.add(inner);
    }

    int[][] adjacencyMatrix = new int[max+1][max+1];

    for(int i=0; i<list.size(); i++) {
      int source = list.get(i).get(0);
      int dest = list.get(i).get(1);
      adjacencyMatrix[source][dest] += 1;
    }

    for(int i=0; i<adjacencyMatrix.length; i++) {
      for(int j=0; j<adjacencyMatrix[i].length; j++) {
        System.out.print(adjacencyMatrix[i][j]);
      }
      System.out.println("");
    }
}

I did not take the weight in account since it does not seems to be revelant for adjacency matrix

A: public static void main(String[] args) {

    Scanner stdin = new Scanner(System.in);

    int nodeCount = 0;

    ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
    while(stdin.hasNext()) {
        String[] str = stdin.nextLine().split("[\\s,]+");
        ArrayList<Integer> inner = new ArrayList<Integer>();
        for(int i = 0; i < str.length; i++) {

            int value = Integer.parseInt(str[i]);
            inner.add(value);

            if(value > nodeCount && i != str.length - 1){
                nodeCount = value;
            }
        }
        list.add(inner);
    }

    int adjMatrix[][] = new int[nodeCount + 1][nodeCount + 1];

    for(ArrayList<Integer> inner : list){
        adjMatrix[inner.get(0)][inner.get(1)] += 1;
    }

    for(int i = 0; i < nodeCount; i++){
        for(int j = 0; j < nodeCount; j++){
            System.out.print(adjMatrix[i][j] + " ");
        }
        System.out.println();
    }
}

A: Maybe you should use something like this as a starting point.
public class AdjacencyMatrix {

    public static void main(String... args) {
        List<Edge> edges = readFromStdIn();
        Graph graph = new Graph(edges);
        int[][] adjacencyMatrix = graph.getAdjacencyMatrix();
        printMatrix(adjacencyMatrix);
    }

    private static List<Edge> readFromStdIn() {
        List<Edge> edges = new ArrayList<Edge>();
        try (Scanner scanner = new Scanner(System.in)) {
            boolean readOn = true;
            while (scanner.hasNext() && readOn) {
                String[] strings = scanner.nextLine().split("[\\s,]+");
                if (strings.length == 3) {
                    edges.add(new Edge(Integer.parseInt(strings[0]), Integer.parseInt(strings[1]),
                            Integer.parseInt(strings[2])));
                } else {
                    readOn = false;
                }
            }
        }
        return edges;
    }

    private static void printMatrix(int[][] matrix) {
        for (int i = 0; i < matrix.length; i++) {
            for (int j = 0; j < matrix[i].length; j++) {
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println();
        }
    }
}

class Edge {
    final int source;
    final int destination;
    final int weight;

    Edge(int source, int destination, int weight) {
        this.source = source;
        this.destination = destination;
        this.weight = weight;
    }
}

class Graph {
    final List<Edge> edges;

    Graph(List<Edge> edges) {
        this.edges = edges;
    }

    public int[][] getAdjacencyMatrix() {
        int n = getNodeCount();
        int[][] matrix = new int[n][n];
        for (Edge e : edges) {
            matrix[e.source][e.destination] = 1;
            // directed graph?
            matrix[e.destination][e.source] = 1;
        }
        return matrix;
    }

    int getNodeCount() {
        int maxNodeNumber = 0;
        for (Edge edge : edges) {
            if (edge.source > maxNodeNumber) {
                maxNodeNumber = edge.source;
            }
            if (edge.destination > maxNodeNumber) {
                maxNodeNumber = edge.destination;
            }
        }
        return maxNodeNumber + 1;
    }
}

It introduces some classes to add some structure to the code, avoids lists when the array length is known.
Besides: it will not create entries with values greater than 1, if edges are contained multiple times.


text:
Q: JAVA + Postgres Limit connections , how to close it ! FATAL: sorry, too many clients already I need to release connection to postgres
My java application interact with postgres and my problem is when i need to call this function more than 200 time postgres crashes , normal thing ... because postgres have limited connections and this script leave a connection opened everytime it execute.
@Override
    public Object[] getExtrasInfosSource(int idSource) {
    StringBuffer sql = new StringBuffer();
        final SessionFactoryImplementor sfi = (SessionFactoryImplementor) getSessionFactory();
        final Settings settings = sfi.getSettings();
        // Appel du procedure stocké "getExtrasInfosForSource(idSource integer)" au niveau de bd
        sql.append("SELECT * from "+settings.getDefaultSchemaName()+".getExtras_Infos_For_Source(:idSource)");
        SQLQuery query = this.getSession().createSQLQuery(sql.toString());
        query.setInteger("idSource", idSource);
        return (Object[]) query.setMaxResults(1).uniqueResult();...

Can you please tell me how to close the connection opened in postgres from this script to avoid the app crash everytime postgres connections is over loaded.

A: According to Hibernate's javadocs you can call .close() on a session.

close()
End the session by releasing the JDBC connection and cleaning up.

Before returning your query results: this.getSession().close();

A: I have solved this issue by adding those variables to my server config , it refresh the IDLE connections (or so) opened left in postgresql
<?xml version="1.0" encoding="utf-8"?>
<Context>
    <Resource name="jdbc/database"
              auth="Container"
              type="javax.sql.DataSource"
              driverClassName="org.postgresql.Driver"
              url="jdbc:postgresql://localhost:5432/DBA"
              username="DBA"
              password="DBA"
              initialSize="34"
              maxActive="80"
              maxIdle="5"

              timeBetweenEvictionRunsMillis="1000"
              minEvictableIdleTimeMillis="2000"
              validationQuery="SELECT 1"
              validationInterval="3000"
              testOnBorrow="true"
              removeAbandoned="true"
              removeAbandonedTimeout="3"/>

</Context>


text:
Q: Does every Young diagram have a unique minimal major index? Given a Young diagram, $Y_\rho$, corresponding to an irreducible complex representation $\rho$ of the symmetric group $S_n$, we can associate a set of major indices $\{ d^\rho_1,\ldots,d^\rho_{k_\rho}\}$, each of which is defined by choosing a standard tableaux on $Y_\rho$ and summing the descents. The $d_i^\rho$ are sometimes referred to as the degrees of $\rho$ and $k_\rho$ is the hook length of $Y_\rho$ (or the dimension of $\rho$).
The question is in two parts. First, for a fixed $\rho$ is the minimal degree unique? Perhaps there is some algorithm that produces a tableaux with minimal major index?
Secondly, can two non-isomorphic irreducibles, $\rho$ and $\mu$ say, have the same minimal degrees?
Thank you in advance for any help.


text:
Q: Selecting random scores from a .txt file and finding their average (Python) I've been trying to select scores at random from a .txt file and then finding the average of these randomly selected scores. Below is an example:
James, 0.974
Harry, 0.971
Ben, 0.968
Tom, 0.965
George, 0.964

For the sake of simplicity, I'd just like to select 2 scores at random to start with. See below:
James, 0.974
Harry, 0.971 <---
Ben, 0.968
Tom, 0.965 <---
George, 0.964

The end result would then be (Harry and Tom):
Average = 0.968
Can anyone help? I've been using 'split', 'import random' etc. But I'm not great at putting these all together. This is embarrassing, but here's what I've got so far...
import random

stroke = random.choice(open('stroke.txt').readlines())
for x in stroke:
    name, score = stroke.split(',')
    score = int(score)
    stroke.append((name, score))
print(stroke)

A: Try with this (explanation on the code):
import random

# read the file in lines
with open('file.txt','r') as f:
    lines = f.read().splitlines()

# split in ',' and get the scores as float numbers
scores = [ float(i.split(',')[1]) for i in lines]

# get two random numbers
rs = random.sample(scores, 2)

# compute the average
avg = sum(rs)/len(rs)
print avg

Now if you wanted to modify your code you could do it like this:
import random

# pick two instead of one
stroke = random.sample(open('file.txt').readlines(),2)

scores = []
for x in stroke:
    # split item of list not the list itself
    name, score = x.split(',')
    # store the two scores on the scores list
    scores.append(float(score))

print (scores[0]+scores[1])/2

As @MadPhysicist proposed in the comments, instead of doing (scores[0]+scores[1])/2 a more general way would be sum(scores)/len(scores) since this would work even for more than just two scores.

A: Assuming that the scores.txt file is formatted like so:
James, 0.974
Harry, 0.971
Ben, 0.968
Tom, 0.965
George, 0.964

Then this should do the trick:
import random

scores = open('scores.txt','r').read()
scores = scores.split('\n')

for i in range(len(scores)):
    scores[i] = scores[i].split(', ')
    scores[i][1] = float(scores[i][1]) * 1000

def rand_avg_scores(scorelist):
    score1 = scorelist.pop(random.randint(0,len(scorelist)-1))
    score2 = scorelist.pop(random.randint(0,len(scorelist)-1))

    finalscore = (score1[1] + score2[1])/2000

    return score1[0], score2[0], finalscore

print(rand_avg_scores(scores))

I added the * 1000 and /2000 bit to account for floating point errors. If the scores have more significant digits, add more zeroes accordingly.

A: Passing as string, but you can change it from file
import random

scoresString = '''
James, 0.974

Harry, 0.971

Ben, 0.968

Tom, 0.965

George, 0.964
'''

# How much randoms
randomCount = 2

# Get lines of the pure string
linesPure = scoresString.split("\n")

# Get lines that have content
rowsContent = [line for line in linesPure if(line.strip())]

# Get random lines
chosenRows = random.sample(rowsContent, randomCount)

# Sum of chosen
sum = 0

for crow in chosenRows:
    sum += float(crow.split(",")[1].strip())

# Calculate average
average = sum / len(chosenRows)

print("Average: %0.3f" % average)


text:
Q: Replacing Div using jQuery .load causes new div links not to work I'm replacing a div using jQuery ajax load to load in a new div:
    $("td.prod2").click(function(){
     $("#products-details").load("/products/Test.aspx");
    });

The new div features an unordered list which replaces the previous unordered list:

Link 1

Link 2

Link 3

When I click on the links in the new div, the content from the original div is reloaded onto the page?
Any ideas?

A: Try binding the event using live instead. This will make sure that when the DOM changes your new content will have the events...
$('td.prod2').live('click', function() {
    $("#products-details").load('/products/Test.aspx');
});

This should definitely resolve the problem you're having.
For more details about live see: http://api.jquery.com/live/
UPDATED: The code you included above looks to be incomplete...What is the content you are loading from '/products/Test.aspx'? I am assuming that it includes a few  that should have this event binded.

A: When you replace elements that have event listeners, those listeners are then disconnected. You need to reinitialize them or use something like jQuery's .live() functionality.


text:
Q: AWS CloudFront adding new domain to distribution and setting new certificate So I'm trying to automate the adding of a new domain to an existing CF distribution and I am getting a Rate exceeded error message.
I am using aws/aws-sdk-php, but I get the same error when I try the same command using aws-cli.
This is the code I have so far:
private function addDistributionAliasAndSetNewCertificate(string $distributionId, string $domainName, string $certificateARN): void
{
    $result = $this->cloudFront->getDistributionConfig(['Id' => $distributionId]);

    $eTag = $result['ETag'];
    $distributionConfig = $result['DistributionConfig'];

    // if the domain is already in the distribution return early.
    if (in_array($domainName, $distributionConfig['Aliases']['Items'], true)) {
        StdOut::writeLine("Domain `{$domainName}` already found in distribution `{$distributionId}` config.");
        return;
    }

    $distributionConfig['Aliases']['Items'][] = $domainName;
    $distributionConfig['Aliases']['Quantity'] = count($distributionConfig['Aliases']['Items']);

    $distributionConfig['ViewerCertificate'] = [
        'ACMCertificateArn' => $certificateARN,
        'MinimumProtocolVersion' => 'TLSv1.1_2016',
    ];
    $distributionConfig['Comment'] = 'Updated by `' . getenv('HOST') . '` on `' . date(DATE_ATOM) . '`';

    try {
        $this->cloudFront->updateDistribution([
            'Id' => $distributionId,
            'DistributionConfig' => $distributionConfig,
            'IfMatch' => $eTag,
        ]);
    } catch (CloudFrontException $e) {
        StdOut::writeLine($e->getAwsErrorMessage());
    }
}

This goes into the catch block with the error message Rate exceeded
When I do the same using the cli tools I get this output:
An error occurred (Throttling) when calling the UpdateDistribution operation (reached max retries: 4): Rate exceeded
I've waited days between calls and it make 0 difference.
Am I doing something wrong?

A: I figured it out.
The problem was that I was overriding/removing the ViewerCertificate.SSLSupportMethod key.


text:
Q: Capitalizing processes in a law suit When writing about a trial, should four-year Statute of Limitations have the four-year spelled out or as 4 year Statute of Limitations?
Also, should Preliminary Hearing, Mediation, Discovery, Pre-Trial Conference, Civil Trial, and Statute of Limitations be in title case or lower case?

A: I did a search on Google Scholar for several of your terms in opinions issued by U.S. federal courts. All of the terms are routinely set in lowercase except in titles. Clearly, the federal court system does not believe they should be capitalized. Leave them in lowercase.
People tend to be too eager to capitalize technical terms, for little reason other than "it seems like the thing to do"--probably because they're so used to reading such things from other writers who used the same line of reasoning. If you come across a term you're unsure about, try asking yourself "Why should this be capitalized?" (or even better, "Why should this not remain lowercase?"). If you can't come up with a good answer, leave it lowercase.

A: As a Canadian court reporter, I have no clue about your first question. However, I capitalize all of your suggested queries.


text:
Q: Nginx error: client intended to send too large body Periodically I get an error:
This site can't be reached.
The webpage at https://example.com/document might be temporarily down or it my have moved permanently to are new web address.

My site is stored on AWS.
I use rails + nginx + passenger.
Nginx error log:
client intended to send too large body: 3729822 bytes,
client: 172.42.35.54, server: example.com,
request: "POST /document HTTP/1.1", host: "test.example.com",
referrer: "https://test.example.com/document/new"

app log:
ActionController::RoutingError (No route matches [GET] "/document")
After a while, the error disappears. I have doubts that this is due to deployment, but I'm not sure. Could you please tell me, with what it can be related and how to fix such a problem?

A: For me path of nginx.conf was /etc/nginx/nginx.conf.
In my case I just added client_max_body_size in http block and it worked for me
http {
    ...
    client_max_body_size 20M;
}

Make sure to restart nginx after changing this config

A: Default Nginx config limits client request body with 1Mb.
You have to increase client_max_body_size to allow users to post large documents.
Don't miss with the context (http, server, location) of this derictive and don't forget to reload configuration or restart Nginx after that.

A: I have updated /etc/nginx/nginx.conf
in my case, I have added client_max_body_size in http block after sendfile on; as below
http {
    ...
    sendfile on;
    client_max_body_size 20M;
}

it is very important to put client_max_body_size after sendfile on;
Don't forget to restart nginx as below after updating the nginx.conf
For ubuntu
sudo service nginx restart

For Centos
sudo systemctl restart nginx


text:
Q: Как найти в двумерном массиве размера N×N минимальный элемент главной диагонали квадратного массива? #include <iostream>

using namespace std;

int main() {
  int n, m;
  int a[500][500], min = a[0][0];
  cin >> n;

  //Ввод массива
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
      cin >> a[i][j];
    }
  }
  min = a[0][0];
  //Поиск минимума
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
        if (a[j][j] > min) {
             min = a[j][j];
        }
    }
  }

  cout << min;
  return 0;
}

A: Вы собираетесь ввести четверть миллиона чисел с клавиатуры? Или генерируйте эти числа, или берите поскромнее размер массива. Не нужно использовать лишние объекты и не нужен никакой вложенный цикл для проверки элементов только главной диагонали. Все очень просто:
const int n = 5;
int a[n][n];
//Ввод массива
for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
        cin >> a[i][j];
    }
}
//Поиск минимума
int min = a[0][0];

for (int j = 1; j < n; j++)
    if (a[j][j] < min)
            min = a[j][j];

cout << min;

A: Добавьте условие проверки на нахождение на главной диагонали и объявляйте минимальный элемент после ввода массива
#include <iostream>

using namespace std;

int main() {
  int n, m;
  int a[500][500], min = a[0][0];
  cin >> n;

  //Ввод массива
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
      cin >> a[i][j];
    }
  }
  min = a[0][0];
  //Поиск минимума
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
        if (a[j][j] < min && i == j) {
             min = a[j][j];
        }
    }
  }

  cout << min;
  return 0;
}

A: #include <numeric>
#include <iostream>
using namespace std;

int main()
{
    constexpr size_t size = 4; // этапа компиляции
    int arr[size][size];

    for (size_t i = 0; i < size; i++)
    {
        for (size_t j = 0; j < size; j++)
        {
            cin >> arr[i][j];
        }
    }

    int min = numeric_limits<int>::max(); // макс. значение int'а
    size_t j = 0;
    for (size_t i = 0; i < size; i++)
    {
        if (arr[i][j] <= min)
            min = arr[i][j];
        j++; // сдвиг по row
    }

    cout << min << endl;
}


text:
Q: javax.xml.ws.soap.SOAPFaultException: Error reading XMLStreamReader: Unexpected EOF in prolog at [row,col {unknown-source}]: [1,0] I am trying to invoke soap webservice over https protocal.
I have wsdl and generated classes by using Apache CXF, version : 3.0.5
when i post the request in soapui, i am getting successfull response from server
but when the same is invoked from Java client getting error : javax.xml.ws.soap.SOAPFaultException: Error reading XMLStreamReader: Unexpected EOF in prolog
Below is java code
package com.cts.pepsi.util;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.xml.ws.BindingProvider;

import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.oracle.xmlns.apps.financials.commonmodules.shared.model.erpintegrationservice.DocumentDetails;
import com.oracle.xmlns.apps.financials.commonmodules.shared.model.erpintegrationservice.ErpIntegrationService;
import com.oracle.xmlns.apps.financials.commonmodules.shared.model.erpintegrationservice.ErpIntegrationService_Service;
import com.oracle.xmlns.apps.financials.commonmodules.shared.model.erpintegrationservice.EssJob;
import com.oracle.xmlns.apps.financials.commonmodules.shared.model.erpintegrationservice.ObjectFactory;

public class SoapClient {
    private static final Logger           log      = LoggerFactory.getLogger(SoapClient.class);

    private String username = "username";
    private String password = "password";

    static ErpIntegrationService erpIntegrationService;
    static long value = 0;
    public static void main(String[] args) {
        log.info("START : Invoking  service");
        System.out.println("done");

        try {

            String documentAccount = null;
            String documentTitle = null;
            String fileName = null;
            String interfaceDetails = null;
            String jobName = null;
            String jobParams = null;
            EssJob essJob = new EssJob();
            List<EssJob> jobList = new ArrayList<EssJob>();
            ObjectFactory erpobjfac = new ObjectFactory();

                documentAccount = "abc$/xyz$/take$";
                documentTitle = "ekat throw bill";
                fileName = "abcd.zip";

                interfaceDetails = "2";

                jobName = "/pqr/stu/ddd/fdg/qwe/tyu/poi,lkj";
                jobParams = "090900909090909090909,andis,2016/05/17,,,,,,,,,,,,,,,,,,,,Y,null";

                essJob.setJobName(erpobjfac.createEssJobJobName(jobName));
                essJob.setParameterList(erpobjfac.createEssJobParameterList(jobParams));
                jobList.add(essJob);

            System.out.println("iiiii  ");
            StringBuffer encodedContent = new StringBuffer();
            encodedContent.append("encoded content");//here Base64 encoded data is appended

            //DocumentDetails
            DocumentDetails docDtls = new DocumentDetails();
            docDtls.setDocumentAccount(erpobjfac.createDocumentDetailsDocumentAccount(documentAccount));
            docDtls.setContentType(erpobjfac.createDocumentDetailsContentType("zip"));
            docDtls.setDocumentTitle(erpobjfac.createDocumentDetailsDocumentTitle(documentTitle));
            docDtls.setFileName(fileName);
            docDtls.setDocumentSecurityGroup(erpobjfac.createDocumentDetailsDocumentSecurityGroup("FAFtakeExcellent"));
            docDtls.setContent(encodedContent.toString().getBytes());

            //NotificationCode
            String notificationCode = "50";

            //CallBackURL
            String callbackURL = "http://somecallbackserver.domain.com/mycallback";

            new SoapClient().authenticate();
            JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
            factory.setServiceClass(ErpIntegrationService.class);
            //factory.setAddress("https://eeln-test.fin.us2.oraclecloud.com:443/publicFinancialCommonErpIntegration/ErpIntegrationService");
            factory.setAddress("http://xmlns.oracle.com/apps/financials/commonModules/shared/model/erpIntegrationService/loadAndImportData");
            factory.getInInterceptors().add(new org.apache.cxf.interceptor.LoggingInInterceptor());
            factory.getOutInterceptors().add(new org.apache.cxf.interceptor.LoggingOutInterceptor());
            //ErpIntegrationService erpIntServiceSoap = (ErpIntegrationService) factory.create();
            erpIntegrationService = (ErpIntegrationService) factory.create();

            value = erpIntegrationService.loadAndImportData(docDtls, jobList, interfaceDetails, notificationCode, callbackURL);
            System.out.println("value is not :- "+value);
        }
        catch (Exception e) {
            log.error("An exception occurred, exiting", e);
        }
    }

    public <K> void authenticate() {
          log.info("Entering authenticate ");
          try {
           ErpIntegrationService_Service erpIntgService_Service = new ErpIntegrationService_Service();

           this.erpIntegrationService = erpIntgService_Service.getErpIntegrationServiceSoapHttpPort();
           Map requestCredentails = ((BindingProvider) this.erpIntegrationService).getRequestContext();
           requestCredentails.put("javax.xml.ws.security.auth.username", this.username);
           requestCredentails.put("javax.xml.ws.security.auth.password", this.password);
           log.info("Exiting authenticate ");
          } catch (Exception exception) {
           log.info("Error in authenticate " + exception.getMessage());
          }
         }

}

below is the log
javax.xml.ws.soap.SOAPFaultException: Error reading XMLStreamReader: Unexpected EOF in prolog
 at [row,col {unknown-source}]: [1,0]
    at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:160)
    at com.sun.proxy.$Proxy52.loadAndImportData(Unknown Source)
    at com.cts.pepsi.util.SoapClient.main(SoapClient.java:109)
Caused by: com.ctc.wstx.exc.WstxEOFException: Unexpected EOF in prolog
 at [row,col {unknown-source}]: [1,0]
    at com.ctc.wstx.sr.StreamScanner.throwUnexpectedEOF(StreamScanner.java:685)
    at com.ctc.wstx.sr.BasicStreamReader.handleEOF(BasicStreamReader.java:2141)
    at com.ctc.wstx.sr.BasicStreamReader.nextFromProlog(BasicStreamReader.java:2047)
    at com.ctc.wstx.sr.BasicStreamReader.next(BasicStreamReader.java:1131)
    at com.ctc.wstx.sr.BasicStreamReader.nextTag(BasicStreamReader.java:1154)
    at org.apache.cxf.binding.soap.interceptor.ReadHeadersInterceptor.handleMessage(ReadHeadersInterceptor.java:165)
    at org.apache.cxf.binding.soap.interceptor.ReadHeadersInterceptor.handleMessage(ReadHeadersInterceptor.java:66)
    at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:307)
    at org.apache.cxf.endpoint.ClientImpl.onMessage(ClientImpl.java:802)
    at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleResponseInternal(HTTPConduit.java:1645)
    at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.handleResponse(HTTPConduit.java:1533)
    at org.apache.cxf.transport.http.HTTPConduit$WrappedOutputStream.close(HTTPConduit.java:1336)
    at org.apache.cxf.io.CacheAndWriteOutputStream.postClose(CacheAndWriteOutputStream.java:56)
    at org.apache.cxf.io.CachedOutputStream.close(CachedOutputStream.java:215)
    at org.apache.cxf.transport.AbstractConduit.close(AbstractConduit.java:56)
    at org.apache.cxf.transport.http.HTTPConduit.close(HTTPConduit.java:652)
    at org.apache.cxf.interceptor.MessageSenderInterceptor$MessageSenderEndingInterceptor.handleMessage(MessageSenderInterceptor.java:62)
    at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:307)
    at org.apache.cxf.endpoint.ClientImpl.doInvoke(ClientImpl.java:516)
    at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:425)
    at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:326)
    at org.apache.cxf.endpoint.ClientImpl.invoke(ClientImpl.java:279)
    at org.apache.cxf.frontend.ClientProxy.invokeSync(ClientProxy.java:96)
    at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:138)
    ... 2 more

i have taken the soap request from the logs and posted from SOAP ui, it worked fine.
i have tried to invoke all operations which exists in wsdl from Java client and the same error is repeated
below is wsdl policy
<wsp:Policy xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="ErpIntegrationServiceSoapHttpPort_Input_Policy" xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy">
   <wsp:ExactlyOne>
      <wsp:All>
         <sp:SignedParts xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
            <sp:Body/>
            <sp:Header Namespace="http://www.w3.org/2005/08/addressing"/>
            <sp:Header Namespace="http://schemas.xmlsoap.org/ws/2004/08/addressing"/>
            <sp:Header Name="fmw-context" Namespace="http://xmlns.oracle.com/fmw/context/1.0"/>
         </sp:SignedParts>
         <sp:EncryptedParts xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
            <sp:Body/>
            <sp:Header Name="fmw-context" Namespace="http://xmlns.oracle.com/fmw/context/1.0"/>
         </sp:EncryptedParts>
      </wsp:All>
      <wsp:All>
         <sp:SignedParts xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
            <sp:Body/>
            <sp:Header Namespace="http://www.w3.org/2005/08/addressing"/>
            <sp:Header Namespace="http://schemas.xmlsoap.org/ws/2004/08/addressing"/>
            <sp:Header Name="fmw-context" Namespace="http://xmlns.oracle.com/fmw/context/1.0"/>
         </sp:SignedParts>
         <sp:EncryptedParts xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
            <sp:Body/>
            <sp:Header Name="fmw-context" Namespace="http://xmlns.oracle.com/fmw/context/1.0"/>
         </sp:EncryptedParts>
      </wsp:All>
      <wsp:All>
         <sp:SignedParts xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
            <sp:Body/>
            <sp:Header Namespace="http://www.w3.org/2005/08/addressing"/>
            <sp:Header Namespace="http://schemas.xmlsoap.org/ws/2004/08/addressing"/>
            <sp:Header Name="fmw-context" Namespace="http://xmlns.oracle.com/fmw/context/1.0"/>
         </sp:SignedParts>
         <sp:EncryptedParts xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
            <sp:Body/>
            <sp:Header Name="fmw-context" Namespace="http://xmlns.oracle.com/fmw/context/1.0"/>
         </sp:EncryptedParts>
      </wsp:All>
      <wsp:All>
         <sp:SignedParts xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
            <sp:Body/>
            <sp:Header Namespace="http://www.w3.org/2005/08/addressing"/>
            <sp:Header Namespace="http://schemas.xmlsoap.org/ws/2004/08/addressing"/>
            <sp:Header Name="fmw-context" Namespace="http://xmlns.oracle.com/fmw/context/1.0"/>
         </sp:SignedParts>
         <sp:EncryptedParts xmlns:sp="http://schemas.xmlsoap.org/ws/2005/07/securitypolicy">
            <sp:Body/>
            <sp:Header Name="fmw-context" Namespace="http://xmlns.oracle.com/fmw/context/1.0"/>
         </sp:EncryptedParts>
      </wsp:All>
   </wsp:ExactlyOne>
</wsp:Policy>

requesting you to please help where i have committed the mistake in java code, thanks


text:
Q: Microsoft MIP JAVA SDK sampe error: "Unrecognized exception: profile_add_engine_async" I am using MIP sdk for JAVA from Microsoft (https://learn.microsoft.com/en-us/information-protection/develop/setup-configure-mip) and trying to execute its sample to read and write MIP labels.
But when I run MIPSample for JAVA I am getting following error message in MIP log.
"2021-02-16 12:23:38.609  common/api_utils.h:232  java (14700)    "Unrecognized exception: profile_add_engine_async"  mipns::TryExecuteFailureCallback"
And my call to
Future<IFileEngine> fileEngineFuture = fileProfile.addEngineAsync(engineSettings);

IFileEngine fileEngine = fileEngineFuture.get();

is not completing successfully.
In API AuthDelegateUserCredentials::acquireToken(), I am successfully able to get 'accessToken' but when I return that same access token, somewhere it crashes, before it could return and attach fileEngine instance.
I windows event viewer I m getting following error
Faulting application name: java.exe, version: 8.0.2420.8, time stamp: 0x5e246f62
Faulting module name: ntdll.dll, version: 10.0.17763.475, time stamp: 0x3230aa04
Exception code: 0xc0000374
Fault offset: 0x00000000000fb049
Faulting process id: 0x1dc0
Faulting application start time: 0x01d7043c7ac79efc
Faulting application path: C:\code\depot\tools\windows\OpenJDK\1.8.0_242\x64\bin\java.exe
Faulting module path: C:\Windows\SYSTEM32\ntdll.dll
Report Id: ddfa73cc-d1e2-48ef-a76e-866bf67aaaa6
Faulting package full name:
Faulting package-relative application ID:

Please let me know what I might be doing wrong here.

A: Can you share the version of the SDK you're using? I haven't been able to reproduce this in 1.7. I'm working on a sample for 1.8 and will see if I can repro there.


text:
Q: Automatically zip a project after it is saved or the editor is closed? My company enforces the use of OneDrive for sync and backup.  I'm currently working on a project that has a lot of static data in JSON files.  OneDrive blocks JSON files.
Is there any way built into webstorm that I could automatically zip the project folder when I save it or close the IDE?  This way I could store that zip in the sync folder and have access to it on my desktop and laptop and have a backup.  Not ideal, but better than nothing I suppose.


text:
Q: Wordpress Redirection Plugin conflicts with Google Ads I have a wordpress website in which I am using the Redirection plugin to handle all the redirects.
I am also running a paid Google Ads Campaign which will land on one of my website pages with the google parameters like gclid and campaign type. But due to some reason these redirects are dropping the gclid.
Can anyone help me with how I can resolve this issue.
Additionally, when I disable the redirect links from the Plugin, it works in certain browsers while many browsers are still showing the old redirects. Does google take sometime to refresh this links? Where does browser store all the redirect links set through redirect plugin.
Has anyone ever faced this type of issue?
I tried disabling the links set in the Redirect Plugin but it was not consistent in all the browsers.
In some browsers, it worked fine while in others it was not working at all.
I am checking the gclid parameter in the network tab, which comes as a query-string attached to my landing page.


text:
Q: Oracle SQL Produce Multi-Columns From the Same Column With Mutual Rows Values I have table element_types with column element_type containing amount types Basic Salary and Housing Allowance, i want to produce 2 column, one for Basic Salary and another for Housing Allowance, these types are linked to another table like employees and the values for those types ..etc, so I want to make 2 separate columns and not displaying types and amounts in rows.
SELECT .....,
       (SELECT element_name
          FROM pay_element_types_tl
         WHERE element_name IN ('Basic Salary')) Salary,
       (SELECT element_name
          FROM pay_element_types_tl
         WHERE element_name IN ('Housing Allowance')) Housing

this gives error

single-row subquery returns multiple rows

how can I achieve what I want?
i've tried to use multi-rows subquery using where but i want more than a column with different names derived from the same column

A: That's a CASE WHEN use case:
SELECT
CASE WHEN element_name = 'Basic Salary'
  THEN element_name END AS Salary,
CASE WHEN element_name = 'Housing Allowance'
  THEN element_name END AS Housing
FROM PAY_ELEMENT_TYPES_TL;

Try out: db<>fiddle
Use aggregation around if required (MAX, MIN etc., depending on what you need)

A: You might use a conditional aggregation to pivot the data as desired like
SELECT MAX(CASE
           WHEN element_name = 'Basic Salary' THEN
                element_name
            END) AS Salary,
       MAX(CASE
           WHEN element_name = 'Housing Allowance' THEN
                element_name
            END) AS Housing
  FROM pay_element_types_tl

eg. move conditions from the WHERE clause to CASE..WHEN expressions while aggregating the values to prevent generating multiple rows


text:
Q: Fittings of three equations Can you help me to do the fit for the following equations to obtain the values of $a$ and $b$.
{20.7 == a + b/(5^4), 28.62 == a + b/(6^4), 32.04 == a + b/(7^4)}

Thanks.

A: I like the solution from @morbo but think that Subsets is better in this case than Permutations.  Permutations will give {1,3} and {3,1} (thinking of this as a set of three values and just looking at indices) and clearly, these yield identical solutions.  So something like this gives the three cases we care about:
eqns = {20.7 == a + b/(5^4), 28.62 == a + b/(6^4),
   32.04 == a + b/(7^4)};
list = Subsets[eqns, {2}];
Table[Solve[list[[i]], {a, b}], {i, 1, Length[list]}]

A: You can also use FindFit to find the best least-squares fit.
data = {{5^4, 20.7}, {6^4, 28.62}, {7^4, 32.04}};
model = a + b/x;
fitVals = FindFit[data, model, {a, b}, x]
(* {a -> 36.0214, b -> -9577.97} *)

It turns out be a rather good fit.
Plot[model /. fitVals, {x, 5^4 - 10, 7^4 + 10}, Epilog -> {PointSize[Medium], Point[data]}]

Norm[(model /. fitVals /. x -> (First /@ data)) - (Last /@ data) ]
(* 0.0138648 *)

A: You have an over defined system namely, 3 equations and 2 variables, as such, you can solve for two equations, but which values are the 'fit' you want, I don't know.
We will generate all combinations:
eqns = {20.7 == a + b/(5^4), 28.62 == a + b/(6^4), 32.04 == a + b/(7^4)};
list = Permutations[eqns, {2}];

Then generate the solutions for all possible combinations.
Table[Solve[list[[i]], {a, b}], {i, 1, Length[list]}]

$ \left(
\begin{array}{c}
 \{a\to 35.997,b\to -9560.66\} \\
 \{a\to 36.0307,b\to -9581.69\} \\
 \{a\to 35.997,b\to -9560.66\} \\
 \{a\to 36.0511,b\to -9630.77\} \\
 \{a\to 36.0307,b\to -9581.69\} \\
 \{a\to 36.0511,b\to -9630.77\} \\
\end{array}
\right) $
Though your question isn't quite clear what you're looking for, hope this is it.


text:
Q: Iphone tab bar icon I should probably be asking this on some art website, but in my iPhone app I am trying to make a center button on my tab like the one Daily booth has, but mine is coming out fuzzy.  Does anyone know how to make then clean and crisp? I used illustrator to create and save the icon as a png.

A: Try setting the image size to 30x30 and remember to only use black and transparency. You can make this bigger for the retina display.
Also, are you saving the image as grayscale?
If you're struggling to make them yourself, why not try glyphish.com?

A: I really like Paint.NET on Windows for image editing, mostly because it is free.
I noticed somebody had created an Effect for Paint.NET to create tab bar icons.  I haven't tried it myself, so can't vouch for it in any way:
http://www.softpedia.com/get/Multimedia/Graphic/Graphic-Plugins/iPhone-TabbarIcon-Maker-Alpha-from-RGB-Intensity.shtml