repo_name stringlengths 6 101 | path stringlengths 4 300 | text stringlengths 7 1.31M |
|---|---|---|
pyvain/WebSight | App/app/src/main/java/fr/pyvain/websight/websight/Request.java | package fr.pyvain.websight.websight;
import android.content.Context;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.net.Uri;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* <p>This class provides methods to request the server.</p>
*
* <p>
* @author <NAME>
* </p>
*/
class Request {
private final Context context;
private HttpURLConnection urlConnection;
/**
* Constuctor Request
*
* @param context
* Must be the context of the activity, used to fetch resources
*/
public Request(Context context) {
this.context = context;
this.urlConnection = null;
}
/**
* Checks if there is an internet connexion available
*
* @return true if there is a connexion
*/
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null;
}
/**
* Sets up a HttpURLConnection for a post request on server whose
* url is given
*
* @param url
* The server's url
*/
private void setPOST(String url) throws IOException, NoConnexionException {
// Opens connection and sets it for POST request
URL urlToRequest = new URL(url);
// openConnection() may throw IOException
int retries = 0;
if (isNetworkConnected()) {
Resources res = context.getResources();
while ((retries < res.getInteger(R.integer.max_connexion_retries)) && (urlConnection == null)) {
try {
urlConnection = (HttpURLConnection) urlToRequest.openConnection();
} catch (IOException e) {
++retries;
}
}
if ((urlConnection == null))
throw new IOException();
}
else
throw new NoConnexionException();
// setDoOuput() and setChunkedStreamingMode() may throw IllegalStateException
// if already connected (not possible here)
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);
}
/**
* Sets up a HttpURLConnection for a post request on server whose
* url is and add an identification token to the header
*
* @param url The server's url
* @param token token used to identify a user
*/
private void setPOST(String url, String token) throws IOException, NoConnexionException {
setPOST(url);
urlConnection.addRequestProperty("Authorization", token);
}
/**
* Sends a POST query to the server
* A HttpUrlConnection must already have been set up with
* a call to setPOST()
*
* @param query
* HTTP Query to send
* @throws IOException
*/
private void sendPOST(String query) throws IOException {
if (urlConnection != null) {
// getOutputStream() may throw IOException
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os));
// write() and close() may throw IOException
writer.write(query);
writer.close();
}
}
/**
* Returns the response code returned by the server
* Can be called only after sending a query with sendPOST
* (else the server may wait for data and
* a call to responseCode() may block)
*
* @return The response code
*
* @see Request#sendPOST
*/
private int responseCode() throws IOException {
if (urlConnection != null) {
// getResponseCode() may throw IOException
return urlConnection.getResponseCode();
} else {
return -1;
}
}
/**
* Returns the response returned by the server
* Can be called only after sending a query with sendPOST
* (else the server may wait for data and
* a call to response() may block)
*
* @return The response code
*
* @see Request#sendPOST
*/
private String response() throws IOException {
if (urlConnection != null) {
String response = "";
// getInputStream() may throw IOException
InputStream is = urlConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
// Reads whole stream
String line;
// readLine() may throw IOException
while ((line = reader.readLine()) != null) {
response += line;
}
return response;
} else {
return "";
}
}
private String errorResponse() throws IOException {
if (urlConnection != null) {
String response = "";
// getInputStream() may throw IOException
InputStream is = urlConnection.getErrorStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
// Reads whole stream
String line;
// readLine() may throw IOException
while ((line = reader.readLine()) != null) {
response += line;
}
return response;
} else {
return "";
}
}
/**
* Asks the server for an access token and returns it
*
* @param email
* Email of the user concerned
* @param password
* <PASSWORD>
* @return The response code
*
* @throws IOException
* @throws InvalidCredentialsException
* @throws ServerException
*/
public String getAccessToken(String email, String password)
throws IOException, InvalidCredentialsException, ServerException, NoConnexionException {
// Sets up connection
Resources resources = this.context.getResources();
String url = resources.getString(R.string.serverUrl);
String signInPath = resources.getString(R.string.signInPath);
// setPost() may throw a IOException
this.setPOST(url + signInPath);
// Sends request
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("email", email)
.appendQueryParameter("password", password);
this.sendPOST(builder.build().getEncodedQuery());
System.out.println("Return code : " + this.responseCode());
// Analyses response
switch (this.responseCode()) {
// Extracts token and returns it
case HttpURLConnection.HTTP_OK:
String response = this.response();
try {
// JSONObject() and getString() may throw JSONException
// if the response is ill-formed
JSONObject json = new JSONObject(response);
return json.getString("jwt");
} catch (JSONException e) {
System.out.println("Received : " + response);
throw new ServerException();
}
// Handles error responses
case HttpURLConnection.HTTP_BAD_REQUEST:
System.out.println(this.errorResponse());
throw new InvalidCredentialsException();
case HttpURLConnection.HTTP_UNAUTHORIZED:
System.out.println(this.errorResponse());
throw new InvalidCredentialsException();
default:
System.out.println(this.errorResponse());
throw new ServerException();
}
}
public void signUp(String email, String password)
throws IOException, EmailAlreadyUsedException,
InvalidCredentialsException, ServerException, NoConnexionException {
// Sets up connection
Resources resources = this.context.getResources();
String url = resources.getString(R.string.serverUrl);
String signUpPath = resources.getString(R.string.signUpPath);
// setPost() may throw a IOException
this.setPOST(url + signUpPath);
// Sends request
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("email", email)
.appendQueryParameter("password", password);
this.sendPOST(builder.build().getEncodedQuery());
System.out.println("Return code : " + this.responseCode());
// Analyses response
switch (this.responseCode()) {
// Exits method successfully
case HttpURLConnection.HTTP_OK:
break;
// Handles error responses
case HttpURLConnection.HTTP_BAD_REQUEST:
System.out.println(this.errorResponse());
String response = this.response();
try {
// JSONObject() and getString() may throw JSONException
// if the response is ill-formed
JSONObject json = new JSONObject(response);
if (json.getString("error").equals("Address is already used")) {
System.out.println(this.errorResponse());
throw new EmailAlreadyUsedException();
} else {
System.out.println(this.errorResponse());
throw new InvalidCredentialsException();
}
} catch (JSONException e) {
System.out.println(this.errorResponse());
throw new ServerException();
}
default:
System.out.println(this.errorResponse());
throw new ServerException();
}
}
/**
* Asks the server for a graph and returns it
*
* @param token
* token to identify a user
* @param keywords
* keywords used to build the graph
* @return The JSon of a graph
*
* @throws IOException
* @throws InvalidCredentialsException
* @throws ServerException
*/
public String getGraph(String token, String[] keywords)
throws IOException, InvalidCredentialsException, ServerException, ServiceUnavailableException, NoConnexionException {
// Sets up connection
Resources resources = this.context.getResources();
String url = resources.getString(R.string.serverUrl);
String getGraphPath = resources.getString(R.string.getGraphPath);
// setPost() may throw a IOException
this.setPOST(url + getGraphPath, token);
// Sends request
Uri.Builder builder = new Uri.Builder();
for (String keyword : keywords)
builder.appendQueryParameter("keywords[]", keyword);
this.sendPOST(builder.build().getEncodedQuery());
System.out.println("Token : " + token);
System.out.println("Return code : " + this.responseCode());
// Analyses response
switch (this.responseCode()) {
// Extracts token and returns it
case HttpURLConnection.HTTP_OK: {
return this.response();
}
// Handles error responses
case HttpURLConnection.HTTP_BAD_REQUEST:
System.out.println(this.errorResponse());
throw new InvalidCredentialsException();
case HttpURLConnection.HTTP_UNAUTHORIZED:
System.out.println(this.errorResponse());
throw new InvalidCredentialsException();
case HttpURLConnection.HTTP_UNAVAILABLE:
System.out.println(this.errorResponse());
throw new ServiceUnavailableException();
default:
System.out.println(this.errorResponse());
throw new ServerException();
}
}
/**
* Asks the server for a graph and returns it
*
* @param token
* token to identify a user
* @param password
* user password
*
* @throws IOException
* @throws InvalidCredentialsException
* @throws ServerException
*/
public void deleteAccount(String token, String password)
throws IOException, InvalidCredentialsException, ServerException, NoConnexionException {
// Sets up connection
Resources resources = this.context.getResources();
String url = resources.getString(R.string.serverUrl);
String deleteAccountPath = resources.getString(R.string.deleteAccuntPath);
// setPost() may throw a IOException
this.setPOST(url + deleteAccountPath, token);
// Sends request
Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("password", password);
this.sendPOST(builder.build().getEncodedQuery());
System.out.println("Return code : " + this.responseCode());
// Analyses response
switch (this.responseCode()) {
case HttpURLConnection.HTTP_OK:
break;
// Handles error responses
case HttpURLConnection.HTTP_BAD_REQUEST:
System.out.println(this.errorResponse());
throw new InvalidCredentialsException();
case HttpURLConnection.HTTP_UNAUTHORIZED:
System.out.println(this.errorResponse());
throw new InvalidCredentialsException();
default:
System.out.println(this.errorResponse());
throw new ServerException();
}
}
/**
* Asks the server for an advice concerning an URL and keywords if relevant
*
* @param token
* token to identify a user
* @param adviceUrl
* URL on which an advice is required
* @param keywords
* keywords used to build the graph
* @return The JSon of a graph
*
* @throws IOException
* @throws InvalidCredentialsException
* @throws ServerException
*/
public String getAdvice(String token, String adviceUrl, String[] keywords)
throws IOException, InvalidCredentialsException, ServerException, NoConnexionException {
// Sets up connection
Resources resources = this.context.getResources();
String url = resources.getString(R.string.serverUrl);
String getGraphPath = resources.getString(R.string.getAdvicePath);
// setPost() may throw a IOException
this.setPOST(url + getGraphPath, token);
// Sends request
Uri.Builder builder = new Uri.Builder();
builder.appendQueryParameter("url", adviceUrl);
System.out.println("url : " + adviceUrl);
if (keywords != null) {
for (String keyword : keywords) {
System.out.println("mot " + keyword);
builder.appendQueryParameter("keywords[]", keyword);
}
}
this.sendPOST(builder.build().getEncodedQuery());
System.out.println("Token : " + token);
System.out.println("Return code : " + this.responseCode());
// Analyses response
switch (this.responseCode()) {
// Extracts token and returns it
case HttpURLConnection.HTTP_OK: {
return this.response();
}
// Handles error responses
case HttpURLConnection.HTTP_BAD_REQUEST:
System.out.println(this.errorResponse());
throw new InvalidCredentialsException();
case HttpURLConnection.HTTP_UNAUTHORIZED:
System.out.println(this.errorResponse());
throw new InvalidCredentialsException();
default:
System.out.println(this.errorResponse());
throw new ServerException();
}
}
/**
* Asks the server to send an email with model letters to ask for information removal
*
* @param token
* token to identify a user
*
* @throws IOException
* @throws InvalidCredentialsException
* @throws ServerException
*/
public void sendModels(String token)
throws IOException, InvalidCredentialsException, ServerException, NoConnexionException {
// Sets up connection
Resources resources = this.context.getResources();
String url = resources.getString(R.string.serverUrl);
String getGraphPath = resources.getString(R.string.sendModelPath);
// setPost() may throw a IOException
this.setPOST(url + getGraphPath, token);
// Sends request
Uri.Builder builder = new Uri.Builder().appendQueryParameter("void", null);
this.sendPOST(builder.build().getEncodedQuery());
System.out.println("Token : " + token);
System.out.println("Return code : " + this.responseCode());
// Analyses response
switch (this.responseCode()) {
// Extracts token and returns it
case HttpURLConnection.HTTP_OK:
break;
// Handles error responses
case HttpURLConnection.HTTP_BAD_REQUEST:
System.out.println(this.errorResponse());
throw new InvalidCredentialsException();
case HttpURLConnection.HTTP_UNAUTHORIZED:
System.out.println(this.errorResponse());
throw new InvalidCredentialsException();
default:
System.out.println(this.errorResponse());
throw new ServerException();
}
}
}
|
june20516/JavaTraining | 20190328/src/Hello.java | public class Hello {
public static void main(String[] args) {
System.out.println("Hello World");
for(String a : args)
System.out.println(" + " + a);
}
} |
miguelsndc/PythonFirstLooks | primeiros-exercicios/lpc066.py | <filename>primeiros-exercicios/lpc066.py
cont = 0
soma = 0
while True:
n = int(input('Digite as notas: 0/10 '))
continuar = str(input('Quer continuar? [S/N]')).strip().upper()
if n < 0 or n > 10:
n = int(input('Nota inválida. Digite as notas: '))
cont += 1
soma += n
med = soma / cont
if continuar == 'N':
print(f'As média das {cont} notas inseridas é {med:.2f}')
break |
kkcookies99/UAST | Dataset/Leetcode/valid/136/303.js | <reponame>kkcookies99/UAST
var singleNumber = function(nums) {
var result = 0;
for(var i = 0; i < nums.length; i ++){
result ^= nums[i];
}
return result;
};
|
OpenSundsvall/api-service-disturbance | src/test/java/se/sundsvall/disturbance/service/mapper/DisturbanceMapperTest.java | <filename>src/test/java/se/sundsvall/disturbance/service/mapper/DisturbanceMapperTest.java
package se.sundsvall.disturbance.service.mapper;
import static java.time.OffsetDateTime.now;
import static java.time.temporal.ChronoUnit.SECONDS;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.within;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.RandomUtils;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import se.sundsvall.disturbance.api.model.Affected;
import se.sundsvall.disturbance.api.model.Category;
import se.sundsvall.disturbance.api.model.DisturbanceCreateRequest;
import se.sundsvall.disturbance.api.model.DisturbanceUpdateRequest;
import se.sundsvall.disturbance.integration.db.model.AffectedEntity;
import se.sundsvall.disturbance.integration.db.model.DisturbanceEntity;
@ExtendWith(MockitoExtension.class)
class DisturbanceMapperTest {
@Test
void toDisturbanceSuccess() {
final var affectedEntity1 = new AffectedEntity();
affectedEntity1.setPartyId("partyId-1");
affectedEntity1.setReference("reference-1");
final var affectedEntity2 = new AffectedEntity();
affectedEntity2.setPartyId("partyId-2");
affectedEntity2.setReference("reference-2");
final var disturbanceEntity = new DisturbanceEntity();
disturbanceEntity.setDisturbanceId("disturbanceId");
disturbanceEntity.setCategory("COMMUNICATION");
disturbanceEntity.setDescription("description");
disturbanceEntity.setTitle("title");
disturbanceEntity.setStatus("OPEN");
disturbanceEntity.setPlannedStartDate(now().plusDays(1));
disturbanceEntity.setPlannedStopDate(now().plusDays(2));
disturbanceEntity.setCreated(now());
disturbanceEntity.setAffectedEntities(List.of(affectedEntity1, affectedEntity2));
final var disturbance = DisturbanceMapper.toDisturbance(disturbanceEntity);
assertThat(disturbance.getCategory()).isEqualTo(Category.COMMUNICATION);
assertThat(disturbance.getId()).isEqualTo("disturbanceId");
assertThat(disturbance.getDescription()).isEqualTo("description");
assertThat(disturbance.getStatus()).isEqualTo(se.sundsvall.disturbance.api.model.Status.OPEN);
assertThat(disturbance.getPlannedStartDate()).isCloseTo(now().plusDays(1), within(2, SECONDS));
assertThat(disturbance.getPlannedStopDate()).isCloseTo(now().plusDays(2), within(2, SECONDS));
assertThat(disturbance.getCreated()).isCloseTo(now(), within(2, SECONDS));
assertThat(disturbance.getAffecteds().size()).isEqualTo(2);
assertThat(disturbance.getAffecteds().get(0).getPartyId()).isEqualTo("partyId-1");
assertThat(disturbance.getAffecteds().get(0).getReference()).isEqualTo("reference-1");
assertThat(disturbance.getAffecteds().get(1).getPartyId()).isEqualTo("partyId-2");
assertThat(disturbance.getAffecteds().get(1).getReference()).isEqualTo("reference-2");
}
@Test
void toDisturbanceEntityFromDisturbanceCreateRequest() {
final var disturbanceCreateRequest = DisturbanceCreateRequest.create()
.withCategory(Category.COMMUNICATION)
.withDescription("Description")
.withId("id")
.withAffecteds(List.of(
Affected.create().withPartyId("partyId-1").withReference("reference-1"),
Affected.create().withPartyId("partyId-1").withReference("reference-1"),
Affected.create().withPartyId("partyId-2").withReference("reference-2"),
Affected.create().withPartyId("partyId-2").withReference("reference-2"),
Affected.create().withPartyId("partyId-3").withReference("reference-3")))
.withPlannedStartDate(now())
.withPlannedStopDate(now().plusDays(1))
.withStatus(se.sundsvall.disturbance.api.model.Status.OPEN)
.withTitle("Title");
final var disturbanceEntity = DisturbanceMapper.toDisturbanceEntity(disturbanceCreateRequest);
assertThat(disturbanceEntity.getAffectedEntities()).hasSize(3); // Duplicates removed.
assertThat(disturbanceEntity.getAffectedEntities()).extracting(AffectedEntity::getReference).containsExactly("reference-1", "reference-2", "reference-3");
assertThat(disturbanceEntity.getAffectedEntities()).extracting(AffectedEntity::getPartyId).containsExactly("partyId-1", "partyId-2", "partyId-3");
assertThat(disturbanceEntity.getCategory()).isEqualTo(Category.COMMUNICATION.toString());
assertThat(disturbanceEntity.getDescription()).isEqualTo("Description");
assertThat(disturbanceEntity.getDisturbanceId()).isEqualTo("id");
assertThat(disturbanceEntity.getPlannedStartDate()).isCloseTo(now(), within(2, SECONDS));
assertThat(disturbanceEntity.getPlannedStopDate()).isCloseTo(now().plusDays(1), within(2, SECONDS));
assertThat(disturbanceEntity.getStatus()).isEqualTo(se.sundsvall.disturbance.api.model.Status.OPEN.toString());
assertThat(disturbanceEntity.getTitle()).isEqualTo("Title");
}
@Test
void toDisturbanceEntityFromDisturbanceUpdateRequest() {
final var category = Category.COMMUNICATION;
final var disturbanceId = "disturbanceId";
final var disturbanceUpdateRequest = DisturbanceUpdateRequest.create()
.withDescription("Description")
.withAffecteds(List.of(
Affected.create().withPartyId("partyId-1").withReference("reference-1"),
Affected.create().withPartyId("partyId-1").withReference("reference-1"),
Affected.create().withPartyId("partyId-2").withReference("reference-2"),
Affected.create().withPartyId("partyId-2").withReference("reference-2"),
Affected.create().withPartyId("partyId-3").withReference("reference-3")))
.withPlannedStartDate(now())
.withPlannedStopDate(now().plusDays(1))
.withStatus(se.sundsvall.disturbance.api.model.Status.OPEN);
final var disturbanceEntity = DisturbanceMapper.toDisturbanceEntity(category, disturbanceId, disturbanceUpdateRequest);
assertThat(disturbanceEntity.getAffectedEntities()).hasSize(3); // Duplicates removed.
assertThat(disturbanceEntity.getAffectedEntities()).extracting(AffectedEntity::getReference).containsExactly("reference-1", "reference-2", "reference-3");
assertThat(disturbanceEntity.getAffectedEntities()).extracting(AffectedEntity::getPartyId).containsExactly("partyId-1", "partyId-2", "partyId-3");
assertThat(disturbanceEntity.getCategory()).isEqualTo(category.toString());
assertThat(disturbanceEntity.getDescription()).isEqualTo("Description");
assertThat(disturbanceEntity.getDisturbanceId()).isEqualTo(disturbanceId);
assertThat(disturbanceEntity.getPlannedStartDate()).isCloseTo(now(), within(2, SECONDS));
assertThat(disturbanceEntity.getPlannedStopDate()).isCloseTo(now().plusDays(1), within(2, SECONDS));
assertThat(disturbanceEntity.getStatus()).isEqualTo(se.sundsvall.disturbance.api.model.Status.OPEN.toString());
assertThat(disturbanceEntity.getTitle()).isNull();
}
@Test
void toMergedDisturbanceEntityAllNewValuesSet() {
/**
* Set up old entity.
*/
final var oldAffected1 = new AffectedEntity();
oldAffected1.setPartyId("oldpartyId-1");
oldAffected1.setReference("oldReference-1");
final var oldAffected2 = new AffectedEntity();
oldAffected2.setPartyId("oldPartyId-2");
oldAffected2.setReference("oldReference-2");
final var oldAffected3 = new AffectedEntity();
oldAffected3.setPartyId("oldPartyId-3");
oldAffected3.setReference("oldReference-3");
final var oldEntity = new DisturbanceEntity();
oldEntity.setId(1L);
oldEntity.setDisturbanceId("oldDisturbanceId");
oldEntity.setCategory("oldStatus");
oldEntity.setDescription("oldDescription");
oldEntity.setTitle("oldTitle");
oldEntity.setStatus("oldStatus");
oldEntity.setPlannedStartDate(now().minusDays(RandomUtils.nextInt(1, 1000)));
oldEntity.setPlannedStopDate(now().plusDays(RandomUtils.nextInt(1, 1000)));
oldEntity.setCreated(now().minusDays(RandomUtils.nextInt(1, 1000)));
oldEntity.setUpdated(now().minusDays(RandomUtils.nextInt(1, 1000)));
oldEntity.setAffectedEntities(new ArrayList<>(List.of(oldAffected1, oldAffected2, oldAffected3)));
/**
* Set up new entity.
*/
final var newAffected1 = new AffectedEntity();
newAffected1.setPartyId("newPartyId-1");
newAffected1.setReference("newReference-1");
final var newAffected2 = new AffectedEntity();
newAffected2.setPartyId("newPartyId-2");
newAffected2.setReference("newReference-2");
final var newEntity = new DisturbanceEntity();
newEntity.setId(0L);
newEntity.setDisturbanceId("newDisturbanceId");
newEntity.setCategory("newStatus");
newEntity.setDescription("newDescription");
newEntity.setTitle("newTitle");
newEntity.setStatus("newStatus");
newEntity.setPlannedStartDate(now().minusDays(RandomUtils.nextInt(1, 1000)));
newEntity.setPlannedStopDate(now().plusDays(RandomUtils.nextInt(1, 1000)));
newEntity.setCreated(now().minusDays(RandomUtils.nextInt(1, 1000)));
newEntity.setUpdated(now().minusDays(RandomUtils.nextInt(1, 1000)));
newEntity.setAffectedEntities(new ArrayList<>(List.of(newAffected1, newAffected2)));
final var mergedDisturbanceEntity = DisturbanceMapper.toMergedDisturbanceEntity(oldEntity, newEntity);
assertThat(mergedDisturbanceEntity).isNotNull();
assertThat(mergedDisturbanceEntity.getAffectedEntities()).isEqualTo(List.of(newAffected1, newAffected2));
assertThat(mergedDisturbanceEntity.getCategory()).isEqualTo(oldEntity.getCategory());
assertThat(mergedDisturbanceEntity.getCreated()).isEqualTo(oldEntity.getCreated());
assertThat(mergedDisturbanceEntity.getDescription()).isEqualTo(newEntity.getDescription());
assertThat(mergedDisturbanceEntity.getDisturbanceId()).isEqualTo(oldEntity.getDisturbanceId());
assertThat(mergedDisturbanceEntity.getId()).isEqualTo(oldEntity.getId());
assertThat(mergedDisturbanceEntity.getPlannedStartDate()).isEqualTo(newEntity.getPlannedStartDate());
assertThat(mergedDisturbanceEntity.getPlannedStopDate()).isEqualTo(newEntity.getPlannedStopDate());
assertThat(mergedDisturbanceEntity.getStatus()).isEqualTo(newEntity.getStatus());
assertThat(mergedDisturbanceEntity.getTitle()).isEqualTo(newEntity.getTitle());
assertThat(mergedDisturbanceEntity.getUpdated()).isEqualTo(oldEntity.getUpdated());
}
@Test
void toMergedDisturbanceEntityNoNewValuesSet() {
/**
* Set up old entity.
*/
final var oldAffected1 = new AffectedEntity();
oldAffected1.setPartyId("oldPartyId-1");
oldAffected1.setReference("oldReference-1");
final var oldAffected2 = new AffectedEntity();
oldAffected2.setPartyId("oldPartyId-2");
oldAffected2.setReference("oldReference-2");
final var oldAffected3 = new AffectedEntity();
oldAffected3.setPartyId("oldPartyId-3");
oldAffected3.setReference("oldReference-3");
final var oldEntity = new DisturbanceEntity();
oldEntity.setId(1L);
oldEntity.setDisturbanceId("oldDisturbanceId");
oldEntity.setCategory("oldStatus");
oldEntity.setDescription("oldDescription");
oldEntity.setTitle("oldTitle");
oldEntity.setStatus("oldStatus");
oldEntity.setPlannedStartDate(now().minusDays(RandomUtils.nextInt(1, 1000)));
oldEntity.setPlannedStopDate(now().plusDays(RandomUtils.nextInt(1, 1000)));
oldEntity.setCreated(now().minusDays(RandomUtils.nextInt(1, 1000)));
oldEntity.setUpdated(now().minusDays(RandomUtils.nextInt(1, 1000)));
oldEntity.setAffectedEntities(new ArrayList<>(List.of(oldAffected1, oldAffected2, oldAffected3)));
final var mergedDisturbanceEntity = DisturbanceMapper.toMergedDisturbanceEntity(oldEntity, new DisturbanceEntity());
assertThat(mergedDisturbanceEntity)
.isNotNull()
.isEqualTo(oldEntity);
}
}
|
fenghan34/LeetCode | code/linked-list/rotate-list.js | <reponame>fenghan34/LeetCode<filename>code/linked-list/rotate-list.js
import { ListNode } from '../../utils'
/**
* @param {ListNode} head
* @param {number} k
* @return {ListNode}
*/
export function rotateRight(head, k) {
if (!head || !head.next || k === 0) return head
const dummy = new ListNode(0, head)
let prev = dummy
let cur = dummy.next
let length = 1
while (cur.next) {
prev = cur
cur = cur.next
length++
}
let count = k % length
if (count === 0) return dummy.next
do {
cur.next = dummy.next
prev.next = null
dummy.next = cur
while (cur.next) {
prev = cur
cur = cur.next
}
count--
} while (count > 0)
return dummy.next
}
export function rotateRightV2(head, k) {
// 快慢指针 O(n)
if (!head || !head.next || k === 0) return head
const dummy = new ListNode(0, head)
let length = 1
while (head.next) {
head = head.next
length++
}
let count = k % length
if (count === 0) return dummy.next
let slow = dummy.next
let fast = slow
while (count-- > 0) {
fast = fast.next
}
while (fast.next) {
fast = fast.next
slow = slow.next
}
fast.next = dummy.next
dummy.next = slow.next
slow.next = null
return dummy.next
}
export function rotateRightV3(head, k) {
// 闭合成环 O(n)
if (!head || !head.next || k === 0) return head
let length = 1
let cur = head
while (cur.next) {
cur = cur.next
length++
}
let count = length - (k % length)
if (count === length) return head
cur.next = head // 连接起始节点
while (count-- > 0) {
cur = cur.next
}
const res = cur.next
cur.next = null
return res
}
|
unseenme/mindspore | tests/ut/cpp/python_input/gtest_input/pre_activate/insert_memcpy_async_for_getnext.py | <reponame>unseenme/mindspore
# Copyright 2020 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
from mindspore.ops import operations as P
from mindspore.ops import Primitive
import mindspore as ms
get_next = P.GetNext([ms.float32, ms.int32], [[32, 64], [32]], 2, "")
memcpy_async = Primitive('memcpy_async')
make_tuple = Primitive('make_tuple')
tuple_getitem = Primitive('tuple_getitem')
class FnDict:
def __init__(self):
self.fnDict = {}
def __call__(self, fn):
self.fnDict[fn.__name__] = fn
def __getitem__(self, name):
return self.fnDict[name]
def test_insert_memcpy_async_for_getnext(tag):
fns = FnDict()
@fns
def getnext_multi_output_before():
res = get_next()
return res
@fns
def getnext_multi_output_after():
res = get_next()
data = tuple_getitem(res, 0)
label = tuple_getitem(res, 1)
memcpy_async_data = memcpy_async(data)
memcpy_async_label = memcpy_async(label)
bind_tuple = make_tuple(memcpy_async_data, memcpy_async_label)
get_item0 = tuple_getitem(bind_tuple, 0)
get_item1 = tuple_getitem(bind_tuple, 1)
bind_tuple = make_tuple(make_tuple(get_item0, get_item1))
return bind_tuple
return fns[tag]
|
zhaomengxiao/MITK | Modules/Gizmo/src/mitkGizmoMapper2D.cpp | /*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include "mitkGizmoMapper2D.h"
#include "mitkGizmo.h"
// MITK includes
#include <mitkBaseRenderer.h>
#include <mitkCameraController.h>
#include <mitkLookupTableProperty.h>
#include <mitkVtkInterpolationProperty.h>
#include <mitkVtkRepresentationProperty.h>
#include <mitkVtkScalarModeProperty.h>
// VTK includes
#include <vtkAppendPolyData.h>
#include <vtkCamera.h>
#include <vtkCellArray.h>
#include <vtkCharArray.h>
#include <vtkConeSource.h>
#include <vtkMath.h>
#include <vtkPointData.h>
#include <vtkSphereSource.h>
#include <vtkVectorOperators.h>
mitk::GizmoMapper2D::LocalStorage::LocalStorage()
{
m_VtkPolyDataMapper = vtkSmartPointer<vtkPolyDataMapper>::New();
m_Actor = vtkSmartPointer<vtkActor>::New();
m_Actor->SetMapper(m_VtkPolyDataMapper);
}
const mitk::Gizmo *mitk::GizmoMapper2D::GetInput()
{
return static_cast<const Gizmo *>(GetDataNode()->GetData());
}
void mitk::GizmoMapper2D::ResetMapper(mitk::BaseRenderer *renderer)
{
LocalStorage *ls = m_LSH.GetLocalStorage(renderer);
ls->m_Actor->VisibilityOff();
}
namespace
{
//! Helper method: will assign given value to all points in given polydata object.
void AssignScalarValueTo(vtkPolyData *polydata, char value)
{
vtkSmartPointer<vtkCharArray> pointData = vtkSmartPointer<vtkCharArray>::New();
int numberOfPoints = polydata->GetNumberOfPoints();
pointData->SetNumberOfComponents(1);
pointData->SetNumberOfTuples(numberOfPoints);
pointData->FillComponent(0, value);
polydata->GetPointData()->SetScalars(pointData);
}
//! Helper method: will create a vtkPolyData representing a disk
//! around center, inside the plane defined by viewRight and viewUp,
//! and with the given radius.
vtkSmartPointer<vtkPolyData> Create2DDisk(mitk::Vector3D viewRight,
mitk::Vector3D viewUp,
mitk::Point3D center,
double radius)
{
// build the axis itself (as a tube around the line defining the axis)
vtkSmartPointer<vtkPolyData> disk = vtkSmartPointer<vtkPolyData>::New();
mitk::Vector3D ringPointer;
unsigned int numberOfRingPoints = 36;
vtkSmartPointer<vtkPoints> ringPoints = vtkSmartPointer<vtkPoints>::New();
vtkSmartPointer<vtkCellArray> ringPoly = vtkSmartPointer<vtkCellArray>::New();
ringPoly->InsertNextCell(numberOfRingPoints + 1);
for (unsigned int segment = 0; segment < numberOfRingPoints; ++segment)
{
double x = std::cos((double)(segment) / (double)numberOfRingPoints * 2.0 * vtkMath::Pi());
double y = std::sin((double)(segment) / (double)numberOfRingPoints * 2.0 * vtkMath::Pi());
ringPointer = viewRight * x + viewUp * y;
ringPoints->InsertPoint(segment, (center + ringPointer * radius).GetDataPointer());
ringPoly->InsertCellPoint(segment);
}
ringPoly->InsertCellPoint(0);
disk->SetPoints(ringPoints);
disk->SetPolys(ringPoly);
return disk;
}
//! Helper method: will create a vtkPolyData representing a 2D arrow
//! that is oriented from arrowStart to arrowTip, orthogonal
//! to camera direction. The arrow tip will contain scalar values
//! of vertexValueScale, the arrow shaft will contain scalar values
//! of vertexValueMove. Those values are used for picking during interaction.
vtkSmartPointer<vtkPolyData> Create2DArrow(mitk::Vector3D cameraDirection,
mitk::Point3D arrowStart,
mitk::Point3D arrowTip,
int vertexValueMove,
int vertexValueScale)
{
mitk::Vector3D arrowDirection = arrowTip - arrowStart;
mitk::Vector3D arrowOrthogonal = itk::CrossProduct(cameraDirection, arrowDirection);
arrowOrthogonal.Normalize();
double triangleFraction = 0.2;
vtkSmartPointer<vtkPolyData> arrow = vtkSmartPointer<vtkPolyData>::New();
vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New();
// shaft : points 0, 1
points->InsertPoint(0, arrowStart.GetDataPointer());
points->InsertPoint(1, (arrowStart + arrowDirection * (1.0 - triangleFraction)).GetDataPointer());
// tip : points 2, 3, 4
points->InsertPoint(2, arrowTip.GetDataPointer());
points->InsertPoint(3,
(arrowStart + (1.0 - triangleFraction) * arrowDirection +
arrowOrthogonal * (0.5 * triangleFraction * arrowDirection.GetNorm()))
.GetDataPointer());
points->InsertPoint(4,
(arrowStart + (1.0 - triangleFraction) * arrowDirection -
arrowOrthogonal * (0.5 * triangleFraction * arrowDirection.GetNorm()))
.GetDataPointer());
arrow->SetPoints(points);
// define line connection for shaft
vtkSmartPointer<vtkCellArray> lines = vtkSmartPointer<vtkCellArray>::New();
vtkIdType shaftLinePoints[] = {0, 1};
lines->InsertNextCell(2, shaftLinePoints);
arrow->SetLines(lines);
// define polygon for triangle
vtkSmartPointer<vtkCellArray> polys = vtkSmartPointer<vtkCellArray>::New();
vtkIdType tipLinePoints[] = {2, 3, 4};
polys->InsertNextCell(3, tipLinePoints);
arrow->SetPolys(polys);
// assign scalar values
vtkSmartPointer<vtkCharArray> pointData = vtkSmartPointer<vtkCharArray>::New();
pointData->SetNumberOfComponents(1);
pointData->SetNumberOfTuples(5);
pointData->FillComponent(0, vertexValueScale);
pointData->SetTuple1(0, vertexValueMove);
pointData->SetTuple1(1, vertexValueMove);
arrow->GetPointData()->SetScalars(pointData);
return arrow;
}
}
vtkPolyData *mitk::GizmoMapper2D::GetVtkPolyData(mitk::BaseRenderer *renderer)
{
return m_LSH.GetLocalStorage(renderer)->m_VtkPolyDataMapper->GetInput();
}
void mitk::GizmoMapper2D::GenerateDataForRenderer(mitk::BaseRenderer *renderer)
{
auto gizmo = GetInput();
auto node = GetDataNode();
LocalStorage *ls = m_LSH.GetLocalStorage(renderer);
// check if something important has changed and we need to re-render
if ((ls->m_LastUpdateTime >= node->GetMTime()) && (ls->m_LastUpdateTime >= gizmo->GetPipelineMTime()) &&
(ls->m_LastUpdateTime >= renderer->GetCameraController()->GetMTime()) &&
(ls->m_LastUpdateTime >= renderer->GetCurrentWorldPlaneGeometryUpdateTime()) &&
(ls->m_LastUpdateTime >= renderer->GetCurrentWorldPlaneGeometry()->GetMTime()) &&
(ls->m_LastUpdateTime >= node->GetPropertyList()->GetMTime()) &&
(ls->m_LastUpdateTime >= node->GetPropertyList(renderer)->GetMTime()))
{
return;
}
ls->m_LastUpdateTime.Modified();
// some special handling around visibility: let two properties steer
// visibility in 2D instead of many renderer specific "visible" properties
bool visible2D = true;
this->GetDataNode()->GetBoolProperty("show in 2D", visible2D);
if (!visible2D && renderer->GetMapperID() == BaseRenderer::Standard2D)
{
ls->m_Actor->VisibilityOff();
return;
}
else
{
ls->m_Actor->VisibilityOn();
}
auto camera = renderer->GetVtkRenderer()->GetActiveCamera();
auto plane = renderer->GetCurrentWorldPlaneGeometry();
Point3D gizmoCenterView = plane->ProjectPointOntoPlane(gizmo->GetCenter());
Vector3D viewUp;
camera->GetViewUp(viewUp.GetDataPointer());
Vector3D cameraDirection;
camera->GetDirectionOfProjection(cameraDirection.GetDataPointer());
Vector3D viewRight = itk::CrossProduct(viewUp, cameraDirection);
auto appender = vtkSmartPointer<vtkAppendPolyData>::New();
double diagonal = std::min(renderer->GetSizeX(), renderer->GetSizeY()) * renderer->GetScaleFactorMMPerDisplayUnit();
double arrowLength = 0.3 * diagonal; // fixed in relation to window size
auto disk = Create2DDisk(viewRight, viewUp, gizmoCenterView - cameraDirection, 0.1 * arrowLength);
AssignScalarValueTo(disk, Gizmo::MoveFreely);
appender->AddInputData(disk);
// loop over directions -1 and +1 for arrows
for (double direction = -1.0; direction < 2.0; direction += 2.0)
{
auto axisX =
Create2DArrow(cameraDirection,
gizmoCenterView,
plane->ProjectPointOntoPlane(gizmo->GetCenter() + (gizmo->GetAxisX() * arrowLength) * direction),
Gizmo::MoveAlongAxisX,
Gizmo::ScaleX);
appender->AddInputData(axisX);
auto axisY =
Create2DArrow(cameraDirection,
gizmoCenterView,
plane->ProjectPointOntoPlane(gizmo->GetCenter() + (gizmo->GetAxisY() * arrowLength) * direction),
Gizmo::MoveAlongAxisY,
Gizmo::ScaleY);
appender->AddInputData(axisY);
auto axisZ =
Create2DArrow(cameraDirection,
gizmoCenterView,
plane->ProjectPointOntoPlane(gizmo->GetCenter() + (gizmo->GetAxisZ() * arrowLength) * direction),
Gizmo::MoveAlongAxisZ,
Gizmo::ScaleZ);
appender->AddInputData(axisZ);
}
ls->m_VtkPolyDataMapper->SetInputConnection(appender->GetOutputPort());
ApplyVisualProperties(renderer);
}
void mitk::GizmoMapper2D::ApplyVisualProperties(BaseRenderer *renderer)
{
LocalStorage *ls = m_LSH.GetLocalStorage(renderer);
float lineWidth = 3.0f;
ls->m_Actor->GetProperty()->SetLineWidth(lineWidth);
mitk::LookupTableProperty::Pointer lookupTableProp;
this->GetDataNode()->GetProperty(lookupTableProp, "LookupTable", renderer);
if (lookupTableProp.IsNotNull())
{
ls->m_VtkPolyDataMapper->SetLookupTable(lookupTableProp->GetLookupTable()->GetVtkLookupTable());
}
bool scalarVisibility = false;
this->GetDataNode()->GetBoolProperty("scalar visibility", scalarVisibility);
ls->m_VtkPolyDataMapper->SetScalarVisibility((scalarVisibility ? 1 : 0));
if (scalarVisibility)
{
mitk::VtkScalarModeProperty *scalarMode;
if (this->GetDataNode()->GetProperty(scalarMode, "scalar mode", renderer))
ls->m_VtkPolyDataMapper->SetScalarMode(scalarMode->GetVtkScalarMode());
else
ls->m_VtkPolyDataMapper->SetScalarModeToDefault();
bool colorMode = false;
this->GetDataNode()->GetBoolProperty("color mode", colorMode);
ls->m_VtkPolyDataMapper->SetColorMode((colorMode ? 1 : 0));
double scalarsMin = 0;
this->GetDataNode()->GetDoubleProperty("ScalarsRangeMinimum", scalarsMin, renderer);
double scalarsMax = 1.0;
this->GetDataNode()->GetDoubleProperty("ScalarsRangeMaximum", scalarsMax, renderer);
ls->m_VtkPolyDataMapper->SetScalarRange(scalarsMin, scalarsMax);
}
}
void mitk::GizmoMapper2D::SetDefaultProperties(mitk::DataNode *node,
mitk::BaseRenderer *renderer /*= nullptr*/,
bool /*= false*/)
{
node->SetProperty("color", ColorProperty::New(0.3, 0.3, 0.3)); // a little lighter than the
// "plane widgets" of
// QmitkStdMultiWidget
node->SetProperty("scalar visibility", BoolProperty::New(true), renderer);
node->SetProperty("ScalarsRangeMinimum", DoubleProperty::New(0), renderer);
node->SetProperty("ScalarsRangeMaximum", DoubleProperty::New((int)Gizmo::NoHandle), renderer);
double colorMoveFreely[] = {1, 0, 0, 1}; // RGBA
double colorAxisX[] = {0.753, 0, 0, 1}; // colors copied from QmitkStdMultiWidget to
double colorAxisY[] = {0, 0.69, 0, 1}; // look alike
double colorAxisZ[] = {0, 0.502, 1, 1};
double colorInactive[] = {0.7, 0.7, 0.7, 1};
// build a nice color table
vtkSmartPointer<vtkLookupTable> lut = vtkSmartPointer<vtkLookupTable>::New();
lut->SetNumberOfTableValues((int)Gizmo::NoHandle + 1);
lut->SetTableRange(0, (int)Gizmo::NoHandle);
lut->SetTableValue(Gizmo::MoveFreely, colorMoveFreely);
lut->SetTableValue(Gizmo::MoveAlongAxisX, colorAxisX);
lut->SetTableValue(Gizmo::MoveAlongAxisY, colorAxisY);
lut->SetTableValue(Gizmo::MoveAlongAxisZ, colorAxisZ);
lut->SetTableValue(Gizmo::RotateAroundAxisX, colorAxisX);
lut->SetTableValue(Gizmo::RotateAroundAxisY, colorAxisY);
lut->SetTableValue(Gizmo::RotateAroundAxisZ, colorAxisZ);
lut->SetTableValue(Gizmo::ScaleX, colorAxisX);
lut->SetTableValue(Gizmo::ScaleY, colorAxisY);
lut->SetTableValue(Gizmo::ScaleZ, colorAxisZ);
lut->SetTableValue(Gizmo::NoHandle, colorInactive);
mitk::LookupTable::Pointer mlut = mitk::LookupTable::New();
mlut->SetVtkLookupTable(lut);
mitk::LookupTableProperty::Pointer lutProp = mitk::LookupTableProperty::New();
lutProp->SetLookupTable(mlut);
node->SetProperty("LookupTable", lutProp, renderer);
node->SetProperty("helper object", BoolProperty::New(true), renderer);
node->SetProperty("visible", BoolProperty::New(true), renderer);
node->SetProperty("show in 2D", BoolProperty::New(true), renderer);
// no "show in 3D" because this would require a specialized mapper for gizmos in 3D
}
|
yangrunkang/upupor | upupor-web/src/main/java/com/upupor/web/page/SyncPageController.java | <filename>upupor-web/src/main/java/com/upupor/web/page/SyncPageController.java
/*
* MIT License
*
* Copyright (c) 2021-2022 yangrunkang
*
* Author: yangrunkang
* Email: <EMAIL>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.upupor.web.page;
import com.upupor.service.data.dao.entity.Content;
import com.upupor.service.data.service.ContentService;
import com.upupor.service.dto.page.ContentIndexDto;
import io.swagger.annotations.Api;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import java.util.Objects;
import static com.upupor.framework.CcConstant.ContentView.CONTENT_INDEX;
import static com.upupor.framework.CcConstant.TWO_COLONS;
/**
* @author YangRunkang(cruise)
* @date 2020/10/25 00:38
*/
@Api(tags = "异步刷新控制器")
@RestController
@RequiredArgsConstructor
public class SyncPageController {
private final ContentService contentService;
@GetMapping("sync/content/like")
public ModelAndView work(ModelAndView model, String contentId) {
Content content = contentService.getContentByContentIdNoStatus(contentId);
if (Objects.isNull(content)) {
return null;
}
contentService.bindLikesMember(content);
ContentIndexDto contentIndexDto = new ContentIndexDto();
contentIndexDto.setContent(content);
model.addObject(contentIndexDto);
model.setViewName(CONTENT_INDEX + TWO_COLONS + "sync_like_area");
return model;
}
}
|
Glost/db_nets_renew_plugin | root/prj/sol/projects/renew2.5source/renew2.5/src/Simulator/src/de/renew/engine/searchqueue/RandomQueueNode.java | <gh_stars>0
package de.renew.engine.searchqueue;
import de.renew.engine.searcher.Searchable;
class RandomQueueNode {
int pos;
final Searchable searchable;
RandomQueueNode(int pos, Searchable searchable) {
this.pos = pos;
this.searchable = searchable;
}
} |
luontola/cqrs-hotel | src/main/java/fi/luontola/cqrshotel/ApiController.java | // Copyright © 2016-2018 <NAME>
// This software is released under the Apache License 2.0.
// The license text is at http://www.apache.org/licenses/LICENSE-2.0
package fi.luontola.cqrshotel;
import fi.luontola.cqrshotel.capacity.queries.CapacityDto;
import fi.luontola.cqrshotel.capacity.queries.GetCapacityByDate;
import fi.luontola.cqrshotel.capacity.queries.GetCapacityByDateRange;
import fi.luontola.cqrshotel.reservation.commands.MakeReservation;
import fi.luontola.cqrshotel.reservation.commands.SearchForAccommodation;
import fi.luontola.cqrshotel.reservation.queries.FindAllReservations;
import fi.luontola.cqrshotel.reservation.queries.FindReservationById;
import fi.luontola.cqrshotel.reservation.queries.ReservationDto;
import fi.luontola.cqrshotel.reservation.queries.ReservationOffer;
import fi.luontola.cqrshotel.room.commands.CreateRoom;
import fi.luontola.cqrshotel.room.queries.FindAllRooms;
import fi.luontola.cqrshotel.room.queries.GetAvailabilityByDateRange;
import fi.luontola.cqrshotel.room.queries.RoomAvailabilityDto;
import fi.luontola.cqrshotel.room.queries.RoomDto;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDate;
import java.util.Map;
import java.util.UUID;
@RestController
public class ApiController {
private final Core core;
public ApiController(Core core) {
this.core = core;
}
@GetMapping("/api")
public String home() {
return "CQRS Hotel API";
}
@GetMapping("/api/status")
public StatusPage status() {
return core.getStatus();
}
@PostMapping("/api/search-for-accommodation")
public ReservationOffer searchForAccommodation(@RequestBody SearchForAccommodation command) {
return (ReservationOffer) core.handle(command);
}
@PostMapping("/api/make-reservation")
public Map<?, ?> makeReservation(@RequestBody MakeReservation command) {
return (Map<?, ?>) core.handle(command); // XXX: WriteObservedPositionToResponseHeaders works only for non-void controller methods
}
@GetMapping("/api/reservations")
public ReservationDto[] reservations() {
return (ReservationDto[]) core.handle(new FindAllReservations());
}
@GetMapping("/api/reservations/{reservationId}")
public ReservationDto reservationById(@PathVariable String reservationId) {
return (ReservationDto) core.handle(new FindReservationById(UUID.fromString(reservationId)));
}
@PostMapping("/api/create-room")
public Map<?, ?> createRoom(@RequestBody CreateRoom command) {
return (Map<?, ?>) core.handle(command); // XXX: WriteObservedPositionToResponseHeaders works only for non-void controller methods
}
@GetMapping("/api/rooms")
public RoomDto[] rooms() {
return (RoomDto[]) core.handle(new FindAllRooms());
}
@GetMapping("/api/capacity/{date}")
public CapacityDto capacityByDate(@PathVariable String date) {
return (CapacityDto) core.handle(new GetCapacityByDate(LocalDate.parse(date)));
}
@GetMapping("/api/capacity/{start}/{end}")
public CapacityDto[] capacityByDateRange(@PathVariable String start,
@PathVariable String end) {
return (CapacityDto[]) core.handle(new GetCapacityByDateRange(LocalDate.parse(start), LocalDate.parse(end)));
}
@GetMapping("/api/availability/{start}/{end}")
public RoomAvailabilityDto[] availabilityByDateRange(@PathVariable String start,
@PathVariable String end) {
return (RoomAvailabilityDto[]) core.handle(new GetAvailabilityByDateRange(LocalDate.parse(start), LocalDate.parse(end)));
}
}
|
zealoussnow/chromium | chrome/browser/vr/location_bar_helper.cc | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/vr/location_bar_helper.h"
#include <memory>
#include "components/omnibox/browser/location_bar_model_impl.h"
class LocationBarModelDelegate;
namespace vr {
namespace {
// This number is arbitrary. For VR, use a number smaller than desktop's 32K, as
// the URL indicator does not show long URLs.
constexpr int kMaxURLDisplayChars = 1024;
} // namespace
LocationBarHelper::LocationBarHelper(BrowserUiInterface* ui,
LocationBarModelDelegate* delegate)
: ui_(ui),
location_bar_model_(
std::make_unique<LocationBarModelImpl>(delegate,
kMaxURLDisplayChars)) {}
LocationBarHelper::~LocationBarHelper() {}
void LocationBarHelper::Update() {
LocationBarState state(location_bar_model_->GetURL(),
location_bar_model_->GetSecurityLevel(),
&location_bar_model_->GetVectorIcon(),
location_bar_model_->ShouldDisplayURL(),
location_bar_model_->IsOfflinePage());
if (current_state_ == state)
return;
current_state_ = state;
ui_->SetLocationBarState(state);
}
} // namespace vr
|
gridgentoo/nats-mq | nats-mq/core/msgconv.go | <gh_stars>10-100
/*
* Copyright 2012-2019 The NATS Authors
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package core
import (
"bytes"
"fmt"
"github.com/ibm-messaging/mq-golang/ibmmq"
"github.com/nats-io/nats-mq/message"
)
// EmptyHandle is used when there is no message handle to pass in
var EmptyHandle ibmmq.MQMessageHandle = ibmmq.MQMessageHandle{}
// Copies the array, empty or not
func copyByteArray(data []byte) []byte {
newArray := make([]byte, len(data))
copy(newArray, data)
newArray = bytes.Trim(newArray, "\x00")
return newArray
}
// Copies the array if it isn't empty, otherwise returns the default
func copyByteArrayIfNotEmpty(data []byte, def []byte, size int32) []byte {
if len(data) == 0 {
return def
}
newArray := bytes.Repeat([]byte{0}, int(size))
copy(newArray, data)
return newArray
}
// mapMQMDToHeader creates a new bridge header from an MQMD, copying all the contents
func mapMQMDToHeader(mqmd *ibmmq.MQMD) message.BridgeHeader {
return message.BridgeHeader{
Version: mqmd.Version,
Report: mqmd.Report,
MsgType: mqmd.MsgType,
Expiry: mqmd.Expiry,
Feedback: mqmd.Feedback,
Encoding: mqmd.Encoding,
CodedCharSetID: mqmd.CodedCharSetId,
Format: mqmd.Format,
Priority: mqmd.Priority,
Persistence: mqmd.Persistence,
MsgID: copyByteArray(mqmd.MsgId),
CorrelID: copyByteArray(mqmd.CorrelId),
BackoutCount: mqmd.BackoutCount,
ReplyToQ: mqmd.ReplyToQ,
ReplyToQMgr: mqmd.ReplyToQMgr,
UserIdentifier: mqmd.UserIdentifier,
AccountingToken: copyByteArray(mqmd.AccountingToken),
ApplIdentityData: mqmd.ApplIdentityData,
PutApplType: mqmd.PutApplType,
PutApplName: mqmd.PutApplName,
PutDate: mqmd.PutDate,
PutTime: mqmd.PutTime,
ApplOriginData: mqmd.ApplOriginData,
GroupID: copyByteArray(mqmd.GroupId),
MsgSeqNumber: mqmd.MsgSeqNumber,
Offset: mqmd.Offset,
MsgFlags: mqmd.MsgFlags,
OriginalLength: mqmd.OriginalLength,
}
}
// mapHeaderToMQMD copies most of the fields, some will be ignored on Put, fields that cannot be set are skiped
func mapHeaderToMQMD(header *message.BridgeHeader) *ibmmq.MQMD {
mqmd := ibmmq.NewMQMD()
/* some fields shouldn't be copied, they aren't user editable
mqmd.Version = header.Version
mqmd.MsgType = header.MsgType
mqmd.Expiry = header.Expiry
mqmd.BackoutCount = header.BackoutCount
mqmd.Persistence = header.Persistence
mqmd.PutDate = header.PutDate
mqmd.PutTime = header.PutTime
*/
mqmd.Report = header.Report
mqmd.Feedback = header.Feedback
mqmd.Encoding = header.Encoding
mqmd.CodedCharSetId = header.CodedCharSetID
mqmd.Format = header.Format
mqmd.Priority = header.Priority
mqmd.MsgId = copyByteArrayIfNotEmpty(header.MsgID, mqmd.MsgId, ibmmq.MQ_MSG_ID_LENGTH)
mqmd.CorrelId = copyByteArrayIfNotEmpty(header.CorrelID, mqmd.CorrelId, ibmmq.MQ_CORREL_ID_LENGTH)
mqmd.ReplyToQ = header.ReplyToQ
mqmd.ReplyToQMgr = header.ReplyToQMgr
mqmd.UserIdentifier = header.UserIdentifier
mqmd.AccountingToken = copyByteArrayIfNotEmpty(header.AccountingToken, mqmd.AccountingToken, ibmmq.MQ_ACCOUNTING_TOKEN_LENGTH)
mqmd.ApplIdentityData = header.ApplIdentityData
mqmd.PutApplType = header.PutApplType
mqmd.PutApplName = header.PutApplName
mqmd.ApplOriginData = header.ApplOriginData
mqmd.GroupId = copyByteArrayIfNotEmpty(header.GroupID, mqmd.GroupId, ibmmq.MQ_GROUP_ID_LENGTH)
mqmd.MsgSeqNumber = header.MsgSeqNumber
mqmd.Offset = header.Offset
mqmd.MsgFlags = header.MsgFlags
mqmd.OriginalLength = header.OriginalLength
return mqmd
}
func (bridge *BridgeServer) copyMessageProperties(handle ibmmq.MQMessageHandle, msg *message.BridgeMessage) error {
if handle == EmptyHandle {
return nil
}
impo := ibmmq.NewMQIMPO()
pd := ibmmq.NewMQPD()
impo.Options = ibmmq.MQIMPO_CONVERT_VALUE | ibmmq.MQIMPO_INQ_FIRST
for propsToRead := true; propsToRead; {
name, value, err := handle.InqMP(impo, pd, "%")
impo.Options = ibmmq.MQIMPO_CONVERT_VALUE | ibmmq.MQIMPO_INQ_NEXT
if err != nil {
mqret := err.(*ibmmq.MQReturn)
if mqret.MQRC != ibmmq.MQRC_PROPERTY_NOT_AVAILABLE {
return err
}
propsToRead = false
} else {
err := msg.SetProperty(name, value) // will extract the type
if err != nil {
return err
}
}
}
return nil
}
func (bridge *BridgeServer) mapPropertiesToHandle(msg *message.BridgeMessage, qmgr *ibmmq.MQQueueManager) (ibmmq.MQMessageHandle, error) {
cmho := ibmmq.NewMQCMHO()
handle, err := qmgr.CrtMH(cmho)
if err != nil {
return handle, err
}
smpo := ibmmq.NewMQSMPO()
pd := ibmmq.NewMQPD()
props := msg.Properties
for name := range props {
value, ok := msg.GetTypedProperty(name)
if !ok {
return handle, fmt.Errorf("broken message property %s", name)
}
err = handle.SetMP(smpo, name, pd, value)
if err != nil {
return handle, err
}
}
return handle, nil
}
//MQToNATSMessage convert an incoming MQ message to a set of NATS bytes and a reply subject
// if the qmgr is nil, the return value is just the message body
// if the qmgr is not nil the message is encoded as a BridgeMessage
// The data array is always just bytes from MQ, and is not an encoded BridgeMessage
// Header fields that are byte arrays are trimmed, "\x00" removed, on conversion to BridgeMessage.Header
func (bridge *BridgeServer) MQToNATSMessage(mqmd *ibmmq.MQMD, handle ibmmq.MQMessageHandle, data []byte, length int, qmgr *ibmmq.MQQueueManager) ([]byte, string, error) {
replySubject := ""
replyChannel := ""
replyQ := ""
replyQMgr := ""
if mqmd != nil {
replyQ = mqmd.ReplyToQ
replyQMgr = mqmd.ReplyToQMgr
}
if replyQ != "" && replyQMgr != "" {
connectTo, ok := bridge.replyToInfo["Q:"+replyQ+"@"+replyQMgr]
if ok {
if connectTo.Subject != "" {
replySubject = connectTo.Subject
} else {
replyChannel = connectTo.Channel
}
}
}
if qmgr == nil {
return data[:length], replySubject, nil
}
mqMsg := message.NewBridgeMessage(data[:length])
mqMsg.Header = mapMQMDToHeader(mqmd)
mqMsg.Header.ReplyToChannel = replyChannel
err := bridge.copyMessageProperties(handle, mqMsg)
if err != nil {
return nil, "", err
}
encoded, err := mqMsg.Encode()
if err != nil {
return nil, "", err
}
return encoded, replySubject, nil
}
// NATSToMQMessage decode an incoming nats message to an MQ message
// if the qmgr is nil, data is considered to just be a message body
// if the qmgr is not nil the message is treated as an encoded BridgeMessage
// The returned byte array just bytes from MQ, and is not an encoded BridgeMessage
// Header fields that are byte arrays are padded, "\x00" added, on conversion from BridgeMessage.Header
func (bridge *BridgeServer) NATSToMQMessage(data []byte, replyTo string, qmgr *ibmmq.MQQueueManager) (*ibmmq.MQMD, ibmmq.MQMessageHandle, []byte, error) {
replyQ := ""
replyQMgr := ""
if replyTo != "" {
connectTo, ok := bridge.replyToInfo["S:"+replyTo]
if !ok {
connectTo, ok = bridge.replyToInfo["C:"+replyTo]
}
if ok && connectTo.Queue != "" {
replyQ = connectTo.Queue
replyQMgr = connectTo.MQ.QueueManager
}
}
if qmgr == nil {
mqmd := ibmmq.NewMQMD()
if replyQ != "" {
mqmd.ReplyToQ = replyQ
mqmd.ReplyToQMgr = replyQMgr
}
return mqmd, EmptyHandle, data, nil
}
// Can't have nil data for encoded message, could have for empty plain message
if data == nil {
return nil, EmptyHandle, nil, fmt.Errorf("tried to convert empty message to BridgeMessage")
}
mqMsg, err := message.DecodeBridgeMessage(data)
if err != nil {
return nil, EmptyHandle, nil, err
}
if mqMsg.Header.ReplyToChannel != "" {
connectTo, ok := bridge.replyToInfo["C:"+mqMsg.Header.ReplyToChannel]
if ok && connectTo.Queue != "" {
replyQ = connectTo.Queue
replyQMgr = connectTo.MQ.QueueManager
}
}
handle, err := bridge.mapPropertiesToHandle(mqMsg, qmgr)
if err != nil {
return nil, EmptyHandle, nil, err
}
mqmd := mapHeaderToMQMD(&mqMsg.Header)
if replyQ != "" {
mqmd.ReplyToQ = replyQ
mqmd.ReplyToQMgr = replyQMgr
}
return mqmd, handle, mqMsg.Body, nil
}
|
scibian/fmgui | src/com/intel/stl/ui/framework/IController.java | /**
* Copyright (c) 2015, Intel Corporation
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Intel Corporation nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.intel.stl.ui.framework;
import com.intel.stl.ui.main.Context;
public interface IController {
/**
*
* Description: sets the context for the controller
*
* @param context
* the context to be used by this controller
*/
void setContext(Context context);
/**
*
* Description: returns the context in use by this controller
*
* @return the context in use by this controller
*/
Context getContext();
/**
*
* Description: invoked during MVC initialization to initialize the model.
* The view is notified after this initialization, even if the controller
* decides that no initialization is needed.
*
*/
void initModel();
/**
*
* Description: submits a task for execution. The task is run under a Swing
* Worker so that Swing Event Dispatch Thread is not blocked
*
* @param task
* the task to be executed
*/
void submitTask(ITask task);
/**
*
* Description: invoked by a task to signal that the task has completed
* successfully. If more than one task is executed, the controller is
* responsible to determine which one has completed.
*
*/
void onTaskSuccess();
/**
*
* Description: invoked by a task to signal that the task has failed.
*
* @param caught
* the error caught during task execution
*/
void onTaskFailure(Throwable caught);
/**
*
* Description: notify all listeners that a change to this model has just
* occurred
*
*/
void notifyModelChanged();
/**
*
* Description: notify all listeners an error occurred while attempting to
* update this model
*
* @param caught
*/
void notifyModelUpdateFailed(Throwable caught);
}
|
zpleefly/libscapi | lib/libOTe/cryptoTools/testsVS_cryptoTools/Cuckoo_TestsVS.cpp | <reponame>zpleefly/libscapi
#include "stdafx.h"
#ifdef _MSC_VER
#include "CppUnitTest.h"
#include "Cuckoo_Tests.h"
#include "Common.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace tests_cryptoTools
{
TEST_CLASS(Cuckoo_Tests)
{
public:
TEST_METHOD(CuckooIndex_many_Test)
{
InitDebugPrinting();
CuckooIndex_many_Test_Impl();
}
TEST_METHOD(CuckooIndex_paramSweep_Test)
{
InitDebugPrinting();
CuckooIndex_paramSweep_Test_Impl();
}
TEST_METHOD(CuckooIndex_parallel_Test)
{
InitDebugPrinting();
CuckooIndex_parallel_Test_Impl();
}
};
}
#endif
|
hhstechgroup/infinispan | core/src/main/java/org/infinispan/marshall/BufferSizePredictorAdapter.java | <reponame>hhstechgroup/infinispan
package org.infinispan.marshall;
/**
* BufferSizePredictorAdapter.
*
* @author <NAME>
* @since 6.0
*/
@Deprecated
public class BufferSizePredictorAdapter implements BufferSizePredictor {
final org.infinispan.commons.marshall.BufferSizePredictor delegate;
public BufferSizePredictorAdapter(org.infinispan.commons.marshall.BufferSizePredictor delegate) {
this.delegate = delegate;
}
@Override
public int nextSize(Object obj) {
return delegate.nextSize(obj);
}
@Override
public void recordSize(int previousSize) {
delegate.recordSize(previousSize);
}
}
|
sadupally/Dev | unisa-tools/unisa-proxy/src/java/za/ac/unisa/lms/tools/proxy/tags/SakaiLinkTag.java | package za.ac.unisa.lms.tools.proxy.tags;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.htmlparser.tags.LinkTag;
import org.htmlparser.util.ParserException;
public class SakaiLinkTag extends LinkTag {
/**
* Eclipse Generated.
*/
private static final long serialVersionUID = -7670524224691620252L;
private static final Log log = LogFactory.getLog(SakaiLinkTag.class);
private String contextPath = "";
private String permParm = "";
private String base = "";
public SakaiLinkTag(String base, String contextPath, String permParm) {
this.base = base;
this.permParm = permParm;
this.contextPath = contextPath;
}
private String doLinkRewrite() throws StringIndexOutOfBoundsException {
String link = getAttribute("href");
if (link == null) return "";
if (link.startsWith("javascript")) {
//Do nothing, link does not get rewritten.
} else if (link.startsWith("/")) {
link = contextPath+link;
} else if (link.indexOf("://") != -1) {
if (link.indexOf(base) != -1) {
link = link.substring(link.indexOf("://")+3, link.length());
link = link.substring(link.indexOf("/")+1, link.length());
link = contextPath+"/"+link;
if(link.contains("/portal")){
setAttribute("target", "_blank");
}
} else {
setAttribute("target", "_blank");
}
}
if ((permParm != null) && (!permParm.equals("")) && (!link.startsWith("javascript"))) {
if (link.indexOf("?") == -1) {
link += "?"+permParm;
} else {
link += "&"+permParm;
}
}
return link;
}
public void doSemanticAction() throws ParserException {
try {
removeAttribute("target");
setLink(doLinkRewrite());
} catch (StringIndexOutOfBoundsException e) {
log.error(e.getMessage());
throw new ParserException(e);
}
}
}
|
lgliuwei/AndroidAdvanceStudy | app/src/main/java/cn/codingblock/androidadvancestudy/contentprovides/system_provider/ContactProviderActivity.java | <gh_stars>1-10
package cn.codingblock.androidadvancestudy.contentprovides.system_provider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import cn.codingblock.androidadvancestudy.R;
import cn.codingblock.libutils.view.ViewUtils;
public class ContactProviderActivity extends AppCompatActivity implements View.OnClickListener {
private final static String TAG = ContactProviderActivity.class.getSimpleName();
Button btn_insert;
Button btn_query;
Button btn_update;
Button btn_delete;
TextView tv_show;
EditText et_name;
EditText et_phone;
String showContact;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_provider);
btn_insert = ViewUtils.find(this, R.id.btn_insert);
btn_query = ViewUtils.find(this, R.id.btn_query);
btn_update = ViewUtils.find(this, R.id.btn_update);
btn_delete = ViewUtils.find(this, R.id.btn_delete);
tv_show = ViewUtils.find(this, R.id.tv_show);
et_name = ViewUtils.find(this, R.id.et_name);
et_phone = ViewUtils.find(this, R.id.et_phone);
btn_insert.setOnClickListener(this);
btn_query.setOnClickListener(this);
btn_update.setOnClickListener(this);
btn_delete.setOnClickListener(this);
tv_show.setMovementMethod(ScrollingMovementMethod.getInstance());
}
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_insert:
insert();
break;
case R.id.btn_query:
query();
break;
case R.id.btn_update:
update();
break;
case R.id.btn_delete:
delete();
break;
}
}
public void insert() {
String name = et_name.getText().toString();
String phone = et_phone.getText().toString();
if (TextUtils.isEmpty(name) || TextUtils.isEmpty(phone)) {
Toast.makeText(getApplicationContext(), "不能为空", Toast.LENGTH_LONG).show();
return;
}
ContentValues values = new ContentValues();
// 往插入一个空值以便获取id
Uri rawContactUri = getContentResolver().insert(ContactsContract.RawContacts.CONTENT_URI, values);
long rawContactId = ContentUris.parseId(rawContactUri);
// ------插入联系人姓名------
// 设置id
values.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
// 设置内容类型
values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
// 设置名字
values.put(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, name);
// 插入姓名
getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);
values.clear();
// ------插入联系人电话------
values.put(ContactsContract.Data.RAW_CONTACT_ID, rawContactId);
values.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
values.put(ContactsContract.CommonDataKinds.Phone.NUMBER, phone);
values.put(ContactsContract.CommonDataKinds.Phone.TYPE, ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE);
getContentResolver().insert(ContactsContract.Data.CONTENT_URI, values);
Toast.makeText(getApplicationContext(), "添加成功", Toast.LENGTH_LONG).show();
query();
}
public void query() {
showContact = "";
// 获取联系人的Cursor集合
Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
while (cursor.moveToNext()) {
// 获取联系人id
String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
// 获取联系人姓名
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
// 获取当前联系人id下的所有电话号码
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + id, null, null);
showContact += "--id="+ id + " | name=" + name + "--\n";
Log.i(TAG, "onCreate: ------id="+ id + " | name=" + name + "------");
while (phones.moveToNext()) {
String phone = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
showContact += "phone = " + phone + "\n";
Log.i(TAG, "onCreate: phone = " + phone);
}
phones.close();
}
cursor.close();
tv_show.setText(showContact);
}
public void update() {
}
public void delete() {
}
}
|
wilebeast/FireFox-OS | B2G/gecko/content/xtf/src/nsIXTFService.h | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef __NS_IXTFSERVICE_H__
#define __NS_IXTFSERVICE_H__
#include "nsISupports.h"
class nsIContent;
class nsINodeInfo;
// {4ac3826f-280e-4572-9ede-6c81a4797861}
#define NS_IXTFSERVICE_IID \
{ 0x4ac3826f, 0x280e, 0x4572, \
{ 0x9e, 0xde, 0x6c, 0x81, 0xa4, 0x79, 0x78, 0x61 } }
class nsIXTFService : public nsISupports
{
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_IXTFSERVICE_IID)
// try to create an xtf element based on namespace
virtual nsresult CreateElement(nsIContent** aResult,
already_AddRefed<nsINodeInfo> aNodeInfo) = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsIXTFService, NS_IXTFSERVICE_IID)
//----------------------------------------------------------------------
// The one class implementing this interface:
// {4EC832DA-6AE7-4185-807B-DADDCB5DA37A}
#define NS_XTFSERVICE_CID \
{ 0x4ec832da, 0x6ae7, 0x4185, { 0x80, 0x7b, 0xda, 0xdd, 0xcb, 0x5d, 0xa3, 0x7a } }
#define NS_XTFSERVICE_CONTRACTID "@mozilla.org/xtf/xtf-service;1"
nsresult NS_NewXTFService(nsIXTFService** aResult);
#endif // __NS_IXTFSERVICE_H__
|
IBPA/FoodAtlas | food_ke/entailment/download.py | import logging
import os
import time
from typing import List, Optional, Tuple
import click
import pandas as pd
import requests
from bs4 import BeautifulSoup
from nltk import sent_tokenize
from pubmed_mapper import Article
from sklearn.feature_extraction.text import CountVectorizer
from tqdm import tqdm
from food_ke.entailment.constants import (
FOOD_PARTS,
FOODS_FROM_FOODB_PATH,
WHOLE_PLANT_TOKEN,
)
from food_ke.entailment.custom_typing import DownloadOutput, NCBIEnt
logging.basicConfig(level=logging.INFO)
FOODS_FROM_FOODB = pd.read_csv(FOODS_FROM_FOODB_PATH)
def pmid_to_pmc_id(pmid):
article = Article.parse_pmid(pmid)
for id_ in article.ids:
if id_.id_type == "pmc":
return id_.id_value
return None
def get_pmc_fulltext(pmcid):
pmcid = pmcid.replace("PMC", "")
response = requests.get(
f"https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?"
f"db=pmc&id={pmcid}&tool=my_tool&email=<EMAIL>"
)
soup = BeautifulSoup(response.content)
fulltext = "\n".join(
[sec.text for sec in soup.find("body").find_all("sec")]
)
return fulltext
def get_pmid_fulltext(pmid):
pmcid = pmid_to_pmc_id(pmid)
fulltext = get_pmc_fulltext(pmcid)
return fulltext
def _get_db_results_by_query(
query: str, db: str, sort: str, retmax: int = 100
) -> List[str]:
"""Searches an NCBI database by a query and returns resulting document ids.
NOTE: When searching pubmed using sort=relevance, results differ slightly
from results obtained using the web search interface sorted by "Best
Match". The returned results from the programmatic search still appear to
be sorted by some form of relevance, just not the same as the one used in
the GUI...
"""
if db not in ["pubmed", "pmc"]:
raise ValueError
query = query.replace(" ", "+")
if retmax is not None:
response = requests.get(
f"https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db={db}&"
f"term={query}&sort={sort}&retmax={retmax}"
)
else:
response = requests.get(
f"https://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?db={db}&"
f"term={query}&sort={sort}"
)
soup = BeautifulSoup(response.content, features="lxml")
return [id.text for id in soup.find_all("id")]
def _get_spanning_ents(ents: List[NCBIEnt]):
return [
ent
for ent in ents
if not any(
[ent.text in x.text and ent.text is not x.text for x in ents]
)
]
def get_annotation_type(annotation):
return annotation.find(attrs={"key": "type"}).text
def get_annotation_text(annotation):
return annotation.find("text").text
def get_annotation_identifier(annotation):
if annotation.find(attrs={"key": "identifier"}) is not None:
return annotation.find(attrs={"key": "identifier"}).text
elif annotation.find(attrs={"key": "Identifier"}) is not None:
return annotation.find(attrs={"key": "Identifier"}).text
else:
return None
def get_annot_is_plant(annot_id):
url = (
f"https://www.ncbi.nlm.nih.gov/Taxonomy/Browser/"
f"wwwtax.cgi?id={annot_id}"
)
response = requests.get(url)
if not response.status_code == 200:
raise ValueError
return "Viridiplantae" in response.text
def load_phenolexplorer_pmids():
pmids = pd.read_csv(
"/content/gdrive/MyDrive/AIFS KE/phenol_explorer_ids.csv"
)
pmids = pmids["0"].unique()
return pmids
def vectorize_sents(
sents, food_names: List[str], compound_names: List[str]
) -> pd.DataFrame:
food_names_lens = [len(x.split()) for x in food_names]
compound_names_lens = [len(x.split()) for x in compound_names]
max_len = max(food_names_lens + compound_names_lens)
vec = CountVectorizer(ngram_range=(1, max_len))
count_matrix = pd.DataFrame(
vec.fit_transform(sents).toarray(),
columns=vec.get_feature_names_out(),
index=sents,
)
return count_matrix
def filter_count_matrix(count_matrix, food_names, compound_names):
food_names_cm = [f for f in food_names if f in count_matrix.columns]
compound_names_cm = [
f for f in compound_names if f in count_matrix.columns
]
count_matrix_filtered = count_matrix[
(count_matrix[food_names_cm].sum(axis=1) > 0)
& (count_matrix[compound_names_cm].sum(axis=1) > 0)
][food_names_cm + compound_names_cm]
return count_matrix_filtered
def filter_sents(text: str, food_names, compound_names):
sents = sent_tokenize(text)
count_matrix = vectorize_sents(sents, food_names, compound_names)
count_matrix_filtered = filter_count_matrix(
count_matrix, food_names, compound_names
)
filtered_sents = count_matrix_filtered.index.tolist()
return filtered_sents
def get_pubtator_annotations(
pmids: Optional[List[str]] = None, pmcids: Optional[List[str]] = None
):
if pmids is not None and pmcids is not None:
raise ValueError("Only one of pmids and pmcids should be provided.")
if pmids is not None:
pmids_joined = ",".join(pmids)
logging.info(f"pmids: {pmids_joined}")
url = (
f"https://www.ncbi.nlm.nih.gov/research/pubtator-api/publications/"
f"export/biocxml?pmids={pmids_joined}"
)
logging.info(f"url: {url}")
elif pmcids is not None:
pmcids_joined = ",".join(["PMC" + str(x) for x in pmcids])
logging.info(f"pmcids: {pmcids_joined}")
url = (
f"https://www.ncbi.nlm.nih.gov/research/pubtator-api/publications/"
f"export/biocxml?pmcids={pmcids_joined}"
)
logging.info(f"url: {url}")
response = requests.get(url)
if response.status_code == 502:
logging.error(url)
logging.error(
"502 Bad Gateway encountered... Pubtator "
"is probably updating the server."
)
return None
if response.status_code != 200:
logging.error(url)
logging.error(response)
raise ValueError
return BeautifulSoup(response.content, features="lxml")
def get_annot_chems_and_species(
annotation, ids={}
) -> Tuple[List[NCBIEnt], List[NCBIEnt], dict]:
chemicals = []
species = []
annot_type = get_annotation_type(annotation)
annot_text = get_annotation_text(annotation)
if annot_type == "Species":
annot_id = get_annotation_identifier(annotation)
if annot_id in ids.keys():
if ids[annot_id] == "plant":
species.append(NCBIEnt(annot_text, annot_id))
else:
if get_annot_is_plant(annot_id):
ids[annot_id] = "plant"
species.append(NCBIEnt(annot_text, annot_id))
else:
ids[annot_id] = "not plant"
elif annot_type == "Chemical":
annot_id = get_annotation_identifier(annotation)
chemicals.append(NCBIEnt(annot_text, annot_id))
return chemicals, species, ids
def get_passage_food_parts(
passage, food_parts_list: List[str] = FOOD_PARTS
) -> List[NCBIEnt]:
text = get_annotation_text(passage)
parts = [NCBIEnt(WHOLE_PLANT_TOKEN, None)]
sentence_tokens = text.split()
for part in food_parts_list:
if part in sentence_tokens:
parts.append(NCBIEnt(part, None))
return parts
def _get_spanning_ents(ents: List[NCBIEnt]):
return [
ent
for ent in ents
if not any(
[ent.text in x.text and ent.text is not x.text for x in ents]
)
]
def generate_sentences_pubtator(
pmid: Optional[str] = None,
pmcid: Optional[str] = None,
filter_sents_chemicals_only: bool = False,
):
filtered_sents_all = []
ids = {}
if pmid is not None:
logging.info(f"Processing PMID {pmid}")
soup = get_pubtator_annotations(pmids=[str(pmid)])
elif pmcid is not None:
logging.info(f"Processing PMCID {pmcid}")
soup = get_pubtator_annotations(pmcids=[str(pmcid)])
article_id = pmid if pmid is not None else pmcid
if soup is not None:
# pubtator will throttle if too many requests... we should be able to
# batch requests (up to 100 ids in one requests) but I had
# difficulties with this. Revisit later.
time.sleep(0.34)
for passage in soup.find_all("passage"):
passage_type = passage.find("infon", {"key": "type"}).get_text()
passage_section_type = passage.find(
"infon", {"key": "section_type"}
)
passage_section_type = (
passage_section_type.get_text()
if passage_section_type
else None
)
logging.info(f"Processing passage: {str(passage)[0:100]}")
species = []
chemicals = []
# food_parts = get_passage_food_parts(passage)
for annotation in passage.find_all("annotation"):
if annotation.find("text") is None:
continue
annot_chems, annot_species, ids = get_annot_chems_and_species(
annotation, ids
)
chemicals += annot_chems
species += annot_species
logging.info(f"species: {species}")
logging.info(f"chemicals: {chemicals}")
if (len(species) > 0 and len(chemicals) > 0) or (
filter_sents_chemicals_only and len(chemicals) > 0
):
# filtered_sents = filter_sents(
# passage.text,
# [x.text for x in species],
# [x.text for x in chemicals],
# )
filtered_sents = sent_tokenize(passage.find("text").text)
for sent in filtered_sents:
sent_chems = [
chem for chem in set(chemicals) if chem.text in sent
]
sent_species = [s for s in set(species) if s.text in sent]
# sent_food_parts_spanning = [
# p
# for p in set(food_parts)
# if (p.text in sent) or (p.text == WHOLE_PLANT_TOKEN)
# ]
sent_chems_spanning = _get_spanning_ents(sent_chems)
sent_species_spanning = _get_spanning_ents(sent_species)
filtered_sents_all.append(
(
article_id,
sent,
sent_chems_spanning,
sent_species_spanning,
# sent_food_parts_spanning,
passage_type,
passage_section_type,
)
)
logging.info(f"Filtered sents all: {filtered_sents_all}")
return filtered_sents_all
def _generate_data_pubtator(
search_term, retmax, sort_by, filter_sents_chemicals_only
):
"""
Searches pubmed for articles relevant to search_term and returns a
dataframe of premise + hypothesis pairs.
"""
logging.info(f"Searching for query {search_term}")
pmids = _get_db_results_by_query(
search_term,
"pubmed",
sort=sort_by,
retmax=retmax,
)
logging.info(f"Found {len(pmids)} pmids for query {search_term}")
pmcids = _get_db_results_by_query(
search_term, "pmc", sort=sort_by, retmax=retmax
)
logging.info(f"Found {len(pmcids)} pmcids for query {search_term}")
filtered_sents_all = []
logging.info("Querying pubtator for pmids")
for id_ in tqdm(pmids):
filtered_sents_all += generate_sentences_pubtator(
pmid=id_, filter_sents_chemicals_only=filter_sents_chemicals_only
)
logging.info("Querying pubtator for pmcids")
for id_ in tqdm(pmcids):
filtered_sents_all += generate_sentences_pubtator(
pmcid=id_, filter_sents_chemicals_only=filter_sents_chemicals_only
)
logging.debug("Filtered sentences")
logging.debug(filtered_sents_all)
df = pd.DataFrame(
filtered_sents_all,
# columns=["pmid", "premise", "chemicals", "species", "food_part"],
columns=[
"pmid",
"premise",
"chemicals",
"species",
"passage_type",
"passage_section_type",
],
)
df = df[~df.premise.str.contains("doi:10")]
df = df[~df.premise.str.contains("MESH")]
return df
def get_annot_is_food_from_foodb(annot_id):
foods_df = FOODS_FROM_FOODB[~FOODS_FROM_FOODB["ncbi_taxonomy_id"].isnull()]
taxid_list = foods_df["ncbi_taxonomy_id"].astype(int).tolist()
return int(annot_id) in taxid_list
def _generate_data_litsense(
search_term: str, food_entity_filter_method: str, retmax, sort_by
):
LITSENSE_URL = (
"https://www.ncbi.nlm.nih.gov/research/litsense-api/api/"
"?query={}&rerank=true"
)
LITSENSE_DELAY = 1.0
if retmax is not None:
logging.warn(
"Warning: retmax is not used for litsense, returning 100 results."
)
if sort_by is not None:
logging.warn("Sort_by is not implemented yet.")
if food_entity_filter_method == "plant":
check_entity_fn = get_annot_is_plant
elif food_entity_filter_method == "foodb":
check_entity_fn = get_annot_is_food_from_foodb
query_url = LITSENSE_URL.format(search_term)
logging.debug(
"sleeping for {} seconds to avoid NCBI throttling".format(
LITSENSE_DELAY
)
)
time.sleep(LITSENSE_DELAY)
logging.info("requesting data from {}".format(query_url))
response = requests.get(query_url)
if response.status_code != 200:
raise ValueError(
"Error requesting data from {}: {}".format(
query_url, response.status_code
)
)
rows = []
logging.info("{} results recieved".format(len(response.json())))
logging.info("Parsing results")
for doc in response.json():
row = {}
row["pmid"] = doc["pmid"]
row["premise"] = doc["text"]
chemicals = []
species = []
if doc["annotations"] is None:
continue
else:
for ent in doc["annotations"]:
start, n_chars, category, ent_id = ent.split("|")
start = int(start)
n_chars = int(n_chars)
ent_text = doc["text"][start : start + n_chars]
if category == "chemical":
chemicals.append(NCBIEnt(ent_text, ent_id))
elif category == "species":
if check_entity_fn(ent_id):
species.append(NCBIEnt(ent_text, ent_id))
row["chemicals"] = chemicals
row["species"] = species
rows.append(row)
df = pd.DataFrame(rows)
return df
def _generate_data(
search_term,
method,
food_entity_filter_method,
retmax,
sort_by,
filter_sents_chemicals_only,
) -> DownloadOutput:
# get data from NCBI resources and detect foods, chemicals, food parts
if method == "litsense":
df = _generate_data_litsense(
search_term, food_entity_filter_method, retmax, sort_by
)
elif method == "pubtator":
df = _generate_data_pubtator(
search_term,
retmax,
sort_by,
filter_sents_chemicals_only=filter_sents_chemicals_only,
)
df["search_term"] = search_term
return df
@click.command()
@click.option("--search-term")
@click.option(
"--search-terms-file",
help="path to txt file with one search term per line",
)
@click.option(
"--method", type=click.Choice(["litsense", "pubtator"]), default="litsense"
)
@click.option(
"--food-entity-filter-method",
type=click.Choice(["plant", "foodb"]),
default="foodb",
)
@click.option(
"--filter-sents-chemicals-only",
type=bool,
default=False,
)
@click.option("--retmax")
@click.option("--sort-by")
@click.option("--save-to")
def download(
search_term: str,
search_terms_file,
method: str,
food_entity_filter_method: str,
filter_sents_chemicals_only: bool,
retmax: int,
sort_by,
save_to,
):
"""
Searches PubTator for a query term and downloads the relevant paper text
and NER annotations. Filters to only include sentences contianing at least
one food and chemical.
"""
if search_term is not None and search_terms_file is not None:
raise ValueError(
"Only one of search_term or search_terms_file should be given"
)
if search_term is not None:
logging.info("Searching for {}".format(search_term))
candidates_df = _generate_data(
search_term,
method,
retmax,
sort_by,
filter_sents_chemicals_only=filter_sents_chemicals_only,
)
elif search_terms_file is not None:
logging.info(f"Reading search terms from {search_terms_file}")
search_terms = [line.strip() for line in open(search_terms_file)]
skip_list = []
if save_to is not None and os.path.isfile(save_to):
output = pd.read_csv(save_to)
skip_list = list(output["search_term"].unique())
if len(skip_list) > 0:
logging.info(
"Output {} already has results for {} search terms: {}".format(
save_to,
len(skip_list),
skip_list,
),
)
for i, search_term in enumerate(search_terms):
if search_term in skip_list:
logging.info(
f"Output for {search_term} already exists, skipping this search term"
)
continue
logging.info(
f"Generating data for {i + 1}/{len(search_terms)} search "
f"term {search_term}"
)
# try:
candidates_df = _generate_data(
search_term,
method,
food_entity_filter_method,
retmax,
sort_by,
filter_sents_chemicals_only=filter_sents_chemicals_only,
)
if save_to is not None:
logging.info(f"Appending data to {save_to}")
if os.path.isfile(save_to):
candidates_df.to_csv(
save_to, mode="a", index=False, header=False
)
else:
candidates_df.to_csv(save_to, index=False)
# except Exception as e:
# logging.error(
# f"Error generating data for search term {search_term}"
# )
# logging.error(e)
if __name__ == "__main__":
download()
|
mikehelmick/CascadeLMS | app/views/blog/index.xml.builder | <filename>app/views/blog/index.xml.builder
xml.instruct!
xml.blog_posts do
@posts.each do |post|
xml.blog_post do
xml.id "#{post.id}"
xml.title "#{post.title}"
xml.featured "#{post.featured}"
xml.author "#{post.user.display_name}"
xml.posted_at CGI.rfc1123_date(post.created_at)
xml.comments "#{post.comments.size}"
xml.body do
xml.cdata! "#{post.body_html}"
end
unless post.item.nil?
xml.aplus_count "#{post.item.aplus_count}"
xml.aplus_users do
xml.user do
post.item.aplus_users(@user).each do |user|
xml.user do
xml.id "#{user.id}"
xml.name "#{user.display_name}"
xml.gravatar_url "#{user.gravatar_url}"
end
end
end
end
end
end
end
end |
jaysonjphillips/mood-tracker-app | client/src/layouts/main.js | import React from 'react'
import { makeStyles } from '@material-ui/core/styles'
import Paper from '@material-ui/core/Paper'
import Grid from '@material-ui/core/Grid'
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1
},
form: {
'& .MuiTextField-root': {
margin: theme.spacing(1)
}
},
paper: {
padding: theme.spacing(2),
textAlign: 'center',
color: theme.palette.text.secondary
},
paperNoCenter: {
padding: theme.spacing(2),
color: theme.palette.text.secondary
}
}))
export default ({ children }) => {
const classes = useStyles()
return (
<div className={classes.root}>
<Grid container spacing={3}>
<Grid item xs={2} />
<Grid item xs={8}>
{children}
</Grid>
<Grid item xs={2} />
<Grid item xs={12} />
{/* Footer */}
<Grid item xs={2}>
</Grid>
<Grid item xs={8} />
<Grid item xs={2}>
</Grid>
</Grid>
</div>
)
}
|
damnitrahul/gatsby-theme-catalyst | themes/gatsby-theme-catalyst-blog/src/components/templates/tag-template.js | <reponame>damnitrahul/gatsby-theme-catalyst<filename>themes/gatsby-theme-catalyst-blog/src/components/templates/tag-template.js
/** @jsx jsx */
import { jsx, Styled } from "theme-ui"
import { Link } from "gatsby"
import { SEO, Layout } from "gatsby-theme-catalyst-core"
const TagPage = ({ posts, tag }) => {
return (
<Layout>
<SEO title={"Tag: " + tag} />
<Styled.h1>Tag: {tag}</Styled.h1>
<Styled.ul>
{posts.map((post) => (
<Styled.li key={post.slug}>
<Styled.p>
<Styled.a as={Link} to={post.slug} sx={{ fontSize: 3 }}>
{post.title}
</Styled.a>
<br />
{post.excerpt}
</Styled.p>
</Styled.li>
))}
</Styled.ul>
</Layout>
)
}
export default TagPage
|
CentriaUniversityOfAppliedSciences/VASTE_logistics_platform | api/controllers/usersVehiclesController.js | <reponame>CentriaUniversityOfAppliedSciences/VASTE_logistics_platform
'use strict';
var fs = require('fs');
var mongoose = require('mongoose'),
usersCars = mongoose.model('UsersVehicles');
var environmentJson = fs.readFileSync("./environment.json");
var environment = JSON.parse(environmentJson);
var apikey = environment.apikey;
exports.link_new_user = function(req, res){
var new_car = new usersCars({vehicleID: req.body.vehicleID, owners:{userID:req.body.userID}});
new_car.save(function(err, user_cars){
if(err)
res.send(err);
res.json(user_cars)
})
};
exports.find_cars_by_userID = function(req,res){
usersCars.find({"owners.userID": req.body.userID}, function(err, car_users){
if(err)
res.send(err);
res.json(car_users);
})
}
|
weitaoxu/dapp_admin | quant-system/src/main/java/com/qkbus/modules/system/service/impl/DictServiceImpl.java | <reponame>weitaoxu/dapp_admin
package com.qkbus.modules.system.service.impl;
import com.github.pagehelper.PageInfo;
import com.qkbus.common.service.impl.BaseServiceImpl;
import com.qkbus.common.utils.QueryHelpPlus;
import com.qkbus.dozer.service.IGenerator;
import com.qkbus.exception.BadRequestException;
import com.qkbus.modules.system.domain.Dict;
import com.qkbus.modules.system.domain.DictDetail;
import com.qkbus.modules.system.service.DictDetailService;
import com.qkbus.modules.system.service.DictService;
import com.qkbus.modules.system.service.dto.DictDto;
import com.qkbus.modules.system.service.dto.DictQueryCriteria;
import com.qkbus.modules.system.service.mapper.DictMapper;
import com.qkbus.utils.FileUtil;
import lombok.AllArgsConstructor;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;
/**
* @author 少林一枝花
* @date 2020-05-14
*/
@Service
@AllArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
@CacheConfig(cacheNames = "dict")
public class DictServiceImpl extends BaseServiceImpl<DictMapper, Dict> implements DictService {
private final IGenerator generator;
private final DictDetailService dictDetailService;
@Override
public Map<String, Object> queryAll(DictQueryCriteria criteria, Pageable pageable) {
getPage(pageable);
PageInfo<Dict> page = new PageInfo<>(queryAll(criteria));
Map<String, Object> map = new LinkedHashMap<>(2);
map.put("content", generator.convert(page.getList(), DictDto.class));
map.put("totalElements", page.getTotal());
return map;
}
@Override
public List<Dict> queryAll(DictQueryCriteria criteria) {
return baseMapper.selectList(QueryHelpPlus.getPredicate(Dict.class, criteria));
}
@Override
public void download(List<DictDto> all, HttpServletResponse response) throws IOException {
List<Map<String, Object>> list = new ArrayList<>();
for (DictDto dict : all) {
Map<String, Object> map = new LinkedHashMap<>();
map.put("字典名称", dict.getName());
map.put("描述", dict.getRemark());
map.put("创建日期", dict.getGmtCreate());
list.add(map);
}
FileUtil.downloadExcel(list, response);
}
@Override
public void create(Dict resources) {
if (resources.getId() != null) {
throw new BadRequestException("A new dict cannot already have an ID");
}
this.save(resources);
}
@Override
@CacheEvict(value = {"DictDetail"}, allEntries = true)
public void update(Dict resources) {
this.updateById(resources);
}
@Override
@CacheEvict(value = {"DictDetail"}, allEntries = true)
public void delete(Set<Long> ids) {
//查询子类
List<DictDetail> dict_id = dictDetailService.query().in("dict_id", ids).list();
List<Long> collect = dict_id.stream().map(DictDetail::getId).collect(Collectors.toList());
//删除子类
dictDetailService.removeByIds(collect);
this.removeByIds(ids);
}
}
|
mirkobrombin/wine | dlls/wintab.dll16/wintab.c | <filename>dlls/wintab.dll16/wintab.c
/*
* Tablet Win16
*
* Copyright 2002 <NAME>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include <stdarg.h>
#include "windef.h"
#include "winbase.h"
#include "wintab.h"
#include "wine/windef16.h"
#include "wine/debug.h"
WINE_DEFAULT_DEBUG_CHANNEL(wintab);
/**********************************************************************/
#define DECLARE_HANDLE16(a) \
typedef HANDLE16 a##16; \
typedef a##16 *P##a##16; \
typedef a##16 *NP##a##16; \
typedef a##16 *LP##a##16
DECLARE_HANDLE16(HMGR); /* manager handle */
DECLARE_HANDLE16(HCTX); /* context handle */
DECLARE_HANDLE16(HWTHOOK); /* hook handle */
/**********************************************************************/
typedef struct tagLOGCONTEXT16 {
char lcName[LCNAMELEN];
UINT16 lcOptions;
UINT16 lcStatus;
UINT16 lcLocks;
UINT16 lcMsgBase;
UINT16 lcDevice;
UINT16 lcPktRate;
WTPKT lcPktData;
WTPKT lcPktMode;
WTPKT lcMoveMask;
DWORD lcBtnDnMask;
DWORD lcBtnUpMask;
LONG lcInOrgX;
LONG lcInOrgY;
LONG lcInOrgZ;
LONG lcInExtX;
LONG lcInExtY;
LONG lcInExtZ;
LONG lcOutOrgX;
LONG lcOutOrgY;
LONG lcOutOrgZ;
LONG lcOutExtX;
LONG lcOutExtY;
LONG lcOutExtZ;
FIX32 lcSensX;
FIX32 lcSensY;
FIX32 lcSensZ;
BOOL16 lcSysMode;
INT16 lcSysOrgX;
INT16 lcSysOrgY;
INT16 lcSysExtX;
INT16 lcSysExtY;
FIX32 lcSysSensX;
FIX32 lcSysSensY;
} LOGCONTEXT16, *PLOGCONTEXT16, *NPLOGCONTEXT16, *LPLOGCONTEXT16;
/**********************************************************************/
typedef BOOL16 (WINAPI * WTENUMPROC16)(HCTX16, LPARAM); /* changed CALLBACK->WINAPI, 1.1 */
typedef BOOL16 (WINAPI * WTCONFIGPROC16)(HCTX16, HWND16);
typedef LRESULT (WINAPI * WTHOOKPROC16)(INT16, WPARAM16, LPARAM);
typedef WTHOOKPROC16 *LPWTHOOKPROC16;
/***********************************************************************
* WTInfo (WINTAB.20)
*/
UINT16 WINAPI WTInfo16(UINT16 wCategory, UINT16 nIndex, LPVOID lpOutput)
{
FIXME("(%hu, %hu, %p): stub\n", wCategory, nIndex, lpOutput);
return 0;
}
/***********************************************************************
* WTOpen (WINTAB.21)
*/
HCTX16 WINAPI WTOpen16(HWND16 hWnd, LPLOGCONTEXT16 lpLogCtx, BOOL16 fEnable)
{
FIXME("(0x%04hx, %p, %hu): stub\n", hWnd, lpLogCtx, fEnable);
return 0;
}
/***********************************************************************
* WTClose (WINTAB.22)
*/
BOOL16 WINAPI WTClose16(HCTX16 hCtx)
{
FIXME("(0x%04hx): stub\n", hCtx);
return TRUE;
}
/***********************************************************************
* WTPacketsGet (WINTAB.23)
*/
INT16 WINAPI WTPacketsGet16(HCTX16 hCtx, INT16 cMaxPkts, LPVOID lpPkts)
{
FIXME("(0x%04hx, %hd, %p): stub\n", hCtx, cMaxPkts, lpPkts);
return 0;
}
/***********************************************************************
* WTPacket (WINTAB.24)
*/
BOOL16 WINAPI WTPacket16(HCTX16 hCtx, UINT16 wSerial, LPVOID lpPkt)
{
FIXME("(0x%04hx, %hd, %p): stub\n", hCtx, wSerial, lpPkt);
return FALSE;
}
/***********************************************************************
* WTEnable (WINTAB.40)
*/
BOOL16 WINAPI WTEnable16(HCTX16 hCtx, BOOL16 fEnable)
{
FIXME("(0x%04hx, %hu): stub\n", hCtx, fEnable);
return FALSE;
}
/***********************************************************************
* WTOverlap (WINTAB.41)
*/
BOOL16 WINAPI WTOverlap16(HCTX16 hCtx, BOOL16 fToTop)
{
FIXME("(0x%04hx, %hu): stub\n", hCtx, fToTop);
return FALSE;
}
/***********************************************************************
* WTConfig (WINTAB.60)
*/
BOOL16 WINAPI WTConfig16(HCTX16 hCtx, HWND16 hWnd)
{
FIXME("(0x%04hx, 0x%04hx): stub\n", hCtx, hWnd);
return FALSE;
}
/***********************************************************************
* WTGet (WINTAB.61)
*/
BOOL16 WINAPI WTGet16(HCTX16 hCtx, LPLOGCONTEXT16 lpLogCtx)
{
FIXME("(0x%04hx, %p): stub\n", hCtx, lpLogCtx);
return FALSE;
}
/***********************************************************************
* WTSet (WINTAB.62)
*/
BOOL16 WINAPI WTSet16(HCTX16 hCtx, LPLOGCONTEXT16 lpLogCtx)
{
FIXME("(0x%04hx, %p): stub\n", hCtx, lpLogCtx);
return FALSE;
}
/***********************************************************************
* WTExtGet (WINTAB.63)
*/
BOOL16 WINAPI WTExtGet16(HCTX16 hCtx, UINT16 wExt, LPVOID lpData)
{
FIXME("(0x%04hx, %hu, %p): stub\n", hCtx, wExt, lpData);
return FALSE;
}
/***********************************************************************
* WTExtSet (WINTAB.64)
*/
BOOL16 WINAPI WTExtSet16(HCTX16 hCtx, UINT16 wExt, LPVOID lpData)
{
FIXME("(0x%04hx, %hu, %p): stub\n", hCtx, wExt, lpData);
return FALSE;
}
/***********************************************************************
* WTSave (WINTAB.65)
*/
BOOL16 WINAPI WTSave16(HCTX16 hCtx, LPVOID lpSaveInfo)
{
FIXME("(0x%04hx, %p): stub\n", hCtx, lpSaveInfo);
return FALSE;
}
/***********************************************************************
* WTRestore (WINTAB.66)
*/
HCTX16 WINAPI WTRestore16(HWND16 hWnd, LPVOID lpSaveInfo, BOOL16 fEnable)
{
FIXME("(0x%04hx, %p, %hu): stub\n", hWnd, lpSaveInfo, fEnable);
return 0;
}
/***********************************************************************
* WTPacketsPeek (WINTAB.80)
*/
INT16 WINAPI WTPacketsPeek16(HCTX16 hCtx, INT16 cMaxPkts, LPVOID lpPkts)
{
FIXME("(0x%04hx, %hd, %p): stub\n", hCtx, cMaxPkts, lpPkts);
return 0;
}
/***********************************************************************
* WTDataGet (WINTAB.81)
*/
INT16 WINAPI WTDataGet16(HCTX16 hCtx, UINT16 wBegin, UINT16 wEnd,
INT16 cMaxPkts, LPVOID lpPkts, LPINT16 lpNPkts)
{
FIXME("(0x%04hx, %hu, %hu, %hd, %p, %p): stub\n",
hCtx, wBegin, wEnd, cMaxPkts, lpPkts, lpNPkts);
return 0;
}
/***********************************************************************
* WTDataPeek (WINTAB.82)
*/
INT16 WINAPI WTDataPeek16(HCTX16 hCtx, UINT16 wBegin, UINT16 wEnd,
INT16 cMaxPkts, LPVOID lpPkts, LPINT16 lpNPkts)
{
FIXME("(0x%04hx, %hu, %hu, %hd, %p, %p): stub\n",
hCtx, wBegin, wEnd, cMaxPkts, lpPkts, lpNPkts);
return 0;
}
/***********************************************************************
* WTQueuePackets (WINTAB.83)
*
* OBSOLETE IN WIN32!
*/
DWORD WINAPI WTQueuePackets16(HCTX16 hCtx)
{
FIXME("(0x%04hx): stub\n", hCtx);
return 0;
}
/***********************************************************************
* WTQueuePacketsEx (WINTAB.200)
*/
BOOL16 WINAPI WTQueuePacketsEx16(HCTX16 hCtx, UINT16 *lpOld, UINT16 *lpNew)
{
FIXME("(0x%04hx, %p, %p): stub\n", hCtx, lpOld, lpNew);
return TRUE;
}
/***********************************************************************
* WTQueueSizeGet (WINTAB.84)
*/
INT16 WINAPI WTQueueSizeGet16(HCTX16 hCtx)
{
FIXME("(0x%04hx): stub\n", hCtx);
return 0;
}
/***********************************************************************
* WTQueueSizeSet (WINTAB.85)
*/
BOOL16 WINAPI WTQueueSizeSet16(HCTX16 hCtx, INT16 nPkts)
{
FIXME("(0x%04hx, %hd): stub\n", hCtx, nPkts);
return FALSE;
}
/***********************************************************************
* WTMgrOpen (WINTAB.100)
*/
HMGR16 WINAPI WTMgrOpen16(HWND16 hWnd, UINT16 wMsgBase)
{
FIXME("(0x%04hx, %hu): stub\n", hWnd, wMsgBase);
return 0;
}
/***********************************************************************
* WTMgrClose (WINTAB.101)
*/
BOOL16 WINAPI WTMgrClose16(HMGR16 hMgr)
{
FIXME("(0x%04hx): stub\n", hMgr);
return FALSE;
}
/***********************************************************************
* WTMgrContextEnum (WINTAB.120)
*/
BOOL16 WINAPI WTMgrContextEnum16(HMGR16 hMgr, WTENUMPROC16 lpEnumFunc, LPARAM lParam)
{
FIXME("(0x%04hx, %p, %ld): stub\n", hMgr, lpEnumFunc, lParam);
return FALSE;
}
/***********************************************************************
* WTMgrContextOwner (WINTAB.121)
*/
HWND16 WINAPI WTMgrContextOwner16(HMGR16 hMgr, HCTX16 hCtx)
{
FIXME("(0x%04hx, 0x%04hx): stub\n", hMgr, hCtx);
return 0;
}
/***********************************************************************
* WTMgrDefContext (WINTAB.122)
*/
HCTX16 WINAPI WTMgrDefContext16(HMGR16 hMgr, BOOL16 fSystem)
{
FIXME("(0x%04hx, %hu): stub\n", hMgr, fSystem);
return 0;
}
/***********************************************************************
* WTMgrDefContextEx (WINTAB.206)
*
* 1.1
*/
HCTX16 WINAPI WTMgrDefContextEx16(HMGR16 hMgr, UINT16 wDevice, BOOL16 fSystem)
{
FIXME("(0x%04hx, %hu, %hu): stub\n", hMgr, wDevice, fSystem);
return 0;
}
/***********************************************************************
* WTMgrDeviceConfig (WINTAB.140)
*/
UINT16 WINAPI WTMgrDeviceConfig16(HMGR16 hMgr, UINT16 wDevice, HWND16 hWnd)
{
FIXME("(0x%04hx, %hu, 0x%04hx): stub\n", hMgr, wDevice, hWnd);
return 0;
}
/***********************************************************************
* WTMgrConfigReplace (WINTAB.141)
*
* OBSOLETE IN WIN32!
*/
BOOL16 WINAPI WTMgrConfigReplace16(HMGR16 hMgr, BOOL16 fInstall,
WTCONFIGPROC16 lpConfigProc)
{
FIXME("(0x%04hx, %hu, %p): stub\n", hMgr, fInstall, lpConfigProc);
return FALSE;
}
/***********************************************************************
* WTMgrConfigReplaceEx (WINTAB.202)
*/
BOOL16 WINAPI WTMgrConfigReplaceEx16(HMGR16 hMgr, BOOL16 fInstall,
LPSTR lpszModule, LPSTR lpszCfgProc)
{
FIXME("(0x%04hx, %hu, %s, %s): stub\n", hMgr, fInstall,
debugstr_a(lpszModule), debugstr_a(lpszCfgProc));
return FALSE;
}
/***********************************************************************
* WTMgrPacketHook (WINTAB.160)
*
* OBSOLETE IN WIN32!
*/
WTHOOKPROC16 WINAPI WTMgrPacketHook16(HMGR16 hMgr, BOOL16 fInstall,
INT16 nType, WTHOOKPROC16 lpFunc)
{
FIXME("(0x%04hx, %hu, %hd, %p): stub\n", hMgr, fInstall, nType, lpFunc);
return 0;
}
/***********************************************************************
* WTMgrPacketHookEx (WINTAB.203)
*/
HWTHOOK16 WINAPI WTMgrPacketHookEx16(HMGR16 hMgr, INT16 nType,
LPSTR lpszModule, LPSTR lpszHookProc)
{
FIXME("(0x%04hx, %hd, %s, %s): stub\n", hMgr, nType,
debugstr_a(lpszModule), debugstr_a(lpszHookProc));
return 0;
}
/***********************************************************************
* WTMgrPacketUnhook (WINTAB.204)
*/
BOOL16 WINAPI WTMgrPacketUnhook16(HWTHOOK16 hHook)
{
FIXME("(0x%04hx): stub\n", hHook);
return FALSE;
}
/***********************************************************************
* WTMgrPacketHookDefProc (WINTAB.161)
*
* OBSOLETE IN WIN32!
*/
LRESULT WINAPI WTMgrPacketHookDefProc16(INT16 nCode, WPARAM16 wParam,
LPARAM lParam, LPWTHOOKPROC16 lplpFunc)
{
FIXME("(%hd, %hu, %lu, %p): stub\n", nCode, wParam, lParam, lplpFunc);
return 0;
}
/***********************************************************************
* WTMgrPacketHookNext (WINTAB.205)
*/
LRESULT WINAPI WTMgrPacketHookNext16(HWTHOOK16 hHook, INT16 nCode,
WPARAM16 wParam, LPARAM lParam)
{
FIXME("(0x%04hx, %hd, %hu, %lu): stub\n", hHook, nCode, wParam, lParam);
return 0;
}
/***********************************************************************
* WTMgrExt (WINTAB.180)
*/
BOOL16 WINAPI WTMgrExt16(HMGR16 hMgr, UINT16 wExt, LPVOID lpData)
{
FIXME("(0x%04hx, %hu, %p): stub\n", hMgr, wExt, lpData);
return FALSE;
}
/***********************************************************************
* WTMgrCsrEnable (WINTAB.181)
*/
BOOL16 WINAPI WTMgrCsrEnable16(HMGR16 hMgr, UINT16 wCursor, BOOL16 fEnable)
{
FIXME("(0x%04hx, %hu, %hu): stub\n", hMgr, wCursor, fEnable);
return FALSE;
}
/***********************************************************************
* WTMgrCsrButtonMap (WINTAB.182)
*/
BOOL16 WINAPI WTMgrCsrButtonMap16(HMGR16 hMgr, UINT16 wCursor,
LPBYTE lpLogBtns, LPBYTE lpSysBtns)
{
FIXME("(0x%04hx, %hu, %p, %p): stub\n", hMgr, wCursor, lpLogBtns, lpSysBtns);
return FALSE;
}
/***********************************************************************
* WTMgrCsrPressureBtnMarks (WINTAB.183)
*
* OBSOLETE IN WIN32! (But only according to documentation)
*/
BOOL16 WINAPI WTMgrCsrPressureBtnMarks16(HMGR16 hMgr, UINT16 wCsr,
DWORD dwNMarks, DWORD dwTMarks)
{
FIXME("(0x%04hx, %hu, %u, %u): stub\n", hMgr, wCsr, dwNMarks, dwTMarks);
return FALSE;
}
/***********************************************************************
* WTMgrCsrPressureBtnMarksEx (WINTAB.201)
*/
BOOL16 WINAPI WTMgrCsrPressureBtnMarksEx16(HMGR16 hMgr, UINT16 wCsr,
UINT16 *lpNMarks, UINT16 *lpTMarks)
{
FIXME("(0x%04hx, %hu, %p, %p): stub\n", hMgr, wCsr, lpNMarks, lpTMarks);
return FALSE;
}
/***********************************************************************
* WTMgrCsrPressureResponse (WINTAB.184)
*/
BOOL16 WINAPI WTMgrCsrPressureResponse16(HMGR16 hMgr, UINT16 wCsr,
UINT16 *lpNResp, UINT16 *lpTResp)
{
FIXME("(0x%04hx, %hu, %p, %p): stub\n", hMgr, wCsr, lpNResp, lpTResp);
return FALSE;
}
/***********************************************************************
* WTMgrCsrExt (WINTAB.185)
*/
BOOL16 WINAPI WTMgrCsrExt16(HMGR16 hMgr, UINT16 wCsr, UINT16 wExt, LPVOID lpData)
{
FIXME("(0x%04hx, %hu, %hu, %p): stub\n", hMgr, wCsr, wExt, lpData);
return FALSE;
}
|
baotiao/zeppelin-gateway | src/s3_cmds/zgw_s3_uploadpart.cc | #include "src/s3_cmds/zgw_s3_object.h"
#include "slash/include/env.h"
#include "src/zgwstore/zgw_define.h"
#include "src/s3_cmds/zgw_s3_xml.h"
bool UploadPartCmd::DoInitial() {
http_response_xml_.clear();
md5_ctx_.Init();
size_t data_size = std::stoul(req_headers_["content-length"]);
size_t m = data_size % zgwstore::kZgwBlockSize;
block_count_ = data_size / zgwstore::kZgwBlockSize + (m > 0 ? 1 : 0);
std::string upload_id = query_params_.at("uploadId");
std::string part_number = query_params_.at("partNumber");
std::string virtual_bucket = "__TMPB" + upload_id +
bucket_name_ + "|" + object_name_;
request_id_ = md5(bucket_name_ +
object_name_ +
upload_id +
part_number +
std::to_string(slash::NowMicros()));
if (!TryAuth()) {
DLOG(INFO) << request_id_ << " " <<
"UploadPart(DoInitial) - Auth failed: " << client_ip_port_;
g_zgw_monitor->AddAuthFailed();
return false;
}
DLOG(INFO) << request_id_ << " " <<
"UploadPart(DoInitial) - " << virtual_bucket <<
" part_number: " << part_number;
// Initial new_object_part_
new_object_part_.bucket_name = virtual_bucket;
new_object_part_.object_name = part_number;
new_object_part_.etag = ""; // Postpone
new_object_part_.size = data_size;
new_object_part_.owner = user_name_;
new_object_part_.last_modified = 0; // Postpone
new_object_part_.storage_class = 0; // Unused
new_object_part_.acl = "FULL_CONTROL";
new_object_part_.upload_id = upload_id;
new_object_part_.data_block = ""; // Postpone
std::string data_blocks;
Status s = store_->AllocateId(user_name_, virtual_bucket, part_number,
block_count_, &block_end_);
if (s.ok()) {
block_start_ = block_end_ - block_count_;
http_ret_code_ = 200;
char buf[100];
sprintf(buf, "%lu-%lu(0,%lu)", block_start_, block_end_ - 1, data_size);
new_object_part_.data_block.assign(buf);
DLOG(INFO) << request_id_ << " " <<
"UploadPart(DoInitial) - AllocateId: " << buf;
} else if (s.ToString().find("Bucket NOT Exists") != std::string::npos ||
s.ToString().find("Bucket Doesn't Belong To This User") !=
std::string::npos) {
http_ret_code_ = 404;
GenerateErrorXml(kNoSuchUpload, upload_id);
return false;
} else {
http_ret_code_ = 500;
LOG(ERROR) << request_id_ << " " <<
"UploadPart(DoInitial) - AllocateId error: " << s.ToString();
return false;
}
return true;
}
// Data size from HTTP is 8MB per invocation, or smaller as the last
void UploadPartCmd::DoReceiveBody(const char* data, size_t data_size) {
if (http_ret_code_ != 200) {
return;
}
char* buf_pos = const_cast<char*>(data);
size_t remain_size = data_size;
while (remain_size > 0) {
if (block_start_ >= block_end_) {
// LOG WARNING
LOG(WARNING) << "PutObject Block error";
return;
}
size_t nwritten = std::min(remain_size, zgwstore::kZgwBlockSize);
status_ = store_->BlockSet(std::to_string(block_start_++),
std::string(buf_pos, nwritten));
if (status_.ok()) {
md5_ctx_.Update(buf_pos, nwritten);
g_zgw_monitor->AddBucketTraffic(bucket_name_, nwritten);
} else {
http_ret_code_ = 500;
LOG(ERROR) << request_id_ << " " <<
"UploadPart(DoReceiveBody) - BlockSet error: " << status_.ToString();
// TODO (gaodq) delete data already saved
}
remain_size -= nwritten;
buf_pos += nwritten;
}
}
void UploadPartCmd::DoAndResponse(pink::HTTPResponse* resp) {
if (http_ret_code_ == 200) {
if (!status_.ok()) {
// Error happend while transmiting to zeppelin
http_ret_code_ = 500;
LOG(ERROR) << request_id_ << " " <<
"UploadPart(DoAndResponse) - BlockSet error: " << status_.ToString();
} else {
// Write meta
new_object_part_.etag = md5_ctx_.ToString();
DLOG(INFO) << request_id_ << " " <<
"UploadPart(DoAndResponse) - MD5: " << new_object_part_.etag;
if (new_object_part_.etag.empty()) {
new_object_part_.etag = "_";
}
new_object_part_.last_modified = slash::NowMicros();
DLOG(INFO) << request_id_ << " " <<
"UploadPart(DoAndResponse) - Lock success";
status_ = store_->AddObject(new_object_part_);
if (!status_.ok()) {
http_ret_code_ = 500;
LOG(ERROR) << request_id_ << " " <<
"UploadPart(DoAndResponse) - AddObject error: " << status_.ToString();
} else {
DLOG(INFO) << request_id_ << " " <<
"UploadPart(DoAndResponse) - UnLock success";
resp->SetHeaders("Last-Modified", http_nowtime(new_object_part_.last_modified));
resp->SetHeaders("ETag", "\"" + new_object_part_.etag + "\"");
}
}
}
g_zgw_monitor->AddApiRequest(kUploadPart, http_ret_code_);
resp->SetStatusCode(http_ret_code_);
resp->SetContentLength(http_response_xml_.size());
}
int UploadPartCmd::DoResponseBody(char* buf, size_t max_size) {
if (max_size < http_response_xml_.size()) {
memcpy(buf, http_response_xml_.data(), max_size);
http_response_xml_.assign(http_response_xml_.substr(max_size));
} else {
memcpy(buf, http_response_xml_.data(), http_response_xml_.size());
}
return std::min(max_size, http_response_xml_.size());
}
|
VinceW0/Leetcode_Python_solutions | Algorithms_easy/1708. Largest Subarray Length K.py | <filename>Algorithms_easy/1708. Largest Subarray Length K.py<gh_stars>1-10
"""
1708. Largest Subarray Length K
Easy
An array A is larger than some array B if for the first index i where A[i] != B[i], A[i] > B[i].
For example, consider 0-indexing:
[1,3,2,4] > [1,2,2,4], since at index 1, 3 > 2.
[1,4,4,4] < [2,1,1,1], since at index 0, 1 < 2.
A subarray is a contiguous subsequence of the array.
Given an integer array nums of distinct integers, return the largest subarray of nums of length k.
Example 1:
Input: nums = [1,4,5,2,3], k = 3
Output: [5,2,3]
Explanation: The subarrays of size 3 are: [1,4,5], [4,5,2], and [5,2,3].
Of these, [5,2,3] is the largest.
Example 2:
Input: nums = [1,4,5,2,3], k = 4
Output: [4,5,2,3]
Explanation: The subarrays of size 4 are: [1,4,5,2], and [4,5,2,3].
Of these, [4,5,2,3] is the largest.
Example 3:
Input: nums = [1,4,5,2,3], k = 1
Output: [5]
Constraints:
1 <= k <= nums.length <= 105
1 <= nums[i] <= 109
All the integers of nums are unique.
Follow up: What if the integers in nums are not distinct?
"""
class Solution:
def largestSubarray(self, nums: List[int], k: int) -> List[int]:
mmax = max(nums[:len(nums)-k+1])
idx = nums.index(mmax)
return nums[idx: idx + k]
|
Ren0503/javascript-algorithms | src/algorithms/sorting/radix-sort/RadixSort.js | import Sort from '../Sort';
// Sử dụng charCode (a = 97, b = 98, v.v.), ta có thể ánh xạ ký tự thành các nhóm từ 0 - 25
const BASE_CHAR_CODE = 97;
const NUMBER_OF_POSSIBLE_DIGITS = 10;
const ENGLISH_ALPHABET_LENGTH = 26;
export default class RadixSort extends Sort {
/**
* @param {*[]} originalArray
* @return {*[]}
*/
sort(originalArray) {
// Giả sử tất cả các phần tử của mảng có cùng kiểu
const isArrayOfNumbers = this.isArrayOfNumbers(originalArray);
let sortedArray = [...originalArray];
const numPasses = this.determineNumPasses(sortedArray);
for (let currentIndex = 0; currentIndex < numPasses; currentIndex += 1) {
const buckets = isArrayOfNumbers
? this.placeElementsInNumberBuckets(sortedArray, currentIndex)
: this.placeElementsInCharacterBuckets(sortedArray, currentIndex, numPasses);
// Làm bẹt các bucket thành sortedArray và lặp lại ở chỉ mục tiếp theo
sortedArray = buckets.reduce((acc, val) => {
return [...acc, ...val];
}, []);
}
return sortedArray;
}
/**
* @param {*[]} array
* @param {number} index
* @return {*[]}
*/
placeElementsInNumberBuckets(array, index) {
// Xem bên dưới. Chúng được sử dụng để xác định chữ số nào sẽ sử dụng để phân bổ bucket
const modded = 10 ** (index + 1);
const divided = 10 ** index;
const buckets = this.createBuckets(NUMBER_OF_POSSIBLE_DIGITS);
array.forEach((element) => {
this.callbacks.visitingCallback(element);
if (element < divided) {
buckets[0].push(element);
} else {
/**
* Giả sử ta có phần tử là 1,052 và hiện đang ở chỉ mục 1 (bắt đầu từ 0).
* Điều này có nghĩa là ta sử dụng '5' làm nhóm. `modded` sẽ là 10 ** (1 + 1), là 100.
* Vì vậy, ta lấy 1,052% 100 (52) và chia nó cho 10 (5,2) và làm tròn nó (5).
*/
const currentDigit = Math.floor((element % modded) / divided);
buckets[currentDigit].push(element);
}
});
return buckets;
}
/**
* @param {*[]} array
* @param {number} index
* @param {number} numPasses
* @return {*[]}
*/
placeElementsInCharacterBuckets(array, index, numPasses) {
const buckets = this.createBuckets(ENGLISH_ALPHABET_LENGTH);
array.forEach((element) => {
this.callbacks.visitingCallback(element);
const currentBucket = this.getCharCodeOfElementAtIndex(element, index, numPasses);
buckets[currentBucket].push(element);
});
return buckets;
}
/**
* @param {string} element
* @param {number} index
* @param {number} numPasses
* @return {number}
*/
getCharCodeOfElementAtIndex(element, index, numPasses) {
// Đặt phần tử vào bucket cuối cùng nếu chưa sẵn sàng để sắp xếp.
if ((numPasses - index) > element.length) {
return ENGLISH_ALPHABET_LENGTH - 1;
}
/**
* Nếu mỗi ký tự đã được sắp xếp, hãy sử dụng ký tự đầu tiên để xác định bucket,
* nếu không thì lặp lại qua các phần tử.
*/
const charPos = index > element.length - 1 ? 0 : element.length - index - 1;
return element.toLowerCase().charCodeAt(charPos) - BASE_CHAR_CODE;
}
/**
* Số lần vượt qua được xác định bởi độ dài của phần tử dài nhất trong mảng.
* Đối với số nguyên, là log10(num) và đối với chuỗi, sẽ là độ dài của chuỗi.
*/
determineNumPasses(array) {
return this.getLengthOfLongestElement(array);
}
/**
* @param {*[]} array
* @return {number}
*/
getLengthOfLongestElement(array) {
if (this.isArrayOfNumbers(array)) {
return Math.floor(Math.log10(Math.max(...array))) + 1;
}
return array.reduce((acc, val) => {
return val.length > acc ? val.length : acc;
}, -Infinity);
}
/**
* @param {*[]} array
* @return {boolean}
*/
isArrayOfNumbers(array) {
// Giả sử tất cả các phần tử của mảng có cùng kiểu
return this.isNumber(array[0]);
}
/**
* @param {number} numBuckets
* @return {*[]}
*/
createBuckets(numBuckets) {
/**
* Việc ánh xạ các bucket vào một mảng thay vì lấp đầy chúng bằng một mảng,
* nhằm ngăn không cho mỗi bucket chứa một tham chiếu đến cùng một mảng.
*/
return new Array(numBuckets).fill(null).map(() => []);
}
/**
* @param {*} element
* @return {boolean}
*/
isNumber(element) {
return Number.isInteger(element);
}
}
|
LeandroTk/Algorithms | coding_interviews/interviews/uber/maxFrequency.js | export function maxFrequency(numbers) {
let maxFrequencyNumber = -1;
let result = -1;
let numberToFrequencyMap = {};
for (let num of numbers) {
if (numberToFrequencyMap[num]) {
numberToFrequencyMap[num]++;
} else {
numberToFrequencyMap[num] = 1;
}
}
Object.entries(numberToFrequencyMap).forEach(([num, frequency]) => {
if (frequency > maxFrequencyNumber) {
maxFrequencyNumber = frequency;
result = Number(num);
}
});
return result;
}
|
niranjan21/skt | public/modules/yarn-returns/services/yarn-returns.client.service.js | 'use strict';
//Yarn returns service used to communicate Yarn returns REST endpoints
angular.module('yarn-returns').factory('YarnReturns', ['$resource',
function($resource) {
return $resource('yarn-returns/:yarnReturnId', { yarnReturnId: '@_id'
}, {
update: {
method: 'PUT'
}
});
}
]); |
xv44586/toolkit4nlp | examples/classification_tnews_contrastive_learning_dropout.py | """
用dropout 做数据增强,构造样本的不同view,来通过增加对比学习增强分类模型的性能
"""
import json
from tqdm import tqdm
from toolkit4nlp.backend import keras, K
from toolkit4nlp.tokenizers import Tokenizer, load_vocab
from toolkit4nlp.models import build_transformer_model, Model
from toolkit4nlp.optimizers import *
from toolkit4nlp.utils import pad_sequences, DataGenerator
from toolkit4nlp.layers import *
from keras.losses import kullback_leibler_divergence as kld
num_classes = 16
maxlen = 64
batch_size = 72
epochs = 5
# BERT base
config_path = '/data/pretrain/chinese_L-12_H-768_A-12/bert_config.json'
checkpoint_path = '/data/pretrain/chinese_L-12_H-768_A-12/bert_model.ckpt'
dict_path = '/data/pretrain/chinese_L-12_H-768_A-12/vocab.txt'
def load_data(filename):
D = []
with open(filename) as f:
for i, l in enumerate(f):
l = json.loads(l)
text, label, label_des = l['sentence'], l['label'], l['label_desc']
label = int(label) - 100 if int(label) < 105 else int(label) - 101
D.append((text, int(label), label_des))
return D
# 加载数据集
train_data = load_data(
'/data/datasets/NLP/CLUE/tnews_public/train.json'
)
valid_data = load_data(
'/data/datasets/NLP/CLUE/tnews_public/dev.json'
)
# 加载并精简词表,建立分词器
token_dict, keep_tokens = load_vocab(
vocab_path=dict_path,
simplified=True,
startswith=['[PAD]', '[UNK]', '[CLS]', '[SEP]'],
)
tokenizer = Tokenizer(token_dict, do_lower_case=True)
class data_generator(DataGenerator):
"""数据生成器
"""
def __iter__(self, shuffle=False):
batch_token_ids, batch_segment_ids, batch_labels = [], [], []
for is_end, (text, label, label_des) in self.get_sample(shuffle):
token_ids, segment_ids = tokenizer.encode(text, maxlen=maxlen)
for i in range(2):
batch_token_ids.append(token_ids)
batch_segment_ids.append(segment_ids)
batch_labels.append([label])
if len(batch_token_ids) == self.batch_size * 2 or is_end:
batch_token_ids = pad_sequences(batch_token_ids)
batch_segment_ids = pad_sequences(batch_segment_ids)
batch_labels = pad_sequences(batch_labels)
yield [batch_token_ids, batch_segment_ids, batch_labels], None
batch_token_ids, batch_segment_ids, batch_labels = [], [], []
# 转换数据集
train_generator = data_generator(data=train_data, batch_size=batch_size)
valid_generator = data_generator(data=valid_data, batch_size=batch_size)
class TotalLoss(Loss):
"计算两部分loss:分类交叉熵和对比loss"
def compute_loss(self, inputs, mask=None):
loss = self.compute_loss_of_classification(inputs)
sim_loss = self.compute_loss_of_similarity(inputs)
return loss + sim_loss
def compute_loss_of_classification(self, inputs, mask=None):
_, _, y_true, _, y_pred = inputs
loss = K.sparse_categorical_crossentropy(y_true, y_pred, from_logits=True)
self.add_metric(loss, 'cls_loss')
return loss
def compute_loss_of_similarity(self, inputs, mask=None):
# _, _, _, y_pred, _ = inputs
_, _, _, _, y_pred = inputs # use last layer's logits
y_true = self.get_labels_of_similarity(y_pred) # 构建标签
y_pred = K.l2_normalize(y_pred, axis=1) # 句向量归一化
similarities = K.dot(y_pred, K.transpose(y_pred)) # 相似度矩阵
similarities = similarities - K.eye(K.shape(y_pred)[0]) * 1e12 # 排除对角线
similarities = similarities * 20 # scale
loss = K.categorical_crossentropy(
y_true, similarities, from_logits=True
)
self.add_metric(loss, 'sim_loss')
return loss
def get_labels_of_similarity(self, y_pred):
idxs = K.arange(0, K.shape(y_pred)[0])
idxs_1 = idxs[None, :]
idxs_2 = (idxs + 1 - idxs % 2 * 2)[:, None]
labels = K.equal(idxs_1, idxs_2)
labels = K.cast(labels, K.floatx())
return labels
def compute_kld(self, inputs, alpha=4, mask=None):
_, _, _, y_pred = inputs
loss = kld(y_pred[::2], y_pred[1::2]) + kld(y_pred[1::2], y_pred[::2])
loss = K.mean(loss) / 4 * alpha
self.add_metric(loss, 'kld')
return loss
bert = build_transformer_model(checkpoint_path=checkpoint_path,
config_path=config_path,
keep_tokens=keep_tokens,
dropout_rate=0.3,
)
label_inputs = Input(shape=(None,), name='label_inputs')
pooler = Lambda(lambda x: x[:, 0])(bert.output)
x = Dense(units=num_classes, activation='softmax', name='classifier')(pooler)
output = TotalLoss(4)(bert.inputs + [label_inputs, pooler, x])
model = Model(bert.inputs + [label_inputs], output)
classifier = Model(bert.inputs, x)
model.compile(optimizer=Adam(2e-5), metrics=['acc'])
model.summary()
def evaluate(val_data=valid_generator):
total = 0.
right = 0.
for (x, s, y_true), _ in tqdm(val_data):
y_pred = classifier.predict([x, s]).argmax(axis=-1)
y_true = y_true[:, 0]
total += len(y_true)
right += (y_true == y_pred).sum()
print(total, right)
return right / total
class Evaluator(keras.callbacks.Callback):
def __init__(self, save_path='best_model.weights'):
self.best_val_acc = 0.
self.save_path = save_path
def on_epoch_end(self, epoch, logs=None):
val_acc = evaluate()
if val_acc > self.best_val_acc:
self.best_val_acc = val_acc
self.model.save_weights(self.save_path)
print('current acc :{}, best val acc: {}'.format(val_acc, self.best_val_acc))
if __name__ == '__main__':
evaluator = Evaluator()
model.fit_generator(train_generator.generator(),
steps_per_epoch=len(train_generator),
epochs=epochs,
callbacks=[evaluator]) |
tamlyn/substance | packages/image/ImageComponent.js | import NodeComponent from '../../ui/NodeComponent'
class ImageComponent extends NodeComponent {
didMount() {
super.didMount.call(this)
this.context.editorSession.onRender('document', this._onDocumentChange, this)
}
dispose() {
super.dispose.call(this)
this.context.editorSession.off(this)
}
// TODO: verify if this check is correct and efficient
_onDocumentChange(change) {
if (change.hasUpdated(this.props.node.id) ||
change.hasUpdated(this.props.node.imageFile)) {
this.rerender()
}
}
render($$) {
let el = super.render($$)
el.addClass('sc-image')
el.append(
$$('img').attr({
src: this.props.node.getUrl(),
}).ref('image')
)
return el
}
/* Custom dropzone protocol */
getDropzoneSpecs() {
return [
{
component: this.refs['image'],
message: 'Replace Image',
dropParams: {
action: 'replace-image',
nodeId: this.props.node.id,
}
}
]
}
handleDrop(tx, dragState) {
let newImageFile = dragState.data.files[0]
if (dragState.external) {
let imageFile = tx.create({
type: 'file',
fileType: 'image',
mimeType: newImageFile.type,
url: URL.createObjectURL(newImageFile)
})
// TODO: we should delete the old image file if there are no
// referenecs to it anymore
tx.set([this.props.node.id, 'imageFile'], imageFile.id)
} else {
let nodeId = dragState.sourceSelection.nodeId
let node = tx.get(nodeId)
if (node.type === 'image') {
// Use the same filenode as the dragged source node
tx.set([this.props.node.id, 'imageFile'], node.imageFile)
}
}
}
}
export default ImageComponent
|
mikiec84/sbt | main-settings/src/main/scala/sbt/ScopeAxis.scala | /*
* sbt
* Copyright 2011 - 2018, Lightbend, Inc.
* Copyright 2008 - 2010, <NAME>
* Licensed under Apache License 2.0 (see LICENSE)
*/
package sbt
import sbt.internal.util.Types.some
sealed trait ScopeAxis[+S] {
def foldStrict[T](f: S => T, ifZero: T, ifThis: T): T = fold(f, ifZero, ifThis)
def fold[T](f: S => T, ifZero: => T, ifThis: => T): T = this match {
case This => ifThis
case Zero => ifZero
case Select(s) => f(s)
}
def toOption: Option[S] = foldStrict(some.fn, None, None)
def map[T](f: S => T): ScopeAxis[T] = foldStrict(s => Select(f(s)), Zero, This)
def isSelect: Boolean = false
}
/**
* This is a scope component that represents not being
* scoped by the user, which later could be further scoped automatically
* by sbt.
*/
case object This extends ScopeAxis[Nothing]
/**
* Zero is a scope component that represents not scoping.
* It is a universal fallback component that is strictly weaker
* than any other values on a scope axis.
*/
case object Zero extends ScopeAxis[Nothing]
/**
* Select is a type constructor that is used to wrap type `S`
* to make a scope component, equivalent of Some in Option.
*/
final case class Select[S](s: S) extends ScopeAxis[S] {
override def isSelect = true
}
object ScopeAxis {
def fromOption[T](o: Option[T]): ScopeAxis[T] = o match {
case Some(v) => Select(v)
case None => Zero
}
}
|
DLQ666/MI-Mall | mi-seckill/src/main/java/com/dlq/seckill/feign/CouponFeignService.java | <reponame>DLQ666/MI-Mall<filename>mi-seckill/src/main/java/com/dlq/seckill/feign/CouponFeignService.java
package com.dlq.seckill.feign;
import com.dlq.common.utils.R;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
/**
*@program: MI-Mall
*@description:
*@author: Hasee
*@create: 2021-03-01 14:25
*/
@FeignClient("mi-coupon")
public interface CouponFeignService {
@GetMapping("/coupon/seckillsession/latest3DaySession")
R getLatest3DaySession();
}
|
lulitao1997/minijavac | src/utils.cpp | <gh_stars>0
#include "utils.hpp"
#include <sstream>
using namespace std;
int error_num;
vector<string> lines;
static const char *reds = "\033[1;31m", *rede = "\033[0m";
static vector<ostringstream> msgs;
static vector<yy::location> locs;
std::ostream &complain(yy::location loc) {
// return std::cerr << loc << ", ";
error_num++;
locs.push_back(loc);
msgs.emplace_back();
return *msgs.rbegin();
// cerr << reds << "ERROR: " << rede << loc << ": " << endl << lines[loc.begin.line] << reds << string(' ', start) << rede << endl;
}
void output_error() {
int idx = 0;
for (const auto &s: locs) {
int start = s.begin.column, end = (s.begin.line == s.end.line ? s.end.column : lines[s.begin.line].size());
cerr << s << reds << " ERROR: " << rede << msgs[idx++].str();
if (!start || !end || (end-start) < 1) continue;
cerr
<< lines[s.begin.line-1]
<< reds << string(start-1, ' ') << string(end-start, '^') << rede << endl;
}
} |
moutainhigh/ses-server | ses-app/ses-web-ros/src/main/java/com/redescooter/ses/web/ros/service/assign/impl/ToBeAssignServiceImpl.java | <gh_stars>0
package com.redescooter.ses.web.ros.service.assign.impl;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.redescooter.ses.api.common.constant.Constant;
import com.redescooter.ses.api.common.enums.assign.FactoryEnum;
import com.redescooter.ses.api.common.enums.assign.ProductTypeEnum;
import com.redescooter.ses.api.common.enums.assign.ScooterTypeEnum;
import com.redescooter.ses.api.common.enums.assign.YearEnum;
import com.redescooter.ses.api.common.enums.customer.CustomerStatusEnum;
import com.redescooter.ses.api.common.enums.customer.CustomerTypeEnum;
import com.redescooter.ses.api.common.enums.date.DayCodeEnum;
import com.redescooter.ses.api.common.enums.date.MonthCodeEnum;
import com.redescooter.ses.api.common.enums.scooter.ScooterModelEnum;
import com.redescooter.ses.api.common.enums.scooter.ScooterModelEnums;
import com.redescooter.ses.api.common.enums.scooter.ScooterStatusEnums;
import com.redescooter.ses.api.common.enums.wms.WmsStockStatusEnum;
import com.redescooter.ses.api.common.vo.base.BooleanResult;
import com.redescooter.ses.api.common.vo.base.GeneralEnter;
import com.redescooter.ses.api.common.vo.base.GeneralResult;
import com.redescooter.ses.api.common.vo.base.PageResult;
import com.redescooter.ses.api.common.vo.base.StringEnter;
import com.redescooter.ses.api.common.vo.scooter.ColorDTO;
import com.redescooter.ses.api.common.vo.scooter.SpecificGroupDTO;
import com.redescooter.ses.api.common.vo.scooter.SyncScooterDataDTO;
import com.redescooter.ses.api.foundation.service.base.AccountBaseService;
import com.redescooter.ses.api.foundation.service.scooter.AssignScooterService;
import com.redescooter.ses.api.foundation.vo.tenant.QueryAccountResult;
import com.redescooter.ses.api.hub.service.admin.ScooterModelService;
import com.redescooter.ses.api.hub.service.corporate.CorporateScooterService;
import com.redescooter.ses.api.hub.service.customer.CusotmerScooterService;
import com.redescooter.ses.api.hub.service.operation.ColorService;
import com.redescooter.ses.api.hub.service.operation.SpecificService;
import com.redescooter.ses.api.hub.vo.HubSaveScooterEnter;
import com.redescooter.ses.api.hub.vo.admin.AdmScooter;
import com.redescooter.ses.api.mobile.b.service.ScooterMobileBService;
import com.redescooter.ses.api.mobile.b.vo.CorDriver;
import com.redescooter.ses.api.mobile.b.vo.CorDriverScooter;
import com.redescooter.ses.api.scooter.service.ScooterService;
import com.redescooter.ses.api.scooter.vo.ScoScooterResult;
import com.redescooter.ses.starter.common.service.IdAppService;
import com.redescooter.ses.tool.utils.SesStringUtils;
import com.redescooter.ses.tool.utils.map.MapUtil;
import com.redescooter.ses.web.ros.constant.SequenceName;
import com.redescooter.ses.web.ros.dao.assign.OpeCarDistributeExMapper;
import com.redescooter.ses.web.ros.dao.assign.OpeCarDistributeMapper;
import com.redescooter.ses.web.ros.dao.assign.OpeCarDistributeNodeMapper;
import com.redescooter.ses.web.ros.dao.base.OpeColorMapper;
import com.redescooter.ses.web.ros.dao.base.OpeCustomerInquiryMapper;
import com.redescooter.ses.web.ros.dao.base.OpeCustomerMapper;
import com.redescooter.ses.web.ros.dao.base.OpeProductionScooterBomMapper;
import com.redescooter.ses.web.ros.dao.base.OpeSaleScooterMapper;
import com.redescooter.ses.web.ros.dao.base.OpeSpecificatTypeMapper;
import com.redescooter.ses.web.ros.dao.base.OpeWmsScooterStockMapper;
import com.redescooter.ses.web.ros.dao.base.OpeWmsStockRecordMapper;
import com.redescooter.ses.web.ros.dao.restproductionorder.OpeInWhouseOrderSerialBindMapper;
import com.redescooter.ses.web.ros.dao.wms.cn.china.OpeWmsStockSerialNumberMapper;
import com.redescooter.ses.web.ros.dm.OpeCarDistribute;
import com.redescooter.ses.web.ros.dm.OpeCarDistributeNode;
import com.redescooter.ses.web.ros.dm.OpeCodebaseRelation;
import com.redescooter.ses.web.ros.dm.OpeCodebaseRsn;
import com.redescooter.ses.web.ros.dm.OpeCodebaseVin;
import com.redescooter.ses.web.ros.dm.OpeColor;
import com.redescooter.ses.web.ros.dm.OpeCustomer;
import com.redescooter.ses.web.ros.dm.OpeCustomerInquiry;
import com.redescooter.ses.web.ros.dm.OpeCustomerInquiryB;
import com.redescooter.ses.web.ros.dm.OpeInWhouseOrderSerialBind;
import com.redescooter.ses.web.ros.dm.OpeProductionScooterBom;
import com.redescooter.ses.web.ros.dm.OpeSaleScooter;
import com.redescooter.ses.web.ros.dm.OpeSimInformation;
import com.redescooter.ses.web.ros.dm.OpeSpecificatType;
import com.redescooter.ses.web.ros.dm.OpeWmsScooterStock;
import com.redescooter.ses.web.ros.dm.OpeWmsStockRecord;
import com.redescooter.ses.web.ros.dm.OpeWmsStockSerialNumber;
import com.redescooter.ses.web.ros.enums.assign.CustomerFormEnum;
import com.redescooter.ses.web.ros.enums.assign.IndustryTypeEnum;
import com.redescooter.ses.web.ros.enums.distributor.DelStatusEnum;
import com.redescooter.ses.web.ros.exception.ExceptionCodeEnums;
import com.redescooter.ses.web.ros.exception.SesWebRosException;
import com.redescooter.ses.web.ros.service.assign.ToBeAssignService;
import com.redescooter.ses.web.ros.service.base.OpeCodebaseRelationService;
import com.redescooter.ses.web.ros.service.base.OpeCodebaseRsnService;
import com.redescooter.ses.web.ros.service.base.OpeCodebaseVinService;
import com.redescooter.ses.web.ros.service.base.OpeCustomerInquiryBService;
import com.redescooter.ses.web.ros.service.base.OpeWmsStockSerialNumberService;
import com.redescooter.ses.web.ros.service.sim.OpeSimInformationService;
import com.redescooter.ses.web.ros.vo.assign.done.enter.AssignedListEnter;
import com.redescooter.ses.web.ros.vo.assign.tobe.enter.CustomerIdEnter;
import com.redescooter.ses.web.ros.vo.assign.tobe.enter.ToBeAssignInputBatteryDetailEnter;
import com.redescooter.ses.web.ros.vo.assign.tobe.enter.ToBeAssignInputBatteryEnter;
import com.redescooter.ses.web.ros.vo.assign.tobe.enter.ToBeAssignLicensePlateNextDetailEnter;
import com.redescooter.ses.web.ros.vo.assign.tobe.enter.ToBeAssignLicensePlateNextEnter;
import com.redescooter.ses.web.ros.vo.assign.tobe.enter.ToBeAssignListEnter;
import com.redescooter.ses.web.ros.vo.assign.tobe.enter.ToBeAssignSeatNextDetailEnter;
import com.redescooter.ses.web.ros.vo.assign.tobe.enter.ToBeAssignSeatNextEnter;
import com.redescooter.ses.web.ros.vo.assign.tobe.enter.ToBeAssignSubmitDetailEnter;
import com.redescooter.ses.web.ros.vo.assign.tobe.enter.ToBeAssignSubmitEnter;
import com.redescooter.ses.web.ros.vo.assign.tobe.result.ToBeAssignColorResult;
import com.redescooter.ses.web.ros.vo.assign.tobe.result.ToBeAssignDetailCustomerInfoResult;
import com.redescooter.ses.web.ros.vo.assign.tobe.result.ToBeAssignDetailResult;
import com.redescooter.ses.web.ros.vo.assign.tobe.result.ToBeAssignDetailScooterInfoResult;
import com.redescooter.ses.web.ros.vo.assign.tobe.result.ToBeAssignDetailScooterInfoSubResult;
import com.redescooter.ses.web.ros.vo.assign.tobe.result.ToBeAssignListResult;
import com.redescooter.ses.web.ros.vo.assign.tobe.result.ToBeAssignNodeResult;
import com.redescooter.ses.web.ros.vo.assign.tobe.result.ToBeAssignNodeScooterInfoResult;
import com.redescooter.ses.web.ros.vo.assign.tobe.result.ToBeAssignNodeScooterInfoSubResult;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.JedisCluster;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @Description 车辆待分配ServiceImpl
* @Author Chris
* @Date 2020/12/27 14:50
*/
@Service
public class ToBeAssignServiceImpl implements ToBeAssignService {
private static final Logger logger = LoggerFactory.getLogger(ToBeAssignServiceImpl.class);
@Autowired
private OpeCarDistributeMapper opeCarDistributeMapper;
@Autowired
private OpeCarDistributeNodeMapper opeCarDistributeNodeMapper;
@Autowired
private OpeCarDistributeExMapper opeCarDistributeExMapper;
@Autowired
private OpeCustomerInquiryMapper opeCustomerInquiryMapper;
@Autowired
private OpeSaleScooterMapper opeSaleScooterMapper;
@Autowired
private OpeColorMapper opeColorMapper;
@Autowired
private OpeSpecificatTypeMapper opeSpecificatTypeMapper;
@Autowired
private OpeWmsScooterStockMapper opeWmsScooterStockMapper;
@Autowired
private OpeCustomerMapper opeCustomerMapper;
@Autowired
private OpeWmsStockRecordMapper opeWmsStockRecordMapper;
@Autowired
private OpeInWhouseOrderSerialBindMapper opeInWhouseOrderSerialBindMapper;
@Autowired
private OpeProductionScooterBomMapper opeProductionScooterBomMapper;
@Autowired
private OpeWmsStockSerialNumberMapper opeWmsStockSerialNumberMapper;
@Autowired
private OpeWmsStockSerialNumberService opeWmsStockSerialNumberService;
@Autowired
private OpeCustomerInquiryBService opeCustomerInquiryBService;
@Autowired
private OpeCodebaseVinService opeCodebaseVinService;
@Autowired
private OpeCodebaseRsnService opeCodebaseRsnService;
@Autowired
private OpeCodebaseRelationService opeCodebaseRelationService;
@DubboReference
private IdAppService idAppService;
@DubboReference
private AccountBaseService accountBaseService;
@DubboReference
private ScooterService scooterService;
@DubboReference
private CorporateScooterService corporateScooterService;
@DubboReference
private CusotmerScooterService cusotmerScooterService;
@DubboReference
private ScooterMobileBService scooterMobileBService;
@DubboReference
private AssignScooterService assignScooterService;
@Autowired
private JedisCluster jedisCluster;
@DubboReference
private ScooterModelService scooterModelService;
/**
* sim card
*/
@Autowired
private OpeSimInformationService simInformationService;
@DubboReference
private SpecificService specificService;
@DubboReference
private ColorService colorService;
/**
* 待分配列表
*/
@Override
public PageResult<ToBeAssignListResult> getToBeAssignList(ToBeAssignListEnter enter) {
logger.info("待分配列表的入参是:[{}]", enter);
SesStringUtils.objStringTrim(enter);
int count = opeCarDistributeExMapper.getToBeAssignListCount(enter);
if (count == 0) {
return PageResult.createZeroRowResult(enter);
}
List<ToBeAssignListResult> list = opeCarDistributeExMapper.getToBeAssignList(enter);
// 正式客户且点击了创建账号的才能流转到待分配列表
/*if (CollectionUtils.isNotEmpty(list)) {
Iterator<ToBeAssignListResult> iterator = list.iterator();
while (iterator.hasNext()) {
ToBeAssignListResult next = iterator.next();
String email = next.getEmail();
// 拿着email去pla_user表查询,如果存在,说明已创建账号 flag:存在就是true,不存在就是false
Boolean flag = assignScooterService.getPlaUserIsExistByEmail(email);
if (!flag) {
iterator.remove();
}
}
}*/
return PageResult.create(enter, count, list);
}
/**
* 待分配列表点击分配带出数据
*/
@Override
public ToBeAssignDetailResult getToBeAssignDetail(CustomerIdEnter enter) {
logger.info("待分配列表点击分配带出数据的入参是:[{}]", enter);
ToBeAssignDetailResult result = new ToBeAssignDetailResult();
// 查询该客户在node表是否存在,如果不存在,添加一条数据
LambdaQueryWrapper<OpeCarDistributeNode> nodeWrapper = new LambdaQueryWrapper<>();
nodeWrapper.eq(OpeCarDistributeNode::getDr, DelStatusEnum.VALID.getCode());
nodeWrapper.eq(OpeCarDistributeNode::getCustomerId, enter.getCustomerId());
List<OpeCarDistributeNode> nodeList = opeCarDistributeNodeMapper.selectList(nodeWrapper);
if (CollectionUtils.isEmpty(nodeList)) {
LambdaQueryWrapper<OpeCustomerInquiry> qw = new LambdaQueryWrapper<>();
qw.eq(OpeCustomerInquiry::getDr, Constant.DR_FALSE);
qw.eq(OpeCustomerInquiry::getCustomerId, enter.getCustomerId());
qw.last("limit 1");
OpeCustomerInquiry inquiry = opeCustomerInquiryMapper.selectOne(qw);
if (null == inquiry) {
throw new SesWebRosException(ExceptionCodeEnums.INQUIRY_IS_NOT_EXIST.getCode(), ExceptionCodeEnums.INQUIRY_IS_NOT_EXIST.getMessage());
}
Long productId = inquiry.getProductId();
OpeSaleScooter saleScooter = opeSaleScooterMapper.selectById(productId);
if (null == saleScooter) {
throw new SesWebRosException(ExceptionCodeEnums.SCOOTER_NOT_EXIST.getCode(), ExceptionCodeEnums.SCOOTER_NOT_EXIST.getMessage());
}
// 根据询价单id获得车辆型号id和颜色id
Long specificatId = saleScooter.getSpecificatId();
Long colorId = saleScooter.getColorId();
OpeCarDistributeNode node = new OpeCarDistributeNode();
node.setId(idAppService.getId(SequenceName.OPE_CAR_DISTRIBUTE_NODE));
node.setDr(DelStatusEnum.VALID.getCode());
node.setTenantId(enter.getTenantId());
node.setUserId(enter.getUserId());
node.setCustomerId(enter.getCustomerId());
node.setNode(1);
node.setAppNode(1);
node.setFlag(0);
node.setCreatedBy(enter.getUserId());
node.setCreatedTime(new Date());
opeCarDistributeNodeMapper.insert(node);
// 主表新增一条数据
OpeCarDistribute model = new OpeCarDistribute();
model.setId(idAppService.getId(SequenceName.OPE_CAR_DISTRIBUTE));
model.setDr(DelStatusEnum.VALID.getCode());
model.setTenantId(enter.getTenantId());
model.setUserId(enter.getUserId());
model.setCustomerId(enter.getCustomerId());
model.setSpecificatTypeId(specificatId);
model.setColorId(colorId);
model.setSeatNumber(2);
model.setQty(1);
model.setCreatedBy(enter.getUserId());
model.setCreatedTime(new Date());
opeCarDistributeMapper.insert(model);
}
// 客户信息
ToBeAssignDetailCustomerInfoResult customerInfo = opeCarDistributeExMapper.getCustomerInfo(enter.getCustomerId());
if (null == customerInfo) {
throw new SesWebRosException(ExceptionCodeEnums.CUSTOMER_NOT_EXIST.getCode(), ExceptionCodeEnums.CUSTOMER_NOT_EXIST.getMessage());
}
String customerType = customerInfo.getCustomerType();
String industryType = customerInfo.getIndustryType();
if (StringUtils.isNotBlank(customerType)) {
customerInfo.setCustomerTypeMsg(CustomerFormEnum.showMsg(customerType));
}
if (StringUtils.isNotBlank(industryType)) {
customerInfo.setIndustryTypeMsg(IndustryTypeEnum.showMsg(industryType));
}
// 得到询价单的产品id
LambdaQueryWrapper<OpeCustomerInquiry> opeCustomerInquiryWrapper = new LambdaQueryWrapper<>();
opeCustomerInquiryWrapper.eq(OpeCustomerInquiry::getDr, DelStatusEnum.VALID.getCode());
opeCustomerInquiryWrapper.eq(OpeCustomerInquiry::getCustomerId, enter.getCustomerId());
List<OpeCustomerInquiry> list = opeCustomerInquiryMapper.selectList(opeCustomerInquiryWrapper);
if (CollectionUtils.isEmpty(list)) {
throw new SesWebRosException(ExceptionCodeEnums.CUSTOMER_NOT_EXIST.getCode(), ExceptionCodeEnums.CUSTOMER_NOT_EXIST.getMessage());
}
List<ToBeAssignDetailScooterInfoResult> scooterList = Lists.newArrayList();
List<ToBeAssignDetailScooterInfoSubResult> subList = Lists.newArrayList();
for (OpeCustomerInquiry o : list) {
ToBeAssignDetailScooterInfoResult scooter = new ToBeAssignDetailScooterInfoResult();
ToBeAssignDetailScooterInfoSubResult sub = new ToBeAssignDetailScooterInfoSubResult();
Long productId = o.getProductId();
if (null == productId) {
throw new SesWebRosException(ExceptionCodeEnums.PRODUCT_IS_NOT_EXIST.getCode(), ExceptionCodeEnums.PRODUCT_IS_NOT_EXIST.getMessage());
}
// 拿着产品id去ope_sale_scooter查询
OpeSaleScooter opeSaleScooter = opeSaleScooterMapper.selectById(productId);
if (null == opeSaleScooter) {
throw new SesWebRosException(ExceptionCodeEnums.PRODUCT_IS_NOT_EXIST.getCode(), ExceptionCodeEnums.PRODUCT_IS_NOT_EXIST.getMessage());
}
// 得到型号id和颜色id
Long specificatId = opeSaleScooter.getSpecificatId();
Long colorId = opeSaleScooter.getColorId();
// 拿着型号id去ope_specificat_type查询
if (null != specificatId) {
String specificatName = getSpecificatNameById(specificatId);
scooter.setSpecificatId(specificatId);
scooter.setSpecificatName(specificatName);
}
// 拿着颜色id去ope_color查询
if (null != colorId) {
Map<String, String> map = getColorNameAndValueById(colorId);
sub.setColorName(map.get("colorName"));
sub.setColorValue(map.get("colorValue"));
sub.setColorId(colorId);
}
// 询价单电池数量
LambdaQueryWrapper<OpeCustomerInquiryB> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(OpeCustomerInquiryB::getDr, Constant.DR_FALSE);
wrapper.eq(OpeCustomerInquiryB::getInquiryId, o.getId());
wrapper.last("limit 1");
OpeCustomerInquiryB inquiryB = opeCustomerInquiryBService.getOne(wrapper);
if (null != inquiryB) {
sub.setBatteryNum(inquiryB.getProductQty());
}
sub.setToBeAssignCount(o.getScooterQuantity());
scooter.setTotalCount(o.getScooterQuantity());
subList.add(sub);
scooter.setScooterList(subList);
scooterList.add(scooter);
}
result.setCustomerInfo(customerInfo);
result.setTaskInfo(scooterList);
result.setRequestId(enter.getRequestId());
return result;
}
/**
* 填写完座位数点击下一步
*/
@Override
@GlobalTransactional(rollbackFor = Exception.class)
public GeneralResult getSeatNext(ToBeAssignSeatNextEnter enter) {
logger.info("填写完座位数点击下一步的入参是:[{}]", enter);
if (null == enter || StringUtils.isBlank(enter.getList())) {
throw new SesWebRosException(ExceptionCodeEnums.SEAT_NOT_EMPTY.getCode(), ExceptionCodeEnums.SEAT_NOT_EMPTY.getMessage());
}
// 解析
List<ToBeAssignSeatNextDetailEnter> list;
try {
list = JSONArray.parseArray(enter.getList(), ToBeAssignSeatNextDetailEnter.class);
} catch (Exception ex) {
throw new SesWebRosException(ExceptionCodeEnums.DATA_EXCEPTION.getCode(), ExceptionCodeEnums.DATA_EXCEPTION.getMessage());
}
if (CollectionUtils.isEmpty(list)) {
throw new SesWebRosException(ExceptionCodeEnums.DATA_EXCEPTION.getCode(), ExceptionCodeEnums.DATA_EXCEPTION.getMessage());
}
for (ToBeAssignSeatNextDetailEnter o : list) {
Long specificatId = o.getSpecificatId();
Integer seatNumber = o.getSeatNumber();
String vinCode = o.getVin().trim();
Integer qty = o.getQty();
// 生成VIN Code,只需车型名称和座位数量这两个变量
/*String vinCode = generateVINCode(specificatId, specificatName, seatNumber);
logger.info("生成的VIN Code是:[{}]", vinCode);*/
// 校验是否已被操作过
LambdaQueryWrapper<OpeCarDistribute> lqw = new LambdaQueryWrapper<>();
lqw.eq(OpeCarDistribute::getDr, Constant.DR_FALSE);
lqw.eq(OpeCarDistribute::getCustomerId, enter.getCustomerId());
lqw.last("limit 1");
OpeCarDistribute instance = opeCarDistributeMapper.selectOne(lqw);
if (null != instance) {
String vin = instance.getVinCode();
if (StringUtils.isNotBlank(vin)) {
throw new SesWebRosException(ExceptionCodeEnums.STEP_HAS_INPUT_IN_APP.getCode(), ExceptionCodeEnums.STEP_HAS_INPUT_IN_APP.getMessage());
}
}
if (vinCode.length() != 17) {
throw new SesWebRosException(ExceptionCodeEnums.VIN_NOT_MATCH.getCode(), ExceptionCodeEnums.VIN_NOT_MATCH.getMessage());
}
if (!vinCode.startsWith("VXSR2A")) {
throw new SesWebRosException(ExceptionCodeEnums.VIN_NOT_MATCH.getCode(), ExceptionCodeEnums.VIN_NOT_MATCH.getMessage());
}
// 根据车型id获得车型名称
OpeSpecificatType specificatType = opeSpecificatTypeMapper.selectById(specificatId);
if (null == specificatType) {
throw new SesWebRosException(ExceptionCodeEnums.SPECIFICAT_TYPE_NOT_EXIST.getCode(), ExceptionCodeEnums.SPECIFICAT_TYPE_NOT_EXIST.getMessage());
}
String productType = ProductTypeEnum.showCode(specificatType.getSpecificatName());
// 截取第7位,车型编号
String productTypeSub = vinCode.substring(6, 7);
if (!StringUtils.equals(productType, productTypeSub)) {
throw new SesWebRosException(ExceptionCodeEnums.VIN_NOT_MATCH.getCode(), ExceptionCodeEnums.VIN_NOT_MATCH.getMessage());
}
// 截取第8位,座位数量
String seatNumberSub = vinCode.substring(7, 8);
if (!StringUtils.equals(String.valueOf(seatNumber), seatNumberSub)) {
throw new SesWebRosException(ExceptionCodeEnums.VIN_NOT_MATCH.getCode(), ExceptionCodeEnums.VIN_NOT_MATCH.getMessage());
}
LambdaQueryWrapper<OpeCarDistribute> checkWrapper = new LambdaQueryWrapper<>();
checkWrapper.eq(OpeCarDistribute::getDr, Constant.DR_FALSE);
checkWrapper.eq(OpeCarDistribute::getVinCode, vinCode);
checkWrapper.last("limit 1");
OpeCarDistribute checkModel = opeCarDistributeMapper.selectOne(checkWrapper);
if (null != checkModel) {
throw new SesWebRosException(ExceptionCodeEnums.VIN_HAS_USED.getCode(), ExceptionCodeEnums.VIN_HAS_USED.getMessage());
}
// 查看vin在码库中是否存在
LambdaQueryWrapper<OpeCodebaseVin> existWrapper = new LambdaQueryWrapper<>();
existWrapper.eq(OpeCodebaseVin::getDr, Constant.DR_FALSE);
existWrapper.eq(OpeCodebaseVin::getStatus, 1);
existWrapper.eq(OpeCodebaseVin::getVin, vinCode);
int count = opeCodebaseVinService.count(existWrapper);
if (count == 0) {
throw new SesWebRosException(ExceptionCodeEnums.VIN_NOT_EXISTS_CODEBASE.getCode(), ExceptionCodeEnums.VIN_NOT_EXISTS_CODEBASE.getMessage());
}
// 修改主表
OpeCarDistribute model = new OpeCarDistribute();
model.setSpecificatTypeId(specificatId);
model.setSeatNumber(seatNumber);
model.setVinCode(vinCode);
model.setQty(qty);
model.setUpdatedBy(enter.getUserId());
model.setUpdatedTime(new Date());
LambdaQueryWrapper<OpeCarDistribute> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(OpeCarDistribute::getCustomerId, enter.getCustomerId());
opeCarDistributeMapper.update(model, wrapper);
// 修改码库此vin为已用
LambdaQueryWrapper<OpeCodebaseVin> vinWrapper = new LambdaQueryWrapper<>();
vinWrapper.eq(OpeCodebaseVin::getDr, Constant.DR_FALSE);
vinWrapper.eq(OpeCodebaseVin::getStatus, 1);
vinWrapper.eq(OpeCodebaseVin::getVin, vinCode);
vinWrapper.last("limit 1");
OpeCodebaseVin codebaseVin = opeCodebaseVinService.getOne(vinWrapper);
if (null != codebaseVin) {
codebaseVin.setStatus(2);
codebaseVin.setUpdatedBy(enter.getUserId());
codebaseVin.setUpdatedTime(new Date());
opeCodebaseVinService.updateById(codebaseVin);
}
// 码库关系表,rsn和vin绑定,先给vin,rsn在绑定车辆时给
LambdaQueryWrapper<OpeCodebaseRelation> relationWrapper = new LambdaQueryWrapper<>();
relationWrapper.eq(OpeCodebaseRelation::getDr, Constant.DR_FALSE);
relationWrapper.eq(OpeCodebaseRelation::getVin, vinCode);
relationWrapper.last("limit 1");
OpeCodebaseRelation codebaseRelation = opeCodebaseRelationService.getOne(relationWrapper);
if (null == codebaseRelation) {
OpeCodebaseRelation relation = new OpeCodebaseRelation();
relation.setId(idAppService.getId(SequenceName.OPE_CUSTOMER));
relation.setDr(Constant.DR_FALSE);
relation.setVin(vinCode);
relation.setStatus(1);
relation.setCreatedBy(enter.getUserId());
relation.setCreatedTime(new Date());
opeCodebaseRelationService.save(relation);
}
}
// node表node字段+1
LambdaQueryWrapper<OpeCarDistributeNode> nodeWrapper = new LambdaQueryWrapper<>();
nodeWrapper.eq(OpeCarDistributeNode::getDr, DelStatusEnum.VALID.getCode());
nodeWrapper.eq(OpeCarDistributeNode::getCustomerId, enter.getCustomerId());
OpeCarDistributeNode node = new OpeCarDistributeNode();
node.setNode(2);
node.setAppNode(2);
node.setFlag(1);
node.setUpdatedBy(enter.getUserId());
node.setUpdatedTime(new Date());
opeCarDistributeNodeMapper.update(node, nodeWrapper);
return new GeneralResult();
}
/**
* 填写完车牌点击下一步
*/
@Override
@GlobalTransactional(rollbackFor = Exception.class)
public GeneralResult getLicensePlateNext(ToBeAssignLicensePlateNextEnter enter) {
logger.info("填写完车牌点击下一步的入参是:[{}]", enter);
if (null == enter || StringUtils.isBlank(enter.getList())) {
throw new SesWebRosException(ExceptionCodeEnums.LICENSE_PLATE_NOT_EMPTY.getCode(), ExceptionCodeEnums.LICENSE_PLATE_NOT_EMPTY.getMessage());
}
// 解析
List<ToBeAssignLicensePlateNextDetailEnter> list;
try {
list = JSONArray.parseArray(enter.getList(), ToBeAssignLicensePlateNextDetailEnter.class);
} catch (Exception ex) {
throw new SesWebRosException(ExceptionCodeEnums.DATA_EXCEPTION.getCode(), ExceptionCodeEnums.DATA_EXCEPTION.getMessage());
}
if (CollectionUtils.isEmpty(list)) {
throw new SesWebRosException(ExceptionCodeEnums.DATA_EXCEPTION.getCode(), ExceptionCodeEnums.DATA_EXCEPTION.getMessage());
}
for (ToBeAssignLicensePlateNextDetailEnter o : list) {
Long id = o.getId();
String licensePlate = o.getLicensePlate().trim();
// 校验是否已被操作过
LambdaQueryWrapper<OpeCarDistribute> lqw = new LambdaQueryWrapper<>();
lqw.eq(OpeCarDistribute::getDr, Constant.DR_FALSE);
lqw.eq(OpeCarDistribute::getCustomerId, enter.getCustomerId());
lqw.last("limit 1");
OpeCarDistribute instance = opeCarDistributeMapper.selectOne(lqw);
if (null != instance) {
String plate = instance.getLicensePlate();
if (StringUtils.isNotBlank(plate)) {
throw new SesWebRosException(ExceptionCodeEnums.STEP_HAS_INPUT_IN_APP.getCode(), ExceptionCodeEnums.STEP_HAS_INPUT_IN_APP.getMessage());
}
}
LambdaQueryWrapper<OpeCarDistribute> checkWrapper = new LambdaQueryWrapper<>();
checkWrapper.eq(OpeCarDistribute::getDr, Constant.DR_FALSE);
checkWrapper.eq(OpeCarDistribute::getLicensePlate, licensePlate);
checkWrapper.last("limit 1");
OpeCarDistribute checkModel = opeCarDistributeMapper.selectOne(checkWrapper);
if (null != checkModel) {
throw new SesWebRosException(ExceptionCodeEnums.PLATE_HAS_USED.getCode(), ExceptionCodeEnums.PLATE_HAS_USED.getMessage());
}
// 修改主表
OpeCarDistribute model = new OpeCarDistribute();
model.setId(id);
model.setLicensePlate(licensePlate);
model.setUpdatedBy(enter.getUserId());
model.setUpdatedTime(new Date());
opeCarDistributeMapper.updateById(model);
}
// node表node字段+1
LambdaQueryWrapper<OpeCarDistributeNode> nodeWrapper = new LambdaQueryWrapper<>();
nodeWrapper.eq(OpeCarDistributeNode::getDr, DelStatusEnum.VALID.getCode());
nodeWrapper.eq(OpeCarDistributeNode::getCustomerId, enter.getCustomerId());
OpeCarDistributeNode node = new OpeCarDistributeNode();
node.setNode(3);
node.setAppNode(3);
node.setUpdatedBy(enter.getUserId());
node.setUpdatedTime(new Date());
opeCarDistributeNodeMapper.update(node, nodeWrapper);
return new GeneralResult();
}
/**
* 根据R.SN获得颜色
*/
@Override
public ToBeAssignColorResult getColorByRSN(StringEnter enter) {
logger.info("根据R.SN获得颜色的入参是:[{}]", enter);
ToBeAssignColorResult result = new ToBeAssignColorResult();
LambdaQueryWrapper<OpeInWhouseOrderSerialBind> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(OpeInWhouseOrderSerialBind::getDr, DelStatusEnum.VALID.getCode());
wrapper.eq(OpeInWhouseOrderSerialBind::getSerialNum, enter.getKeyword());
wrapper.orderByDesc(OpeInWhouseOrderSerialBind::getCreatedTime);
List<OpeInWhouseOrderSerialBind> list = opeInWhouseOrderSerialBindMapper.selectList(wrapper);
if (CollectionUtils.isNotEmpty(list)) {
OpeInWhouseOrderSerialBind model = list.get(0);
Long productId = model.getProductId();
if (null == productId) {
throw new SesWebRosException(ExceptionCodeEnums.PRODUCT_IS_NOT_EXIST.getCode(), ExceptionCodeEnums.PRODUCT_IS_NOT_EXIST.getMessage());
}
OpeProductionScooterBom bom = opeProductionScooterBomMapper.selectById(productId);
Long colorId = bom.getColorId();
if (null == colorId) {
throw new SesWebRosException(ExceptionCodeEnums.COLOR_NOT_EXIST.getCode(), ExceptionCodeEnums.COLOR_NOT_EXIST.getMessage());
}
OpeColor color = opeColorMapper.selectById(colorId);
if (null != color) {
result.setColorId(color.getId());
result.setColorName(color.getColorName());
result.setColorValue(color.getColorValue());
result.setRequestId(enter.getRequestId());
}
}
return result;
}
/**
* 填写完R.SN并点击提交
*/
@Override
@GlobalTransactional(rollbackFor = Exception.class)
public GeneralResult submit(ToBeAssignSubmitEnter enter) {
logger.info("填写完R.SN并点击提交的入参是:[{}]", enter);
if (null == enter || StringUtils.isBlank(enter.getList())) {
throw new SesWebRosException(ExceptionCodeEnums.RSN_NOT_EMPTY.getCode(), ExceptionCodeEnums.RSN_NOT_EMPTY.getMessage());
}
// 解析
List<ToBeAssignSubmitDetailEnter> list;
try {
list = JSONArray.parseArray(enter.getList(), ToBeAssignSubmitDetailEnter.class);
} catch (Exception ex) {
throw new SesWebRosException(ExceptionCodeEnums.DATA_EXCEPTION.getCode(), ExceptionCodeEnums.DATA_EXCEPTION.getMessage());
}
if (CollectionUtils.isEmpty(list)) {
throw new SesWebRosException(ExceptionCodeEnums.DATA_EXCEPTION.getCode(), ExceptionCodeEnums.DATA_EXCEPTION.getMessage());
}
for (ToBeAssignSubmitDetailEnter o : list) {
Long id = o.getId();
String rsn = o.getRsn().trim();
Long colorId = o.getColorId();
String bluetoothAddress = o.getBluetoothAddress().trim();
String tabletSn = o.getTabletSn().trim();
String bbi = o.getBbi().trim();
String controller = o.getController().trim();
String electricMachinery = o.getElectricMachinery().trim();
String meter = o.getMeter().trim();
String imei = o.getImei().trim();
// 校验是否已被操作过
LambdaQueryWrapper<OpeCarDistribute> scooterWrapper = new LambdaQueryWrapper<>();
scooterWrapper.eq(OpeCarDistribute::getDr, Constant.DR_FALSE);
scooterWrapper.eq(OpeCarDistribute::getCustomerId, enter.getCustomerId());
scooterWrapper.last("limit 1");
OpeCarDistribute instance = opeCarDistributeMapper.selectOne(scooterWrapper);
if (null != instance) {
if (StringUtils.isNotBlank(instance.getRsn()) || StringUtils.isNotBlank(instance.getTabletSn()) || StringUtils.isNotBlank(instance.getBluetoothAddress())) {
throw new SesWebRosException(ExceptionCodeEnums.STEP_HAS_INPUT_IN_APP.getCode(), ExceptionCodeEnums.STEP_HAS_INPUT_IN_APP.getMessage());
}
}
LambdaQueryWrapper<OpeCarDistribute> lqw = new LambdaQueryWrapper<>();
lqw.eq(OpeCarDistribute::getDr, Constant.DR_FALSE);
lqw.eq(OpeCarDistribute::getRsn, rsn);
lqw.last("limit 1");
OpeCarDistribute checkModel = opeCarDistributeMapper.selectOne(lqw);
if (null != checkModel) {
throw new SesWebRosException(ExceptionCodeEnums.RSN_HAS_USED.getCode(), ExceptionCodeEnums.RSN_HAS_USED.getMessage());
}
// 查看rsn在码库中是否存在
LambdaQueryWrapper<OpeCodebaseRsn> existWrapper = new LambdaQueryWrapper<>();
existWrapper.eq(OpeCodebaseRsn::getDr, Constant.DR_FALSE);
existWrapper.eq(OpeCodebaseRsn::getStatus, 1);
existWrapper.eq(OpeCodebaseRsn::getRsn, rsn);
int count = opeCodebaseRsnService.count(existWrapper);
if (count == 0) {
throw new SesWebRosException(ExceptionCodeEnums.RSN_NOT_EXISTS_CODEBASE.getCode(), ExceptionCodeEnums.RSN_NOT_EXISTS_CODEBASE.getMessage());
}
// 修改主表
OpeCarDistribute model = new OpeCarDistribute();
model.setId(id);
model.setRsn(rsn);
model.setBluetoothAddress(bluetoothAddress);
model.setTabletSn(tabletSn);
model.setColorId(colorId);
model.setBbi(bbi);
model.setController(controller);
model.setElectricMachinery(electricMachinery);
model.setMeter(meter);
model.setImei(imei);
model.setUpdatedBy(enter.getUserId());
model.setUpdatedTime(new Date());
opeCarDistributeMapper.updateById(model);
// 修改码库此RSN为已用
LambdaQueryWrapper<OpeCodebaseRsn> rsnWrapper = new LambdaQueryWrapper<>();
rsnWrapper.eq(OpeCodebaseRsn::getDr, Constant.DR_FALSE);
rsnWrapper.eq(OpeCodebaseRsn::getStatus, 1);
rsnWrapper.eq(OpeCodebaseRsn::getRsn, rsn);
rsnWrapper.last("limit 1");
OpeCodebaseRsn codebaseRsn = opeCodebaseRsnService.getOne(rsnWrapper);
if (null != codebaseRsn) {
codebaseRsn.setStatus(2);
codebaseRsn.setUpdatedBy(enter.getUserId());
codebaseRsn.setUpdatedTime(new Date());
opeCodebaseRsnService.updateById(codebaseRsn);
}
// 修改码库关系表
OpeCodebaseRelation relation = new OpeCodebaseRelation();
relation.setRsn(rsn);
relation.setStatus(2);
LambdaQueryWrapper<OpeCodebaseRelation> relationWrapper = new LambdaQueryWrapper<>();
relationWrapper.eq(OpeCodebaseRelation::getDr, Constant.DR_FALSE);
relationWrapper.eq(OpeCodebaseRelation::getVin, o.getVin());
relationWrapper.eq(OpeCodebaseRelation::getStatus, 1);
opeCodebaseRelationService.update(relation, relationWrapper);
}
// node表node字段+1
LambdaQueryWrapper<OpeCarDistributeNode> nodeWrapper = new LambdaQueryWrapper<>();
nodeWrapper.eq(OpeCarDistributeNode::getDr, DelStatusEnum.VALID.getCode());
nodeWrapper.eq(OpeCarDistributeNode::getCustomerId, enter.getCustomerId());
OpeCarDistributeNode node = new OpeCarDistributeNode();
node.setNode(4);
node.setAppNode(4);
node.setUpdatedBy(enter.getUserId());
node.setUpdatedTime(new Date());
opeCarDistributeNodeMapper.update(node, nodeWrapper);
return new GeneralResult(enter.getRequestId());
}
/**
* 录入电池
*/
@Override
@GlobalTransactional(rollbackFor = Exception.class)
public GeneralResult inputBattery(ToBeAssignInputBatteryEnter enter) {
logger.info("录入电池的入参是:[{}]", enter);
if (null == enter || StringUtils.isBlank(enter.getList())) {
throw new SesWebRosException(ExceptionCodeEnums.BATTERY_NOT_EMPTY.getCode(), ExceptionCodeEnums.BATTERY_NOT_EMPTY.getMessage());
}
// 解析
List<ToBeAssignInputBatteryDetailEnter> list;
try {
list = JSONArray.parseArray(enter.getList(), ToBeAssignInputBatteryDetailEnter.class);
} catch (Exception ex) {
throw new SesWebRosException(ExceptionCodeEnums.DATA_EXCEPTION.getCode(), ExceptionCodeEnums.DATA_EXCEPTION.getMessage());
}
if (CollectionUtils.isEmpty(list)) {
throw new SesWebRosException(ExceptionCodeEnums.DATA_EXCEPTION.getCode(), ExceptionCodeEnums.DATA_EXCEPTION.getMessage());
}
// 客户信息
OpeCustomer opeCustomer = opeCustomerMapper.selectById(enter.getCustomerId());
if (null == opeCustomer) {
throw new SesWebRosException(ExceptionCodeEnums.CUSTOMER_NOT_EXIST.getCode(), ExceptionCodeEnums.CUSTOMER_NOT_EXIST.getMessage());
}
if (!StringUtils.equals(opeCustomer.getStatus(), CustomerStatusEnum.OFFICIAL_CUSTOMER.getValue())) {
throw new SesWebRosException(ExceptionCodeEnums.CONVERT_TO_FORMAL_CUSTOMER_FIRST.getCode(), ExceptionCodeEnums.CONVERT_TO_FORMAL_CUSTOMER_FIRST.getMessage());
}
// 查询客户的账号信息(查pla_user表)
QueryAccountResult accountInfo = accountBaseService.customerAccountDeatil(opeCustomer.getEmail());
if (null == accountInfo) {
throw new SesWebRosException(ExceptionCodeEnums.ACCOUNT_IS_NOT_EXIST.getCode(), ExceptionCodeEnums.ACCOUNT_IS_NOT_EXIST.getMessage());
}
// 客户和车辆产生绑定关系
List<HubSaveScooterEnter> saveRelationList = Lists.newArrayList();
boolean stockFlag = false;
for (ToBeAssignInputBatteryDetailEnter o : list) {
Long id = o.getId();
String battery = o.getBattery().trim();
// 校验是否已被操作过
LambdaQueryWrapper<OpeCarDistribute> batteryWrapper = new LambdaQueryWrapper<>();
batteryWrapper.eq(OpeCarDistribute::getDr, Constant.DR_FALSE);
batteryWrapper.eq(OpeCarDistribute::getCustomerId, enter.getCustomerId());
batteryWrapper.last("limit 1");
OpeCarDistribute instance = opeCarDistributeMapper.selectOne(batteryWrapper);
if (null != instance) {
String cell = instance.getBattery();
if (StringUtils.isNotBlank(cell)) {
throw new SesWebRosException(ExceptionCodeEnums.STEP_HAS_INPUT_IN_APP.getCode(), ExceptionCodeEnums.STEP_HAS_INPUT_IN_APP.getMessage());
}
}
LambdaQueryWrapper<OpeCarDistribute> checkWrapper = new LambdaQueryWrapper<>();
checkWrapper.eq(OpeCarDistribute::getDr, Constant.DR_FALSE);
checkWrapper.like(OpeCarDistribute::getBattery, battery);
checkWrapper.last("limit 1");
OpeCarDistribute checkModel = opeCarDistributeMapper.selectOne(checkWrapper);
if (null != checkModel) {
throw new SesWebRosException(ExceptionCodeEnums.BATTERY_HAS_USED.getCode(), ExceptionCodeEnums.BATTERY_HAS_USED.getMessage());
}
// 修改主表
OpeCarDistribute obj = new OpeCarDistribute();
obj.setId(id);
obj.setBattery(battery);
obj.setUpdatedBy(enter.getUserId());
obj.setUpdatedTime(new Date());
opeCarDistributeMapper.updateById(obj);
// 获得车牌号
OpeCarDistribute opeCarDistribute = opeCarDistributeMapper.selectById(id);
String licensePlate = opeCarDistribute.getLicensePlate();
String rsn = opeCarDistribute.getRsn();
// 修改成品库车辆库存
// 获得询价单型号id和颜色id
CustomerIdEnter customerIdEnter = new CustomerIdEnter();
customerIdEnter.setCustomerId(enter.getCustomerId());
Map<String, Long> map = getSpecificatIdAndColorId(customerIdEnter);
Long specificatId = map.get("specificatId");
Long inquiryColorId = map.get("colorId");
// 法国仓库指定车型和颜色
LambdaQueryWrapper<OpeWmsScooterStock> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(OpeWmsScooterStock::getDr, DelStatusEnum.VALID.getCode());
wrapper.eq(OpeWmsScooterStock::getGroupId, specificatId);
wrapper.eq(OpeWmsScooterStock::getColorId, inquiryColorId);
wrapper.eq(OpeWmsScooterStock::getStockType, 2);
wrapper.orderByDesc(OpeWmsScooterStock::getCreatedTime);
List<OpeWmsScooterStock> stockList = opeWmsScooterStockMapper.selectList(wrapper);
OpeWmsScooterStock stock = null;
if (CollectionUtils.isNotEmpty(stockList)) {
stock = stockList.get(0);
// 得到原先库存的可用库存数量和已用库存数量
Long stockId = stock.getId();
Integer ableStockQty = stock.getAbleStockQty();
Integer usedStockQty = stock.getUsedStockQty();
// 如果原先库存不足,抛出异常
if (ableStockQty < 1) {
stockFlag = true;
break;
}
// 原先库存的可用库存数量-1,已用库存数量+1
OpeWmsScooterStock param = new OpeWmsScooterStock();
param.setId(stockId);
param.setAbleStockQty(ableStockQty - 1);
param.setUsedStockQty(usedStockQty + 1);
param.setUpdatedBy(enter.getUserId());
param.setUpdatedTime(new Date());
opeWmsScooterStockMapper.updateById(param);
}
// 新增出库记录
if (null != stock) {
OpeWmsStockRecord record = new OpeWmsStockRecord();
record.setId(idAppService.getId(SequenceName.OPE_WMS_STOCK_RECORD));
record.setDr(DelStatusEnum.VALID.getCode());
record.setRelationId(stock.getId());
record.setRelationType(7);
record.setInWhQty(1);
record.setRecordType(2);
record.setStockType(2);
record.setCreatedBy(enter.getUserId());
record.setCreatedTime(new Date());
opeWmsStockRecordMapper.insert(record);
}
// 获得规格名称
String specificatName = getSpecificatNameById(opeCarDistribute.getSpecificatTypeId());
// 数据同步
// 根据rsn查询sco_scooter表
ScoScooterResult scoScooter = scooterService.getScoScooterByTableSn(rsn);
if (null == scoScooter) {
throw new SesWebRosException(ExceptionCodeEnums.SCOOTER_NOT_EXIST.getCode(), ExceptionCodeEnums.SCOOTER_NOT_EXIST.getMessage());
}
Long scooterId = scoScooter.getId();
// 修改sco_scooter的牌照
scooterService.updateScooterNo(scooterId, licensePlate);
// 将数据存储到corporate库(tob)
logger.info("客户类型是:[{}]", opeCustomer.getCustomerType());
if (StringUtils.equals(opeCustomer.getCustomerType(), CustomerTypeEnum.ENTERPRISE.getValue())) {
// 新增cor_tenant_scooter表
HubSaveScooterEnter item = new HubSaveScooterEnter();
item.setScooterId(scooterId);
item.setModel(ScooterModelEnums.showValueByCode(specificatName));
item.setLongitude(MapUtil.randomLonLat(Constant.lng));
item.setLatitude(MapUtil.randomLonLat(Constant.lng));
item.setLicensePlate(licensePlate);
item.setLicensePlatePicture(null);
item.setStatus(ScooterStatusEnums.AVAILABLE.getValue());
item.setUserId(accountInfo.getId());
item.setTenantId(accountInfo.getTenantId());
saveRelationList.add(item);
corporateScooterService.saveScooter(saveRelationList);
logger.info("客户类型是公司,新增corporate库");
// 新增cor_driver表
long driverId = idAppService.getId(SequenceName.OPE_CAR_DISTRIBUTE);
CorDriver driver = new CorDriver();
driver.setId(driverId);
driver.setTenantId(accountInfo.getTenantId());
driver.setUserId(accountInfo.getId());
driver.setStatus("1");
driver.setCreatedBy(enter.getUserId());
driver.setCreatedTime(new Date());
scooterMobileBService.addCorDriver(driver);
// 新增cor_driver_scooter表
CorDriverScooter scooter = new CorDriverScooter();
scooter.setId(idAppService.getId(SequenceName.OPE_CAR_DISTRIBUTE));
scooter.setTenantId(accountInfo.getTenantId());
scooter.setDriverId(driverId);
scooter.setScooterId(scooterId);
scooter.setStatus("1");
scooter.setBeginTime(new Date());
scooter.setCreatedBy(enter.getUserId());
scooter.setCreatedTime(new Date());
scooterMobileBService.addCorDriverScooter(scooter);
}
// 将数据存储到consumer库(toc)
if (StringUtils.equals(opeCustomer.getCustomerType(), CustomerTypeEnum.PERSONAL.getValue())) {
HubSaveScooterEnter item = new HubSaveScooterEnter();
item.setScooterId(scooterId);
item.setModel(ScooterModelEnums.showValueByCode(specificatName));
item.setLongitude(MapUtil.randomLonLat(Constant.lng));
item.setLatitude(MapUtil.randomLonLat(Constant.lng));
item.setLicensePlate(licensePlate);
item.setLicensePlatePicture(null);
item.setStatus(ScooterStatusEnums.AVAILABLE.getValue());
item.setUserId(accountInfo.getId());
item.setTenantId(accountInfo.getTenantId());
saveRelationList.add(item);
cusotmerScooterService.saveScooter(saveRelationList);
logger.info("客户类型是个人,新增consumer库");
}
// 根据rsn修改库存产品序列号表的库存状态为不可用
LambdaQueryWrapper<OpeWmsStockSerialNumber> qw = new LambdaQueryWrapper<>();
qw.eq(OpeWmsStockSerialNumber::getDr, DelStatusEnum.VALID.getCode());
qw.eq(OpeWmsStockSerialNumber::getRsn, rsn);
qw.eq(OpeWmsStockSerialNumber::getStockStatus, WmsStockStatusEnum.AVAILABLE.getStatus());
List<OpeWmsStockSerialNumber> serialNumberList = opeWmsStockSerialNumberMapper.selectList(qw);
if (CollectionUtils.isNotEmpty(serialNumberList)) {
for (OpeWmsStockSerialNumber serialNumber : serialNumberList) {
if (null != serialNumber) {
serialNumber.setStockStatus(WmsStockStatusEnum.UNAVAILABLE.getStatus());
opeWmsStockSerialNumberService.updateById(serialNumber);
}
}
}
// 创建oms车辆信息
LambdaQueryWrapper<OpeCarDistribute> omsWrapper = new LambdaQueryWrapper<>();
omsWrapper.eq(OpeCarDistribute::getDr, Constant.DR_FALSE);
omsWrapper.eq(OpeCarDistribute::getCustomerId, enter.getCustomerId());
omsWrapper.last("limit 1");
OpeCarDistribute model = opeCarDistributeMapper.selectOne(omsWrapper);
if (null == model) {
throw new SesWebRosException(ExceptionCodeEnums.ASSIGN_SCOOTER_WRONG.getCode(), ExceptionCodeEnums.ASSIGN_SCOOTER_WRONG.getMessage());
}
// 型号名称
String modelName = getSpecificatNameById(model.getSpecificatTypeId());
CustomerIdEnter customerEnter = new CustomerIdEnter();
customerEnter.setCustomerId(enter.getCustomerId());
Map<String, Long> inquiryMap = getSpecificatIdAndColorId(customerEnter);
logger.info("询价单型号和颜色分别是:[{}]", inquiryMap);
Long groupId = inquiryMap.get("specificatId");
Long colorId = inquiryMap.get("colorId");
AdmScooter admScooter = scooterModelService.getScooterBySn(model.getTabletSn());
if (null != admScooter) {
throw new SesWebRosException(ExceptionCodeEnums.SN_ALREADY_EXISTS.getCode(), ExceptionCodeEnums.SN_ALREADY_EXISTS.getMessage());
}
logger.info("车辆不存在");
SpecificGroupDTO group = specificService.getSpecificGroupById(groupId);
ColorDTO color = colorService.getColorInfoById(colorId);
if (null == group) {
throw new SesWebRosException(ExceptionCodeEnums.GROUP_NOT_EXIST.getCode(), ExceptionCodeEnums.GROUP_NOT_EXIST.getMessage());
}
if (null == color) {
throw new SesWebRosException(ExceptionCodeEnums.COLOR_NOT_EXIST.getCode(), ExceptionCodeEnums.COLOR_NOT_EXIST.getMessage());
}
// 新增adm_scooter表
AdmScooter scooter = new AdmScooter();
scooter.setId(idAppService.getId(SequenceName.OPE_CAR_DISTRIBUTE_NODE));
scooter.setDr(Constant.DR_FALSE);
scooter.setSn(model.getTabletSn());
scooter.setGroupId(groupId);
scooter.setColorId(colorId);
scooter.setMacAddress(model.getBluetoothAddress());
scooter.setScooterController(ScooterModelEnum.getScooterModelType(modelName));
scooter.setCreatedBy(0L);
scooter.setCreatedTime(new Date());
scooter.setUpdatedBy(0L);
scooter.setUpdatedTime(new Date());
scooter.setColorName(color.getColorName());
scooter.setColorValue(color.getColorValue());
scooter.setGroupName(group.getGroupName());
scooter.setMacName(model.getBluetoothAddress());
scooterModelService.insertScooter(scooter);
logger.info("新增adm_scooter表成功");
// 根据平板序列号(sn)查询在sco_scooter表是否存在 不存在返回true 存在返回false
Boolean flag = scooterService.getSnIsExist(scooter.getSn());
if (flag) {
logger.info("sn在sco_scooter表不存在");
String scooterNo = generateScooterNo();
scooterService.syncScooterData(buildData(scooter.getId(), scooter.getSn(), scooter.getScooterController(), enter.getUserId(), scooterNo));
}
}
if (stockFlag) {
throw new SesWebRosException(ExceptionCodeEnums.SCOOTER_STOCK_IS_NOT_ENOUGH.getCode(), ExceptionCodeEnums.SCOOTER_STOCK_IS_NOT_ENOUGH.getMessage());
}
/*---------------sim 信息录入--------------*/
LambdaQueryWrapper<OpeCarDistribute> qw = new LambdaQueryWrapper<>();
qw.eq(OpeCarDistribute::getDr, Constant.DR_FALSE);
qw.eq(OpeCarDistribute::getCustomerId, opeCustomer.getId());
qw.last("limit 1");
OpeCarDistribute opeCarDistribute = opeCarDistributeMapper.selectOne(qw);
if (null != opeCarDistribute) {
OpeSimInformation simInfo = new OpeSimInformation();
String iccid = jedisCluster.get(opeCarDistribute.getTabletSn());
if (StringUtils.isNotBlank(iccid)) {
simInfo.setSimIccid(iccid);
}
simInfo.setRsn(opeCarDistribute.getRsn());
simInfo.setBluetoothMacAddress(opeCarDistribute.getBluetoothAddress());
simInfo.setTabletSn(opeCarDistribute.getTabletSn());
simInfo.setVin(opeCarDistribute.getVinCode());
simInfo.setCreatedBy(enter.getUserId());
simInfo.setCreatedTime(new Date());
simInformationService.save(simInfo);
jedisCluster.del(opeCarDistribute.getTabletSn());
}
/*---------------sim 信息录入--------------*/
// node表node字段+1
LambdaQueryWrapper<OpeCarDistributeNode> nodeWrapper = new LambdaQueryWrapper<>();
nodeWrapper.eq(OpeCarDistributeNode::getDr, Constant.DR_FALSE);
nodeWrapper.eq(OpeCarDistributeNode::getCustomerId, enter.getCustomerId());
OpeCarDistributeNode node = new OpeCarDistributeNode();
node.setNode(5);
node.setAppNode(5);
node.setFlag(2);
node.setUpdatedBy(enter.getUserId());
node.setUpdatedTime(new Date());
opeCarDistributeNodeMapper.update(node, nodeWrapper);
return new GeneralResult(enter.getRequestId());
}
/**
* 查询客户走到哪个节点并带出数据
*/
@Override
public ToBeAssignNodeResult getNode(CustomerIdEnter enter) {
logger.info("查询客户走到哪个节点并带出数据的入参是:[{}]", enter);
ToBeAssignNodeResult result = new ToBeAssignNodeResult();
// 根据客户id查询node表
LambdaQueryWrapper<OpeCarDistributeNode> nodeWrapper = new LambdaQueryWrapper<>();
nodeWrapper.eq(OpeCarDistributeNode::getDr, DelStatusEnum.VALID.getCode());
nodeWrapper.eq(OpeCarDistributeNode::getCustomerId, enter.getCustomerId());
nodeWrapper.orderByDesc(OpeCarDistributeNode::getCreatedTime);
List<OpeCarDistributeNode> nodeList = opeCarDistributeNodeMapper.selectList(nodeWrapper);
if (CollectionUtils.isEmpty(nodeList)) {
throw new SesWebRosException(ExceptionCodeEnums.CUSTOMER_NOT_EXIST.getCode(), ExceptionCodeEnums.CUSTOMER_NOT_EXIST.getMessage());
}
OpeCarDistributeNode opeCarDistributeNode = nodeList.get(0);
Integer node = opeCarDistributeNode.getNode();
node = null == node ? 1 : node;
// 客户信息
ToBeAssignDetailCustomerInfoResult customerInfo = opeCarDistributeExMapper.getCustomerInfo(enter.getCustomerId());
if (null == customerInfo) {
throw new SesWebRosException(ExceptionCodeEnums.CUSTOMER_NOT_EXIST.getCode(), ExceptionCodeEnums.CUSTOMER_NOT_EXIST.getMessage());
}
String customerType = customerInfo.getCustomerType();
String industryType = customerInfo.getIndustryType();
if (StringUtils.isNotBlank(customerType)) {
customerInfo.setCustomerTypeMsg(CustomerFormEnum.showMsg(customerType));
}
if (StringUtils.isNotBlank(industryType)) {
customerInfo.setIndustryTypeMsg(IndustryTypeEnum.showMsg(industryType));
}
// 任务清单
LambdaQueryWrapper<OpeCustomerInquiry> opeCustomerInquiryWrapper = new LambdaQueryWrapper<>();
opeCustomerInquiryWrapper.eq(OpeCustomerInquiry::getDr, DelStatusEnum.VALID.getCode());
opeCustomerInquiryWrapper.eq(OpeCustomerInquiry::getCustomerId, enter.getCustomerId());
List<OpeCustomerInquiry> tempList = opeCustomerInquiryMapper.selectList(opeCustomerInquiryWrapper);
if (CollectionUtils.isEmpty(tempList)) {
throw new SesWebRosException(ExceptionCodeEnums.CUSTOMER_NOT_EXIST.getCode(), ExceptionCodeEnums.CUSTOMER_NOT_EXIST.getMessage());
}
List<ToBeAssignDetailScooterInfoResult> taskList = Lists.newArrayList();
List<ToBeAssignDetailScooterInfoSubResult> taskSubList = Lists.newArrayList();
Long inquiryId = null;
for (OpeCustomerInquiry o : tempList) {
inquiryId = o.getId();
ToBeAssignDetailScooterInfoResult task = new ToBeAssignDetailScooterInfoResult();
ToBeAssignDetailScooterInfoSubResult sub = new ToBeAssignDetailScooterInfoSubResult();
Long productId = o.getProductId();
if (null == productId) {
throw new SesWebRosException(ExceptionCodeEnums.PRODUCT_IS_NOT_EXIST.getCode(), ExceptionCodeEnums.PRODUCT_IS_NOT_EXIST.getMessage());
}
// 拿着产品id去ope_sale_scooter查询
OpeSaleScooter opeSaleScooter = opeSaleScooterMapper.selectById(productId);
if (null == opeSaleScooter) {
throw new SesWebRosException(ExceptionCodeEnums.PRODUCT_IS_NOT_EXIST.getCode(), ExceptionCodeEnums.PRODUCT_IS_NOT_EXIST.getMessage());
}
// 得到型号id和颜色id
Long specificatId = opeSaleScooter.getSpecificatId();
Long colorId = opeSaleScooter.getColorId();
// 拿着型号id去ope_specificat_type查询
if (null != specificatId) {
String specificatName = getSpecificatNameById(specificatId);
task.setSpecificatId(specificatId);
task.setSpecificatName(specificatName);
}
// 拿着颜色id去ope_color查询
if (null != colorId) {
Map<String, String> map = getColorNameAndValueById(colorId);
sub.setColorName(map.get("colorName"));
sub.setColorValue(map.get("colorValue"));
sub.setColorId(colorId);
}
// 询价单电池数量
LambdaQueryWrapper<OpeCustomerInquiryB> lqw = new LambdaQueryWrapper<>();
lqw.eq(OpeCustomerInquiryB::getDr, Constant.DR_FALSE);
lqw.eq(OpeCustomerInquiryB::getInquiryId, inquiryId);
lqw.last("limit 1");
OpeCustomerInquiryB inquiryB = opeCustomerInquiryBService.getOne(lqw);
if (null != inquiryB) {
sub.setBatteryNum(inquiryB.getProductQty());
}
sub.setToBeAssignCount(o.getScooterQuantity());
task.setTotalCount(o.getScooterQuantity());
taskSubList.add(sub);
task.setScooterList(taskSubList);
taskList.add(task);
}
// 车辆信息,查询已分配的数据
LambdaQueryWrapper<OpeCarDistribute> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(OpeCarDistribute::getDr, DelStatusEnum.VALID.getCode());
wrapper.eq(OpeCarDistribute::getCustomerId, enter.getCustomerId());
List<OpeCarDistribute> list = opeCarDistributeMapper.selectList(wrapper);
if (CollectionUtils.isEmpty(list)) {
result.setNode(node);
result.setCustomerInfo(customerInfo);
result.setTaskInfo(taskList);
return result;
}
List<ToBeAssignNodeScooterInfoResult> scooterList = Lists.newArrayList();
List<ToBeAssignNodeScooterInfoSubResult> subList = Lists.newArrayList();
Integer totalCount = 0;
for (OpeCarDistribute model : list) {
ToBeAssignNodeScooterInfoSubResult sub = new ToBeAssignNodeScooterInfoSubResult();
sub.setId(model.getId());
sub.setToBeAssignCount(model.getQty());
if (null != model.getQty()) {
totalCount += model.getQty();
}
sub.setSeatNumber(model.getSeatNumber());
sub.setVinCode(model.getVinCode());
sub.setLicensePlate(model.getLicensePlate());
sub.setRsn(model.getRsn());
// 询价单电池数量
LambdaQueryWrapper<OpeCustomerInquiryB> lqw = new LambdaQueryWrapper<>();
lqw.eq(OpeCustomerInquiryB::getDr, Constant.DR_FALSE);
lqw.eq(OpeCustomerInquiryB::getInquiryId, inquiryId);
lqw.last("limit 1");
OpeCustomerInquiryB inquiryB = opeCustomerInquiryBService.getOne(lqw);
if (null != inquiryB) {
sub.setBatteryNum(inquiryB.getProductQty());
}
// 根据customerId查找node,如果node或者appNode小于等于3(录入车辆),颜色给空,如果大于3,给颜色
LambdaQueryWrapper<OpeCarDistributeNode> qw = new LambdaQueryWrapper<>();
qw.eq(OpeCarDistributeNode::getDr, Constant.DR_FALSE);
qw.eq(OpeCarDistributeNode::getCustomerId, enter.getCustomerId());
qw.last("limit 1");
OpeCarDistributeNode nodeModel = opeCarDistributeNodeMapper.selectOne(qw);
if (null != nodeModel) {
if (nodeModel.getNode() > 3 || nodeModel.getAppNode() > 3) {
if (null != model.getColorId()) {
Map<String, String> map = getColorNameAndValueById(model.getColorId());
sub.setColorId(model.getColorId());
sub.setColorName(map.get("colorName"));
sub.setColorValue(map.get("colorValue"));
}
}
}
/*if (null != model.getColorId()) {
Map<String, String> map = getColorNameAndValueById(model.getColorId());
sub.setColorId(model.getColorId());
sub.setColorName(map.get("colorName"));
sub.setColorValue(map.get("colorValue"));
}*/
sub.setQty(model.getQty());
sub.setBluetoothAddress(model.getBluetoothAddress());
sub.setTabletSn(model.getTabletSn());
if (StringUtils.isBlank(model.getBattery())) {
sub.setBatteryList(new ArrayList<>());
} else {
String[] split = model.getBattery().split(",");
List<String> batteryList = new ArrayList<>(Arrays.asList(split));
batteryList.removeAll(Collections.singleton(null));
sub.setBatteryList(batteryList);
}
subList.add(sub);
ToBeAssignNodeScooterInfoResult scooter = new ToBeAssignNodeScooterInfoResult();
if (null != model.getSpecificatTypeId()) {
String specificatName = getSpecificatNameById(model.getSpecificatTypeId());
scooter.setSpecificatId(model.getSpecificatTypeId());
scooter.setSpecificatName(specificatName);
}
scooterList.add(scooter);
scooter.setScooterList(subList);
scooter.setTotalCount(totalCount);
}
result.setNode(node);
result.setCustomerInfo(customerInfo);
result.setScooterInfo(scooterList);
result.setTaskInfo(taskList);
result.setRequestId(enter.getRequestId());
return result;
}
/**
* 待分配列表和已分配列表的tab数量统计
*/
@Override
public Map<String, Object> getTabCount(GeneralEnter enter) {
Map<String, Object> result = Maps.newHashMapWithExpectedSize(3);
// 待分配列表条数
int toBeAssignCount = opeCarDistributeExMapper.getToBeAssignListCount(new ToBeAssignListEnter());
/*List<ToBeAssignListResult> list = opeCarDistributeExMapper.getToBeAssignListNoPage(enter);
// 正式客户且点击了创建账号的才能流转到待分配列表
if (CollectionUtils.isNotEmpty(list)) {
Iterator<ToBeAssignListResult> iterator = list.iterator();
while (iterator.hasNext()) {
ToBeAssignListResult next = iterator.next();
String email = next.getEmail();
// 拿着email去pla_user表查询,如果存在,说明已创建账号 flag:存在就是true,不存在就是false
Boolean flag = assignScooterService.getPlaUserIsExistByEmail(email);
if (!flag) {
iterator.remove();
}
}
}*/
// 已分配列表条数
int assignedCount = opeCarDistributeExMapper.getAssignedListCount(new AssignedListEnter());
// 处理中列表条数
int doingCount = opeCarDistributeExMapper.getDoingListCount(new ToBeAssignListEnter());
result.put("toBeAssignCount", toBeAssignCount);
result.put("assignedCount", assignedCount);
result.put("doingCount", doingCount);
return result;
}
/**
* 点击分配按钮校验车辆库存数量
*/
@Override
public BooleanResult checkScooterStock(CustomerIdEnter enter) {
logger.info("点击分配按钮校验车辆库存数量的入参是:[{}]", enter);
BooleanResult result = new BooleanResult();
// 获得询价单客户需求车辆数
Integer scooterQuantity = 0;
LambdaQueryWrapper<OpeCustomerInquiry> inquiryWrapper = new LambdaQueryWrapper<>();
inquiryWrapper.eq(OpeCustomerInquiry::getDr, DelStatusEnum.VALID.getCode());
inquiryWrapper.eq(OpeCustomerInquiry::getCustomerId, enter.getCustomerId());
List<OpeCustomerInquiry> inquiryList = opeCustomerInquiryMapper.selectList(inquiryWrapper);
if (CollectionUtils.isNotEmpty(inquiryList)) {
OpeCustomerInquiry customerInquiry = inquiryList.get(0);
scooterQuantity = customerInquiry.getScooterQuantity();
}
// 获得询价单型号id和颜色id
Map<String, Long> map = getSpecificatIdAndColorId(enter);
Long specificatId = map.get("specificatId");
Long colorId = map.get("colorId");
// 获得法国仓库指定车型和颜色的可用库存数量
LambdaQueryWrapper<OpeWmsScooterStock> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(OpeWmsScooterStock::getDr, DelStatusEnum.VALID.getCode());
wrapper.eq(OpeWmsScooterStock::getGroupId, specificatId);
wrapper.eq(OpeWmsScooterStock::getColorId, colorId);
wrapper.eq(OpeWmsScooterStock::getStockType, 2);
wrapper.orderByDesc(OpeWmsScooterStock::getCreatedTime);
List<OpeWmsScooterStock> list = opeWmsScooterStockMapper.selectList(wrapper);
if (CollectionUtils.isEmpty(list)) {
result.setSuccess(Boolean.FALSE); // 正确
//result.setSuccess(Boolean.TRUE); //暂时
return result;
}
OpeWmsScooterStock scooterStock = list.get(0);
Integer ableStockQty = scooterStock.getAbleStockQty();
ableStockQty = null == ableStockQty ? 0 : ableStockQty;
// 询价单客户需求车辆数和可用库存数量作对比
if (scooterQuantity > ableStockQty) {
result.setSuccess(Boolean.FALSE);
} else if (scooterQuantity <= ableStockQty) {
result.setSuccess(Boolean.TRUE);
}
result.setRequestId(enter.getRequestId());
return result;
}
/**
* 组装同步车辆数据
*/
private List<SyncScooterDataDTO> buildData(Long scooterId, String tabletSn, Integer scooterModel, Long userId, String scooterNo) {
SyncScooterDataDTO model = new SyncScooterDataDTO();
model.setId(scooterId);
model.setScooterNo(scooterNo);
model.setTabletSn(tabletSn);
model.setModel(String.valueOf(scooterModel));
model.setUserId(userId);
return new ArrayList<>(Arrays.asList(model));
}
/**
* 生成车辆编号
*/
private String generateScooterNo() {
Calendar cal = Calendar.getInstance();
String year = String.valueOf(cal.get(Calendar.YEAR));
int month = cal.get(Calendar.MONTH) + 1;
int day = cal.get(Calendar.DAY_OF_MONTH);
// 编号规则:区域 + 产品范围 + 结构类型 + 额定功率 + 生产地点 + 年份 + 月份 + 生产流水号(数量从1开始)
StringBuilder sb = new StringBuilder();
sb.append("FR");
sb.append("ED");
sb.append("D");
sb.append("0");
sb.append(year.substring(2, 4));
sb.append(MonthCodeEnum.getMonthCodeByMonth(month));
// 获取当前时间戳,并截取最后6位拼接在编号最后
String timeStamp = String.valueOf(System.currentTimeMillis());
String sub = timeStamp.substring(timeStamp.length() - 6);
String number = String.format("%s%s%s", DayCodeEnum.getDayCodeByDay(day), "1", sub);
sb.append(number);
return sb.toString();
}
/**
* 点击分配按钮校验询价单是否被操作过
*/
/*@Override
public BooleanResult checkOperation(CustomerIdEnter enter) {
BooleanResult result = new BooleanResult();
result.setSuccess(Boolean.TRUE);
LambdaQueryWrapper<OpeCarDistributeNode> qw = new LambdaQueryWrapper<>();
qw.eq(OpeCarDistributeNode::getDr, Constant.DR_FALSE);
qw.eq(OpeCarDistributeNode::getCustomerId, enter.getCustomerId());
qw.last("limit 1");
OpeCarDistributeNode node = opeCarDistributeNodeMapper.selectOne(qw);
if (null != node) {
Integer flag = node.getFlag();
if (flag == 1 || flag == 2) {
result.setSuccess(Boolean.FALSE);
}
}
result.setRequestId(enter.getRequestId());
return result;
}*/
/**
* 根据客户id获得询价单型号id和颜色id
*/
public Map<String, Long> getSpecificatIdAndColorId(CustomerIdEnter enter) {
Map<String, Long> result = Maps.newHashMapWithExpectedSize(2);
// 得到询价单的产品id
LambdaQueryWrapper<OpeCustomerInquiry> opeCustomerInquiryWrapper = new LambdaQueryWrapper<>();
opeCustomerInquiryWrapper.eq(OpeCustomerInquiry::getDr, DelStatusEnum.VALID.getCode());
opeCustomerInquiryWrapper.eq(OpeCustomerInquiry::getCustomerId, enter.getCustomerId());
opeCustomerInquiryWrapper.orderByDesc(OpeCustomerInquiry::getCreatedTime);
List<OpeCustomerInquiry> list = opeCustomerInquiryMapper.selectList(opeCustomerInquiryWrapper);
if (CollectionUtils.isEmpty(list)) {
throw new SesWebRosException(ExceptionCodeEnums.CUSTOMER_NOT_EXIST.getCode(), ExceptionCodeEnums.CUSTOMER_NOT_EXIST.getMessage());
}
OpeCustomerInquiry customerInquiry = list.get(0);
Long productId = customerInquiry.getProductId();
if (null == productId) {
throw new SesWebRosException(ExceptionCodeEnums.PRODUCT_IS_NOT_EXIST.getCode(), ExceptionCodeEnums.PRODUCT_IS_NOT_EXIST.getMessage());
}
// 拿着产品id去ope_sale_scooter查询
OpeSaleScooter opeSaleScooter = opeSaleScooterMapper.selectById(productId);
if (null == opeSaleScooter) {
throw new SesWebRosException(ExceptionCodeEnums.PRODUCT_IS_NOT_EXIST.getCode(), ExceptionCodeEnums.PRODUCT_IS_NOT_EXIST.getMessage());
}
// 得到型号id和颜色id
Long groupId = opeSaleScooter.getGroupId();
Long colorId = opeSaleScooter.getColorId();
result.put("specificatId", groupId);
result.put("colorId", colorId);
return result;
}
/**
* 根据型号id获取型号名称
*/
public String getSpecificatNameById(Long specificatId) {
if (null == specificatId) {
throw new SesWebRosException(ExceptionCodeEnums.SPECIFICAT_ID_NOT_EMPTY.getCode(), ExceptionCodeEnums.SPECIFICAT_ID_NOT_EMPTY.getMessage());
}
OpeSpecificatType specificatType = opeSpecificatTypeMapper.selectById(specificatId);
if (null != specificatType) {
String name = specificatType.getSpecificatName();
if (StringUtils.isNotBlank(name)) {
return name;
}
}
throw new SesWebRosException(ExceptionCodeEnums.SPECIFICAT_TYPE_NOT_EXIST.getCode(), ExceptionCodeEnums.SPECIFICAT_TYPE_NOT_EXIST.getMessage());
}
/**
* 根据颜色id获取颜色名称和色值
*/
public Map<String, String> getColorNameAndValueById(Long colorId) {
if (null == colorId) {
throw new SesWebRosException(ExceptionCodeEnums.COLOR_ID_NOT_EMPTY.getCode(), ExceptionCodeEnums.COLOR_ID_NOT_EMPTY.getMessage());
}
Map<String, String> map = Maps.newHashMapWithExpectedSize(2);
OpeColor color = opeColorMapper.selectById(colorId);
if (null != color) {
String colorName = color.getColorName();
String colorValue = color.getColorValue();
if (StringUtils.isNotBlank(colorName)) {
map.put("colorName", colorName);
}
if (StringUtils.isNotBlank(colorValue)) {
map.put("colorValue", colorValue);
}
return map;
}
throw new SesWebRosException(ExceptionCodeEnums.COLOR_NOT_EXIST.getCode(), ExceptionCodeEnums.COLOR_NOT_EXIST.getMessage());
}
/**
* 从指定数组中生成随机数
*/
public String generateRangeRandom() {
String[] array = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "X"};
int index = (int) (Math.random() * array.length);
return array[index];
}
/**
* 替换Vin的第九位数字(校验vin)
* @param vin
* @return
*/
public static String checkVIN(String vin) {
Map vinMapWeighting = null;
Map vinMapValue = null;
vinMapWeighting = new HashMap();
vinMapValue = new HashMap();
vinMapWeighting.put(1, 8);
vinMapWeighting.put(2, 7);
vinMapWeighting.put(3, 6);
vinMapWeighting.put(4, 5);
vinMapWeighting.put(5, 4);
vinMapWeighting.put(6, 3);
vinMapWeighting.put(7, 2);
vinMapWeighting.put(8, 10);
vinMapWeighting.put(9, 0);
vinMapWeighting.put(10, 9);
vinMapWeighting.put(11, 8);
vinMapWeighting.put(12, 7);
vinMapWeighting.put(13, 6);
vinMapWeighting.put(14, 5);
vinMapWeighting.put(15, 4);
vinMapWeighting.put(16, 3);
vinMapWeighting.put(17, 2);
vinMapValue.put('0', 0);
vinMapValue.put('1', 1);
vinMapValue.put('2', 2);
vinMapValue.put('3', 3);
vinMapValue.put('4', 4);
vinMapValue.put('5', 5);
vinMapValue.put('6', 6);
vinMapValue.put('7', 7);
vinMapValue.put('8', 8);
vinMapValue.put('9', 9);
vinMapValue.put('A', 1);
vinMapValue.put('B', 2);
vinMapValue.put('C', 3);
vinMapValue.put('D', 4);
vinMapValue.put('E', 5);
vinMapValue.put('F', 6);
vinMapValue.put('G', 7);
vinMapValue.put('H', 8);
vinMapValue.put('J', 1);
vinMapValue.put('K', 2);
vinMapValue.put('M', 4);
vinMapValue.put('L', 3);
vinMapValue.put('N', 5);
vinMapValue.put('P', 7);
vinMapValue.put('R', 9);
vinMapValue.put('S', 2);
vinMapValue.put('T', 3);
vinMapValue.put('U', 4);
vinMapValue.put('V', 5);
vinMapValue.put('W', 6);
vinMapValue.put('X', 7);
vinMapValue.put('Y', 8);
vinMapValue.put('Z', 9);
boolean reultFlag = false;
String uppervin = vin.toUpperCase();
//排除字母O、I
if (vin == null || uppervin.indexOf("O") >= 0 || uppervin.indexOf("I") >= 0) {
reultFlag = false;
} else {
//1:长度为17
if (vin.length() == 17) {
int amount = 0;
char[] vinArr = uppervin.toCharArray();
for (int i = 0; i < vinArr.length; i++) {
//VIN码从从第一位开始,码数字的对应值×该位的加权值,计算全部17位的乘积值相加
Object o = vinMapValue.get(vinArr[i]);
Object o2 = vinMapWeighting.get(i + 1);
amount += Integer.parseInt(o==null?"":o.toString()) * Integer.parseInt(o2==null?"":o2.toString());
}
if (amount % 11 == 10) {
return "X";
} else {
int result = amount%11;
return String.valueOf(result);
}
}
}
return null;
}
/**
* 生成VIN Code
*/
public String generateVINCode(Long specificatId, String specificatName, Integer seatNumber) {
String msg = "VXS";
StringBuffer result = new StringBuffer();
// 世界工厂代码和车辆类型
result.append(msg);
result.append(ScooterTypeEnum.R2A.getCode());
// 车型编号和座位数量
String productType = ProductTypeEnum.showCode(specificatName);
result.append(productType);
result.append(seatNumber);
// 指定随机数
String random = generateRangeRandom();
result.append(random);
// 年份字母和工厂编号
Calendar cal = Calendar.getInstance();
String year = String.valueOf(cal.get(Calendar.YEAR));
String value = YearEnum.showValue(year);
result.append(value);
result.append(FactoryEnum.AOGE.getCode());
// 6位数递增序列号
List<Integer> codeList = Lists.newArrayList();
LambdaQueryWrapper<OpeCarDistribute> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(OpeCarDistribute::getSpecificatTypeId, specificatId);
wrapper.eq(OpeCarDistribute::getSeatNumber, seatNumber);
List<OpeCarDistribute> list = opeCarDistributeMapper.selectList(wrapper);
if (CollectionUtils.isNotEmpty(list)) {
// 得到自增编号,从倒数第6位开始截取
for (OpeCarDistribute o : list) {
String vinCode = o.getVinCode();
if (StringUtils.isNotBlank(vinCode)) {
String sub = vinCode.substring(vinCode.length() - 6);
codeList.add(Integer.valueOf(sub));
}
}
if (CollectionUtils.isNotEmpty(codeList)) {
// 倒序排列
codeList.sort(Comparator.reverseOrder());
NumberFormat nf = NumberFormat.getInstance();
nf.setGroupingUsed(false);
nf.setMaximumIntegerDigits(6);
nf.setMinimumIntegerDigits(6);
String code = nf.format(new Double(codeList.get(0) + 1));
result.append(code);
} else {
result.append("000001");
}
} else {
result.append("000001");
}
//根据生成的vin得到正确的第九位数字
String nineCode = checkVIN(result.toString());
//用正确的第九位数字替换之前随机生成的第九位数字
result.replace(8,9, nineCode);
return result.toString();
}
/**
* 生成105条SSN
*/
@Override
public List<String> testGenerateVINCode(GeneralEnter enter) {
Integer[] array = {1, 2};
List<String> list = Lists.newArrayList();
for (int i = 0; i < 400; i++) {
int index = (int) (Math.random() * array.length);
Integer seat = array[index];
String s = show(Long.valueOf("1006236"), "E50", 2, i + 1);
list.add(s);
}
return list;
}
/**
* @param specificatId 规格类型id
* @param specificatName 车型类型
* @param seatNumber 座位数量类型
* @param i
* @return
*/
@Override
public String show(Long specificatId, String specificatName, Integer seatNumber, int i) {
String msg = "VXS";
StringBuffer result = new StringBuffer();
// 世界工厂代码和车辆类型
result.append(msg);
result.append(ScooterTypeEnum.R2A.getCode());
// 车型编号和座位数量
String productType = ProductTypeEnum.showCode(specificatName);
result.append(productType);
result.append(seatNumber);
// 指定随机数
String random = generateRangeRandom();
result.append(random);
// 年份字母和工厂编号
Calendar cal = Calendar.getInstance();
String year = String.valueOf(cal.get(Calendar.YEAR));
String value = YearEnum.showValue(year);
result.append(value);
result.append(FactoryEnum.AOGE.getCode());
/*if (i < 10) {
result.append("00000" + i);
} else if (i < 100) {
result.append("0000" + i);
} else if (i < 1000) {
result.append("000" + i);
}*/
List<Integer> codeList = Lists.newArrayList();
LambdaQueryWrapper<OpeCarDistribute> wrapper = new LambdaQueryWrapper<>();
wrapper.eq(OpeCarDistribute::getSpecificatTypeId, specificatId);
wrapper.eq(OpeCarDistribute::getSeatNumber, seatNumber);
List<OpeCarDistribute> list = opeCarDistributeMapper.selectList(wrapper);
if (CollectionUtils.isNotEmpty(list)) {
// 得到自增编号,从倒数第6位开始截取
for (OpeCarDistribute o : list) {
String vinCode = o.getVinCode();
String sub = vinCode.substring(vinCode.length() - 6);
codeList.add(Integer.valueOf(sub));
}
// 倒序排列
codeList.sort(Comparator.reverseOrder());
NumberFormat nf = NumberFormat.getInstance();
nf.setGroupingUsed(false);
nf.setMaximumIntegerDigits(6);
nf.setMinimumIntegerDigits(6);
String code = nf.format(new Double(codeList.get(0) + 1));
result.append(code);
} else {
result.append("000001");
}
//根据生成的vin得到正确的第九位数字
String nineCode = checkVIN(result.toString());
//用正确的第九位数字替换之前随机生成的第九位数字
result.replace(8,9, nineCode);
logger.info(result.toString()+"{result>>>>>>>>>>>>>>>>>>>>>>>}");
// 新增到主表
OpeCarDistribute model = new OpeCarDistribute();
model.setTenantId(1L);
model.setUserId(1L);
model.setCustomerId(1L);
model.setSpecificatTypeId(specificatId);
model.setSeatNumber(seatNumber);
model.setCreatedBy(1L);
model.setVinCode(result.toString());
model.setCreatedTime(new Date());
opeCarDistributeMapper.insert(model);
return result.toString();
}
}
|
janvi16/-HACKTOBERFEST2K20 | Python/list_comprehension.py | <gh_stars>10-100
# create a list
nums = [i for i in range(10)]
print(nums)
# with conditional
odds = [i for i in nums if i % 2 != 0]
print(odds)
|
serbaut/cloudstack | api/src/org/apache/cloudstack/api/response/RolePermissionResponse.java | <gh_stars>10-100
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package org.apache.cloudstack.api.response;
import com.cloud.serializer.Param;
import com.google.gson.annotations.SerializedName;
import org.apache.cloudstack.acl.RolePermission;
import org.apache.cloudstack.acl.Rule;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.BaseResponse;
import org.apache.cloudstack.api.EntityReference;
@EntityReference(value = RolePermission.class)
public class RolePermissionResponse extends BaseResponse {
@SerializedName(ApiConstants.ID)
@Param(description = "the ID of the role permission")
private String id;
@SerializedName(ApiConstants.ROLE_ID)
@Param(description = "the ID of the role to which the role permission belongs")
private String roleId;
@SerializedName(ApiConstants.ROLE_NAME)
@Param(description = "the name of the role to which the role permission belongs")
private String roleName;
@SerializedName(ApiConstants.RULE)
@Param(description = "the api name or wildcard rule")
private String rule;
@SerializedName(ApiConstants.PERMISSION)
@Param(description = "the permission type of the api name or wildcard rule, allow/deny")
private String rulePermission;
@SerializedName(ApiConstants.DESCRIPTION)
@Param(description = "the description of the role permission")
private String ruleDescription;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getRoleId() {
return roleId;
}
public void setRoleId(String roleId) {
this.roleId = roleId;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getRule() {
return rule;
}
public void setRule(Rule rule) {
if (rule != null) {
this.rule = rule.getRuleString();
}
}
public String getRulePermission() {
return rulePermission;
}
public void setRulePermission(RolePermission.Permission rulePermission) {
if (rulePermission != null) {
this.rulePermission = rulePermission.name().toLowerCase();
}
}
public void setDescription(String description) {
this.ruleDescription = description;
}
} |
projectPiki/pikmin2 | src/plugProjectOgawaU/ogAngleMgr.cpp | <gh_stars>10-100
#include "types.h"
#include "og/Screen/AngleMgr.h"
#include "Dolphin/math.h"
namespace og {
namespace Screen {
/*
* --INFO--
* Address: 8033028C
* Size: 00002C
*/
AngleMgr::AngleMgr()
{
m_currentAngle = 0.0f;
m_angleStep = 0.0f;
m_targetAngle = 0.0f;
m_interpRate = 0.3f;
m_scale = 1.0f;
m_state = AGM_Start;
}
/*
* --INFO--
* Address: 803302B8
* Size: 000010
*/
void AngleMgr::init(float curAngle, float interpRate, float scale)
{
m_currentAngle = curAngle;
m_interpRate = interpRate;
m_scale = scale;
}
/*
* --INFO--
* Address: 803302C8
* Size: 000080
*/
void AngleMgr::chase(float target, float step)
{
// Wrap to (0, TAU)
m_targetAngle = target;
while (m_targetAngle < 0.0f) {
m_targetAngle += TAU;
}
while (m_targetAngle > TAU) {
m_targetAngle -= TAU;
}
// Wrap to (-HALF_PI, HALF_PI)
m_angleStep = step;
if (m_angleStep > HALF_PI) {
m_angleStep = HALF_PI;
}
if (m_angleStep < -HALF_PI) {
m_angleStep = -HALF_PI;
}
m_state = AGM_Chase;
}
/*
* --INFO--
* Address: 80330348
* Size: 0001A8
*/
float AngleMgr::calc()
{
if (m_state == AGM_Chase) {
m_currentAngle += m_angleStep;
if (m_currentAngle < 0.0f) {
m_currentAngle += TAU;
} else if (m_currentAngle >= TAU) {
m_currentAngle = (m_currentAngle - TAU);
}
f32 distance = m_targetAngle - m_currentAngle;
if (FABS(distance) > PI) {
// TODO: figure out what f2 is!
f32 f2 = TAU - FABS(distance);
if (distance > 0.0f) {
if ((m_angleStep > 0.0f) && (f2 > FABS(m_angleStep * m_scale))) {
m_angleStep = (-m_angleStep * m_interpRate);
}
} else if ((m_angleStep < 0.0f) && (f2 > FABS(m_angleStep * m_scale))) {
m_angleStep = (-m_angleStep * m_interpRate);
}
} else {
f32 f2 = FABS(distance);
if (distance > 0.0f) {
if ((m_angleStep < 0.0f) && (f2 > FABS(m_angleStep * m_scale))) {
m_angleStep = (-m_angleStep * m_interpRate);
}
} else if ((m_angleStep > 0.0f) && (f2 > FABS(m_angleStep * m_scale))) {
m_angleStep = (-m_angleStep * m_interpRate);
}
}
if (FABS(m_angleStep) < 0.001f) {
m_state = AGM_Finish;
m_currentAngle = m_targetAngle;
m_angleStep = 0.0f;
}
}
return m_currentAngle;
}
} // namespace Screen
} // namespace og
|
opendata26/PSVRTracker | src/psvrservice/Device/Enumerator/TrackerDeviceEnumerator.h | #ifndef TRACKER_DEVICE_ENUMERATOR_H
#define TRACKER_DEVICE_ENUMERATOR_H
//-- includes -----
#include "DeviceEnumerator.h"
#include "USBApiInterface.h"
#include <string>
//-- definitions -----
class TrackerDeviceEnumerator : public DeviceEnumerator
{
public:
enum eAPIType
{
CommunicationType_INVALID= -1,
CommunicationType_USB,
CommunicationType_WMF,
CommunicationType_ALL
};
TrackerDeviceEnumerator(eAPIType api_type);
TrackerDeviceEnumerator(eAPIType api_type, CommonSensorState::eDeviceType deviceTypeFilter);
TrackerDeviceEnumerator(const std::string &usb_path);
~TrackerDeviceEnumerator();
bool is_valid() const override;
bool next() override;
const char *get_path() const override;
int get_vendor_id() const override;
int get_product_id() const override;
inline int get_camera_index() const { return camera_index; }
eAPIType get_api_type() const;
const class WMFCameraEnumerator *get_windows_media_foundation_camera_enumerator() const;
const class TrackerUSBDeviceEnumerator *get_usb_tracker_enumerator() const;
protected:
void allocate_child_enumerator(int enumerator_index);
private:
eAPIType api_type;
DeviceEnumerator **enumerators;
int enumerator_count;
int enumerator_index;
int camera_index;
};
#endif // TRACKER_DEVICE_ENUMERATOR_H |
lauracristinaes/aula-java | hibernate-release-5.3.7.Final/project/hibernate-core/src/main/java/org/hibernate/result/internal/OutputsImpl.java | /*
* Hibernate, Relational Persistence for Idiomatic Java
*
* License: GNU Lesser General Public License (LGPL), version 2.1 or later.
* See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
*/
package org.hibernate.result.internal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.function.Supplier;
import org.hibernate.JDBCException;
import org.hibernate.engine.spi.QueryParameters;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.internal.CoreLogging;
import org.hibernate.loader.EntityAliases;
import org.hibernate.loader.custom.CustomLoader;
import org.hibernate.loader.custom.CustomQuery;
import org.hibernate.loader.custom.Return;
import org.hibernate.loader.custom.RootReturn;
import org.hibernate.loader.custom.sql.SQLQueryReturnProcessor;
import org.hibernate.param.ParameterBinder;
import org.hibernate.result.NoMoreReturnsException;
import org.hibernate.result.Output;
import org.hibernate.result.Outputs;
import org.hibernate.result.spi.ResultContext;
import org.jboss.logging.Logger;
/**
* @author <NAME>
*/
public class OutputsImpl implements Outputs {
private static final Logger log = CoreLogging.logger( OutputsImpl.class );
private final ResultContext context;
private final PreparedStatement jdbcStatement;
private final CustomLoaderExtension loader;
private CurrentReturnState currentReturnState;
public OutputsImpl(ResultContext context, PreparedStatement jdbcStatement) {
this.context = context;
this.jdbcStatement = jdbcStatement;
// For now... but see the LoadPlan work; eventually this should just be a ResultSetProcessor.
this.loader = buildSpecializedCustomLoader( context );
try {
final boolean isResultSet = jdbcStatement.execute();
currentReturnState = buildCurrentReturnState( isResultSet );
}
catch (SQLException e) {
throw convert( e, "Error calling CallableStatement.getMoreResults" );
}
}
private CurrentReturnState buildCurrentReturnState(boolean isResultSet) {
int updateCount = -1;
if ( ! isResultSet ) {
try {
updateCount = jdbcStatement.getUpdateCount();
}
catch (SQLException e) {
throw convert( e, "Error calling CallableStatement.getUpdateCount" );
}
}
return buildCurrentReturnState( isResultSet, updateCount );
}
protected CurrentReturnState buildCurrentReturnState(boolean isResultSet, int updateCount) {
return new CurrentReturnState( isResultSet, updateCount );
}
protected JDBCException convert(SQLException e, String message) {
return context.getSession().getJdbcServices().getSqlExceptionHelper().convert(
e,
message,
context.getSql()
);
}
@Override
public Output getCurrent() {
if ( currentReturnState == null ) {
return null;
}
return currentReturnState.getOutput();
}
@Override
public boolean goToNext() {
if ( currentReturnState == null ) {
return false;
}
if ( currentReturnState.indicatesMoreOutputs() ) {
// prepare the next return state
try {
final boolean isResultSet = jdbcStatement.getMoreResults();
currentReturnState = buildCurrentReturnState( isResultSet );
}
catch (SQLException e) {
throw convert( e, "Error calling CallableStatement.getMoreResults" );
}
}
// and return
return currentReturnState != null && currentReturnState.indicatesMoreOutputs();
}
@Override
public void release() {
try {
jdbcStatement.close();
}
catch (SQLException e) {
log.debug( "Unable to close PreparedStatement", e );
}
}
private List extractCurrentResults() {
try {
return extractResults( jdbcStatement.getResultSet() );
}
catch (SQLException e) {
throw convert( e, "Error calling CallableStatement.getResultSet" );
}
}
protected List extractResults(ResultSet resultSet) {
try {
return loader.processResultSet( resultSet );
}
catch (SQLException e) {
throw convert( e, "Error extracting results from CallableStatement" );
}
}
/**
* Encapsulates the information needed to interpret the current return within a result
*/
protected class CurrentReturnState {
private final boolean isResultSet;
private final int updateCount;
private Output rtn;
protected CurrentReturnState(boolean isResultSet, int updateCount) {
this.isResultSet = isResultSet;
this.updateCount = updateCount;
}
public boolean indicatesMoreOutputs() {
return isResultSet() || getUpdateCount() >= 0;
}
public boolean isResultSet() {
return isResultSet;
}
public int getUpdateCount() {
return updateCount;
}
public Output getOutput() {
if ( rtn == null ) {
rtn = buildOutput();
}
return rtn;
}
protected Output buildOutput() {
if ( log.isDebugEnabled() ) {
log.debugf(
"Building Return [isResultSet=%s, updateCount=%s, extendedReturn=%s",
isResultSet(),
getUpdateCount(),
hasExtendedReturns()
);
}
if ( isResultSet() ) {
return buildResultSetOutput( extractCurrentResults() );
}
else if ( getUpdateCount() >= 0 ) {
return buildUpdateCountOutput( updateCount );
}
else if ( hasExtendedReturns() ) {
return buildExtendedReturn();
}
throw new NoMoreReturnsException();
}
// hooks for stored procedure (out param) processing ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
protected Output buildResultSetOutput(List list) {
return new ResultSetOutputImpl( list );
}
protected Output buildResultSetOutput(Supplier<List> listSupplier) {
return new ResultSetOutputImpl( listSupplier );
}
protected Output buildUpdateCountOutput(int updateCount) {
return new UpdateCountOutputImpl( updateCount );
}
protected boolean hasExtendedReturns() {
return false;
}
protected Output buildExtendedReturn() {
throw new IllegalStateException( "State does not define extended returns" );
}
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Hooks into Hibernate's Loader hierarchy for ResultSet -> Object mapping
private static CustomLoaderExtension buildSpecializedCustomLoader(final ResultContext context) {
// might be better to just manually construct the Return(s).. SQLQueryReturnProcessor does a lot of
// work that is really unnecessary here.
final SQLQueryReturnProcessor processor = new SQLQueryReturnProcessor(
context.getQueryReturns(),
context.getSession().getFactory()
);
processor.process();
final List<org.hibernate.loader.custom.Return> customReturns = processor.generateCallableReturns();
CustomQuery customQuery = new CustomQuery() {
@Override
public String getSQL() {
return context.getSql();
}
@Override
public Set<String> getQuerySpaces() {
return context.getSynchronizedQuerySpaces();
}
@Override
public List<ParameterBinder> getParameterValueBinders() {
// no parameters in terms of embedded in the SQL string
return Collections.emptyList();
}
@Override
public List<org.hibernate.loader.custom.Return> getCustomQueryReturns() {
return customReturns;
}
};
return new CustomLoaderExtension(
customQuery,
context.getQueryParameters(),
context.getSession()
);
}
private static class CustomLoaderExtension extends CustomLoader {
private static final EntityAliases[] NO_ALIASES = new EntityAliases[0];
private final QueryParameters queryParameters;
private final SharedSessionContractImplementor session;
private final EntityAliases[] entityAliases;
private boolean needsDiscovery = true;
public CustomLoaderExtension(
CustomQuery customQuery,
QueryParameters queryParameters,
SharedSessionContractImplementor session) {
super( customQuery, session.getFactory() );
this.queryParameters = queryParameters;
this.session = session;
entityAliases = interpretEntityAliases( customQuery.getCustomQueryReturns() );
}
private EntityAliases[] interpretEntityAliases(List<Return> customQueryReturns) {
final List<EntityAliases> entityAliases = new ArrayList<>();
for ( Return queryReturn : customQueryReturns ) {
if ( !RootReturn.class.isInstance( queryReturn ) ) {
continue;
}
entityAliases.add( ( (RootReturn) queryReturn ).getEntityAliases() );
}
if ( entityAliases.isEmpty() ) {
return NO_ALIASES;
}
return entityAliases.toArray( new EntityAliases[ entityAliases.size() ] );
}
@Override
protected EntityAliases[] getEntityAliases() {
return entityAliases;
}
// todo : this would be a great way to add locking to stored procedure support (at least where returning entities).
public List processResultSet(ResultSet resultSet) throws SQLException {
if ( needsDiscovery ) {
super.autoDiscoverTypes( resultSet );
// todo : EntityAliases discovery
needsDiscovery = false;
}
return super.processResultSet(
resultSet,
queryParameters,
session,
true,
null,
Integer.MAX_VALUE,
Collections.emptyList()
);
}
}
}
|
Stephen-Seo/SwapShop | src/swapShop/entities/BlueBricks.cpp | <reponame>Stephen-Seo/SwapShop<gh_stars>0
#include <swapShop/entities/BlueBricks.hpp>
BlueBricks::BlueBricks(const sf::Texture& texture) :
SwapEntity(texture),
timeCounter(0.0f),
currentFrame(0)
{
sprite.setSprite(0, 6*16, 0);
sprite.setSprite(16, 6*16, 1);
sprite.setSprite(2*16, 6*16, 2);
sprite.setSprite(3*16, 6*16, 3);
}
void BlueBricks::updateCurrent(sf::Time dt, Context context)
{
timeCounter += dt.asSeconds();
if(timeCounter >= BLUE_BRICKS_FRAME_TIME)
{
timeCounter = 0.0f;
currentFrame = (currentFrame + 1) % 4;
sprite.displaySprite(currentFrame);
}
sprite.update(dt);
}
void BlueBricks::handleEventCurrent(const sf::Event& event, Context context)
{
}
void BlueBricks::drawCurrent(sf::RenderTarget& target, sf::RenderStates states) const
{
target.draw(sprite, states);
}
|
PolySync/core-python-api | ps_util/features/steps/esr_eth_msg_xcp.py | <reponame>PolySync/core-python-api<gh_stars>0
# WARNING: Auto-generated file. Any changes are subject to being overwritten
# by setup.py build script.
#!/usr/bin/python
import time
from behave import given
from behave import when
from behave import then
from hamcrest import assert_that, equal_to
try:
import polysync.node as ps_node
from polysync.data_model.types import Py_esr_eth_msg_xcp
from polysync.data_model._internal.compare import esr_eth_msg_xcp_type_convert_testable, Py_esr_eth_msg_xcp_initialize_random
from polysync.data_model.message_support.esr_eth_msg_xcp import publish, subscribe
except ImportError:
raise ImportError(
'Py_esr_eth_msg_xcp module dependencies \
missing for tests, is the project built?')
@given('I have a Py_esr_eth_msg_xcp object')
def step_impl(context):
pass
@when('I convert it to its C API equivalent a esr_eth_msg_xcp')
def step_impl(context):
pass
@when('I convert the esr_eth_msg_xcp back to a Py_esr_eth_msg_xcp')
def step_impl(context):
pass
@then('the esr_eth_msg_xcp values are equivalent to each Py_esr_eth_msg_xcp value')
def step_impl(context):
msg = Py_esr_eth_msg_xcp_initialize_random()
result = esr_eth_msg_xcp_type_convert_testable(msg)
assert not result, result
@given('a esr_eth_msg_xcp.publish function exists')
def step_impl(context):
assert callable(publish)
@when('I try to publish something that is not of type Py_esr_eth_msg_xcp')
def step_impl(context):
bad_obj = "not the right type of object!"
context.exception = None
try:
publish(bad_obj)
except Exception as e:
context.exception = e
@then('a {exeption} indicates the type was not Py_esr_eth_msg_xcp')
def step_impl(context, exeption):
assert isinstance(context.exception, eval(exeption)), \
"Invalid exception %s - expected %s" \
% (type(context.exception).__name__, exeption)
GLOBAL_TIMESTAMP = None
GLOBAL_GUID = None
def Py_esr_eth_msg_xcp_handler(msg):
if msg.header.src_guid == GLOBAL_GUID:
global GLOBAL_TIMESTAMP
GLOBAL_TIMESTAMP = msg.header.timestamp
@given(u'I have a licensed PsNode for publishing Py_esr_eth_msg_xcp')
def step_impl(context):
assert context.node_ref
global GLOBAL_GUID
GLOBAL_GUID = context.my_guid
@given(u'I have a Py_esr_eth_msg_xcp')
def step_impl(context):
context.msg = Py_esr_eth_msg_xcp()
context.msg.header.timestamp = 0xFFFF
@given(u'I have a handler for Py_esr_eth_msg_xcp subscription')
def step_impl(context):
assert Py_esr_eth_msg_xcp_handler
subscribe(handler=Py_esr_eth_msg_xcp_handler)
@when(u'I publish my Py_esr_eth_msg_xcp')
def step_impl(context):
publish(context.msg)
@then(u'I receive the corresponding Py_esr_eth_msg_xcp in my handler')
def step_impl(context):
global GLOBAL_TIMESTAMP
while not GLOBAL_TIMESTAMP:
time.sleep(1)
assert_that(context.msg.header.timestamp, equal_to(GLOBAL_TIMESTAMP))
|
xzhan96/chromium.src | third_party/WebKit/Source/core/frame/FrameView.cpp | /*
* Copyright (C) 1998, 1999 <NAME> <<EMAIL>>
* 1999 <NAME> <<EMAIL>>
* 1999 <NAME> <<EMAIL>>
* 2000 <NAME> <<EMAIL>>
* Copyright (C) 2004, 2005, 2006, 2007, 2008 Apple Inc. All rights reserved.
* (C) 2006 <NAME> (<EMAIL>)
* (C) 2006 <NAME> (<EMAIL>)
* Copyright (C) 2009 Google Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "core/frame/FrameView.h"
#include "core/HTMLNames.h"
#include "core/MediaTypeNames.h"
#include "core/animation/DocumentAnimations.h"
#include "core/css/FontFaceSet.h"
#include "core/css/resolver/StyleResolver.h"
#include "core/dom/AXObjectCache.h"
#include "core/dom/DOMNodeIds.h"
#include "core/dom/ElementVisibilityObserver.h"
#include "core/dom/Fullscreen.h"
#include "core/dom/IntersectionObserverCallback.h"
#include "core/dom/IntersectionObserverController.h"
#include "core/dom/IntersectionObserverInit.h"
#include "core/dom/TaskRunnerHelper.h"
#include "core/editing/EditingUtilities.h"
#include "core/editing/FrameSelection.h"
#include "core/editing/RenderedPosition.h"
#include "core/editing/markers/DocumentMarkerController.h"
#include "core/events/ErrorEvent.h"
#include "core/fetch/ResourceFetcher.h"
#include "core/frame/BrowserControls.h"
#include "core/frame/EventHandlerRegistry.h"
#include "core/frame/FrameHost.h"
#include "core/frame/LocalFrame.h"
#include "core/frame/Location.h"
#include "core/frame/PageScaleConstraintsSet.h"
#include "core/frame/PerformanceMonitor.h"
#include "core/frame/Settings.h"
#include "core/frame/VisualViewport.h"
#include "core/html/HTMLFrameElement.h"
#include "core/html/HTMLPlugInElement.h"
#include "core/html/TextControlElement.h"
#include "core/html/parser/TextResourceDecoder.h"
#include "core/input/EventHandler.h"
#include "core/inspector/InspectorInstrumentation.h"
#include "core/inspector/InspectorTraceEvents.h"
#include "core/layout/LayoutAnalyzer.h"
#include "core/layout/LayoutCounter.h"
#include "core/layout/LayoutEmbeddedObject.h"
#include "core/layout/LayoutPart.h"
#include "core/layout/LayoutScrollbar.h"
#include "core/layout/LayoutScrollbarPart.h"
#include "core/layout/LayoutView.h"
#include "core/layout/ScrollAlignment.h"
#include "core/layout/TextAutosizer.h"
#include "core/layout/TracedLayoutObject.h"
#include "core/layout/api/LayoutBoxModel.h"
#include "core/layout/api/LayoutItem.h"
#include "core/layout/api/LayoutPartItem.h"
#include "core/layout/api/LayoutViewItem.h"
#include "core/layout/compositing/CompositedLayerMapping.h"
#include "core/layout/compositing/CompositedSelection.h"
#include "core/layout/compositing/CompositingInputsUpdater.h"
#include "core/layout/compositing/PaintLayerCompositor.h"
#include "core/layout/svg/LayoutSVGRoot.h"
#include "core/loader/DocumentLoader.h"
#include "core/loader/FrameLoader.h"
#include "core/loader/FrameLoaderClient.h"
#include "core/observer/ResizeObserverController.h"
#include "core/page/AutoscrollController.h"
#include "core/page/ChromeClient.h"
#include "core/page/FocusController.h"
#include "core/page/FrameTree.h"
#include "core/page/Page.h"
#include "core/page/scrolling/RootScrollerUtil.h"
#include "core/page/scrolling/ScrollingCoordinator.h"
#include "core/page/scrolling/TopDocumentRootScrollerController.h"
#include "core/paint/FramePainter.h"
#include "core/paint/PaintLayer.h"
#include "core/paint/PrePaintTreeWalk.h"
#include "core/plugins/PluginView.h"
#include "core/style/ComputedStyle.h"
#include "core/svg/SVGDocumentExtensions.h"
#include "core/svg/SVGSVGElement.h"
#include "platform/Histogram.h"
#include "platform/HostWindow.h"
#include "platform/RuntimeEnabledFeatures.h"
#include "platform/ScriptForbiddenScope.h"
#include "platform/fonts/FontCache.h"
#include "platform/geometry/DoubleRect.h"
#include "platform/geometry/FloatRect.h"
#include "platform/geometry/LayoutRect.h"
#include "platform/graphics/GraphicsContext.h"
#include "platform/graphics/GraphicsLayer.h"
#include "platform/graphics/GraphicsLayerDebugInfo.h"
#include "platform/graphics/compositing/PaintArtifactCompositor.h"
#include "platform/graphics/paint/CullRect.h"
#include "platform/graphics/paint/PaintController.h"
#include "platform/graphics/paint/ScopedPaintChunkProperties.h"
#include "platform/json/JSONValues.h"
#include "platform/scheduler/CancellableTaskFactory.h"
#include "platform/scroll/ScrollAnimatorBase.h"
#include "platform/scroll/ScrollbarTheme.h"
#include "platform/text/TextStream.h"
#include "platform/tracing/TraceEvent.h"
#include "platform/tracing/TracedValue.h"
#include "public/platform/WebDisplayItemList.h"
#include "public/platform/WebFrameScheduler.h"
#include "wtf/CurrentTime.h"
#include "wtf/PtrUtil.h"
#include "wtf/StdLibExtras.h"
#include <memory>
// Used to check for dirty layouts violating document lifecycle rules.
// If arg evaluates to true, the program will continue. If arg evaluates to
// false, program will crash if DCHECK_IS_ON() or return false from the current
// function.
#define CHECK_FOR_DIRTY_LAYOUT(arg) \
do { \
if (!(arg)) { \
NOTREACHED(); \
return false; \
} \
} while (false)
namespace blink {
using namespace HTMLNames;
// The maximum number of updateWidgets iterations that should be done before
// returning.
static const unsigned maxUpdateWidgetsIterations = 2;
static const double resourcePriorityUpdateDelayAfterScroll = 0.250;
static bool s_initialTrackAllPaintInvalidations = false;
FrameView::FrameView(LocalFrame& frame)
: m_frame(frame),
m_displayMode(WebDisplayModeBrowser),
m_canHaveScrollbars(true),
m_hasPendingLayout(false),
m_inSynchronousPostLayout(false),
m_postLayoutTasksTimer(TaskRunnerHelper::get(TaskType::Internal, &frame),
this,
&FrameView::postLayoutTimerFired),
m_updateWidgetsTimer(TaskRunnerHelper::get(TaskType::Internal, &frame),
this,
&FrameView::updateWidgetsTimerFired),
m_isTransparent(false),
m_baseBackgroundColor(Color::white),
m_mediaType(MediaTypeNames::screen),
m_safeToPropagateScrollToParent(true),
m_scrollCorner(nullptr),
m_stickyPositionObjectCount(0),
m_inputEventsScaleFactorForEmulation(1),
m_layoutSizeFixedToFrameSize(true),
m_didScrollTimer(this, &FrameView::didScrollTimerFired),
m_browserControlsViewportAdjustment(0),
m_needsUpdateWidgetGeometries(false),
m_needsUpdateViewportIntersection(true),
#if ENABLE(ASSERT)
m_hasBeenDisposed(false),
#endif
m_horizontalScrollbarMode(ScrollbarAuto),
m_verticalScrollbarMode(ScrollbarAuto),
m_horizontalScrollbarLock(false),
m_verticalScrollbarLock(false),
m_scrollbarsSuppressed(false),
m_inUpdateScrollbars(false),
m_frameTimingRequestsDirty(true),
m_hiddenForThrottling(false),
m_subtreeThrottled(false),
m_lifecycleUpdatesThrottled(false),
m_needsPaintPropertyUpdate(true),
m_currentUpdateLifecyclePhasesTargetState(
DocumentLifecycle::Uninitialized),
m_scrollAnchor(this),
m_scrollbarManager(*this),
m_needsScrollbarsUpdate(false),
m_suppressAdjustViewSize(false),
m_allowsLayoutInvalidationAfterLayoutClean(true) {
init();
}
FrameView* FrameView::create(LocalFrame& frame) {
FrameView* view = new FrameView(frame);
view->show();
return view;
}
FrameView* FrameView::create(LocalFrame& frame, const IntSize& initialSize) {
FrameView* view = new FrameView(frame);
view->Widget::setFrameRect(IntRect(view->location(), initialSize));
view->setLayoutSizeInternal(initialSize);
view->show();
return view;
}
FrameView::~FrameView() {
ASSERT(m_hasBeenDisposed);
}
DEFINE_TRACE(FrameView) {
visitor->trace(m_frame);
visitor->trace(m_fragmentAnchor);
visitor->trace(m_scrollableAreas);
visitor->trace(m_animatingScrollableAreas);
visitor->trace(m_autoSizeInfo);
visitor->trace(m_children);
visitor->trace(m_viewportScrollableArea);
visitor->trace(m_visibilityObserver);
visitor->trace(m_scrollAnchor);
visitor->trace(m_anchoringAdjustmentQueue);
visitor->trace(m_scrollbarManager);
Widget::trace(visitor);
ScrollableArea::trace(visitor);
}
void FrameView::reset() {
// The compositor throttles the main frame using deferred commits, we can't
// throttle it here or it seems the root compositor doesn't get setup
// properly.
if (RuntimeEnabledFeatures::
renderingPipelineThrottlingLoadingIframesEnabled())
m_lifecycleUpdatesThrottled = !frame().isMainFrame();
m_hasPendingLayout = false;
m_layoutSchedulingEnabled = true;
m_inSynchronousPostLayout = false;
m_layoutCount = 0;
m_nestedLayoutCount = 0;
m_postLayoutTasksTimer.stop();
m_updateWidgetsTimer.stop();
m_firstLayout = true;
m_safeToPropagateScrollToParent = true;
m_lastViewportSize = IntSize();
m_lastZoomFactor = 1.0f;
m_trackedObjectPaintInvalidations = wrapUnique(
s_initialTrackAllPaintInvalidations ? new Vector<ObjectPaintInvalidation>
: nullptr);
m_visuallyNonEmptyCharacterCount = 0;
m_visuallyNonEmptyPixelCount = 0;
m_isVisuallyNonEmpty = false;
m_layoutObjectCounter.reset();
clearFragmentAnchor();
m_viewportConstrainedObjects.reset();
m_layoutSubtreeRootList.clear();
m_orthogonalWritingModeRootList.clear();
}
// Call function for each non-throttled frame view in pre tree order.
// Note it needs a null check of the frame's layoutView to access it in case of
// detached frames.
template <typename Function>
void FrameView::forAllNonThrottledFrameViews(const Function& function) {
if (shouldThrottleRendering())
return;
function(*this);
for (Frame* child = m_frame->tree().firstChild(); child;
child = child->tree().nextSibling()) {
if (!child->isLocalFrame())
continue;
if (FrameView* childView = toLocalFrame(child)->view())
childView->forAllNonThrottledFrameViews(function);
}
}
void FrameView::init() {
reset();
m_size = LayoutSize();
// Propagate the marginwidth/height and scrolling modes to the view.
if (m_frame->owner() &&
m_frame->owner()->scrollingMode() == ScrollbarAlwaysOff)
setCanHaveScrollbars(false);
}
void FrameView::setupRenderThrottling() {
if (m_visibilityObserver)
return;
// We observe the frame owner element instead of the document element, because
// if the document has no content we can falsely think the frame is invisible.
// Note that this means we cannot throttle top-level frames or (currently)
// frames whose owner element is remote.
Element* targetElement = frame().deprecatedLocalOwner();
if (!targetElement)
return;
m_visibilityObserver = new ElementVisibilityObserver(
targetElement, WTF::bind(
[](FrameView* frameView, bool isVisible) {
if (!frameView)
return;
frameView->updateRenderThrottlingStatus(
!isVisible, frameView->m_subtreeThrottled);
frameView->maybeRecordLoadReason();
},
wrapWeakPersistent(this)));
m_visibilityObserver->start();
}
void FrameView::dispose() {
RELEASE_ASSERT(!isInPerformLayout());
if (ScrollAnimatorBase* scrollAnimator = existingScrollAnimator())
scrollAnimator->cancelAnimation();
cancelProgrammaticScrollAnimation();
detachScrollbars();
if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
scrollingCoordinator->willDestroyScrollableArea(this);
// We need to clear the RootFrameViewport's animator since it gets called
// from non-GC'd objects and RootFrameViewport will still have a pointer to
// this class.
if (m_viewportScrollableArea)
m_viewportScrollableArea->clearScrollableArea();
clearScrollableArea();
// Destroy |m_autoSizeInfo| as early as possible, to avoid dereferencing
// partially destroyed |this| via |m_autoSizeInfo->m_frameView|.
m_autoSizeInfo.clear();
m_postLayoutTasksTimer.stop();
m_didScrollTimer.stop();
// FIXME: Do we need to do something here for OOPI?
HTMLFrameOwnerElement* ownerElement = m_frame->deprecatedLocalOwner();
// TODO(dcheng): It seems buggy that we can have an owner element that points
// to another Widget. This can happen when a plugin element loads a frame
// (widget A of type FrameView) and then loads a plugin (widget B of type
// WebPluginContainerImpl). In this case, the frame's view is A and the frame
// element's owned widget is B. See https://crbug.com/673170 for an example.
if (ownerElement && ownerElement->ownedWidget() == this)
ownerElement->setWidget(nullptr);
#if ENABLE(ASSERT)
m_hasBeenDisposed = true;
#endif
}
void FrameView::detachScrollbars() {
// Previously, we detached custom scrollbars as early as possible to prevent
// Document::detachLayoutTree() from messing with the view such that its
// scroll bars won't be torn down. However, scripting in
// Document::detachLayoutTree() is forbidden
// now, so it's not clear if these edge cases can still happen.
// However, for Oilpan, we still need to remove the native scrollbars before
// we lose the connection to the HostWindow, so we just unconditionally
// detach any scrollbars now.
m_scrollbarManager.dispose();
if (m_scrollCorner) {
m_scrollCorner->destroy();
m_scrollCorner = nullptr;
}
}
void FrameView::ScrollbarManager::setHasHorizontalScrollbar(bool hasScrollbar) {
if (hasScrollbar == hasHorizontalScrollbar())
return;
if (hasScrollbar) {
m_hBar = createScrollbar(HorizontalScrollbar);
m_scrollableArea->layoutBox()->document().view()->addChild(m_hBar.get());
m_scrollableArea->didAddScrollbar(*m_hBar, HorizontalScrollbar);
m_hBar->styleChanged();
m_hBarIsAttached = 1;
} else {
m_hBarIsAttached = 0;
destroyScrollbar(HorizontalScrollbar);
}
m_scrollableArea->setScrollCornerNeedsPaintInvalidation();
}
void FrameView::ScrollbarManager::setHasVerticalScrollbar(bool hasScrollbar) {
if (hasScrollbar == hasVerticalScrollbar())
return;
if (hasScrollbar) {
m_vBar = createScrollbar(VerticalScrollbar);
m_scrollableArea->layoutBox()->document().view()->addChild(m_vBar.get());
m_scrollableArea->didAddScrollbar(*m_vBar, VerticalScrollbar);
m_vBar->styleChanged();
m_vBarIsAttached = 1;
} else {
m_vBarIsAttached = 0;
destroyScrollbar(VerticalScrollbar);
}
m_scrollableArea->setScrollCornerNeedsPaintInvalidation();
}
Scrollbar* FrameView::ScrollbarManager::createScrollbar(
ScrollbarOrientation orientation) {
Element* customScrollbarElement = nullptr;
LocalFrame* customScrollbarFrame = nullptr;
LayoutBox* box = m_scrollableArea->layoutBox();
if (box->document().view()->shouldUseCustomScrollbars(customScrollbarElement,
customScrollbarFrame)) {
return LayoutScrollbar::createCustomScrollbar(
m_scrollableArea.get(), orientation, customScrollbarElement,
customScrollbarFrame);
}
// Nobody set a custom style, so we just use a native scrollbar.
return Scrollbar::create(m_scrollableArea.get(), orientation,
RegularScrollbar,
&box->frame()->page()->chromeClient());
}
void FrameView::ScrollbarManager::destroyScrollbar(
ScrollbarOrientation orientation) {
Member<Scrollbar>& scrollbar =
orientation == HorizontalScrollbar ? m_hBar : m_vBar;
DCHECK(orientation == HorizontalScrollbar ? !m_hBarIsAttached
: !m_vBarIsAttached);
if (!scrollbar)
return;
m_scrollableArea->willRemoveScrollbar(*scrollbar, orientation);
m_scrollableArea->layoutBox()->document().view()->removeChild(
scrollbar.get());
scrollbar->disconnectFromScrollableArea();
scrollbar = nullptr;
}
void FrameView::recalculateCustomScrollbarStyle() {
bool didStyleChange = false;
if (horizontalScrollbar() && horizontalScrollbar()->isCustomScrollbar()) {
horizontalScrollbar()->styleChanged();
didStyleChange = true;
}
if (verticalScrollbar() && verticalScrollbar()->isCustomScrollbar()) {
verticalScrollbar()->styleChanged();
didStyleChange = true;
}
if (didStyleChange) {
updateScrollbarGeometry();
updateScrollCorner();
positionScrollbarLayers();
}
}
void FrameView::invalidateAllCustomScrollbarsOnActiveChanged() {
bool usesWindowInactiveSelector =
m_frame->document()->styleEngine().usesWindowInactiveSelector();
const ChildrenWidgetSet* viewChildren = children();
for (const Member<Widget>& child : *viewChildren) {
Widget* widget = child.get();
if (widget->isFrameView())
toFrameView(widget)->invalidateAllCustomScrollbarsOnActiveChanged();
else if (usesWindowInactiveSelector && widget->isScrollbar() &&
toScrollbar(widget)->isCustomScrollbar())
toScrollbar(widget)->styleChanged();
}
if (usesWindowInactiveSelector)
recalculateCustomScrollbarStyle();
}
void FrameView::clear() {
reset();
setScrollbarsSuppressed(true);
}
bool FrameView::didFirstLayout() const {
return !m_firstLayout;
}
void FrameView::invalidateRect(const IntRect& rect) {
LayoutPartItem layoutItem = m_frame->ownerLayoutItem();
if (layoutItem.isNull())
return;
IntRect paintInvalidationRect = rect;
paintInvalidationRect.move(
(layoutItem.borderLeft() + layoutItem.paddingLeft()).toInt(),
(layoutItem.borderTop() + layoutItem.paddingTop()).toInt());
// FIXME: We should not allow paint invalidation out of paint invalidation
// state. crbug.com/457415
DisablePaintInvalidationStateAsserts paintInvalidationAssertDisabler;
layoutItem.invalidatePaintRectangle(LayoutRect(paintInvalidationRect));
}
void FrameView::setFrameRect(const IntRect& newRect) {
IntRect oldRect = frameRect();
if (newRect == oldRect)
return;
Widget::setFrameRect(newRect);
const bool frameSizeChanged = oldRect.size() != newRect.size();
m_needsScrollbarsUpdate = frameSizeChanged;
// TODO(wjmaclean): find out why scrollbars fail to resize for complex
// subframes after changing the zoom level. For now always calling
// updateScrollbarsIfNeeded() here fixes the issue, but it would be good to
// discover the deeper cause of this. http://crbug.com/607987.
updateScrollbarsIfNeeded();
frameRectsChanged();
updateParentScrollableAreaSet();
if (LayoutViewItem layoutView = this->layoutViewItem()) {
// TODO(majidvp): It seems that this only needs to be called when size
// is updated ignoring any change in the location.
if (layoutView.usesCompositing())
layoutView.compositor()->frameViewDidChangeSize();
}
if (frameSizeChanged) {
viewportSizeChanged(newRect.width() != oldRect.width(),
newRect.height() != oldRect.height());
if (m_frame->isMainFrame())
m_frame->host()->visualViewport().mainFrameDidChangeSize();
frame().loader().restoreScrollPositionAndViewState();
}
}
Page* FrameView::page() const {
return frame().page();
}
LayoutView* FrameView::layoutView() const {
return frame().contentLayoutObject();
}
LayoutViewItem FrameView::layoutViewItem() const {
return LayoutViewItem(frame().contentLayoutObject());
}
ScrollingCoordinator* FrameView::scrollingCoordinator() const {
Page* p = page();
return p ? p->scrollingCoordinator() : 0;
}
CompositorAnimationTimeline* FrameView::compositorAnimationTimeline() const {
ScrollingCoordinator* c = scrollingCoordinator();
return c ? c->compositorAnimationTimeline() : nullptr;
}
LayoutBox* FrameView::layoutBox() const {
return layoutView();
}
FloatQuad FrameView::localToVisibleContentQuad(
const FloatQuad& quad,
const LayoutObject* localObject,
MapCoordinatesFlags flags) const {
LayoutBox* box = layoutBox();
if (!box)
return quad;
DCHECK(localObject);
FloatQuad result = localObject->localToAncestorQuad(quad, box, flags);
result.move(-scrollOffset());
return result;
}
void FrameView::setCanHaveScrollbars(bool canHaveScrollbars) {
m_canHaveScrollbars = canHaveScrollbars;
ScrollbarMode newVerticalMode = m_verticalScrollbarMode;
if (canHaveScrollbars && m_verticalScrollbarMode == ScrollbarAlwaysOff)
newVerticalMode = ScrollbarAuto;
else if (!canHaveScrollbars)
newVerticalMode = ScrollbarAlwaysOff;
ScrollbarMode newHorizontalMode = m_horizontalScrollbarMode;
if (canHaveScrollbars && m_horizontalScrollbarMode == ScrollbarAlwaysOff)
newHorizontalMode = ScrollbarAuto;
else if (!canHaveScrollbars)
newHorizontalMode = ScrollbarAlwaysOff;
setScrollbarModes(newHorizontalMode, newVerticalMode);
}
bool FrameView::shouldUseCustomScrollbars(
Element*& customScrollbarElement,
LocalFrame*& customScrollbarFrame) const {
customScrollbarElement = nullptr;
customScrollbarFrame = nullptr;
if (Settings* settings = m_frame->settings()) {
if (!settings->allowCustomScrollbarInMainFrame() && m_frame->isMainFrame())
return false;
}
// FIXME: We need to update the scrollbar dynamically as documents change (or
// as doc elements and bodies get discovered that have custom styles).
Document* doc = m_frame->document();
// Try the <body> element first as a scrollbar source.
Element* body = doc ? doc->body() : 0;
if (body && body->layoutObject() &&
body->layoutObject()->style()->hasPseudoStyle(PseudoIdScrollbar)) {
customScrollbarElement = body;
return true;
}
// If the <body> didn't have a custom style, then the root element might.
Element* docElement = doc ? doc->documentElement() : 0;
if (docElement && docElement->layoutObject() &&
docElement->layoutObject()->style()->hasPseudoStyle(PseudoIdScrollbar)) {
customScrollbarElement = docElement;
return true;
}
return false;
}
Scrollbar* FrameView::createScrollbar(ScrollbarOrientation orientation) {
return m_scrollbarManager.createScrollbar(orientation);
}
void FrameView::setContentsSize(const IntSize& size) {
if (size == contentsSize())
return;
m_contentsSize = size;
updateScrollbars();
ScrollableArea::contentsResized();
Page* page = frame().page();
if (!page)
return;
updateParentScrollableAreaSet();
page->chromeClient().contentsSizeChanged(m_frame.get(), size);
frame().loader().restoreScrollPositionAndViewState();
if (!RuntimeEnabledFeatures::rootLayerScrollingEnabled()) {
// The presence of overflow depends on the contents size. The scroll
// properties can change depending on whether overflow scrolling occurs.
setNeedsPaintPropertyUpdate();
}
}
void FrameView::adjustViewSize() {
if (m_suppressAdjustViewSize)
return;
LayoutViewItem layoutViewItem = this->layoutViewItem();
if (layoutViewItem.isNull())
return;
ASSERT(m_frame->view() == this);
const IntRect rect = layoutViewItem.documentRect();
const IntSize& size = rect.size();
const IntPoint origin(-rect.x(), -rect.y());
if (scrollOrigin() != origin) {
ScrollableArea::setScrollOrigin(origin);
// setContentSize (below) also calls updateScrollbars so we can avoid
// updating scrollbars twice by skipping the call here when the content
// size does not change.
if (!m_frame->document()->printing() && size == contentsSize())
updateScrollbars();
}
setContentsSize(size);
}
void FrameView::adjustViewSizeAndLayout() {
adjustViewSize();
if (needsLayout()) {
AutoReset<bool> suppressAdjustViewSize(&m_suppressAdjustViewSize, true);
layout();
}
}
void FrameView::calculateScrollbarModesFromOverflowStyle(
const ComputedStyle* style,
ScrollbarMode& hMode,
ScrollbarMode& vMode) {
hMode = vMode = ScrollbarAuto;
EOverflow overflowX = style->overflowX();
EOverflow overflowY = style->overflowY();
if (!shouldIgnoreOverflowHidden()) {
if (overflowX == OverflowHidden)
hMode = ScrollbarAlwaysOff;
if (overflowY == OverflowHidden)
vMode = ScrollbarAlwaysOff;
}
if (overflowX == OverflowScroll)
hMode = ScrollbarAlwaysOn;
if (overflowY == OverflowScroll)
vMode = ScrollbarAlwaysOn;
}
void FrameView::calculateScrollbarModes(
ScrollbarMode& hMode,
ScrollbarMode& vMode,
ScrollbarModesCalculationStrategy strategy) {
#define RETURN_SCROLLBAR_MODE(mode) \
{ \
hMode = vMode = mode; \
return; \
}
// Setting scrolling="no" on an iframe element disables scrolling.
if (m_frame->owner() &&
m_frame->owner()->scrollingMode() == ScrollbarAlwaysOff)
RETURN_SCROLLBAR_MODE(ScrollbarAlwaysOff);
// Framesets can't scroll.
Node* body = m_frame->document()->body();
if (isHTMLFrameSetElement(body) && body->layoutObject())
RETURN_SCROLLBAR_MODE(ScrollbarAlwaysOff);
// Scrollbars can be disabled by FrameView::setCanHaveScrollbars.
if (!m_canHaveScrollbars && strategy != RulesFromWebContentOnly)
RETURN_SCROLLBAR_MODE(ScrollbarAlwaysOff);
// This will be the LayoutObject for either the body element or the html
// element (see Document::viewportDefiningElement).
LayoutObject* viewport = viewportLayoutObject();
if (!viewport || !viewport->style())
RETURN_SCROLLBAR_MODE(ScrollbarAuto);
if (viewport->isSVGRoot()) {
// Don't allow overflow to affect <img> and css backgrounds
if (toLayoutSVGRoot(viewport)->isEmbeddedThroughSVGImage())
RETURN_SCROLLBAR_MODE(ScrollbarAuto);
// FIXME: evaluate if we can allow overflow for these cases too.
// Overflow is always hidden when stand-alone SVG documents are embedded.
if (toLayoutSVGRoot(viewport)
->isEmbeddedThroughFrameContainingSVGDocument())
RETURN_SCROLLBAR_MODE(ScrollbarAlwaysOff);
}
calculateScrollbarModesFromOverflowStyle(viewport->style(), hMode, vMode);
#undef RETURN_SCROLLBAR_MODE
}
void FrameView::updateAcceleratedCompositingSettings() {
if (LayoutViewItem layoutViewItem = this->layoutViewItem())
layoutViewItem.compositor()->updateAcceleratedCompositingSettings();
}
void FrameView::recalcOverflowAfterStyleChange() {
LayoutViewItem layoutViewItem = this->layoutViewItem();
RELEASE_ASSERT(!layoutViewItem.isNull());
if (!layoutViewItem.needsOverflowRecalcAfterStyleChange())
return;
layoutViewItem.recalcOverflowAfterStyleChange();
// Changing overflow should notify scrolling coordinator to ensures that it
// updates non-fast scroll rects even if there is no layout.
if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
scrollingCoordinator->notifyOverflowUpdated();
IntRect documentRect = layoutViewItem.documentRect();
if (scrollOrigin() == -documentRect.location() &&
contentsSize() == documentRect.size())
return;
if (needsLayout())
return;
// TODO(pdr): This should be refactored to just block scrollbar updates as
// we are not in a scrollbar update here and m_inUpdateScrollbars has other
// side effects. This scope is only for preventing a synchronous layout from
// scroll origin changes which would not be allowed during style recalc.
InUpdateScrollbarsScope inUpdateScrollbarsScope(this);
bool shouldHaveHorizontalScrollbar = false;
bool shouldHaveVerticalScrollbar = false;
computeScrollbarExistence(shouldHaveHorizontalScrollbar,
shouldHaveVerticalScrollbar, documentRect.size());
bool hasHorizontalScrollbar = horizontalScrollbar();
bool hasVerticalScrollbar = verticalScrollbar();
if (hasHorizontalScrollbar != shouldHaveHorizontalScrollbar ||
hasVerticalScrollbar != shouldHaveVerticalScrollbar) {
setNeedsLayout();
return;
}
adjustViewSize();
updateScrollbarGeometry();
if (scrollOriginChanged())
setNeedsLayout();
}
bool FrameView::usesCompositedScrolling() const {
LayoutViewItem layoutView = this->layoutViewItem();
if (layoutView.isNull())
return false;
if (m_frame->settings() &&
m_frame->settings()->preferCompositingToLCDTextEnabled())
return layoutView.compositor()->inCompositingMode();
return false;
}
bool FrameView::shouldScrollOnMainThread() const {
if (ScrollingCoordinator* sc = scrollingCoordinator()) {
if (sc->shouldUpdateScrollLayerPositionOnMainThread())
return true;
}
return ScrollableArea::shouldScrollOnMainThread();
}
GraphicsLayer* FrameView::layerForScrolling() const {
LayoutViewItem layoutView = this->layoutViewItem();
if (layoutView.isNull())
return nullptr;
return layoutView.compositor()->frameScrollLayer();
}
GraphicsLayer* FrameView::layerForHorizontalScrollbar() const {
LayoutViewItem layoutView = this->layoutViewItem();
if (layoutView.isNull())
return nullptr;
return layoutView.compositor()->layerForHorizontalScrollbar();
}
GraphicsLayer* FrameView::layerForVerticalScrollbar() const {
LayoutViewItem layoutView = this->layoutViewItem();
if (layoutView.isNull())
return nullptr;
return layoutView.compositor()->layerForVerticalScrollbar();
}
GraphicsLayer* FrameView::layerForScrollCorner() const {
LayoutViewItem layoutView = this->layoutViewItem();
if (layoutView.isNull())
return nullptr;
return layoutView.compositor()->layerForScrollCorner();
}
bool FrameView::isEnclosedInCompositingLayer() const {
// FIXME: It's a bug that compositing state isn't always up to date when this
// is called. crbug.com/366314
DisableCompositingQueryAsserts disabler;
LayoutItem frameOwnerLayoutItem = m_frame->ownerLayoutItem();
return !frameOwnerLayoutItem.isNull() &&
frameOwnerLayoutItem.enclosingLayer()
->enclosingLayerForPaintInvalidationCrossingFrameBoundaries();
}
void FrameView::countObjectsNeedingLayout(unsigned& needsLayoutObjects,
unsigned& totalObjects,
bool& isSubtree) {
needsLayoutObjects = 0;
totalObjects = 0;
isSubtree = isSubtreeLayout();
if (isSubtree)
m_layoutSubtreeRootList.countObjectsNeedingLayout(needsLayoutObjects,
totalObjects);
else
LayoutSubtreeRootList::countObjectsNeedingLayoutInRoot(
layoutView(), needsLayoutObjects, totalObjects);
}
inline void FrameView::forceLayoutParentViewIfNeeded() {
LayoutPartItem ownerLayoutItem = m_frame->ownerLayoutItem();
if (ownerLayoutItem.isNull() || !ownerLayoutItem.frame())
return;
LayoutReplaced* contentBox = embeddedReplacedContent();
if (!contentBox)
return;
LayoutSVGRoot* svgRoot = toLayoutSVGRoot(contentBox);
if (svgRoot->everHadLayout() && !svgRoot->needsLayout())
return;
// If the embedded SVG document appears the first time, the ownerLayoutObject
// has already finished layout without knowing about the existence of the
// embedded SVG document, because LayoutReplaced embeddedReplacedContent()
// returns 0, as long as the embedded document isn't loaded yet. Before
// bothering to lay out the SVG document, mark the ownerLayoutObject needing
// layout and ask its FrameView for a layout. After that the
// LayoutEmbeddedObject (ownerLayoutObject) carries the correct size, which
// LayoutSVGRoot::computeReplacedLogicalWidth/Height rely on, when laying out
// for the first time, or when the LayoutSVGRoot size has changed dynamically
// (eg. via <script>).
FrameView* frameView = ownerLayoutItem.frame()->view();
// Mark the owner layoutObject as needing layout.
ownerLayoutItem.setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(
LayoutInvalidationReason::Unknown);
// Synchronously enter layout, to layout the view containing the host
// object/embed/iframe.
ASSERT(frameView);
frameView->layout();
}
void FrameView::performPreLayoutTasks() {
TRACE_EVENT0("blink,benchmark", "FrameView::performPreLayoutTasks");
lifecycle().advanceTo(DocumentLifecycle::InPreLayout);
// Don't schedule more layouts, we're in one.
AutoReset<bool> changeSchedulingEnabled(&m_layoutSchedulingEnabled, false);
if (!m_nestedLayoutCount && !m_inSynchronousPostLayout &&
m_postLayoutTasksTimer.isActive()) {
// This is a new top-level layout. If there are any remaining tasks from the
// previous layout, finish them now.
m_inSynchronousPostLayout = true;
performPostLayoutTasks();
m_inSynchronousPostLayout = false;
}
bool wasResized = wasViewportResized();
Document* document = m_frame->document();
if (wasResized)
document->notifyResizeForViewportUnits();
// Viewport-dependent or device-dependent media queries may cause us to need
// completely different style information.
bool mainFrameRotation =
m_frame->isMainFrame() && m_frame->settings() &&
m_frame->settings()->mainFrameResizesAreOrientationChanges();
if (!document->styleResolver() ||
(wasResized &&
document->styleResolver()->mediaQueryAffectedByViewportChange()) ||
(wasResized && mainFrameRotation &&
document->styleResolver()->mediaQueryAffectedByDeviceChange())) {
document->mediaQueryAffectingValueChanged();
} else if (wasResized) {
document->evaluateMediaQueryList();
}
document->updateStyleAndLayoutTree();
lifecycle().advanceTo(DocumentLifecycle::StyleClean);
if (shouldPerformScrollAnchoring())
m_scrollAnchor.notifyBeforeLayout();
}
bool FrameView::shouldPerformScrollAnchoring() const {
return RuntimeEnabledFeatures::scrollAnchoringEnabled() &&
!RuntimeEnabledFeatures::rootLayerScrollingEnabled() &&
m_scrollAnchor.hasScroller() &&
layoutBox()->style()->overflowAnchor() != AnchorNone &&
!m_frame->document()->finishingOrIsPrinting();
}
static inline void layoutFromRootObject(LayoutObject& root) {
LayoutState layoutState(root);
root.layout();
}
void FrameView::prepareLayoutAnalyzer() {
bool isTracing = false;
TRACE_EVENT_CATEGORY_GROUP_ENABLED(
TRACE_DISABLED_BY_DEFAULT("blink.debug.layout"), &isTracing);
if (!isTracing) {
m_analyzer.reset();
return;
}
if (!m_analyzer)
m_analyzer = makeUnique<LayoutAnalyzer>();
m_analyzer->reset();
}
std::unique_ptr<TracedValue> FrameView::analyzerCounters() {
if (!m_analyzer)
return TracedValue::create();
std::unique_ptr<TracedValue> value = m_analyzer->toTracedValue();
value->setString("host", layoutViewItem().document().location()->host());
value->setString("frame",
String::format("0x%" PRIxPTR,
reinterpret_cast<uintptr_t>(m_frame.get())));
value->setInteger("contentsHeightAfterLayout",
layoutViewItem().documentRect().height());
value->setInteger("visibleHeight", visibleHeight());
value->setInteger(
"approximateBlankCharacterCount",
FontFaceSet::approximateBlankCharacterCount(*m_frame->document()));
return value;
}
#define PERFORM_LAYOUT_TRACE_CATEGORIES \
"blink,benchmark,rail," TRACE_DISABLED_BY_DEFAULT("blink.debug.layout")
void FrameView::performLayout(bool inSubtreeLayout) {
ASSERT(inSubtreeLayout || m_layoutSubtreeRootList.isEmpty());
int contentsHeightBeforeLayout = layoutViewItem().documentRect().height();
TRACE_EVENT_BEGIN1(PERFORM_LAYOUT_TRACE_CATEGORIES,
"FrameView::performLayout", "contentsHeightBeforeLayout",
contentsHeightBeforeLayout);
prepareLayoutAnalyzer();
ScriptForbiddenScope forbidScript;
ASSERT(!isInPerformLayout());
lifecycle().advanceTo(DocumentLifecycle::InPerformLayout);
// performLayout is the actual guts of layout().
// FIXME: The 300 other lines in layout() probably belong in other helper
// functions so that a single human could understand what layout() is actually
// doing.
forceLayoutParentViewIfNeeded();
if (hasOrthogonalWritingModeRoots())
layoutOrthogonalWritingModeRoots();
if (inSubtreeLayout) {
if (m_analyzer)
m_analyzer->increment(LayoutAnalyzer::PerformLayoutRootLayoutObjects,
m_layoutSubtreeRootList.size());
for (auto& root : m_layoutSubtreeRootList.ordered()) {
if (!root->needsLayout())
continue;
layoutFromRootObject(*root);
// We need to ensure that we mark up all layoutObjects up to the
// LayoutView for paint invalidation. This simplifies our code as we just
// always do a full tree walk.
if (LayoutItem container = LayoutItem(root->container()))
container.setMayNeedPaintInvalidation();
}
m_layoutSubtreeRootList.clear();
} else {
layoutFromRootObject(*layoutView());
}
m_frame->document()->fetcher()->updateAllImageResourcePriorities();
lifecycle().advanceTo(DocumentLifecycle::AfterPerformLayout);
TRACE_EVENT_END1(PERFORM_LAYOUT_TRACE_CATEGORIES, "FrameView::performLayout",
"counters", analyzerCounters());
FirstMeaningfulPaintDetector::from(*m_frame->document())
.markNextPaintAsMeaningfulIfNeeded(
m_layoutObjectCounter, contentsHeightBeforeLayout,
layoutViewItem().documentRect().height(), visibleHeight());
}
void FrameView::scheduleOrPerformPostLayoutTasks() {
if (m_postLayoutTasksTimer.isActive())
return;
if (!m_inSynchronousPostLayout) {
m_inSynchronousPostLayout = true;
// Calls resumeScheduledEvents()
performPostLayoutTasks();
m_inSynchronousPostLayout = false;
}
if (!m_postLayoutTasksTimer.isActive() &&
(needsLayout() || m_inSynchronousPostLayout)) {
// If we need layout or are already in a synchronous call to
// postLayoutTasks(), defer widget updates and event dispatch until after we
// return. postLayoutTasks() can make us need to update again, and we can
// get stuck in a nasty cycle unless we call it through the timer here.
m_postLayoutTasksTimer.startOneShot(0, BLINK_FROM_HERE);
if (needsLayout())
layout();
}
}
void FrameView::layout() {
// We should never layout a Document which is not in a LocalFrame.
ASSERT(m_frame);
ASSERT(m_frame->view() == this);
ASSERT(m_frame->page());
ScriptForbiddenScope forbidScript;
if (isInPerformLayout() || shouldThrottleRendering() ||
!m_frame->document()->isActive())
return;
TRACE_EVENT0("blink,benchmark", "FrameView::layout");
if (m_autoSizeInfo)
m_autoSizeInfo->autoSizeIfNeeded();
m_hasPendingLayout = false;
DocumentLifecycle::Scope lifecycleScope(lifecycle(),
DocumentLifecycle::LayoutClean);
Document* document = m_frame->document();
TRACE_EVENT_BEGIN1("devtools.timeline", "Layout", "beginData",
InspectorLayoutEvent::beginData(this));
PerformanceMonitor::willUpdateLayout(document);
performPreLayoutTasks();
// TODO(crbug.com/460956): The notion of a single root for layout is no longer
// applicable. Remove or update this code.
LayoutObject* rootForThisLayout = layoutView();
FontCachePurgePreventer fontCachePurgePreventer;
{
AutoReset<bool> changeSchedulingEnabled(&m_layoutSchedulingEnabled, false);
m_nestedLayoutCount++;
updateCounters();
// If the layout view was marked as needing layout after we added items in
// the subtree roots we need to clear the roots and do the layout from the
// layoutView.
if (layoutViewItem().needsLayout())
clearLayoutSubtreeRootsAndMarkContainingBlocks();
layoutViewItem().clearHitTestCache();
bool inSubtreeLayout = isSubtreeLayout();
// TODO(crbug.com/460956): The notion of a single root for layout is no
// longer applicable. Remove or update this code.
if (inSubtreeLayout)
rootForThisLayout = m_layoutSubtreeRootList.randomRoot();
if (!rootForThisLayout) {
// FIXME: Do we need to set m_size here?
NOTREACHED();
return;
}
if (!inSubtreeLayout) {
clearLayoutSubtreeRootsAndMarkContainingBlocks();
Node* body = document->body();
if (body && body->layoutObject()) {
if (isHTMLFrameSetElement(*body)) {
body->layoutObject()->setChildNeedsLayout();
} else if (isHTMLBodyElement(*body)) {
if (!m_firstLayout && m_size.height() != layoutSize().height() &&
body->layoutObject()->enclosingBox()->stretchesToViewport())
body->layoutObject()->setChildNeedsLayout();
}
}
ScrollbarMode hMode;
ScrollbarMode vMode;
calculateScrollbarModes(hMode, vMode);
// Now set our scrollbar state for the layout.
ScrollbarMode currentHMode = horizontalScrollbarMode();
ScrollbarMode currentVMode = verticalScrollbarMode();
if (m_firstLayout) {
setScrollbarsSuppressed(true);
m_firstLayout = false;
m_lastViewportSize = layoutSize(IncludeScrollbars);
m_lastZoomFactor = layoutViewItem().style()->zoom();
// Set the initial vMode to AlwaysOn if we're auto.
if (vMode == ScrollbarAuto) {
// This causes a vertical scrollbar to appear.
setVerticalScrollbarMode(ScrollbarAlwaysOn);
}
// Set the initial hMode to AlwaysOff if we're auto.
if (hMode == ScrollbarAuto) {
// This causes a horizontal scrollbar to disappear.
setHorizontalScrollbarMode(ScrollbarAlwaysOff);
}
setScrollbarModes(hMode, vMode);
setScrollbarsSuppressed(false);
} else if (hMode != currentHMode || vMode != currentVMode) {
setScrollbarModes(hMode, vMode);
}
updateScrollbarsIfNeeded();
LayoutSize oldSize = m_size;
m_size = LayoutSize(layoutSize());
if (oldSize != m_size && !m_firstLayout) {
LayoutBox* rootLayoutObject =
document->documentElement()
? document->documentElement()->layoutBox()
: 0;
LayoutBox* bodyLayoutObject = rootLayoutObject && document->body()
? document->body()->layoutBox()
: 0;
if (bodyLayoutObject && bodyLayoutObject->stretchesToViewport())
bodyLayoutObject->setChildNeedsLayout();
else if (rootLayoutObject && rootLayoutObject->stretchesToViewport())
rootLayoutObject->setChildNeedsLayout();
}
}
TRACE_EVENT_OBJECT_SNAPSHOT_WITH_ID(
TRACE_DISABLED_BY_DEFAULT("blink.debug.layout.trees"), "LayoutTree",
this, TracedLayoutObject::create(*layoutView(), false));
performLayout(inSubtreeLayout);
if (!inSubtreeLayout && !document->printing())
adjustViewSizeAndLayout();
ASSERT(m_layoutSubtreeRootList.isEmpty());
} // Reset m_layoutSchedulingEnabled to its previous value.
checkDoesNotNeedLayout();
m_frameTimingRequestsDirty = true;
// FIXME: Could find the common ancestor layer of all dirty subtrees and mark
// from there. crbug.com/462719
layoutViewItem().enclosingLayer()->updateLayerPositionsAfterLayout();
TRACE_EVENT_OBJECT_SNAPSHOT_WITH_ID(
TRACE_DISABLED_BY_DEFAULT("blink.debug.layout.trees"), "LayoutTree", this,
TracedLayoutObject::create(*layoutView(), true));
layoutViewItem().compositor()->didLayout();
m_layoutCount++;
if (AXObjectCache* cache = document->axObjectCache()) {
const KURL& url = document->url();
if (url.isValid() && !url.isAboutBlankURL())
cache->handleLayoutComplete(document);
}
updateDocumentAnnotatedRegions();
checkDoesNotNeedLayout();
scheduleOrPerformPostLayoutTasks();
checkDoesNotNeedLayout();
// FIXME: The notion of a single root for layout is no longer applicable.
// Remove or update this code. crbug.com/460596
TRACE_EVENT_END1("devtools.timeline", "Layout", "endData",
InspectorLayoutEvent::endData(rootForThisLayout));
InspectorInstrumentation::didUpdateLayout(m_frame.get());
PerformanceMonitor::didUpdateLayout(document);
m_nestedLayoutCount--;
if (m_nestedLayoutCount)
return;
#if ENABLE(ASSERT)
// Post-layout assert that nobody was re-marked as needing layout during
// layout.
layoutView()->assertSubtreeIsLaidOut();
#endif
frame().document()->layoutUpdated();
checkDoesNotNeedLayout();
}
void FrameView::invalidateTreeIfNeeded(
const PaintInvalidationState& paintInvalidationState) {
DCHECK(!RuntimeEnabledFeatures::slimmingPaintInvalidationEnabled());
if (shouldThrottleRendering())
return;
lifecycle().advanceTo(DocumentLifecycle::InPaintInvalidation);
RELEASE_ASSERT(!layoutViewItem().isNull());
LayoutViewItem rootForPaintInvalidation = layoutViewItem();
ASSERT(!rootForPaintInvalidation.needsLayout());
TRACE_EVENT1("blink", "FrameView::invalidateTree", "root",
rootForPaintInvalidation.debugName().ascii());
invalidatePaintIfNeeded(paintInvalidationState);
rootForPaintInvalidation.invalidateTreeIfNeeded(paintInvalidationState);
#if ENABLE(ASSERT)
layoutView()->assertSubtreeClearedPaintInvalidationFlags();
#endif
lifecycle().advanceTo(DocumentLifecycle::PaintInvalidationClean);
}
void FrameView::invalidatePaintIfNeeded(
const PaintInvalidationState& paintInvalidationState) {
RELEASE_ASSERT(!layoutViewItem().isNull());
if (!RuntimeEnabledFeatures::rootLayerScrollingEnabled())
invalidatePaintOfScrollControlsIfNeeded(paintInvalidationState);
if (m_frame->selection().isCaretBoundsDirty())
m_frame->selection().invalidateCaretRect();
// Temporary callback for crbug.com/487345,402044
// TODO(ojan): Make this more general to be used by PositionObserver
// and rAF throttling.
IntRect visibleRect = rootFrameToContents(computeVisibleArea());
layoutViewItem().sendMediaPositionChangeNotifications(visibleRect);
}
IntRect FrameView::computeVisibleArea() {
// Return our clipping bounds in the root frame.
IntRect us(frameRect());
if (FrameView* parent = parentFrameView()) {
us = parent->contentsToRootFrame(us);
IntRect parentRect = parent->computeVisibleArea();
if (parentRect.isEmpty())
return IntRect();
us.intersect(parentRect);
}
return us;
}
FloatSize FrameView::viewportSizeForViewportUnits() const {
float zoom = frame().pageZoomFactor();
FloatSize layoutSize;
LayoutViewItem layoutViewItem = this->layoutViewItem();
if (layoutViewItem.isNull())
return layoutSize;
layoutSize.setWidth(layoutViewItem.viewWidth(IncludeScrollbars) / zoom);
layoutSize.setHeight(layoutViewItem.viewHeight(IncludeScrollbars) / zoom);
if (RuntimeEnabledFeatures::inertTopControlsEnabled()) {
// We use the layoutSize rather than frameRect to calculate viewport units
// so that we get correct results on mobile where the page is laid out into
// a rect that may be larger than the viewport (e.g. the 980px fallback
// width for desktop pages). Since the layout height is statically set to
// be the viewport with browser controls showing, we add the browser
// controls height, compensating for page scale as well, since we want to
// use the viewport with browser controls hidden for vh (to match Safari).
BrowserControls& browserControls = m_frame->host()->browserControls();
int viewportWidth = m_frame->host()->visualViewport().size().width();
if (m_frame->isMainFrame() && layoutSize.width() && viewportWidth) {
float pageScaleAtLayoutWidth = viewportWidth / layoutSize.width();
layoutSize.expand(0, browserControls.height() / pageScaleAtLayoutWidth);
}
}
return layoutSize;
}
DocumentLifecycle& FrameView::lifecycle() const {
return m_frame->document()->lifecycle();
}
LayoutReplaced* FrameView::embeddedReplacedContent() const {
LayoutViewItem layoutViewItem = this->layoutViewItem();
if (layoutViewItem.isNull())
return nullptr;
LayoutObject* firstChild = layoutView()->firstChild();
if (!firstChild || !firstChild->isBox())
return nullptr;
// Currently only embedded SVG documents participate in the size-negotiation
// logic.
if (firstChild->isSVGRoot())
return toLayoutSVGRoot(firstChild);
return nullptr;
}
void FrameView::addPart(LayoutPart* object) {
m_parts.add(object);
}
void FrameView::removePart(LayoutPart* object) {
m_parts.remove(object);
}
void FrameView::updateWidgetGeometries() {
Vector<RefPtr<LayoutPart>> parts;
copyToVector(m_parts, parts);
for (auto part : parts) {
// Script or plugins could detach the frame so abort processing if that
// happens.
if (layoutViewItem().isNull())
break;
if (Widget* widget = part->widget()) {
if (widget->isFrameView()) {
FrameView* frameView = toFrameView(widget);
bool didNeedLayout = frameView->needsLayout();
part->updateWidgetGeometry();
if (!didNeedLayout && !frameView->shouldThrottleRendering())
frameView->checkDoesNotNeedLayout();
} else {
part->updateWidgetGeometry();
}
}
}
}
void FrameView::addPartToUpdate(LayoutEmbeddedObject& object) {
ASSERT(isInPerformLayout());
// Tell the DOM element that it needs a widget update.
Node* node = object.node();
ASSERT(node);
if (isHTMLObjectElement(*node) || isHTMLEmbedElement(*node))
toHTMLPlugInElement(node)->setNeedsWidgetUpdate(true);
m_partUpdateSet.add(&object);
}
void FrameView::setDisplayMode(WebDisplayMode mode) {
if (mode == m_displayMode)
return;
m_displayMode = mode;
if (m_frame->document())
m_frame->document()->mediaQueryAffectingValueChanged();
}
void FrameView::setMediaType(const AtomicString& mediaType) {
ASSERT(m_frame->document());
m_frame->document()->mediaQueryAffectingValueChanged();
m_mediaType = mediaType;
}
AtomicString FrameView::mediaType() const {
// See if we have an override type.
if (m_frame->settings() &&
!m_frame->settings()->mediaTypeOverride().isEmpty())
return AtomicString(m_frame->settings()->mediaTypeOverride());
return m_mediaType;
}
void FrameView::adjustMediaTypeForPrinting(bool printing) {
if (printing) {
if (m_mediaTypeWhenNotPrinting.isNull())
m_mediaTypeWhenNotPrinting = mediaType();
setMediaType(MediaTypeNames::print);
} else {
if (!m_mediaTypeWhenNotPrinting.isNull())
setMediaType(m_mediaTypeWhenNotPrinting);
m_mediaTypeWhenNotPrinting = nullAtom;
}
}
bool FrameView::contentsInCompositedLayer() const {
LayoutViewItem layoutViewItem = this->layoutViewItem();
return !layoutViewItem.isNull() &&
layoutViewItem.compositingState() == PaintsIntoOwnBacking;
}
void FrameView::addBackgroundAttachmentFixedObject(LayoutObject* object) {
ASSERT(!m_backgroundAttachmentFixedObjects.contains(object));
m_backgroundAttachmentFixedObjects.add(object);
if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
scrollingCoordinator->frameViewHasBackgroundAttachmentFixedObjectsDidChange(
this);
// TODO(pdr): When slimming paint v2 is enabled, invalidate the scroll paint
// property subtree for this so main thread scroll reasons are recomputed.
}
void FrameView::removeBackgroundAttachmentFixedObject(LayoutObject* object) {
ASSERT(m_backgroundAttachmentFixedObjects.contains(object));
m_backgroundAttachmentFixedObjects.remove(object);
if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
scrollingCoordinator->frameViewHasBackgroundAttachmentFixedObjectsDidChange(
this);
// TODO(pdr): When slimming paint v2 is enabled, invalidate the scroll paint
// property subtree for this so main thread scroll reasons are recomputed.
}
void FrameView::addViewportConstrainedObject(LayoutObject* object) {
if (!m_viewportConstrainedObjects)
m_viewportConstrainedObjects = wrapUnique(new ViewportConstrainedObjectSet);
if (!m_viewportConstrainedObjects->contains(object)) {
m_viewportConstrainedObjects->add(object);
if (ScrollingCoordinator* scrollingCoordinator =
this->scrollingCoordinator())
scrollingCoordinator->frameViewFixedObjectsDidChange(this);
}
}
void FrameView::removeViewportConstrainedObject(LayoutObject* object) {
if (m_viewportConstrainedObjects &&
m_viewportConstrainedObjects->contains(object)) {
m_viewportConstrainedObjects->remove(object);
if (ScrollingCoordinator* scrollingCoordinator =
this->scrollingCoordinator())
scrollingCoordinator->frameViewFixedObjectsDidChange(this);
}
}
void FrameView::viewportSizeChanged(bool widthChanged, bool heightChanged) {
DCHECK(widthChanged || heightChanged);
showOverlayScrollbars();
if (RuntimeEnabledFeatures::rootLayerScrollingEnabled()) {
// The background must be repainted when the FrameView is resized, even if
// the initial containing block does not change (so we can't rely on layout
// to issue the invalidation). This is because the background fills the
// main GraphicsLayer, which takes the size of the layout viewport.
// TODO(skobes): Paint non-fixed backgrounds into the scrolling contents
// layer and avoid this invalidation (http://crbug.com/568847).
LayoutViewItem lvi = layoutViewItem();
if (!lvi.isNull())
lvi.setShouldDoFullPaintInvalidation();
}
if (RuntimeEnabledFeatures::inertTopControlsEnabled() && layoutView() &&
layoutView()->style()->hasFixedBackgroundImage()) {
// In the case where we don't change layout size from top control resizes,
// we wont perform a layout. If we have a fixed background image however,
// the background layer needs to get resized so we should request a layout
// explicitly.
PaintLayer* layer = layoutView()->layer();
if (layoutView()->compositor()->needsFixedRootBackgroundLayer(layer)) {
setNeedsLayout();
} else if (!RuntimeEnabledFeatures::rootLayerScrollingEnabled()) {
// If root layer scrolls is on, we've already issued a full invalidation
// above.
layoutView()->setShouldDoFullPaintInvalidationOnResizeIfNeeded(
widthChanged, heightChanged);
}
}
if (!hasViewportConstrainedObjects())
return;
for (const auto& viewportConstrainedObject : *m_viewportConstrainedObjects) {
LayoutObject* layoutObject = viewportConstrainedObject;
const ComputedStyle& style = layoutObject->styleRef();
if (widthChanged) {
if (style.width().isFixed() &&
(style.left().isAuto() || style.right().isAuto()))
layoutObject->setNeedsPositionedMovementLayout();
else
layoutObject->setNeedsLayoutAndFullPaintInvalidation(
LayoutInvalidationReason::SizeChanged);
}
if (heightChanged) {
if (style.height().isFixed() &&
(style.top().isAuto() || style.bottom().isAuto()))
layoutObject->setNeedsPositionedMovementLayout();
else
layoutObject->setNeedsLayoutAndFullPaintInvalidation(
LayoutInvalidationReason::SizeChanged);
}
}
}
IntPoint FrameView::lastKnownMousePosition() const {
return m_frame->eventHandler().lastKnownMousePosition();
}
bool FrameView::shouldSetCursor() const {
Page* page = frame().page();
return page && page->visibilityState() != PageVisibilityStateHidden &&
page->focusController().isActive() &&
page->settings().deviceSupportsMouse();
}
void FrameView::scrollContentsIfNeededRecursive() {
forAllNonThrottledFrameViews(
[](FrameView& frameView) { frameView.scrollContentsIfNeeded(); });
}
void FrameView::invalidateBackgroundAttachmentFixedObjects() {
for (const auto& layoutObject : m_backgroundAttachmentFixedObjects)
layoutObject->setShouldDoFullPaintInvalidation();
}
bool FrameView::invalidateViewportConstrainedObjects() {
bool fastPathAllowed = true;
for (const auto& viewportConstrainedObject : *m_viewportConstrainedObjects) {
LayoutObject* layoutObject = viewportConstrainedObject;
LayoutItem layoutItem = LayoutItem(layoutObject);
ASSERT(layoutItem.style()->hasViewportConstrainedPosition());
ASSERT(layoutItem.hasLayer());
PaintLayer* layer = LayoutBoxModel(layoutItem).layer();
if (layer->isPaintInvalidationContainer())
continue;
if (layer->subtreeIsInvisible())
continue;
// invalidate even if there is an ancestor with a filter that moves pixels.
layoutItem
.setShouldDoFullPaintInvalidationIncludingNonCompositingDescendants();
TRACE_EVENT_INSTANT1(
TRACE_DISABLED_BY_DEFAULT("devtools.timeline.invalidationTracking"),
"ScrollInvalidationTracking", TRACE_EVENT_SCOPE_THREAD, "data",
InspectorScrollInvalidationTrackingEvent::data(*layoutObject));
// If the fixed layer has a blur/drop-shadow filter applied on at least one
// of its parents, we cannot scroll using the fast path, otherwise the
// outsets of the filter will be moved around the page.
if (layer->hasAncestorWithFilterThatMovesPixels())
fastPathAllowed = false;
}
return fastPathAllowed;
}
bool FrameView::scrollContentsFastPath(const IntSize& scrollDelta) {
if (!contentsInCompositedLayer())
return false;
invalidateBackgroundAttachmentFixedObjects();
if (!m_viewportConstrainedObjects ||
m_viewportConstrainedObjects->isEmpty()) {
InspectorInstrumentation::didUpdateLayout(m_frame.get());
return true;
}
if (!invalidateViewportConstrainedObjects())
return false;
InspectorInstrumentation::didUpdateLayout(m_frame.get());
return true;
}
void FrameView::scrollContentsSlowPath() {
TRACE_EVENT0("blink", "FrameView::scrollContentsSlowPath");
// We need full invalidation during slow scrolling. For slimming paint, full
// invalidation of the LayoutView is not enough. We also need to invalidate
// all of the objects.
// FIXME: Find out what are enough to invalidate in slow path scrolling.
// crbug.com/451090#9.
ASSERT(!layoutViewItem().isNull());
if (contentsInCompositedLayer())
layoutViewItem()
.layer()
->compositedLayerMapping()
->setContentsNeedDisplay();
else
layoutViewItem()
.setShouldDoFullPaintInvalidationIncludingNonCompositingDescendants();
if (contentsInCompositedLayer()) {
IntRect updateRect = visibleContentRect();
ASSERT(!layoutViewItem().isNull());
// FIXME: We should not allow paint invalidation out of paint invalidation
// state. crbug.com/457415
DisablePaintInvalidationStateAsserts disabler;
layoutViewItem().invalidatePaintRectangle(LayoutRect(updateRect));
}
LayoutPartItem frameLayoutItem = m_frame->ownerLayoutItem();
if (!frameLayoutItem.isNull()) {
if (isEnclosedInCompositingLayer()) {
LayoutRect rect(
frameLayoutItem.borderLeft() + frameLayoutItem.paddingLeft(),
frameLayoutItem.borderTop() + frameLayoutItem.paddingTop(),
LayoutUnit(visibleWidth()), LayoutUnit(visibleHeight()));
// FIXME: We should not allow paint invalidation out of paint invalidation
// state. crbug.com/457415
DisablePaintInvalidationStateAsserts disabler;
frameLayoutItem.invalidatePaintRectangle(rect);
return;
}
}
}
void FrameView::restoreScrollbar() {
setScrollbarsSuppressed(false);
}
void FrameView::processUrlFragment(const KURL& url,
UrlFragmentBehavior behavior) {
// If our URL has no ref, then we have no place we need to jump to.
// OTOH If CSS target was set previously, we want to set it to 0, recalc
// and possibly paint invalidation because :target pseudo class may have been
// set (see bug 11321).
// Similarly for svg, if we had a previous svgView() then we need to reset
// the initial view if we don't have a fragment.
if (!url.hasFragmentIdentifier() && !m_frame->document()->cssTarget() &&
!m_frame->document()->isSVGDocument())
return;
String fragmentIdentifier = url.fragmentIdentifier();
if (processUrlFragmentHelper(fragmentIdentifier, behavior))
return;
// Try again after decoding the ref, based on the document's encoding.
if (m_frame->document()->encoding().isValid())
processUrlFragmentHelper(
decodeURLEscapeSequences(fragmentIdentifier,
m_frame->document()->encoding()),
behavior);
}
bool FrameView::processUrlFragmentHelper(const String& name,
UrlFragmentBehavior behavior) {
ASSERT(m_frame->document());
if (behavior == UrlFragmentScroll &&
!m_frame->document()->isRenderingReady()) {
m_frame->document()->setGotoAnchorNeededAfterStylesheetsLoad(true);
return false;
}
m_frame->document()->setGotoAnchorNeededAfterStylesheetsLoad(false);
Element* anchorNode = m_frame->document()->findAnchor(name);
// Setting to null will clear the current target.
m_frame->document()->setCSSTarget(anchorNode);
if (m_frame->document()->isSVGDocument()) {
if (SVGSVGElement* svg =
SVGDocumentExtensions::rootElement(*m_frame->document())) {
svg->setupInitialView(name, anchorNode);
if (!anchorNode)
return true;
}
}
// Implement the rule that "" and "top" both mean top of page as in other
// browsers.
if (!anchorNode && !(name.isEmpty() || equalIgnoringCase(name, "top")))
return false;
if (behavior == UrlFragmentScroll)
setFragmentAnchor(anchorNode ? static_cast<Node*>(anchorNode)
: m_frame->document());
// If the anchor accepts keyboard focus and fragment scrolling is allowed,
// move focus there to aid users relying on keyboard navigation.
// If anchorNode is not focusable or fragment scrolling is not allowed,
// clear focus, which matches the behavior of other browsers.
if (anchorNode) {
m_frame->document()->updateStyleAndLayoutIgnorePendingStylesheets();
if (behavior == UrlFragmentScroll && anchorNode->isFocusable()) {
anchorNode->focus();
} else {
if (behavior == UrlFragmentScroll)
m_frame->document()->setSequentialFocusNavigationStartingPoint(
anchorNode);
m_frame->document()->clearFocusedElement();
}
}
return true;
}
void FrameView::setFragmentAnchor(Node* anchorNode) {
ASSERT(anchorNode);
m_fragmentAnchor = anchorNode;
// We need to update the layout tree before scrolling.
m_frame->document()->updateStyleAndLayoutTree();
// If layout is needed, we will scroll in performPostLayoutTasks. Otherwise,
// scroll immediately.
LayoutViewItem layoutViewItem = this->layoutViewItem();
if (!layoutViewItem.isNull() && layoutViewItem.needsLayout())
layout();
else
scrollToFragmentAnchor();
}
void FrameView::clearFragmentAnchor() {
m_fragmentAnchor = nullptr;
}
void FrameView::didUpdateElasticOverscroll() {
Page* page = frame().page();
if (!page)
return;
FloatSize elasticOverscroll = page->chromeClient().elasticOverscroll();
if (horizontalScrollbar()) {
float delta =
elasticOverscroll.width() - horizontalScrollbar()->elasticOverscroll();
if (delta != 0) {
horizontalScrollbar()->setElasticOverscroll(elasticOverscroll.width());
scrollAnimator().notifyContentAreaScrolled(FloatSize(delta, 0));
setScrollbarNeedsPaintInvalidation(HorizontalScrollbar);
}
}
if (verticalScrollbar()) {
float delta =
elasticOverscroll.height() - verticalScrollbar()->elasticOverscroll();
if (delta != 0) {
verticalScrollbar()->setElasticOverscroll(elasticOverscroll.height());
scrollAnimator().notifyContentAreaScrolled(FloatSize(0, delta));
setScrollbarNeedsPaintInvalidation(VerticalScrollbar);
}
}
}
IntSize FrameView::layoutSize(
IncludeScrollbarsInRect scrollbarInclusion) const {
return scrollbarInclusion == ExcludeScrollbars
? excludeScrollbars(m_layoutSize)
: m_layoutSize;
}
void FrameView::setLayoutSize(const IntSize& size) {
ASSERT(!layoutSizeFixedToFrameSize());
setLayoutSizeInternal(size);
}
void FrameView::didScrollTimerFired(TimerBase*) {
if (m_frame->document() && !m_frame->document()->layoutViewItem().isNull())
m_frame->document()->fetcher()->updateAllImageResourcePriorities();
}
void FrameView::updateLayersAndCompositingAfterScrollIfNeeded(
const ScrollOffset& scrollDelta) {
// Nothing to do after scrolling if there are no fixed position elements.
if (!hasViewportConstrainedObjects())
return;
// Update sticky position objects which are stuck to the viewport.
for (const auto& viewportConstrainedObject : *m_viewportConstrainedObjects) {
LayoutObject* layoutObject = viewportConstrainedObject;
PaintLayer* layer = toLayoutBoxModelObject(layoutObject)->layer();
if (layoutObject->style()->position() == StickyPosition) {
// TODO(skobes): Resolve circular dependency between scroll offset and
// compositing state, and remove this disabler. https://crbug.com/420741
DisableCompositingQueryAsserts disabler;
layer->updateLayerPositionsAfterOverflowScroll(scrollDelta);
}
}
// If there fixed position elements, scrolling may cause compositing layers to
// change. Update widget and layer positions after scrolling, but only if
// we're not inside of layout.
if (!m_nestedLayoutCount) {
updateWidgetGeometries();
LayoutViewItem layoutViewItem = this->layoutViewItem();
if (!layoutViewItem.isNull())
layoutViewItem.layer()->setNeedsCompositingInputsUpdate();
}
}
bool FrameView::computeCompositedSelection(LocalFrame& frame,
CompositedSelection& selection) {
if (!frame.view() || frame.view()->shouldThrottleRendering())
return false;
const VisibleSelection& visibleSelection = frame.selection().selection();
if (visibleSelection.isNone())
return false;
// Non-editable caret selections lack any kind of UI affordance, and
// needn't be tracked by the client.
if (visibleSelection.isCaret() && !visibleSelection.isContentEditable())
return false;
VisiblePosition visibleStart(visibleSelection.visibleStart());
RenderedPosition renderedStart(visibleStart);
renderedStart.positionInGraphicsLayerBacking(selection.start, true);
if (!selection.start.layer)
return false;
VisiblePosition visibleEnd(visibleSelection.visibleEnd());
RenderedPosition renderedEnd(visibleEnd);
renderedEnd.positionInGraphicsLayerBacking(selection.end, false);
if (!selection.end.layer)
return false;
selection.type = visibleSelection.getSelectionType();
selection.isEditable = visibleSelection.isContentEditable();
if (selection.isEditable) {
if (TextControlElement* enclosingTextControlElement =
enclosingTextControl(visibleSelection.rootEditableElement())) {
selection.isEmptyTextControl =
enclosingTextControlElement->value().isEmpty();
}
}
selection.start.isTextDirectionRTL |=
primaryDirectionOf(*visibleSelection.start().anchorNode()) == RTL;
selection.end.isTextDirectionRTL |=
primaryDirectionOf(*visibleSelection.end().anchorNode()) == RTL;
return true;
}
void FrameView::updateCompositedSelectionIfNeeded() {
if (!RuntimeEnabledFeatures::compositedSelectionUpdateEnabled())
return;
TRACE_EVENT0("blink", "FrameView::updateCompositedSelectionIfNeeded");
Page* page = frame().page();
ASSERT(page);
CompositedSelection selection;
LocalFrame* focusedFrame = page->focusController().focusedFrame();
LocalFrame* localFrame = (focusedFrame && (focusedFrame->localFrameRoot() ==
m_frame->localFrameRoot()))
? focusedFrame
: nullptr;
if (localFrame && computeCompositedSelection(*localFrame, selection)) {
page->chromeClient().updateCompositedSelection(localFrame, selection);
} else {
if (!localFrame) {
// Clearing the mainframe when there is no focused frame (and hence
// no localFrame) is legacy behaviour, and implemented here to
// satisfy ParameterizedWebFrameTest.CompositedSelectionBoundsCleared's
// first check that the composited selection has been cleared even
// though no frame has focus yet. If this is not desired, then the
// expectation needs to be removed from the test.
localFrame = m_frame->localFrameRoot();
}
if (localFrame)
page->chromeClient().clearCompositedSelection(localFrame);
}
}
HostWindow* FrameView::getHostWindow() const {
Page* page = frame().page();
if (!page)
return nullptr;
return &page->chromeClient();
}
void FrameView::contentsResized() {
if (m_frame->isMainFrame() && m_frame->document()) {
if (TextAutosizer* textAutosizer = m_frame->document()->textAutosizer())
textAutosizer->updatePageInfoInAllFrames();
}
ScrollableArea::contentsResized();
setNeedsLayout();
}
void FrameView::scrollbarExistenceDidChange() {
// We check to make sure the view is attached to a frame() as this method can
// be triggered before the view is attached by LocalFrame::createView(...)
// setting various values such as setScrollBarModes(...) for example. An
// ASSERT is triggered when a view is layout before being attached to a
// frame().
if (!frame().view())
return;
bool usesOverlayScrollbars = ScrollbarTheme::theme().usesOverlayScrollbars();
// FIXME: this call to layout() could be called within FrameView::layout(),
// but before performLayout(), causing double-layout. See also
// crbug.com/429242.
if (!usesOverlayScrollbars && needsLayout())
layout();
if (!layoutViewItem().isNull() && layoutViewItem().usesCompositing()) {
layoutViewItem().compositor()->frameViewScrollbarsExistenceDidChange();
if (!usesOverlayScrollbars)
layoutViewItem().compositor()->frameViewDidChangeSize();
}
}
void FrameView::handleLoadCompleted() {
// Once loading has completed, allow autoSize one last opportunity to
// reduce the size of the frame.
if (m_autoSizeInfo)
m_autoSizeInfo->autoSizeIfNeeded();
// If there is a pending layout, the fragment anchor will be cleared when it
// finishes.
if (!needsLayout())
clearFragmentAnchor();
}
void FrameView::clearLayoutSubtreeRoot(const LayoutObject& root) {
m_layoutSubtreeRootList.remove(const_cast<LayoutObject&>(root));
}
void FrameView::clearLayoutSubtreeRootsAndMarkContainingBlocks() {
m_layoutSubtreeRootList.clearAndMarkContainingBlocksForLayout();
}
void FrameView::addOrthogonalWritingModeRoot(LayoutBox& root) {
DCHECK(!root.isLayoutScrollbarPart());
m_orthogonalWritingModeRootList.add(root);
}
void FrameView::removeOrthogonalWritingModeRoot(LayoutBox& root) {
m_orthogonalWritingModeRootList.remove(root);
}
bool FrameView::hasOrthogonalWritingModeRoots() const {
return !m_orthogonalWritingModeRootList.isEmpty();
}
static inline void removeFloatingObjectsForSubtreeRoot(LayoutObject& root) {
// TODO(kojii): Under certain conditions, moveChildTo() defers
// removeFloatingObjects() until the containing block layouts. For
// instance, when descendants of the moving child is floating,
// removeChildNode() does not clear them. In such cases, at this
// point, FloatingObjects may contain old or even deleted objects.
// Dealing this in markAllDescendantsWithFloatsForLayout() could
// solve, but since that is likely to suffer the performance and
// since the containing block of orthogonal writing mode roots
// having floats is very rare, prefer to re-create
// FloatingObjects.
if (LayoutBlock* cb = root.containingBlock()) {
if ((cb->normalChildNeedsLayout() || cb->selfNeedsLayout()) &&
cb->isLayoutBlockFlow())
toLayoutBlockFlow(cb)->removeFloatingObjects();
}
}
void FrameView::layoutOrthogonalWritingModeRoots() {
for (auto& root : m_orthogonalWritingModeRootList.ordered()) {
ASSERT(root->isBox() && toLayoutBox(*root).isOrthogonalWritingModeRoot());
if (!root->needsLayout() || root->isOutOfFlowPositioned() ||
root->isColumnSpanAll() ||
!root->styleRef().logicalHeight().isIntrinsicOrAuto()) {
continue;
}
removeFloatingObjectsForSubtreeRoot(*root);
layoutFromRootObject(*root);
}
}
bool FrameView::checkLayoutInvalidationIsAllowed() const {
if (m_allowsLayoutInvalidationAfterLayoutClean)
return true;
// If we are updating all lifecycle phases beyond LayoutClean, we don't expect
// dirty layout after LayoutClean.
CHECK_FOR_DIRTY_LAYOUT(lifecycle().state() < DocumentLifecycle::LayoutClean);
return true;
}
void FrameView::scheduleRelayout() {
DCHECK(m_frame->view() == this);
if (!m_layoutSchedulingEnabled)
return;
// TODO(crbug.com/590856): It's still broken when we choose not to crash when
// the check fails.
if (!checkLayoutInvalidationIsAllowed())
return;
if (!needsLayout())
return;
if (!m_frame->document()->shouldScheduleLayout())
return;
TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"),
"InvalidateLayout", TRACE_EVENT_SCOPE_THREAD, "data",
InspectorInvalidateLayoutEvent::data(m_frame.get()));
clearLayoutSubtreeRootsAndMarkContainingBlocks();
if (m_hasPendingLayout)
return;
m_hasPendingLayout = true;
if (!shouldThrottleRendering())
page()->animator().scheduleVisualUpdate(m_frame.get());
}
void FrameView::scheduleRelayoutOfSubtree(LayoutObject* relayoutRoot) {
DCHECK(m_frame->view() == this);
// TODO(crbug.com/590856): It's still broken when we choose not to crash when
// the check fails.
if (!checkLayoutInvalidationIsAllowed())
return;
// FIXME: Should this call shouldScheduleLayout instead?
if (!m_frame->document()->isActive())
return;
LayoutView* layoutView = this->layoutView();
if (layoutView && layoutView->needsLayout()) {
if (relayoutRoot)
relayoutRoot->markContainerChainForLayout(false);
return;
}
if (relayoutRoot == layoutView)
m_layoutSubtreeRootList.clearAndMarkContainingBlocksForLayout();
else
m_layoutSubtreeRootList.add(*relayoutRoot);
if (m_layoutSchedulingEnabled) {
m_hasPendingLayout = true;
if (!shouldThrottleRendering())
page()->animator().scheduleVisualUpdate(m_frame.get());
lifecycle().ensureStateAtMost(DocumentLifecycle::StyleClean);
}
TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("devtools.timeline"),
"InvalidateLayout", TRACE_EVENT_SCOPE_THREAD, "data",
InspectorInvalidateLayoutEvent::data(m_frame.get()));
}
bool FrameView::layoutPending() const {
// FIXME: This should check Document::lifecycle instead.
return m_hasPendingLayout;
}
bool FrameView::isInPerformLayout() const {
return lifecycle().state() == DocumentLifecycle::InPerformLayout;
}
bool FrameView::needsLayout() const {
// This can return true in cases where the document does not have a body yet.
// Document::shouldScheduleLayout takes care of preventing us from scheduling
// layout in that case.
LayoutViewItem layoutViewItem = this->layoutViewItem();
return layoutPending() ||
(!layoutViewItem.isNull() && layoutViewItem.needsLayout()) ||
isSubtreeLayout();
}
NOINLINE bool FrameView::checkDoesNotNeedLayout() const {
CHECK_FOR_DIRTY_LAYOUT(!layoutPending());
CHECK_FOR_DIRTY_LAYOUT(layoutViewItem().isNull() ||
!layoutViewItem().needsLayout());
CHECK_FOR_DIRTY_LAYOUT(!isSubtreeLayout());
return true;
}
void FrameView::setNeedsLayout() {
LayoutViewItem layoutViewItem = this->layoutViewItem();
if (layoutViewItem.isNull())
return;
// TODO(crbug.com/590856): It's still broken if we choose not to crash when
// the check fails.
if (!checkLayoutInvalidationIsAllowed())
return;
layoutViewItem.setNeedsLayout(LayoutInvalidationReason::Unknown);
}
bool FrameView::isTransparent() const {
return m_isTransparent;
}
void FrameView::setTransparent(bool isTransparent) {
m_isTransparent = isTransparent;
DisableCompositingQueryAsserts disabler;
if (!layoutViewItem().isNull() &&
layoutViewItem().layer()->hasCompositedLayerMapping())
layoutViewItem().layer()->compositedLayerMapping()->updateContentsOpaque();
}
bool FrameView::hasOpaqueBackground() const {
return !m_isTransparent && !m_baseBackgroundColor.hasAlpha();
}
Color FrameView::baseBackgroundColor() const {
return m_baseBackgroundColor;
}
void FrameView::setBaseBackgroundColor(const Color& backgroundColor) {
m_baseBackgroundColor = backgroundColor;
if (!layoutViewItem().isNull() &&
layoutViewItem().layer()->hasCompositedLayerMapping()) {
CompositedLayerMapping* compositedLayerMapping =
layoutViewItem().layer()->compositedLayerMapping();
compositedLayerMapping->updateContentsOpaque();
if (compositedLayerMapping->mainGraphicsLayer())
compositedLayerMapping->mainGraphicsLayer()->setNeedsDisplay();
}
recalculateScrollbarOverlayColorTheme(documentBackgroundColor());
if (!shouldThrottleRendering())
page()->animator().scheduleVisualUpdate(m_frame.get());
}
void FrameView::updateBackgroundRecursively(const Color& backgroundColor,
bool transparent) {
forAllNonThrottledFrameViews(
[backgroundColor, transparent](FrameView& frameView) {
frameView.setTransparent(transparent);
frameView.setBaseBackgroundColor(backgroundColor);
});
}
void FrameView::scrollToFragmentAnchor() {
Node* anchorNode = m_fragmentAnchor;
if (!anchorNode)
return;
// Scrolling is disabled during updateScrollbars (see
// isProgrammaticallyScrollable). Bail now to avoid clearing m_fragmentAnchor
// before we actually have a chance to scroll.
if (m_inUpdateScrollbars)
return;
if (anchorNode->layoutObject()) {
LayoutRect rect;
if (anchorNode != m_frame->document()) {
rect = anchorNode->boundingBox();
} else if (RuntimeEnabledFeatures::rootLayerScrollingEnabled()) {
if (Element* documentElement = m_frame->document()->documentElement())
rect = documentElement->boundingBox();
}
Frame* boundaryFrame = m_frame->findUnsafeParentScrollPropagationBoundary();
// FIXME: Handle RemoteFrames
if (boundaryFrame && boundaryFrame->isLocalFrame())
toLocalFrame(boundaryFrame)
->view()
->setSafeToPropagateScrollToParent(false);
// Scroll nested layers and frames to reveal the anchor.
// Align to the top and to the closest side (this matches other browsers).
anchorNode->layoutObject()->scrollRectToVisible(
rect, ScrollAlignment::alignToEdgeIfNeeded,
ScrollAlignment::alignTopAlways);
if (boundaryFrame && boundaryFrame->isLocalFrame())
toLocalFrame(boundaryFrame)
->view()
->setSafeToPropagateScrollToParent(true);
if (AXObjectCache* cache = m_frame->document()->existingAXObjectCache())
cache->handleScrolledToAnchor(anchorNode);
}
// The fragment anchor should only be maintained while the frame is still
// loading. If the frame is done loading, clear the anchor now. Otherwise,
// restore it since it may have been cleared during scrollRectToVisible.
m_fragmentAnchor =
m_frame->document()->isLoadCompleted() ? nullptr : anchorNode;
}
bool FrameView::updateWidgets() {
// This is always called from updateWidgetsTimerFired.
// m_updateWidgetsTimer should only be scheduled if we have widgets to update.
// Thus I believe we can stop checking isEmpty here, and just ASSERT isEmpty:
// FIXME: This assert has been temporarily removed due to
// https://crbug.com/430344
if (m_nestedLayoutCount > 1 || m_partUpdateSet.isEmpty())
return true;
// Need to swap because script will run inside the below loop and invalidate
// the iterator.
EmbeddedObjectSet objects;
objects.swap(m_partUpdateSet);
for (const auto& embeddedObject : objects) {
LayoutEmbeddedObject& object = *embeddedObject;
HTMLPlugInElement* element = toHTMLPlugInElement(object.node());
// The object may have already been destroyed (thus node cleared),
// but FrameView holds a manual ref, so it won't have been deleted.
if (!element)
continue;
// No need to update if it's already crashed or known to be missing.
if (object.showsUnavailablePluginIndicator())
continue;
if (element->needsWidgetUpdate())
element->updateWidget();
object.updateWidgetGeometry();
// Prevent plugins from causing infinite updates of themselves.
// FIXME: Do we really need to prevent this?
m_partUpdateSet.remove(&object);
}
return m_partUpdateSet.isEmpty();
}
void FrameView::updateWidgetsTimerFired(TimerBase*) {
ASSERT(!isInPerformLayout());
for (unsigned i = 0; i < maxUpdateWidgetsIterations; ++i) {
if (updateWidgets())
return;
}
}
void FrameView::flushAnyPendingPostLayoutTasks() {
ASSERT(!isInPerformLayout());
if (m_postLayoutTasksTimer.isActive())
performPostLayoutTasks();
if (m_updateWidgetsTimer.isActive()) {
m_updateWidgetsTimer.stop();
updateWidgetsTimerFired(nullptr);
}
}
void FrameView::scheduleUpdateWidgetsIfNecessary() {
ASSERT(!isInPerformLayout());
if (m_updateWidgetsTimer.isActive() || m_partUpdateSet.isEmpty())
return;
m_updateWidgetsTimer.startOneShot(0, BLINK_FROM_HERE);
}
void FrameView::performPostLayoutTasks() {
// FIXME: We can reach here, even when the page is not active!
// http/tests/inspector/elements/html-link-import.html and many other
// tests hit that case.
// We should ASSERT(isActive()); or at least return early if we can!
// Always called before or after performLayout(), part of the highest-level
// layout() call.
ASSERT(!isInPerformLayout());
TRACE_EVENT0("blink,benchmark", "FrameView::performPostLayoutTasks");
m_postLayoutTasksTimer.stop();
m_frame->selection().setCaretRectNeedsUpdate();
m_frame->selection().updateAppearance();
ASSERT(m_frame->document());
FontFaceSet::didLayout(*m_frame->document());
// Cursor update scheduling is done by the local root, which is the main frame
// if there are no RemoteFrame ancestors in the frame tree. Use of
// localFrameRoot() is discouraged but will change when cursor update
// scheduling is moved from EventHandler to PageEventHandler.
frame().localFrameRoot()->eventHandler().scheduleCursorUpdate();
updateWidgetGeometries();
// Plugins could have torn down the page inside updateWidgetGeometries().
if (layoutViewItem().isNull())
return;
scheduleUpdateWidgetsIfNecessary();
if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
scrollingCoordinator->notifyGeometryChanged();
scrollToFragmentAnchor();
sendResizeEventIfNeeded();
}
bool FrameView::wasViewportResized() {
ASSERT(m_frame);
LayoutViewItem layoutViewItem = this->layoutViewItem();
if (layoutViewItem.isNull())
return false;
ASSERT(layoutViewItem.style());
return (layoutSize(IncludeScrollbars) != m_lastViewportSize ||
layoutViewItem.style()->zoom() != m_lastZoomFactor);
}
void FrameView::sendResizeEventIfNeeded() {
ASSERT(m_frame);
LayoutViewItem layoutViewItem = this->layoutViewItem();
if (layoutViewItem.isNull() || layoutViewItem.document().printing())
return;
if (!wasViewportResized())
return;
m_lastViewportSize = layoutSize(IncludeScrollbars);
m_lastZoomFactor = layoutViewItem.style()->zoom();
if (RuntimeEnabledFeatures::visualViewportAPIEnabled())
m_frame->document()->enqueueVisualViewportResizeEvent();
m_frame->document()->enqueueResizeEvent();
if (m_frame->isMainFrame())
InspectorInstrumentation::didResizeMainFrame(m_frame.get());
}
void FrameView::postLayoutTimerFired(TimerBase*) {
performPostLayoutTasks();
}
void FrameView::updateCounters() {
LayoutView* view = layoutView();
if (!view->hasLayoutCounters())
return;
for (LayoutObject* layoutObject = view; layoutObject;
layoutObject = layoutObject->nextInPreOrder()) {
if (!layoutObject->isCounter())
continue;
toLayoutCounter(layoutObject)->updateCounter();
}
}
bool FrameView::shouldUseIntegerScrollOffset() const {
if (m_frame->settings() &&
!m_frame->settings()->preferCompositingToLCDTextEnabled())
return true;
return ScrollableArea::shouldUseIntegerScrollOffset();
}
bool FrameView::isActive() const {
Page* page = frame().page();
return page && page->focusController().isActive();
}
void FrameView::invalidatePaintForTickmarks() {
if (Scrollbar* scrollbar = verticalScrollbar())
scrollbar->setNeedsPaintInvalidation(
static_cast<ScrollbarPart>(~ThumbPart));
}
void FrameView::getTickmarks(Vector<IntRect>& tickmarks) const {
if (!m_tickmarks.isEmpty())
tickmarks = m_tickmarks;
else
tickmarks = frame().document()->markers().renderedRectsForMarkers(
DocumentMarker::TextMatch);
}
void FrameView::setInputEventsTransformForEmulation(const IntSize& offset,
float contentScaleFactor) {
m_inputEventsOffsetForEmulation = offset;
m_inputEventsScaleFactorForEmulation = contentScaleFactor;
}
IntSize FrameView::inputEventsOffsetForEmulation() const {
return m_inputEventsOffsetForEmulation;
}
float FrameView::inputEventsScaleFactor() const {
float pageScale = m_frame->host()->visualViewport().scale();
return pageScale * m_inputEventsScaleFactorForEmulation;
}
bool FrameView::scrollbarsCanBeActive() const {
if (m_frame->view() != this)
return false;
return !!m_frame->document();
}
void FrameView::scrollbarVisibilityChanged() {
LayoutViewItem viewItem = layoutViewItem();
if (!viewItem.isNull())
viewItem.clearHitTestCache();
}
IntRect FrameView::scrollableAreaBoundingBox() const {
LayoutPartItem ownerLayoutItem = frame().ownerLayoutItem();
if (ownerLayoutItem.isNull())
return frameRect();
return ownerLayoutItem.absoluteContentQuad().enclosingBoundingBox();
}
bool FrameView::isScrollable() {
return getScrollingReasons() == Scrollable;
}
bool FrameView::isProgrammaticallyScrollable() {
return !m_inUpdateScrollbars;
}
FrameView::ScrollingReasons FrameView::getScrollingReasons() {
// Check for:
// 1) If there an actual overflow.
// 2) display:none or visibility:hidden set to self or inherited.
// 3) overflow{-x,-y}: hidden;
// 4) scrolling: no;
// Covers #1
IntSize contentsSize = this->contentsSize();
IntSize visibleContentSize = visibleContentRect().size();
if ((contentsSize.height() <= visibleContentSize.height() &&
contentsSize.width() <= visibleContentSize.width()))
return NotScrollableNoOverflow;
// Covers #2.
// FIXME: Do we need to fix this for OOPI?
HTMLFrameOwnerElement* owner = m_frame->deprecatedLocalOwner();
if (owner &&
(!owner->layoutObject() || !owner->layoutObject()->visibleToHitTesting()))
return NotScrollableNotVisible;
// Cover #3 and #4.
ScrollbarMode horizontalMode;
ScrollbarMode verticalMode;
calculateScrollbarModes(horizontalMode, verticalMode,
RulesFromWebContentOnly);
if (horizontalMode == ScrollbarAlwaysOff &&
verticalMode == ScrollbarAlwaysOff)
return NotScrollableExplicitlyDisabled;
return Scrollable;
}
void FrameView::updateParentScrollableAreaSet() {
// That ensures that only inner frames are cached.
FrameView* parentFrameView = this->parentFrameView();
if (!parentFrameView)
return;
if (!isScrollable()) {
parentFrameView->removeScrollableArea(this);
return;
}
parentFrameView->addScrollableArea(this);
}
bool FrameView::shouldSuspendScrollAnimations() const {
return !m_frame->document()->loadEventFinished();
}
void FrameView::scrollbarStyleChanged() {
// FIXME: Why does this only apply to the main frame?
if (!m_frame->isMainFrame())
return;
adjustScrollbarOpacity();
contentsResized();
updateScrollbars();
positionScrollbarLayers();
}
void FrameView::notifyPageThatContentAreaWillPaint() const {
Page* page = m_frame->page();
if (!page)
return;
contentAreaWillPaint();
if (!m_scrollableAreas)
return;
for (const auto& scrollableArea : *m_scrollableAreas) {
if (!scrollableArea->scrollbarsCanBeActive())
continue;
scrollableArea->contentAreaWillPaint();
}
}
bool FrameView::scrollAnimatorEnabled() const {
return m_frame->settings() && m_frame->settings()->scrollAnimatorEnabled();
}
void FrameView::updateDocumentAnnotatedRegions() const {
Document* document = m_frame->document();
if (!document->hasAnnotatedRegions())
return;
Vector<AnnotatedRegionValue> newRegions;
collectAnnotatedRegions(*(document->layoutBox()), newRegions);
if (newRegions == document->annotatedRegions())
return;
document->setAnnotatedRegions(newRegions);
if (Page* page = m_frame->page())
page->chromeClient().annotatedRegionsChanged();
}
void FrameView::didAttachDocument() {
FrameHost* frameHost = m_frame->host();
DCHECK(frameHost);
DCHECK(m_frame->document());
if (m_frame->isMainFrame()) {
ScrollableArea& visualViewport = frameHost->visualViewport();
ScrollableArea* layoutViewport = layoutViewportScrollableArea();
DCHECK(layoutViewport);
RootFrameViewport* rootFrameViewport =
RootFrameViewport::create(visualViewport, *layoutViewport);
m_viewportScrollableArea = rootFrameViewport;
frameHost->globalRootScrollerController().initializeViewportScrollCallback(
*rootFrameViewport);
}
}
void FrameView::updateScrollCorner() {
RefPtr<ComputedStyle> cornerStyle;
IntRect cornerRect = scrollCornerRect();
Document* doc = m_frame->document();
if (doc && !cornerRect.isEmpty()) {
// Try the <body> element first as a scroll corner source.
if (Element* body = doc->body()) {
if (LayoutObject* layoutObject = body->layoutObject())
cornerStyle = layoutObject->getUncachedPseudoStyle(
PseudoStyleRequest(PseudoIdScrollbarCorner), layoutObject->style());
}
if (!cornerStyle) {
// If the <body> didn't have a custom style, then the root element might.
if (Element* docElement = doc->documentElement()) {
if (LayoutObject* layoutObject = docElement->layoutObject())
cornerStyle = layoutObject->getUncachedPseudoStyle(
PseudoStyleRequest(PseudoIdScrollbarCorner),
layoutObject->style());
}
}
if (!cornerStyle) {
// If we have an owning ipage/LocalFrame element, then it can set the
// custom scrollbar also.
LayoutPartItem layoutItem = m_frame->ownerLayoutItem();
if (!layoutItem.isNull())
cornerStyle = layoutItem.getUncachedPseudoStyle(
PseudoStyleRequest(PseudoIdScrollbarCorner), layoutItem.style());
}
}
if (cornerStyle) {
if (!m_scrollCorner)
m_scrollCorner = LayoutScrollbarPart::createAnonymous(doc, this);
m_scrollCorner->setStyleWithWritingModeOfParent(cornerStyle.release());
setScrollCornerNeedsPaintInvalidation();
} else if (m_scrollCorner) {
m_scrollCorner->destroy();
m_scrollCorner = nullptr;
}
}
Color FrameView::documentBackgroundColor() const {
// The LayoutView's background color is set in
// Document::inheritHtmlAndBodyElementStyles. Blend this with the base
// background color of the FrameView. This should match the color drawn by
// ViewPainter::paintBoxDecorationBackground.
Color result = baseBackgroundColor();
LayoutItem documentLayoutObject = layoutViewItem();
if (!documentLayoutObject.isNull())
result = result.blend(
documentLayoutObject.resolveColor(CSSPropertyBackgroundColor));
return result;
}
FrameView* FrameView::parentFrameView() const {
if (!parent())
return nullptr;
Frame* parentFrame = m_frame->tree().parent();
if (parentFrame && parentFrame->isLocalFrame())
return toLocalFrame(parentFrame)->view();
return nullptr;
}
void FrameView::didChangeGlobalRootScroller() {
if (!m_frame->settings() || !m_frame->settings()->viewportEnabled())
return;
// Avoid drawing two sets of scrollbars when visual viewport is enabled.
bool hasHorizontalScrollbar = horizontalScrollbar();
bool hasVerticalScrollbar = verticalScrollbar();
bool shouldHaveHorizontalScrollbar = false;
bool shouldHaveVerticalScrollbar = false;
computeScrollbarExistence(shouldHaveHorizontalScrollbar,
shouldHaveVerticalScrollbar, contentsSize());
m_scrollbarManager.setHasHorizontalScrollbar(shouldHaveHorizontalScrollbar);
m_scrollbarManager.setHasVerticalScrollbar(shouldHaveVerticalScrollbar);
if (hasHorizontalScrollbar != shouldHaveHorizontalScrollbar ||
hasVerticalScrollbar != shouldHaveVerticalScrollbar)
scrollbarExistenceDidChange();
}
void FrameView::updateWidgetGeometriesIfNeeded() {
if (!m_needsUpdateWidgetGeometries)
return;
m_needsUpdateWidgetGeometries = false;
updateWidgetGeometries();
}
void FrameView::updateAllLifecyclePhases() {
frame().localFrameRoot()->view()->updateLifecyclePhasesInternal(
DocumentLifecycle::PaintClean);
}
// TODO(chrishtr): add a scrolling update lifecycle phase.
void FrameView::updateLifecycleToCompositingCleanPlusScrolling() {
if (RuntimeEnabledFeatures::slimmingPaintV2Enabled())
updateAllLifecyclePhasesExceptPaint();
else
frame().localFrameRoot()->view()->updateLifecyclePhasesInternal(
DocumentLifecycle::CompositingClean);
}
void FrameView::updateAllLifecyclePhasesExceptPaint() {
frame().localFrameRoot()->view()->updateLifecyclePhasesInternal(
DocumentLifecycle::PrePaintClean);
}
void FrameView::updateLifecycleToLayoutClean() {
frame().localFrameRoot()->view()->updateLifecyclePhasesInternal(
DocumentLifecycle::LayoutClean);
}
void FrameView::scheduleVisualUpdateForPaintInvalidationIfNeeded() {
LocalFrame* localFrameRoot = frame().localFrameRoot();
if (localFrameRoot->view()->m_currentUpdateLifecyclePhasesTargetState <
DocumentLifecycle::PaintInvalidationClean ||
lifecycle().state() >= DocumentLifecycle::PrePaintClean) {
// Schedule visual update to process the paint invalidation in the next
// cycle.
localFrameRoot->scheduleVisualUpdateUnlessThrottled();
}
// Otherwise the paint invalidation will be handled in paint invalidation
// phase of this cycle.
}
void FrameView::notifyResizeObservers() {
// Controller exists only if ResizeObserver was created.
if (!frame().document()->resizeObserverController())
return;
ResizeObserverController& resizeController =
m_frame->document()->ensureResizeObserverController();
DCHECK(lifecycle().state() >= DocumentLifecycle::LayoutClean);
size_t minDepth = 0;
for (minDepth = resizeController.gatherObservations(0);
minDepth != ResizeObserverController::kDepthBottom;
minDepth = resizeController.gatherObservations(minDepth)) {
resizeController.deliverObservations();
frame().document()->updateStyleAndLayout();
}
if (resizeController.skippedObservations()) {
resizeController.clearObservations();
ErrorEvent* error = ErrorEvent::create(
"ResizeObserver loop limit exceeded",
SourceLocation::capture(m_frame->document()), nullptr);
m_frame->document()->dispatchErrorEvent(error, NotSharableCrossOrigin);
// Ensure notifications will get delivered in next cycle.
if (FrameView* frameView = m_frame->view())
frameView->scheduleAnimation();
}
DCHECK(!layoutView()->needsLayout());
}
// TODO(leviw): We don't assert lifecycle information from documents in child
// PluginViews.
void FrameView::updateLifecyclePhasesInternal(
DocumentLifecycle::LifecycleState targetState) {
if (m_currentUpdateLifecyclePhasesTargetState !=
DocumentLifecycle::Uninitialized) {
NOTREACHED() << "FrameView::updateLifecyclePhasesInternal() reentrance";
return;
}
// This must be called from the root frame, since it recurses down, not up.
// Otherwise the lifecycles of the frames might be out of sync.
DCHECK(m_frame->isLocalRoot());
// Only the following target states are supported.
DCHECK(targetState == DocumentLifecycle::LayoutClean ||
targetState == DocumentLifecycle::CompositingClean ||
targetState == DocumentLifecycle::PrePaintClean ||
targetState == DocumentLifecycle::PaintClean);
if (!m_frame->document()->isActive())
return;
AutoReset<DocumentLifecycle::LifecycleState> targetStateScope(
&m_currentUpdateLifecyclePhasesTargetState, targetState);
if (shouldThrottleRendering()) {
updateViewportIntersectionsForSubtree(
std::min(targetState, DocumentLifecycle::CompositingClean));
return;
}
updateStyleAndLayoutIfNeededRecursive();
DCHECK(lifecycle().state() >= DocumentLifecycle::LayoutClean);
if (targetState == DocumentLifecycle::LayoutClean) {
updateViewportIntersectionsForSubtree(targetState);
return;
}
forAllNonThrottledFrameViews([](FrameView& frameView) {
frameView.performScrollAnchoringAdjustments();
});
if (targetState == DocumentLifecycle::PaintClean) {
forAllNonThrottledFrameViews(
[](FrameView& frameView) { frameView.notifyResizeObservers(); });
}
if (LayoutViewItem view = layoutViewItem()) {
forAllNonThrottledFrameViews([](FrameView& frameView) {
frameView.checkDoesNotNeedLayout();
frameView.m_allowsLayoutInvalidationAfterLayoutClean = false;
});
{
TRACE_EVENT1("devtools.timeline", "UpdateLayerTree", "data",
InspectorUpdateLayerTreeEvent::data(m_frame.get()));
if (!RuntimeEnabledFeatures::slimmingPaintV2Enabled()) {
view.compositor()->updateIfNeededRecursive();
} else {
DocumentAnimations::updateAnimations(layoutView()->document());
forAllNonThrottledFrameViews([](FrameView& frameView) {
frameView.layoutView()->commitPendingSelection();
});
}
scrollContentsIfNeededRecursive();
DCHECK(RuntimeEnabledFeatures::slimmingPaintInvalidationEnabled() ||
lifecycle().state() >= DocumentLifecycle::CompositingClean);
m_frame->host()->globalRootScrollerController().didUpdateCompositing();
if (targetState >= DocumentLifecycle::PrePaintClean) {
if (!RuntimeEnabledFeatures::slimmingPaintInvalidationEnabled())
invalidateTreeIfNeededRecursive();
if (view.compositor()->inCompositingMode())
scrollingCoordinator()->updateAfterCompositingChangeIfNeeded();
updateCompositedSelectionIfNeeded();
}
}
if (targetState >= DocumentLifecycle::PrePaintClean) {
updatePaintProperties();
}
if (targetState == DocumentLifecycle::PaintClean) {
if (!m_frame->document()->printing())
synchronizedPaint();
if (RuntimeEnabledFeatures::slimmingPaintV2Enabled())
pushPaintArtifactToCompositor();
DCHECK(!view.hasPendingSelection());
DCHECK((m_frame->document()->printing() &&
lifecycle().state() == DocumentLifecycle::PrePaintClean) ||
lifecycle().state() == DocumentLifecycle::PaintClean);
}
forAllNonThrottledFrameViews([](FrameView& frameView) {
frameView.checkDoesNotNeedLayout();
frameView.m_allowsLayoutInvalidationAfterLayoutClean = true;
});
}
updateViewportIntersectionsForSubtree(targetState);
}
void FrameView::enqueueScrollAnchoringAdjustment(
ScrollableArea* scrollableArea) {
m_anchoringAdjustmentQueue.add(scrollableArea);
}
void FrameView::performScrollAnchoringAdjustments() {
for (WeakMember<ScrollableArea>& scroller : m_anchoringAdjustmentQueue) {
if (scroller) {
DCHECK(scroller->scrollAnchor());
scroller->scrollAnchor()->adjust();
}
}
m_anchoringAdjustmentQueue.clear();
}
void FrameView::updatePaintProperties() {
TRACE_EVENT0("blink", "FrameView::updatePaintProperties");
if (!m_paintController)
m_paintController = PaintController::create();
forAllNonThrottledFrameViews([](FrameView& frameView) {
frameView.lifecycle().advanceTo(DocumentLifecycle::InPrePaint);
});
// TODO(chrishtr): merge this into the actual pre-paint tree walk.
if (RuntimeEnabledFeatures::slimmingPaintV2Enabled())
forAllNonThrottledFrameViews([](FrameView& frameView) {
CompositingInputsUpdater(frameView.layoutView()->layer()).update();
});
if (RuntimeEnabledFeatures::slimmingPaintInvalidationEnabled())
PrePaintTreeWalk().walk(*this);
forAllNonThrottledFrameViews([](FrameView& frameView) {
frameView.lifecycle().advanceTo(DocumentLifecycle::PrePaintClean);
});
}
void FrameView::synchronizedPaint() {
TRACE_EVENT0("blink", "FrameView::synchronizedPaint");
SCOPED_BLINK_UMA_HISTOGRAM_TIMER("Blink.Paint.UpdateTime");
ASSERT(frame() == page()->mainFrame() ||
(!frame().tree().parent()->isLocalFrame()));
LayoutViewItem view = layoutViewItem();
ASSERT(!view.isNull());
forAllNonThrottledFrameViews([](FrameView& frameView) {
frameView.lifecycle().advanceTo(DocumentLifecycle::InPaint);
});
if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) {
if (layoutView()->layer()->needsRepaint()) {
GraphicsContext graphicsContext(*m_paintController);
paint(graphicsContext, CullRect(LayoutRect::infiniteIntRect()));
m_paintController->commitNewDisplayItems(LayoutSize());
}
} else {
// A null graphics layer can occur for painting of SVG images that are not
// parented into the main frame tree, or when the FrameView is the main
// frame view of a page overlay. The page overlay is in the layer tree of
// the host page and will be painted during synchronized painting of the
// host page.
if (GraphicsLayer* rootGraphicsLayer =
view.compositor()->rootGraphicsLayer()) {
synchronizedPaintRecursively(rootGraphicsLayer);
}
// TODO(sataya.m):Main frame doesn't create RootFrameViewport in some
// webkit_unit_tests (http://crbug.com/644788).
if (m_viewportScrollableArea) {
if (GraphicsLayer* layerForHorizontalScrollbar =
m_viewportScrollableArea->layerForHorizontalScrollbar()) {
synchronizedPaintRecursively(layerForHorizontalScrollbar);
}
if (GraphicsLayer* layerForVerticalScrollbar =
m_viewportScrollableArea->layerForVerticalScrollbar()) {
synchronizedPaintRecursively(layerForVerticalScrollbar);
}
if (GraphicsLayer* layerForScrollCorner =
m_viewportScrollableArea->layerForScrollCorner()) {
synchronizedPaintRecursively(layerForScrollCorner);
}
}
}
forAllNonThrottledFrameViews([](FrameView& frameView) {
frameView.lifecycle().advanceTo(DocumentLifecycle::PaintClean);
LayoutViewItem layoutViewItem = frameView.layoutViewItem();
if (!layoutViewItem.isNull())
layoutViewItem.layer()->clearNeedsRepaintRecursively();
});
}
void FrameView::synchronizedPaintRecursively(GraphicsLayer* graphicsLayer) {
if (graphicsLayer->drawsContent())
graphicsLayer->paint(nullptr);
if (!RuntimeEnabledFeatures::slimmingPaintV2Enabled()) {
if (GraphicsLayer* maskLayer = graphicsLayer->maskLayer())
synchronizedPaintRecursively(maskLayer);
if (GraphicsLayer* contentsClippingMaskLayer =
graphicsLayer->contentsClippingMaskLayer())
synchronizedPaintRecursively(contentsClippingMaskLayer);
}
for (auto& child : graphicsLayer->children())
synchronizedPaintRecursively(child);
}
void FrameView::pushPaintArtifactToCompositor() {
TRACE_EVENT0("blink", "FrameView::pushPaintArtifactToCompositor");
ASSERT(RuntimeEnabledFeatures::slimmingPaintV2Enabled());
Page* page = frame().page();
if (!page)
return;
if (!m_paintArtifactCompositor) {
m_paintArtifactCompositor = PaintArtifactCompositor::create();
page->chromeClient().attachRootLayer(
m_paintArtifactCompositor->getWebLayer(), &frame());
}
SCOPED_BLINK_UMA_HISTOGRAM_TIMER("Blink.Compositing.UpdateTime");
m_paintArtifactCompositor->update(
m_paintController->paintArtifact(),
m_paintController->paintChunksRasterInvalidationTrackingMap());
}
std::unique_ptr<JSONObject> FrameView::compositedLayersAsJSON(
LayerTreeFlags flags) {
return frame()
.localFrameRoot()
->view()
->m_paintArtifactCompositor->layersAsJSON(flags);
}
void FrameView::updateStyleAndLayoutIfNeededRecursive() {
SCOPED_BLINK_UMA_HISTOGRAM_TIMER("Blink.StyleAndLayout.UpdateTime");
updateStyleAndLayoutIfNeededRecursiveInternal();
}
void FrameView::updateStyleAndLayoutIfNeededRecursiveInternal() {
if (shouldThrottleRendering() || !m_frame->document()->isActive())
return;
ScopedFrameBlamer frameBlamer(m_frame);
TRACE_EVENT0("blink", "FrameView::updateStyleAndLayoutIfNeededRecursive");
// We have to crawl our entire subtree looking for any FrameViews that need
// layout and make sure they are up to date.
// Mac actually tests for intersection with the dirty region and tries not to
// update layout for frames that are outside the dirty region. Not only does
// this seem pointless (since those frames will have set a zero timer to
// layout anyway), but it is also incorrect, since if two frames overlap, the
// first could be excluded from the dirty region but then become included
// later by the second frame adding rects to the dirty region when it lays
// out.
m_frame->document()->updateStyleAndLayoutTree();
CHECK(!shouldThrottleRendering());
CHECK(m_frame->document()->isActive());
CHECK(!m_nestedLayoutCount);
if (needsLayout())
layout();
checkDoesNotNeedLayout();
// WebView plugins need to update regardless of whether the
// LayoutEmbeddedObject that owns them needed layout.
// TODO(leviw): This currently runs the entire lifecycle on plugin WebViews.
// We should have a way to only run these other Documents to the same
// lifecycle stage as this frame.
const ChildrenWidgetSet* viewChildren = children();
for (const Member<Widget>& child : *viewChildren) {
if ((*child).isPluginContainer())
toPluginView(child.get())->updateAllLifecyclePhases();
}
checkDoesNotNeedLayout();
// FIXME: Calling layout() shouldn't trigger script execution or have any
// observable effects on the frame tree but we're not quite there yet.
HeapVector<Member<FrameView>> frameViews;
for (Frame* child = m_frame->tree().firstChild(); child;
child = child->tree().nextSibling()) {
if (!child->isLocalFrame())
continue;
if (FrameView* view = toLocalFrame(child)->view())
frameViews.append(view);
}
for (const auto& frameView : frameViews)
frameView->updateStyleAndLayoutIfNeededRecursiveInternal();
// These asserts ensure that parent frames are clean, when child frames
// finished updating layout and style.
checkDoesNotNeedLayout();
#if ENABLE(ASSERT)
m_frame->document()->layoutView()->assertLaidOut();
#endif
updateWidgetGeometriesIfNeeded();
if (lifecycle().state() < DocumentLifecycle::LayoutClean)
lifecycle().advanceTo(DocumentLifecycle::LayoutClean);
// Ensure that we become visually non-empty eventually.
// TODO(esprehn): This should check isRenderingReady() instead.
if (frame().document()->hasFinishedParsing() &&
frame().loader().stateMachine()->committedFirstRealDocumentLoad())
m_isVisuallyNonEmpty = true;
}
void FrameView::invalidateTreeIfNeededRecursive() {
SCOPED_BLINK_UMA_HISTOGRAM_TIMER("Blink.PaintInvalidation.UpdateTime");
invalidateTreeIfNeededRecursiveInternal();
}
void FrameView::invalidateTreeIfNeededRecursiveInternal() {
DCHECK(!RuntimeEnabledFeatures::slimmingPaintV2Enabled());
CHECK(layoutView());
// We need to stop recursing here since a child frame view might not be
// throttled even though we are (e.g., it didn't compute its visibility yet).
if (shouldThrottleRendering())
return;
TRACE_EVENT1("blink", "FrameView::invalidateTreeIfNeededRecursive", "root",
layoutView()->debugName().ascii());
Vector<const LayoutObject*> pendingDelayedPaintInvalidations;
PaintInvalidationState rootPaintInvalidationState(
*layoutView(), pendingDelayedPaintInvalidations);
if (lifecycle().state() < DocumentLifecycle::PaintInvalidationClean)
invalidateTreeIfNeeded(rootPaintInvalidationState);
// Some frames may be not reached during the above invalidateTreeIfNeeded
// because
// - the frame is a detached frame; or
// - it didn't need paint invalidation.
// We need to call invalidateTreeIfNeededRecursive() for such frames to finish
// required paint invalidation and advance their life cycle state.
for (Frame* child = m_frame->tree().firstChild(); child;
child = child->tree().nextSibling()) {
if (child->isLocalFrame()) {
FrameView& childFrameView = *toLocalFrame(child)->view();
// The children frames can be in any state, including stopping.
// Thus we have to check that it makes sense to do paint
// invalidation onto them here.
if (!childFrameView.layoutView())
continue;
childFrameView.invalidateTreeIfNeededRecursiveInternal();
}
}
// Process objects needing paint invalidation on the next frame. See the
// definition of PaintInvalidationDelayedFull for more details.
for (auto& target : pendingDelayedPaintInvalidations)
target->getMutableForPainting().setShouldDoFullPaintInvalidation(
PaintInvalidationDelayedFull);
}
void FrameView::enableAutoSizeMode(const IntSize& minSize,
const IntSize& maxSize) {
if (!m_autoSizeInfo)
m_autoSizeInfo = FrameViewAutoSizeInfo::create(this);
m_autoSizeInfo->configureAutoSizeMode(minSize, maxSize);
setLayoutSizeFixedToFrameSize(true);
setNeedsLayout();
scheduleRelayout();
}
void FrameView::disableAutoSizeMode() {
if (!m_autoSizeInfo)
return;
setLayoutSizeFixedToFrameSize(false);
setNeedsLayout();
scheduleRelayout();
// Since autosize mode forces the scrollbar mode, change them to being auto.
setVerticalScrollbarLock(false);
setHorizontalScrollbarLock(false);
setScrollbarModes(ScrollbarAuto, ScrollbarAuto);
m_autoSizeInfo.clear();
}
void FrameView::forceLayoutForPagination(const FloatSize& pageSize,
const FloatSize& originalPageSize,
float maximumShrinkFactor) {
// Dumping externalRepresentation(m_frame->layoutObject()).ascii() is a good
// trick to see the state of things before and after the layout
if (LayoutView* layoutView = this->layoutView()) {
float pageLogicalWidth = layoutView->style()->isHorizontalWritingMode()
? pageSize.width()
: pageSize.height();
float pageLogicalHeight = layoutView->style()->isHorizontalWritingMode()
? pageSize.height()
: pageSize.width();
LayoutUnit flooredPageLogicalWidth =
static_cast<LayoutUnit>(pageLogicalWidth);
LayoutUnit flooredPageLogicalHeight =
static_cast<LayoutUnit>(pageLogicalHeight);
layoutView->setLogicalWidth(flooredPageLogicalWidth);
layoutView->setPageLogicalHeight(flooredPageLogicalHeight);
layoutView->setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(
LayoutInvalidationReason::PrintingChanged);
layout();
// If we don't fit in the given page width, we'll lay out again. If we don't
// fit in the page width when shrunk, we will lay out at maximum shrink and
// clip extra content.
// FIXME: We are assuming a shrink-to-fit printing implementation. A
// cropping implementation should not do this!
bool horizontalWritingMode = layoutView->style()->isHorizontalWritingMode();
const LayoutRect& documentRect = LayoutRect(layoutView->documentRect());
LayoutUnit docLogicalWidth =
horizontalWritingMode ? documentRect.width() : documentRect.height();
if (docLogicalWidth > pageLogicalWidth) {
FloatSize expectedPageSize(
std::min<float>(documentRect.width().toFloat(),
pageSize.width() * maximumShrinkFactor),
std::min<float>(documentRect.height().toFloat(),
pageSize.height() * maximumShrinkFactor));
FloatSize maxPageSize = m_frame->resizePageRectsKeepingRatio(
FloatSize(originalPageSize.width(), originalPageSize.height()),
expectedPageSize);
pageLogicalWidth =
horizontalWritingMode ? maxPageSize.width() : maxPageSize.height();
pageLogicalHeight =
horizontalWritingMode ? maxPageSize.height() : maxPageSize.width();
flooredPageLogicalWidth = static_cast<LayoutUnit>(pageLogicalWidth);
flooredPageLogicalHeight = static_cast<LayoutUnit>(pageLogicalHeight);
layoutView->setLogicalWidth(flooredPageLogicalWidth);
layoutView->setPageLogicalHeight(flooredPageLogicalHeight);
layoutView->setNeedsLayoutAndPrefWidthsRecalcAndFullPaintInvalidation(
LayoutInvalidationReason::PrintingChanged);
layout();
const LayoutRect& updatedDocumentRect =
LayoutRect(layoutView->documentRect());
LayoutUnit docLogicalHeight = horizontalWritingMode
? updatedDocumentRect.height()
: updatedDocumentRect.width();
LayoutUnit docLogicalTop = horizontalWritingMode
? updatedDocumentRect.y()
: updatedDocumentRect.x();
LayoutUnit docLogicalRight = horizontalWritingMode
? updatedDocumentRect.maxX()
: updatedDocumentRect.maxY();
LayoutUnit clippedLogicalLeft;
if (!layoutView->style()->isLeftToRightDirection())
clippedLogicalLeft = LayoutUnit(docLogicalRight - pageLogicalWidth);
LayoutRect overflow(clippedLogicalLeft, docLogicalTop,
LayoutUnit(pageLogicalWidth), docLogicalHeight);
if (!horizontalWritingMode)
overflow = overflow.transposedRect();
layoutView->clearLayoutOverflow();
layoutView->addLayoutOverflow(
overflow); // This is how we clip in case we overflow again.
}
}
adjustViewSizeAndLayout();
}
IntRect FrameView::convertFromLayoutItem(
const LayoutItem& layoutItem,
const IntRect& layoutObjectRect) const {
// Convert from page ("absolute") to FrameView coordinates.
LayoutRect rect = enclosingLayoutRect(
layoutItem.localToAbsoluteQuad(FloatRect(layoutObjectRect))
.boundingBox());
rect.move(LayoutSize(-scrollOffset()));
return pixelSnappedIntRect(rect);
}
IntRect FrameView::convertToLayoutItem(const LayoutItem& layoutItem,
const IntRect& frameRect) const {
IntRect rectInContent = frameToContents(frameRect);
// Convert from FrameView coords into page ("absolute") coordinates.
rectInContent.move(scrollOffsetInt());
// FIXME: we don't have a way to map an absolute rect down to a local quad, so
// just move the rect for now.
rectInContent.setLocation(roundedIntPoint(
layoutItem.absoluteToLocal(rectInContent.location(), UseTransforms)));
return rectInContent;
}
IntPoint FrameView::convertFromLayoutItem(
const LayoutItem& layoutItem,
const IntPoint& layoutObjectPoint) const {
IntPoint point = roundedIntPoint(
layoutItem.localToAbsolute(layoutObjectPoint, UseTransforms));
// Convert from page ("absolute") to FrameView coordinates.
point.move(-scrollOffsetInt());
return point;
}
IntPoint FrameView::convertToLayoutItem(const LayoutItem& layoutItem,
const IntPoint& framePoint) const {
IntPoint point = framePoint;
// Convert from FrameView coords into page ("absolute") coordinates.
point += IntSize(scrollX(), scrollY());
return roundedIntPoint(layoutItem.absoluteToLocal(point, UseTransforms));
}
IntRect FrameView::convertToContainingWidget(const IntRect& localRect) const {
if (const FrameView* parentView = toFrameView(parent())) {
// Get our layoutObject in the parent view
LayoutPartItem layoutItem = m_frame->ownerLayoutItem();
if (layoutItem.isNull())
return localRect;
IntRect rect(localRect);
// Add borders and padding??
rect.move((layoutItem.borderLeft() + layoutItem.paddingLeft()).toInt(),
(layoutItem.borderTop() + layoutItem.paddingTop()).toInt());
return parentView->convertFromLayoutItem(layoutItem, rect);
}
return localRect;
}
IntRect FrameView::convertFromContainingWidget(
const IntRect& parentRect) const {
if (const FrameView* parentView = toFrameView(parent())) {
// Get our layoutObject in the parent view
LayoutPartItem layoutItem = m_frame->ownerLayoutItem();
if (layoutItem.isNull())
return parentRect;
IntRect rect = parentView->convertToLayoutItem(layoutItem, parentRect);
// Subtract borders and padding
rect.move((-layoutItem.borderLeft() - layoutItem.paddingLeft()).toInt(),
(-layoutItem.borderTop() - layoutItem.paddingTop().toInt()));
return rect;
}
return parentRect;
}
IntPoint FrameView::convertToContainingWidget(
const IntPoint& localPoint) const {
if (const FrameView* parentView = toFrameView(parent())) {
// Get our layoutObject in the parent view
LayoutPartItem layoutItem = m_frame->ownerLayoutItem();
if (layoutItem.isNull())
return localPoint;
IntPoint point(localPoint);
// Add borders and padding
point.move((layoutItem.borderLeft() + layoutItem.paddingLeft()).toInt(),
(layoutItem.borderTop() + layoutItem.paddingTop()).toInt());
return parentView->convertFromLayoutItem(layoutItem, point);
}
return localPoint;
}
IntPoint FrameView::convertFromContainingWidget(
const IntPoint& parentPoint) const {
if (const FrameView* parentView = toFrameView(parent())) {
// Get our layoutObject in the parent view
LayoutPartItem layoutItem = m_frame->ownerLayoutItem();
if (layoutItem.isNull())
return parentPoint;
IntPoint point = parentView->convertToLayoutItem(layoutItem, parentPoint);
// Subtract borders and padding
point.move((-layoutItem.borderLeft() - layoutItem.paddingLeft()).toInt(),
(-layoutItem.borderTop() - layoutItem.paddingTop()).toInt());
return point;
}
return parentPoint;
}
void FrameView::setInitialTracksPaintInvalidationsForTesting(
bool trackPaintInvalidations) {
s_initialTrackAllPaintInvalidations = trackPaintInvalidations;
}
void FrameView::setTracksPaintInvalidations(bool trackPaintInvalidations) {
if (trackPaintInvalidations == isTrackingPaintInvalidations())
return;
for (Frame* frame = m_frame->tree().top(); frame;
frame = frame->tree().traverseNext()) {
if (!frame->isLocalFrame())
continue;
if (LayoutViewItem layoutView = toLocalFrame(frame)->contentLayoutItem()) {
layoutView.frameView()->m_trackedObjectPaintInvalidations = wrapUnique(
trackPaintInvalidations ? new Vector<ObjectPaintInvalidation>
: nullptr);
if (RuntimeEnabledFeatures::slimmingPaintV2Enabled()) {
m_paintController->setTracksRasterInvalidations(
trackPaintInvalidations);
m_paintArtifactCompositor->setTracksRasterInvalidations(
trackPaintInvalidations);
} else {
layoutView.compositor()->setTracksRasterInvalidations(
trackPaintInvalidations);
}
}
}
TRACE_EVENT_INSTANT1(TRACE_DISABLED_BY_DEFAULT("blink.invalidation"),
"FrameView::setTracksPaintInvalidations",
TRACE_EVENT_SCOPE_GLOBAL, "enabled",
trackPaintInvalidations);
}
void FrameView::trackObjectPaintInvalidation(const DisplayItemClient& client,
PaintInvalidationReason reason) {
if (!m_trackedObjectPaintInvalidations)
return;
ObjectPaintInvalidation invalidation = {client.debugName(), reason};
m_trackedObjectPaintInvalidations->append(invalidation);
}
std::unique_ptr<JSONArray> FrameView::trackedObjectPaintInvalidationsAsJSON()
const {
if (!m_trackedObjectPaintInvalidations)
return nullptr;
std::unique_ptr<JSONArray> result = JSONArray::create();
for (Frame* frame = m_frame->tree().top(); frame;
frame = frame->tree().traverseNext()) {
if (!frame->isLocalFrame())
continue;
if (LayoutViewItem layoutView = toLocalFrame(frame)->contentLayoutItem()) {
if (!layoutView.frameView()->m_trackedObjectPaintInvalidations)
continue;
for (const auto& item :
*layoutView.frameView()->m_trackedObjectPaintInvalidations) {
std::unique_ptr<JSONObject> itemJSON = JSONObject::create();
itemJSON->setString("object", item.name);
itemJSON->setString("reason",
paintInvalidationReasonToString(item.reason));
result->pushObject(std::move(itemJSON));
}
}
}
return result;
}
void FrameView::addResizerArea(LayoutBox& resizerBox) {
if (!m_resizerAreas)
m_resizerAreas = wrapUnique(new ResizerAreaSet);
m_resizerAreas->add(&resizerBox);
}
void FrameView::removeResizerArea(LayoutBox& resizerBox) {
if (!m_resizerAreas)
return;
ResizerAreaSet::iterator it = m_resizerAreas->find(&resizerBox);
if (it != m_resizerAreas->end())
m_resizerAreas->remove(it);
}
void FrameView::addScrollableArea(ScrollableArea* scrollableArea) {
ASSERT(scrollableArea);
if (!m_scrollableAreas)
m_scrollableAreas = new ScrollableAreaSet;
m_scrollableAreas->add(scrollableArea);
if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
scrollingCoordinator->scrollableAreasDidChange();
}
void FrameView::removeScrollableArea(ScrollableArea* scrollableArea) {
if (!m_scrollableAreas)
return;
m_scrollableAreas->remove(scrollableArea);
if (ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator())
scrollingCoordinator->scrollableAreasDidChange();
}
void FrameView::addAnimatingScrollableArea(ScrollableArea* scrollableArea) {
ASSERT(scrollableArea);
if (!m_animatingScrollableAreas)
m_animatingScrollableAreas = new ScrollableAreaSet;
m_animatingScrollableAreas->add(scrollableArea);
}
void FrameView::removeAnimatingScrollableArea(ScrollableArea* scrollableArea) {
if (!m_animatingScrollableAreas)
return;
m_animatingScrollableAreas->remove(scrollableArea);
}
void FrameView::setParent(Widget* parentView) {
if (parentView == parent())
return;
Widget::setParent(parentView);
updateParentScrollableAreaSet();
setNeedsUpdateViewportIntersection();
setupRenderThrottling();
if (parentFrameView())
m_subtreeThrottled = parentFrameView()->canThrottleRendering();
}
void FrameView::removeChild(Widget* child) {
ASSERT(child->parent() == this);
if (child->isFrameView())
removeScrollableArea(toFrameView(child));
child->setParent(0);
m_children.remove(child);
}
bool FrameView::visualViewportSuppliesScrollbars() {
// On desktop, we always use the layout viewport's scrollbars.
if (!m_frame->settings() || !m_frame->settings()->viewportEnabled() ||
!m_frame->document() || !m_frame->host())
return false;
const TopDocumentRootScrollerController& controller =
m_frame->host()->globalRootScrollerController();
if (!controller.globalRootScroller())
return false;
return RootScrollerUtil::scrollableAreaFor(
*controller.globalRootScroller()) ==
layoutViewportScrollableArea();
}
AXObjectCache* FrameView::axObjectCache() const {
if (frame().document())
return frame().document()->existingAXObjectCache();
return nullptr;
}
void FrameView::setCursor(const Cursor& cursor) {
Page* page = frame().page();
if (!page || !page->settings().deviceSupportsMouse())
return;
page->chromeClient().setCursor(cursor, m_frame);
}
void FrameView::frameRectsChanged() {
TRACE_EVENT0("blink", "FrameView::frameRectsChanged");
if (layoutSizeFixedToFrameSize())
setLayoutSizeInternal(frameRect().size());
setNeedsUpdateViewportIntersection();
for (const auto& child : m_children)
child->frameRectsChanged();
}
void FrameView::setLayoutSizeInternal(const IntSize& size) {
if (m_layoutSize == size)
return;
m_layoutSize = size;
contentsResized();
}
void FrameView::didAddScrollbar(Scrollbar& scrollbar,
ScrollbarOrientation orientation) {
ScrollableArea::didAddScrollbar(scrollbar, orientation);
}
void FrameView::setBrowserControlsViewportAdjustment(float adjustment) {
m_browserControlsViewportAdjustment = adjustment;
}
IntSize FrameView::maximumScrollOffsetInt() const {
// Make the same calculation as in CC's LayerImpl::MaxScrollOffset()
// FIXME: We probably shouldn't be storing the bounds in a float.
// crbug.com/422331.
IntSize visibleSize =
visibleContentSize(ExcludeScrollbars) + browserControlsSize();
IntSize contentBounds = contentsSize();
IntSize maximumOffset =
toIntSize(-scrollOrigin() + (contentBounds - visibleSize));
return maximumOffset.expandedTo(minimumScrollOffsetInt());
}
void FrameView::addChild(Widget* child) {
ASSERT(child != this && !child->parent());
child->setParent(this);
m_children.add(child);
}
void FrameView::setScrollbarModes(ScrollbarMode horizontalMode,
ScrollbarMode verticalMode,
bool horizontalLock,
bool verticalLock) {
bool needsUpdate = false;
// If the page's overflow setting has disabled scrolling, do not allow
// anything to override that setting, http://crbug.com/426447
LayoutObject* viewport = viewportLayoutObject();
if (viewport && !shouldIgnoreOverflowHidden()) {
if (viewport->style()->overflowX() == OverflowHidden)
horizontalMode = ScrollbarAlwaysOff;
if (viewport->style()->overflowY() == OverflowHidden)
verticalMode = ScrollbarAlwaysOff;
}
if (horizontalMode != horizontalScrollbarMode() &&
!m_horizontalScrollbarLock) {
m_horizontalScrollbarMode = horizontalMode;
needsUpdate = true;
}
if (verticalMode != verticalScrollbarMode() && !m_verticalScrollbarLock) {
m_verticalScrollbarMode = verticalMode;
needsUpdate = true;
}
if (horizontalLock)
setHorizontalScrollbarLock();
if (verticalLock)
setVerticalScrollbarLock();
if (!needsUpdate)
return;
updateScrollbars();
if (!layerForScrolling())
return;
WebLayer* layer = layerForScrolling()->platformLayer();
if (!layer)
return;
layer->setUserScrollable(userInputScrollable(HorizontalScrollbar),
userInputScrollable(VerticalScrollbar));
}
IntSize FrameView::visibleContentSize(
IncludeScrollbarsInRect scrollbarInclusion) const {
return scrollbarInclusion == ExcludeScrollbars
? excludeScrollbars(frameRect().size())
: frameRect().size();
}
IntRect FrameView::visibleContentRect(
IncludeScrollbarsInRect scrollbarInclusion) const {
return IntRect(IntPoint(flooredIntSize(m_scrollOffset)),
visibleContentSize(scrollbarInclusion));
}
IntSize FrameView::contentsSize() const {
return m_contentsSize;
}
void FrameView::clipPaintRect(FloatRect* paintRect) const {
// Paint the whole rect if "mainFrameClipsContent" is false, meaning that
// WebPreferences::record_whole_document is true.
if (!m_frame->settings()->mainFrameClipsContent())
return;
paintRect->intersect(
page()->chromeClient().visibleContentRectForPainting().value_or(
visibleContentRect()));
}
IntSize FrameView::minimumScrollOffsetInt() const {
return IntSize(-scrollOrigin().x(), -scrollOrigin().y());
}
void FrameView::adjustScrollbarOpacity() {
if (horizontalScrollbar() && layerForHorizontalScrollbar()) {
bool isOpaqueScrollbar = !horizontalScrollbar()->isOverlayScrollbar();
layerForHorizontalScrollbar()->setContentsOpaque(isOpaqueScrollbar);
}
if (verticalScrollbar() && layerForVerticalScrollbar()) {
bool isOpaqueScrollbar = !verticalScrollbar()->isOverlayScrollbar();
layerForVerticalScrollbar()->setContentsOpaque(isOpaqueScrollbar);
}
}
int FrameView::scrollSize(ScrollbarOrientation orientation) const {
Scrollbar* scrollbar =
((orientation == HorizontalScrollbar) ? horizontalScrollbar()
: verticalScrollbar());
// If no scrollbars are present, the content may still be scrollable.
if (!scrollbar) {
IntSize scrollSize = m_contentsSize - visibleContentRect().size();
scrollSize.clampNegativeToZero();
return orientation == HorizontalScrollbar ? scrollSize.width()
: scrollSize.height();
}
return scrollbar->totalSize() - scrollbar->visibleSize();
}
void FrameView::updateScrollOffset(const ScrollOffset& offset,
ScrollType scrollType) {
ScrollOffset scrollDelta = offset - m_scrollOffset;
if (scrollDelta.isZero())
return;
showOverlayScrollbars();
if (RuntimeEnabledFeatures::rootLayerScrollingEnabled()) {
// Don't scroll the FrameView!
ASSERT_NOT_REACHED();
}
m_scrollOffset = offset;
if (!scrollbarsSuppressed())
m_pendingScrollDelta += scrollDelta;
if (scrollTypeClearsFragmentAnchor(scrollType))
clearFragmentAnchor();
updateLayersAndCompositingAfterScrollIfNeeded(scrollDelta);
Document* document = m_frame->document();
document->enqueueScrollEventForNode(document);
m_frame->eventHandler().dispatchFakeMouseMoveEventSoon();
Page* page = frame().page();
if (page)
page->chromeClient().clearToolTip(*m_frame);
LayoutViewItem layoutViewItem = document->layoutViewItem();
if (!layoutViewItem.isNull()) {
if (layoutViewItem.usesCompositing())
layoutViewItem.compositor()->frameViewDidScroll();
layoutViewItem.clearHitTestCache();
}
m_didScrollTimer.startOneShot(resourcePriorityUpdateDelayAfterScroll,
BLINK_FROM_HERE);
if (AXObjectCache* cache = m_frame->document()->existingAXObjectCache())
cache->handleScrollPositionChanged(this);
frame().loader().saveScrollState();
didChangeScrollOffset();
if (scrollType == CompositorScroll && m_frame->isMainFrame()) {
if (DocumentLoader* documentLoader = m_frame->loader().documentLoader())
documentLoader->initialScrollState().wasScrolledByUser = true;
}
if (scrollType != AnchoringScroll && scrollType != ClampingScroll)
clearScrollAnchor();
}
void FrameView::didChangeScrollOffset() {
frame().loader().client()->didChangeScrollOffset();
if (frame().isMainFrame())
frame().host()->chromeClient().mainFrameScrollOffsetChanged();
if (!RuntimeEnabledFeatures::rootLayerScrollingEnabled()) {
// The scroll translation paint property depends on scroll offset.
setNeedsPaintPropertyUpdate();
}
}
void FrameView::clearScrollAnchor() {
if (!RuntimeEnabledFeatures::scrollAnchoringEnabled())
return;
m_scrollAnchor.clear();
}
bool FrameView::hasOverlayScrollbars() const {
return (horizontalScrollbar() &&
horizontalScrollbar()->isOverlayScrollbar()) ||
(verticalScrollbar() && verticalScrollbar()->isOverlayScrollbar());
}
void FrameView::computeScrollbarExistence(
bool& newHasHorizontalScrollbar,
bool& newHasVerticalScrollbar,
const IntSize& docSize,
ComputeScrollbarExistenceOption option) {
if ((m_frame->settings() && m_frame->settings()->hideScrollbars()) ||
visualViewportSuppliesScrollbars()) {
newHasHorizontalScrollbar = false;
newHasVerticalScrollbar = false;
return;
}
bool hasHorizontalScrollbar = horizontalScrollbar();
bool hasVerticalScrollbar = verticalScrollbar();
newHasHorizontalScrollbar = hasHorizontalScrollbar;
newHasVerticalScrollbar = hasVerticalScrollbar;
if (RuntimeEnabledFeatures::rootLayerScrollingEnabled())
return;
ScrollbarMode hScroll = m_horizontalScrollbarMode;
ScrollbarMode vScroll = m_verticalScrollbarMode;
if (hScroll != ScrollbarAuto)
newHasHorizontalScrollbar = (hScroll == ScrollbarAlwaysOn);
if (vScroll != ScrollbarAuto)
newHasVerticalScrollbar = (vScroll == ScrollbarAlwaysOn);
if (m_scrollbarsSuppressed ||
(hScroll != ScrollbarAuto && vScroll != ScrollbarAuto))
return;
if (hScroll == ScrollbarAuto)
newHasHorizontalScrollbar = docSize.width() > visibleWidth();
if (vScroll == ScrollbarAuto)
newHasVerticalScrollbar = docSize.height() > visibleHeight();
if (hasOverlayScrollbars())
return;
IntSize fullVisibleSize = visibleContentRect(IncludeScrollbars).size();
bool attemptToRemoveScrollbars =
(option == FirstPass && docSize.width() <= fullVisibleSize.width() &&
docSize.height() <= fullVisibleSize.height());
if (attemptToRemoveScrollbars) {
if (hScroll == ScrollbarAuto)
newHasHorizontalScrollbar = false;
if (vScroll == ScrollbarAuto)
newHasVerticalScrollbar = false;
}
}
void FrameView::updateScrollbarGeometry() {
if (horizontalScrollbar()) {
int thickness = horizontalScrollbar()->scrollbarThickness();
int clientWidth = visibleWidth();
IntRect oldRect(horizontalScrollbar()->frameRect());
IntRect hBarRect(
(shouldPlaceVerticalScrollbarOnLeft() && verticalScrollbar())
? verticalScrollbar()->width()
: 0,
height() - thickness,
width() - (verticalScrollbar() ? verticalScrollbar()->width() : 0),
thickness);
horizontalScrollbar()->setFrameRect(hBarRect);
if (oldRect != horizontalScrollbar()->frameRect())
setScrollbarNeedsPaintInvalidation(HorizontalScrollbar);
horizontalScrollbar()->setEnabled(contentsWidth() > clientWidth);
horizontalScrollbar()->setProportion(clientWidth, contentsWidth());
horizontalScrollbar()->offsetDidChange();
}
if (verticalScrollbar()) {
int thickness = verticalScrollbar()->scrollbarThickness();
int clientHeight = visibleHeight();
IntRect oldRect(verticalScrollbar()->frameRect());
IntRect vBarRect(
shouldPlaceVerticalScrollbarOnLeft() ? 0 : (width() - thickness), 0,
thickness,
height() -
(horizontalScrollbar() ? horizontalScrollbar()->height() : 0));
verticalScrollbar()->setFrameRect(vBarRect);
if (oldRect != verticalScrollbar()->frameRect())
setScrollbarNeedsPaintInvalidation(VerticalScrollbar);
verticalScrollbar()->setEnabled(contentsHeight() > clientHeight);
verticalScrollbar()->setProportion(clientHeight, contentsHeight());
verticalScrollbar()->offsetDidChange();
}
}
bool FrameView::adjustScrollbarExistence(
ComputeScrollbarExistenceOption option) {
ASSERT(m_inUpdateScrollbars);
// If we came in here with the view already needing a layout, then go ahead
// and do that first. (This will be the common case, e.g., when the page
// changes due to window resizing for example). This layout will not re-enter
// updateScrollbars and does not count towards our max layout pass total.
if (!m_scrollbarsSuppressed)
scrollbarExistenceDidChange();
bool hasHorizontalScrollbar = horizontalScrollbar();
bool hasVerticalScrollbar = verticalScrollbar();
bool newHasHorizontalScrollbar = false;
bool newHasVerticalScrollbar = false;
computeScrollbarExistence(newHasHorizontalScrollbar, newHasVerticalScrollbar,
contentsSize(), option);
bool scrollbarExistenceChanged =
hasHorizontalScrollbar != newHasHorizontalScrollbar ||
hasVerticalScrollbar != newHasVerticalScrollbar;
if (!scrollbarExistenceChanged)
return false;
m_scrollbarManager.setHasHorizontalScrollbar(newHasHorizontalScrollbar);
m_scrollbarManager.setHasVerticalScrollbar(newHasVerticalScrollbar);
if (m_scrollbarsSuppressed)
return true;
if (!hasOverlayScrollbars())
contentsResized();
scrollbarExistenceDidChange();
return true;
}
bool FrameView::needsScrollbarReconstruction() const {
Element* customScrollbarElement = nullptr;
LocalFrame* customScrollbarFrame = nullptr;
bool shouldUseCustom =
shouldUseCustomScrollbars(customScrollbarElement, customScrollbarFrame);
bool hasAnyScrollbar = horizontalScrollbar() || verticalScrollbar();
bool hasCustom =
(horizontalScrollbar() && horizontalScrollbar()->isCustomScrollbar()) ||
(verticalScrollbar() && verticalScrollbar()->isCustomScrollbar());
return hasAnyScrollbar && (shouldUseCustom != hasCustom);
}
bool FrameView::shouldIgnoreOverflowHidden() const {
return m_frame->settings()->ignoreMainFrameOverflowHiddenQuirk() &&
m_frame->isMainFrame();
}
void FrameView::updateScrollbarsIfNeeded() {
if (m_needsScrollbarsUpdate || needsScrollbarReconstruction() ||
scrollOriginChanged())
updateScrollbars();
}
void FrameView::updateScrollbars() {
m_needsScrollbarsUpdate = false;
if (RuntimeEnabledFeatures::rootLayerScrollingEnabled())
return;
// Avoid drawing two sets of scrollbars when visual viewport is enabled.
if (visualViewportSuppliesScrollbars()) {
m_scrollbarManager.setHasHorizontalScrollbar(false);
m_scrollbarManager.setHasVerticalScrollbar(false);
adjustScrollOffsetFromUpdateScrollbars();
return;
}
if (m_inUpdateScrollbars)
return;
InUpdateScrollbarsScope inUpdateScrollbarsScope(this);
bool scrollbarExistenceChanged = false;
if (needsScrollbarReconstruction()) {
m_scrollbarManager.setHasHorizontalScrollbar(false);
m_scrollbarManager.setHasVerticalScrollbar(false);
scrollbarExistenceChanged = true;
}
int maxUpdateScrollbarsPass =
hasOverlayScrollbars() || m_scrollbarsSuppressed ? 1 : 3;
for (int updateScrollbarsPass = 0;
updateScrollbarsPass < maxUpdateScrollbarsPass; updateScrollbarsPass++) {
if (!adjustScrollbarExistence(updateScrollbarsPass ? Incremental
: FirstPass))
break;
scrollbarExistenceChanged = true;
}
updateScrollbarGeometry();
if (scrollbarExistenceChanged) {
// FIXME: Is frameRectsChanged really necessary here? Have any frame rects
// changed?
frameRectsChanged();
positionScrollbarLayers();
updateScrollCorner();
}
adjustScrollOffsetFromUpdateScrollbars();
}
void FrameView::adjustScrollOffsetFromUpdateScrollbars() {
ScrollOffset clamped = clampScrollOffset(scrollOffset());
if (clamped != scrollOffset() || scrollOriginChanged()) {
ScrollableArea::setScrollOffset(clamped, ClampingScroll);
resetScrollOriginChanged();
}
}
void FrameView::scrollContentsIfNeeded() {
if (m_pendingScrollDelta.isZero())
return;
ScrollOffset scrollDelta = m_pendingScrollDelta;
m_pendingScrollDelta = ScrollOffset();
// FIXME: Change scrollContents() to take DoubleSize. crbug.com/414283.
scrollContents(flooredIntSize(scrollDelta));
}
void FrameView::scrollContents(const IntSize& scrollDelta) {
HostWindow* window = getHostWindow();
if (!window)
return;
TRACE_EVENT0("blink", "FrameView::scrollContents");
if (!scrollContentsFastPath(-scrollDelta))
scrollContentsSlowPath();
// This call will move children with native widgets (plugins) and invalidate
// them as well.
frameRectsChanged();
}
IntPoint FrameView::contentsToFrame(const IntPoint& pointInContentSpace) const {
return pointInContentSpace - scrollOffsetInt();
}
IntRect FrameView::contentsToFrame(const IntRect& rectInContentSpace) const {
return IntRect(contentsToFrame(rectInContentSpace.location()),
rectInContentSpace.size());
}
FloatPoint FrameView::frameToContents(const FloatPoint& pointInFrame) const {
return pointInFrame + scrollOffset();
}
IntPoint FrameView::frameToContents(const IntPoint& pointInFrame) const {
return pointInFrame + scrollOffsetInt();
}
IntRect FrameView::frameToContents(const IntRect& rectInFrame) const {
return IntRect(frameToContents(rectInFrame.location()), rectInFrame.size());
}
IntPoint FrameView::rootFrameToContents(const IntPoint& rootFramePoint) const {
IntPoint framePoint = convertFromRootFrame(rootFramePoint);
return frameToContents(framePoint);
}
IntRect FrameView::rootFrameToContents(const IntRect& rootFrameRect) const {
return IntRect(rootFrameToContents(rootFrameRect.location()),
rootFrameRect.size());
}
IntPoint FrameView::contentsToRootFrame(const IntPoint& contentsPoint) const {
IntPoint framePoint = contentsToFrame(contentsPoint);
return convertToRootFrame(framePoint);
}
IntRect FrameView::contentsToRootFrame(const IntRect& contentsRect) const {
IntRect rectInFrame = contentsToFrame(contentsRect);
return convertToRootFrame(rectInFrame);
}
FloatPoint FrameView::rootFrameToContents(
const FloatPoint& pointInRootFrame) const {
FloatPoint framePoint = convertFromRootFrame(pointInRootFrame);
return frameToContents(framePoint);
}
IntRect FrameView::viewportToContents(const IntRect& rectInViewport) const {
IntRect rectInRootFrame =
m_frame->host()->visualViewport().viewportToRootFrame(rectInViewport);
IntRect frameRect = convertFromRootFrame(rectInRootFrame);
return frameToContents(frameRect);
}
IntPoint FrameView::viewportToContents(const IntPoint& pointInViewport) const {
IntPoint pointInRootFrame =
m_frame->host()->visualViewport().viewportToRootFrame(pointInViewport);
IntPoint pointInFrame = convertFromRootFrame(pointInRootFrame);
return frameToContents(pointInFrame);
}
IntRect FrameView::contentsToViewport(const IntRect& rectInContents) const {
IntRect rectInFrame = contentsToFrame(rectInContents);
IntRect rectInRootFrame = convertToRootFrame(rectInFrame);
return m_frame->host()->visualViewport().rootFrameToViewport(rectInRootFrame);
}
IntPoint FrameView::contentsToViewport(const IntPoint& pointInContents) const {
IntPoint pointInFrame = contentsToFrame(pointInContents);
IntPoint pointInRootFrame = convertToRootFrame(pointInFrame);
return m_frame->host()->visualViewport().rootFrameToViewport(
pointInRootFrame);
}
IntRect FrameView::contentsToScreen(const IntRect& rect) const {
HostWindow* window = getHostWindow();
if (!window)
return IntRect();
return window->viewportToScreen(contentsToViewport(rect), this);
}
IntRect FrameView::soonToBeRemovedContentsToUnscaledViewport(
const IntRect& rectInContents) const {
IntRect rectInFrame = contentsToFrame(rectInContents);
IntRect rectInRootFrame = convertToRootFrame(rectInFrame);
return enclosingIntRect(
m_frame->host()->visualViewport().mainViewToViewportCSSPixels(
rectInRootFrame));
}
IntPoint FrameView::soonToBeRemovedUnscaledViewportToContents(
const IntPoint& pointInViewport) const {
IntPoint pointInRootFrame = flooredIntPoint(
m_frame->host()->visualViewport().viewportCSSPixelsToRootFrame(
pointInViewport));
IntPoint pointInThisFrame = convertFromRootFrame(pointInRootFrame);
return frameToContents(pointInThisFrame);
}
Scrollbar* FrameView::scrollbarAtFramePoint(const IntPoint& pointInFrame) {
if (horizontalScrollbar() &&
horizontalScrollbar()->shouldParticipateInHitTesting() &&
horizontalScrollbar()->frameRect().contains(pointInFrame))
return horizontalScrollbar();
if (verticalScrollbar() &&
verticalScrollbar()->shouldParticipateInHitTesting() &&
verticalScrollbar()->frameRect().contains(pointInFrame))
return verticalScrollbar();
return nullptr;
}
static void positionScrollbarLayer(GraphicsLayer* graphicsLayer,
Scrollbar* scrollbar) {
if (!graphicsLayer || !scrollbar)
return;
IntRect scrollbarRect = scrollbar->frameRect();
graphicsLayer->setPosition(scrollbarRect.location());
if (scrollbarRect.size() == graphicsLayer->size())
return;
graphicsLayer->setSize(FloatSize(scrollbarRect.size()));
if (graphicsLayer->hasContentsLayer()) {
graphicsLayer->setContentsRect(
IntRect(0, 0, scrollbarRect.width(), scrollbarRect.height()));
return;
}
graphicsLayer->setDrawsContent(true);
graphicsLayer->setNeedsDisplay();
}
static void positionScrollCornerLayer(GraphicsLayer* graphicsLayer,
const IntRect& cornerRect) {
if (!graphicsLayer)
return;
graphicsLayer->setDrawsContent(!cornerRect.isEmpty());
graphicsLayer->setPosition(cornerRect.location());
if (cornerRect.size() != graphicsLayer->size())
graphicsLayer->setNeedsDisplay();
graphicsLayer->setSize(FloatSize(cornerRect.size()));
}
void FrameView::positionScrollbarLayers() {
positionScrollbarLayer(layerForHorizontalScrollbar(), horizontalScrollbar());
positionScrollbarLayer(layerForVerticalScrollbar(), verticalScrollbar());
positionScrollCornerLayer(layerForScrollCorner(), scrollCornerRect());
}
bool FrameView::userInputScrollable(ScrollbarOrientation orientation) const {
Document* document = frame().document();
Element* fullscreenElement = Fullscreen::fullscreenElementFrom(*document);
if (fullscreenElement && fullscreenElement != document->documentElement())
return false;
if (RuntimeEnabledFeatures::rootLayerScrollingEnabled())
return false;
ScrollbarMode mode = (orientation == HorizontalScrollbar)
? m_horizontalScrollbarMode
: m_verticalScrollbarMode;
return mode == ScrollbarAuto || mode == ScrollbarAlwaysOn;
}
bool FrameView::shouldPlaceVerticalScrollbarOnLeft() const {
return false;
}
Widget* FrameView::getWidget() {
return this;
}
LayoutRect FrameView::scrollIntoView(const LayoutRect& rectInContent,
const ScrollAlignment& alignX,
const ScrollAlignment& alignY,
ScrollType scrollType) {
LayoutRect viewRect(visibleContentRect());
LayoutRect exposeRect =
ScrollAlignment::getRectToExpose(viewRect, rectInContent, alignX, alignY);
if (exposeRect != viewRect) {
setScrollOffset(
ScrollOffset(exposeRect.x().toFloat(), exposeRect.y().toFloat()),
scrollType);
}
// Scrolling the FrameView cannot change the input rect's location relative to
// the document.
return rectInContent;
}
IntRect FrameView::scrollCornerRect() const {
IntRect cornerRect;
if (hasOverlayScrollbars())
return cornerRect;
if (horizontalScrollbar() && width() - horizontalScrollbar()->width() > 0) {
cornerRect.unite(IntRect(shouldPlaceVerticalScrollbarOnLeft()
? 0
: horizontalScrollbar()->width(),
height() - horizontalScrollbar()->height(),
width() - horizontalScrollbar()->width(),
horizontalScrollbar()->height()));
}
if (verticalScrollbar() && height() - verticalScrollbar()->height() > 0) {
cornerRect.unite(IntRect(shouldPlaceVerticalScrollbarOnLeft()
? 0
: (width() - verticalScrollbar()->width()),
verticalScrollbar()->height(),
verticalScrollbar()->width(),
height() - verticalScrollbar()->height()));
}
return cornerRect;
}
bool FrameView::isScrollCornerVisible() const {
return !scrollCornerRect().isEmpty();
}
ScrollBehavior FrameView::scrollBehaviorStyle() const {
Element* scrollElement = m_frame->document()->scrollingElement();
LayoutObject* layoutObject =
scrollElement ? scrollElement->layoutObject() : nullptr;
if (layoutObject &&
layoutObject->style()->getScrollBehavior() == ScrollBehaviorSmooth)
return ScrollBehaviorSmooth;
return ScrollBehaviorInstant;
}
void FrameView::paint(GraphicsContext& context,
const CullRect& cullRect) const {
paint(context, GlobalPaintNormalPhase, cullRect);
}
void FrameView::paint(GraphicsContext& context,
const GlobalPaintFlags globalPaintFlags,
const CullRect& cullRect) const {
FramePainter(*this).paint(context, globalPaintFlags, cullRect);
}
void FrameView::paintContents(GraphicsContext& context,
const GlobalPaintFlags globalPaintFlags,
const IntRect& damageRect) const {
FramePainter(*this).paintContents(context, globalPaintFlags, damageRect);
}
bool FrameView::isPointInScrollbarCorner(const IntPoint& pointInRootFrame) {
if (!scrollbarCornerPresent())
return false;
IntPoint framePoint = convertFromRootFrame(pointInRootFrame);
if (horizontalScrollbar()) {
int horizontalScrollbarYMin = horizontalScrollbar()->frameRect().y();
int horizontalScrollbarYMax = horizontalScrollbar()->frameRect().y() +
horizontalScrollbar()->frameRect().height();
int horizontalScrollbarXMin = horizontalScrollbar()->frameRect().x() +
horizontalScrollbar()->frameRect().width();
return framePoint.y() > horizontalScrollbarYMin &&
framePoint.y() < horizontalScrollbarYMax &&
framePoint.x() > horizontalScrollbarXMin;
}
int verticalScrollbarXMin = verticalScrollbar()->frameRect().x();
int verticalScrollbarXMax = verticalScrollbar()->frameRect().x() +
verticalScrollbar()->frameRect().width();
int verticalScrollbarYMin = verticalScrollbar()->frameRect().y() +
verticalScrollbar()->frameRect().height();
return framePoint.x() > verticalScrollbarXMin &&
framePoint.x() < verticalScrollbarXMax &&
framePoint.y() > verticalScrollbarYMin;
}
bool FrameView::scrollbarCornerPresent() const {
return (horizontalScrollbar() &&
width() - horizontalScrollbar()->width() > 0) ||
(verticalScrollbar() && height() - verticalScrollbar()->height() > 0);
}
IntRect FrameView::convertFromScrollbarToContainingWidget(
const Scrollbar& scrollbar,
const IntRect& localRect) const {
// Scrollbars won't be transformed within us
IntRect newRect = localRect;
newRect.moveBy(scrollbar.location());
return newRect;
}
IntRect FrameView::convertFromContainingWidgetToScrollbar(
const Scrollbar& scrollbar,
const IntRect& parentRect) const {
IntRect newRect = parentRect;
// Scrollbars won't be transformed within us
newRect.moveBy(-scrollbar.location());
return newRect;
}
// FIXME: test these on windows
IntPoint FrameView::convertFromScrollbarToContainingWidget(
const Scrollbar& scrollbar,
const IntPoint& localPoint) const {
// Scrollbars won't be transformed within us
IntPoint newPoint = localPoint;
newPoint.moveBy(scrollbar.location());
return newPoint;
}
IntPoint FrameView::convertFromContainingWidgetToScrollbar(
const Scrollbar& scrollbar,
const IntPoint& parentPoint) const {
IntPoint newPoint = parentPoint;
// Scrollbars won't be transformed within us
newPoint.moveBy(-scrollbar.location());
return newPoint;
}
static void setNeedsCompositingUpdate(LayoutViewItem layoutViewItem,
CompositingUpdateType updateType) {
if (PaintLayerCompositor* compositor =
!layoutViewItem.isNull() ? layoutViewItem.compositor() : nullptr)
compositor->setNeedsCompositingUpdate(updateType);
}
void FrameView::setParentVisible(bool visible) {
if (isParentVisible() == visible)
return;
// As parent visibility changes, we may need to recomposite this frame view
// and potentially child frame views.
setNeedsCompositingUpdate(layoutViewItem(), CompositingUpdateRebuildTree);
Widget::setParentVisible(visible);
if (!isSelfVisible())
return;
for (const auto& child : m_children)
child->setParentVisible(visible);
}
void FrameView::show() {
if (!isSelfVisible()) {
setSelfVisible(true);
if (ScrollingCoordinator* scrollingCoordinator =
this->scrollingCoordinator())
scrollingCoordinator->frameViewVisibilityDidChange();
setNeedsCompositingUpdate(layoutViewItem(), CompositingUpdateRebuildTree);
updateParentScrollableAreaSet();
if (isParentVisible()) {
for (const auto& child : m_children)
child->setParentVisible(true);
}
}
Widget::show();
}
void FrameView::hide() {
if (isSelfVisible()) {
if (isParentVisible()) {
for (const auto& child : m_children)
child->setParentVisible(false);
}
setSelfVisible(false);
if (ScrollingCoordinator* scrollingCoordinator =
this->scrollingCoordinator())
scrollingCoordinator->frameViewVisibilityDidChange();
setNeedsCompositingUpdate(layoutViewItem(), CompositingUpdateRebuildTree);
updateParentScrollableAreaSet();
}
Widget::hide();
}
int FrameView::viewportWidth() const {
int viewportWidth = layoutSize(IncludeScrollbars).width();
return adjustForAbsoluteZoom(viewportWidth, layoutView());
}
ScrollableArea* FrameView::getScrollableArea() {
if (m_viewportScrollableArea)
return m_viewportScrollableArea.get();
return layoutViewportScrollableArea();
}
ScrollableArea* FrameView::layoutViewportScrollableArea() {
if (!RuntimeEnabledFeatures::rootLayerScrollingEnabled())
return this;
LayoutViewItem layoutViewItem = this->layoutViewItem();
return layoutViewItem.isNull() ? nullptr : layoutViewItem.getScrollableArea();
}
RootFrameViewport* FrameView::getRootFrameViewport() {
return m_viewportScrollableArea.get();
}
LayoutObject* FrameView::viewportLayoutObject() const {
if (Document* document = frame().document()) {
if (Element* element = document->viewportDefiningElement())
return element->layoutObject();
}
return nullptr;
}
void FrameView::collectAnnotatedRegions(
LayoutObject& layoutObject,
Vector<AnnotatedRegionValue>& regions) const {
// LayoutTexts don't have their own style, they just use their parent's style,
// so we don't want to include them.
if (layoutObject.isText())
return;
layoutObject.addAnnotatedRegions(regions);
for (LayoutObject* curr = layoutObject.slowFirstChild(); curr;
curr = curr->nextSibling())
collectAnnotatedRegions(*curr, regions);
}
void FrameView::setNeedsUpdateViewportIntersection() {
for (FrameView* parent = parentFrameView(); parent;
parent = parent->parentFrameView())
parent->m_needsUpdateViewportIntersectionInSubtree = true;
}
void FrameView::updateViewportIntersectionsForSubtree(
DocumentLifecycle::LifecycleState targetState) {
// TODO(dcheng): Since widget tree updates are deferred, FrameViews might
// still be in the widget hierarchy even though the associated Document is
// already detached. Investigate if this check and a similar check in
// lifecycle updates are still needed when there are no more deferred widget
// updates: https://crbug.com/561683
if (!frame().document()->isActive())
return;
// Notify javascript IntersectionObservers
if (targetState == DocumentLifecycle::PaintClean &&
frame().document()->intersectionObserverController())
frame()
.document()
->intersectionObserverController()
->computeTrackedIntersectionObservations();
if (!m_needsUpdateViewportIntersectionInSubtree)
return;
m_needsUpdateViewportIntersectionInSubtree = false;
for (Frame* child = m_frame->tree().firstChild(); child;
child = child->tree().nextSibling()) {
if (!child->isLocalFrame())
continue;
if (FrameView* view = toLocalFrame(child)->view())
view->updateViewportIntersectionsForSubtree(targetState);
}
}
void FrameView::updateRenderThrottlingStatusForTesting() {
m_visibilityObserver->deliverObservationsForTesting();
}
void FrameView::updateRenderThrottlingStatus(bool hidden,
bool subtreeThrottled) {
TRACE_EVENT0("blink", "FrameView::updateRenderThrottlingStatus");
DCHECK(!isInPerformLayout());
DCHECK(!m_frame->document() || !m_frame->document()->inStyleRecalc());
bool wasThrottled = canThrottleRendering();
// Note that we disallow throttling of 0x0 frames because some sites use
// them to drive UI logic.
m_hiddenForThrottling = hidden && !frameRect().isEmpty();
m_subtreeThrottled = subtreeThrottled;
bool isThrottled = canThrottleRendering();
bool becameUnthrottled = wasThrottled && !isThrottled;
// If this FrameView became unthrottled or throttled, we must make sure all
// its children are notified synchronously. Otherwise we 1) might attempt to
// paint one of the children with an out-of-date layout before
// |updateRenderThrottlingStatus| has made it throttled or 2) fail to
// unthrottle a child whose parent is unthrottled by a later notification.
if (wasThrottled != isThrottled) {
for (const Member<Widget>& child : *children()) {
if (child->isFrameView()) {
FrameView* childView = toFrameView(child);
childView->updateRenderThrottlingStatus(
childView->m_hiddenForThrottling, isThrottled);
}
}
}
ScrollingCoordinator* scrollingCoordinator = this->scrollingCoordinator();
if (becameUnthrottled) {
// ScrollingCoordinator needs to update according to the new throttling
// status.
if (scrollingCoordinator)
scrollingCoordinator->notifyGeometryChanged();
// Start ticking animation frames again if necessary.
if (page())
page()->animator().scheduleVisualUpdate(m_frame.get());
// Force a full repaint of this frame to ensure we are not left with a
// partially painted version of this frame's contents if we skipped
// painting them while the frame was throttled.
LayoutViewItem layoutViewItem = this->layoutViewItem();
if (!layoutViewItem.isNull())
layoutViewItem.invalidatePaintForViewAndCompositedLayers();
}
bool hasHandlers = m_frame->host() &&
m_frame->host()->eventHandlerRegistry().hasEventHandlers(
EventHandlerRegistry::TouchStartOrMoveEventBlocking);
if (wasThrottled != canThrottleRendering() && scrollingCoordinator &&
hasHandlers)
scrollingCoordinator->touchEventTargetRectsDidChange();
#if DCHECK_IS_ON()
// Make sure we never have an unthrottled frame inside a throttled one.
FrameView* parent = parentFrameView();
while (parent) {
DCHECK(canThrottleRendering() || !parent->canThrottleRendering());
parent = parent->parentFrameView();
}
#endif
}
// TODO(esprehn): Rename this and the method on Document to
// recordDeferredLoadReason().
void FrameView::maybeRecordLoadReason() {
FrameView* parent = parentFrameView();
if (frame().document()->frame()) {
if (!parent) {
HTMLFrameOwnerElement* element = frame().deprecatedLocalOwner();
if (!element)
frame().document()->maybeRecordLoadReason(WouldLoadOutOfProcess);
// Having no layout object means the frame is not drawn.
else if (!element->layoutObject())
frame().document()->maybeRecordLoadReason(WouldLoadDisplayNone);
} else {
// Assume the main frame has always loaded since we don't track its
// visibility.
bool parentLoaded =
!parent->parentFrameView() ||
parent->frame().document()->wouldLoadReason() > Created;
// If the parent wasn't loaded, the children won't be either.
if (parentLoaded) {
if (frameRect().isEmpty())
frame().document()->maybeRecordLoadReason(WouldLoadZeroByZero);
else if (frameRect().maxY() < 0 && frameRect().maxX() < 0)
frame().document()->maybeRecordLoadReason(WouldLoadAboveAndLeft);
else if (frameRect().maxY() < 0)
frame().document()->maybeRecordLoadReason(WouldLoadAbove);
else if (frameRect().maxX() < 0)
frame().document()->maybeRecordLoadReason(WouldLoadLeft);
else if (!m_hiddenForThrottling)
frame().document()->maybeRecordLoadReason(WouldLoadVisible);
}
}
}
}
bool FrameView::shouldThrottleRendering() const {
return canThrottleRendering() && lifecycle().throttlingAllowed();
}
bool FrameView::canThrottleRendering() const {
if (m_lifecycleUpdatesThrottled)
return true;
if (!RuntimeEnabledFeatures::renderingPipelineThrottlingEnabled())
return false;
if (m_subtreeThrottled)
return true;
// We only throttle hidden cross-origin frames. This is to avoid a situation
// where an ancestor frame directly depends on the pipeline timing of a
// descendant and breaks as a result of throttling. The rationale is that
// cross-origin frames must already communicate with asynchronous messages,
// so they should be able to tolerate some delay in receiving replies from a
// throttled peer.
return m_hiddenForThrottling && m_frame->isCrossOriginSubframe();
}
void FrameView::beginLifecycleUpdates() {
// Avoid pumping frames for the initially empty document.
if (!frame().loader().stateMachine()->committedFirstRealDocumentLoad())
return;
m_lifecycleUpdatesThrottled = false;
setupRenderThrottling();
updateRenderThrottlingStatus(m_hiddenForThrottling, m_subtreeThrottled);
// The compositor will "defer commits" for the main frame until we
// explicitly request them.
if (frame().isMainFrame())
frame().host()->chromeClient().beginLifecycleUpdates();
}
void FrameView::setInitialViewportSize(const IntSize& viewportSize) {
if (viewportSize == m_initialViewportSize)
return;
m_initialViewportSize = viewportSize;
if (Document* document = m_frame->document())
document->styleEngine().initialViewportChanged();
}
int FrameView::initialViewportWidth() const {
DCHECK(m_frame->isMainFrame());
return m_initialViewportSize.width();
}
int FrameView::initialViewportHeight() const {
DCHECK(m_frame->isMainFrame());
return m_initialViewportSize.height();
}
} // namespace blink
|
tsegismont/rhq-metrics | core/rx-java-driver/src/main/java/org/hawkular/rx/cassandra/driver/RxSession.java | <reponame>tsegismont/rhq-metrics<filename>core/rx-java-driver/src/main/java/org/hawkular/rx/cassandra/driver/RxSession.java
/*
* Copyright 2014-2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hawkular.rx.cassandra.driver;
import java.io.Closeable;
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.PreparedStatement;
import com.datastax.driver.core.RegularStatement;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.Statement;
import rx.Observable;
import rx.Scheduler;
import rx.schedulers.Schedulers;
/**
* An RxJava flavor of the DataStax's Java driver {@link Session} interface.
*
* @author jsanda
*/
public interface RxSession extends Closeable {
/**
* @see Session#getLoggedKeyspace()
*/
String getLoggedKeyspace();
/**
* @see Session#init()
*/
RxSession init();
/**
* Asynchronously execute a query and emit the corresponding {@link ResultSet} on the
* {@link Schedulers#computation()} scheduler.
*
* @param query the CQL query to execute
*
* @return an {@link Observable} emitting just one {@link ResultSet} item
*/
Observable<ResultSet> execute(String query);
/**
* Asynchronously execute a query and fetch {@link Row}s, emitted on the {@link Schedulers#computation()}
* scheduler.
*
* @param query the CQL query to execute
*
* @return an {@link Observable} emitting {@link Row} items
*/
Observable<Row> executeAndFetch(String query);
/**
* Asynchronously execute a query and emit the corresponding {@link ResultSet} on the specified {@code scheduler}.
*
* @param query the CQL query to execute
* @param scheduler the {@link Scheduler} on which the returned {@link Observable} operates
*
* @return an {@link Observable} emitting just one {@link ResultSet} item
*/
Observable<ResultSet> execute(String query, Scheduler scheduler);
/**
* Asynchronously execute a query and fetch {@link Row}s, emitted on the specified {@code scheduler}.
*
* @param query the CQL query to execute
* @param scheduler the {@link Scheduler} on which the returned {@link Observable} operates
*
* @return an {@link Observable} emitting {@link Row} items
*/
Observable<Row> executeAndFetch(String query, Scheduler scheduler);
/**
* Asynchronously execute a query and emit the corresponding {@link ResultSet} on the
* {@link Schedulers#computation()} scheduler, using the provided {@code values}.
*
* @param query the CQL query to execute
* @param values values required for the execution of the query
*
* @return an {@link Observable} emitting just one {@link ResultSet} item
*/
Observable<ResultSet> execute(String query, Object... values);
/**
* Asynchronously execute a query and fetch {@link Row}s, emitted on the {@link Schedulers#computation()}
* scheduler, using the provided {@code values}.
*
* @param query the CQL query to execute
* @param values values required for the execution of the query
*
* @return an {@link Observable} emitting {@link Row} items
*/
Observable<Row> executeAndFetch(String query, Object... values);
/**
* Asynchronously execute a query and emit the corresponding {@link ResultSet} on the specified {@code scheduler},
* using the proved {@code values}.
*
* @param query the CQL query to execute
* @param scheduler the {@link Scheduler} on which the returned {@link Observable} operates
* @param values values required for the execution of the query
*
* @return an {@link Observable} emitting just one {@link ResultSet} item
*/
Observable<ResultSet> execute(String query, Scheduler scheduler, Object... values);
/**
* Asynchronously execute a query and fetch {@link Row}s, emitted on the specified {@code scheduler}, using the
* provided {@code values}.
*
* @param query the CQL query to execute
* @param scheduler the {@link Scheduler} on which the returned {@link Observable} operates
* @param values values required for the execution of the query
*
* @return an {@link Observable} emitting {@link Row} items
*/
Observable<Row> executeAndFetch(String query, Scheduler scheduler, Object... values);
/**
* Asynchronously execute a query and emit the corresponding {@link ResultSet} on the
* {@link Schedulers#computation()} scheduler.
*
* @param statement the CQL query to execute, of any {@link Statement} type
*
* @return an {@link Observable} emitting just one {@link ResultSet} item
*/
Observable<ResultSet> execute(Statement statement);
/**
* Asynchronously execute a query and fetch {@link Row}s, emitted on the {@link Schedulers#computation()}
* scheduler.
*
* @param statement the CQL query to execute, of any {@link Statement} type
*
* @return an {@link Observable} emitting {@link Row} items
*/
Observable<Row> executeAndFetch(Statement statement);
/**
* Asynchronously execute a query and emit the corresponding {@link ResultSet} on the specified {@code scheduler}.
*
* @param statement the CQL query to execute, of any {@link Statement} type
* @param scheduler the {@link Scheduler} on which the returned {@link Observable} operates
*
* @return an {@link Observable} emitting just one {@link ResultSet} item
*/
Observable<ResultSet> execute(Statement statement, Scheduler scheduler);
/**
* Asynchronously execute a query and fetch {@link Row}s, emitted on the specified {@code scheduler}.
*
* @param statement the CQL query to execute, of any {@link Statement} type
* @param scheduler the {@link Scheduler} on which the returned {@link Observable} operates
*
* @return an {@link Observable} emitting {@link Row} items
*/
Observable<Row> executeAndFetch(Statement statement, Scheduler scheduler);
/**
* Asynchronously prepare a query and emit the corresponding {@link PreparedStatement} on the
* {@link Schedulers#computation()} scheduler.
*
* @param query the CQL query to prepare
*
* @return an {@link Observable} emitting just one {@link PreparedStatement} item
*/
Observable<PreparedStatement> prepare(String query);
/**
* Asynchronously prepare a query and emit the corresponding {@link PreparedStatement} on the specified
* {@code scheduler}.
*
* @param query the CQL query to prepare
*
* @return an {@link Observable} emitting just one {@link PreparedStatement} item
*/
Observable<PreparedStatement> prepare(String query, Scheduler scheduler);
/**
* Asynchronously prepare a query and emit the corresponding {@link PreparedStatement} on the
* {@link Schedulers#computation()} scheduler.
*
* @param statement the {@link RegularStatement} to prepare
*
* @return an {@link Observable} emitting just one {@link PreparedStatement} item
* @see Session#prepareAsync(RegularStatement)
*/
Observable<PreparedStatement> prepare(RegularStatement statement);
/**
* Asynchronously prepare a query and emit the corresponding {@link PreparedStatement} on the specified
* {@code scheduler}.
*
* @param statement the {@link RegularStatement} to prepare
*
* @return an {@link Observable} emitting just one {@link PreparedStatement} item
* @see Session#prepareAsync(RegularStatement)
*/
Observable<PreparedStatement> prepare(RegularStatement statement, Scheduler scheduler);
/**
* @see Session#close()
*/
void close();
/**
* @see Session#isClosed()
*/
boolean isClosed();
/**
* @see Session#getCluster()
*/
Cluster getCluster();
/**
* @return the underlying {@link Session} object
*/
Session getSession();
/**
* @see Session#getState()
*/
Session.State getState();
}
|
raymondfx/cert-verifier-js | test/fixtures/index.js | <filename>test/fixtures/index.js
import EthereumMainV2Valid from './ethereum-main-valid-2.0';
import EthereumMainInvalidMerkleRoot from './ethereum-merkle-root-unmatch-2.0';
import EthereumMainRevoked from './ethereum-revoked-2.0';
import EthereumRopstenV2Valid from './ethereum-ropsten-valid-2.0';
import EthereumTampered from './ethereum-tampered-2.0';
import MainnetInvalidMerkleReceipt from './mainnet-invalid-merkle-receipt-2.0';
import MainnetMerkleRootUmmatch from './mainnet-merkle-root-unmatch-2.0';
import MainnetV2Revoked from './mainnet-revoked-2.0';
import MainnetV2Valid from './mainnet-valid-2.0';
import MainnetV2AlphaValid from './mainnet-valid-2.0-alpha';
import MocknetV2Valid from './mocknet-valid-2.0';
import RegtestV2Valid from './regtest-valid-2.0';
import TestnetV1IssuerUrl404 from './testnet-404-issuer-url-1.2';
import TestnetV1NoIssuerProfile from './testnet-no-issuer-profile-1.2';
import TestnetRevokedV2 from './testnet-revoked-key-2.0';
import TestnetTamperedHashes from './testnet-tampered-hashes-2.0';
import TestnetV1Valid from './testnet-valid-1.2';
import TestnetV2Valid from './testnet-valid-2.0';
import TestnetV2ValidV1Issuer from './testnet-valid-v1-issuer-2.0';
export default {
EthereumMainV2Valid,
EthereumMainInvalidMerkleRoot,
EthereumMainRevoked,
EthereumRopstenV2Valid,
EthereumTampered,
MainnetInvalidMerkleReceipt,
MainnetMerkleRootUmmatch,
MainnetV2Revoked,
MainnetV2Valid,
MainnetV2AlphaValid,
MocknetV2Valid,
RegtestV2Valid,
TestnetV1IssuerUrl404,
TestnetV1NoIssuerProfile,
TestnetRevokedV2,
TestnetTamperedHashes,
TestnetV1Valid,
TestnetV2Valid,
TestnetV2ValidV1Issuer
};
|
JPuigV/api-scala | src/main/tv/codely/api/entry_point/controller/user/UserGetController.scala | package tv.codely.api.entry_point.controller.user
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.server.Directives.complete
import akka.http.scaladsl.server.StandardRoute
import spray.json.DefaultJsonProtocol
import tv.codely.api.module.user.application.UsersSearcher
import tv.codely.api.module.user.infrastructure.marshaller.UserJsonFormatMarshaller._
final class UserGetController(searcher: UsersSearcher) extends SprayJsonSupport with DefaultJsonProtocol {
def get(): StandardRoute = complete(searcher.all())
}
|
jpvanoosten/VolumeTiledForwardShading | Engine/inc/Graphics/DX12/DescriptorAllocatorDX12.h | <gh_stars>10-100
#pragma once
/*
* Copyright(c) 2015 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files(the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions :
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
/**
* @file DescriptorAllocatorDX12.h
* @date February 24, 2016
* @author jeremiah
*
* @brief Descriptor allocator.
*/
namespace Graphics
{
class DeviceDX12;
class DescriptorAllocatorDX12
{
public:
DescriptorAllocatorDX12( Microsoft::WRL::ComPtr<ID3D12Device> d3d12Device, D3D12_DESCRIPTOR_HEAP_TYPE type, uint32_t numDescriptorsPerHeap = 256 );
virtual ~DescriptorAllocatorDX12();
D3D12_CPU_DESCRIPTOR_HANDLE Allocate( uint32_t numDescriptors = 1 );
protected:
Microsoft::WRL::ComPtr<ID3D12DescriptorHeap> CreateDescriptorHeap( D3D12_DESCRIPTOR_HEAP_TYPE type, uint32_t numDescriptors );
private:
using DescriptorHeapPool = std::vector< Microsoft::WRL::ComPtr<ID3D12DescriptorHeap> >;
Microsoft::WRL::ComPtr<ID3D12Device> m_d3d12Device;
Microsoft::WRL::ComPtr<ID3D12DescriptorHeap> m_CurrentHeap;
CD3DX12_CPU_DESCRIPTOR_HANDLE m_CurrentHandle;
D3D12_DESCRIPTOR_HEAP_TYPE m_HeapType;
std::mutex m_Mutex;
DescriptorHeapPool m_DescriptorHeapPool;
uint32_t m_NumDescriptorsPerHeap;
uint32_t m_DescriptorSize;
uint32_t m_NumFreeHandles;
};
} |
m34434/JavaGimmicks | core/src/main/java/net/sf/javagimmicks/transform/BidiTransforming.java | package net.sf.javagimmicks.transform;
/**
* An interface for objects that carry a {@link BidiFunction} for internally
* transforming objects.
*
* @param <F>
* the source object type of the contained {@link BidiFunction}
* @param <T>
* the target object type of the contained {@link BidiFunction}
*/
public interface BidiTransforming<F, T> extends Transforming<F, T>
{
/**
* Returns the internal {@link BidiFunction}
*
* @return the internal {@link BidiFunction}
*/
public BidiFunction<F, T> getTransformerBidiFunction();
}
|
Symphoomc1f/krexusj | back/src/main/java/com/java110/things/Controller/community/CommunityController.java | package com.java110.things.Controller.community;
import com.alibaba.fastjson.JSONObject;
import com.java110.things.Controller.BaseController;
import com.java110.things.entity.community.CommunityDto;
import com.java110.things.entity.response.ResultDto;
import com.java110.things.service.community.ICommunityService;
import com.java110.things.util.Assert;
import com.java110.things.util.BeanConvertUtil;
import com.java110.things.util.SeqUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
/**
* @ClassName CommunityController
* @Description TODO 小区信息控制类
* @Author wuxw
* @Date 2020/5/16 10:36
* @Version 1.0
* add by wuxw 2020/5/16
**/
@RestController
@RequestMapping(path = "/api/community")
public class CommunityController extends BaseController {
@Autowired
private ICommunityService communityServiceImpl;
/**
* 添加设备接口类
*
* @param param 请求报文 包括设备 前台填写信息
* @return 成功或者失败
* @throws Exception
*/
@RequestMapping(path = "/saveCommunity", method = RequestMethod.POST)
public ResponseEntity<String> saveCommunity(@RequestBody String param, HttpServletRequest request) throws Exception {
JSONObject paramObj = super.getParamJson(param);
Assert.hasKeyAndValue(paramObj, "address", "请求报文中未包含地址");
Assert.hasKeyAndValue(paramObj, "cityCode", "请求报文中未包含城市地区");
Assert.hasKeyAndValue(paramObj, "name", "请求报文中未包含小区名称");
CommunityDto communityDto = BeanConvertUtil.covertBean(paramObj, CommunityDto.class);
communityDto.setAppId(super.getAppId(request));
communityDto.setCommunityId(SeqUtil.getId());
ResultDto resultDto = communityServiceImpl.saveCommunity(communityDto);
return super.createResponseEntity(resultDto);
}
/**
* 更新小区信息
*
* @param param 请求报文
* @return 成功或者失败
* @throws Exception
*/
@RequestMapping(path = "/updateCommunitys", method = RequestMethod.POST)
public ResponseEntity<String> updateCommunitys(@RequestBody String param, HttpServletRequest request) throws Exception {
JSONObject paramObj = super.getParamJson(param);
Assert.hasKeyAndValue(paramObj, "address", "请求报文中未包含地址");
Assert.hasKeyAndValue(paramObj, "name", "请求报文中未包含小区名称");
Assert.hasKeyAndValue(paramObj, "extCommunityId", "请求报文中未包含外部编码");
CommunityDto communityDto = BeanConvertUtil.covertBean(paramObj, CommunityDto.class);
ResultDto resultDto = communityServiceImpl.updateCommunity(communityDto);
return super.createResponseEntity(resultDto);
}
/**
* 添加设备接口类
*
* @param communityId 页数
* @return 成功或者失败
* @throws Exception
*/
@RequestMapping(path = "/getCommunitys", method = RequestMethod.GET)
public ResponseEntity<String> getCommunitys(@RequestParam String communityId,
@RequestParam int page,
@RequestParam int row,
HttpServletRequest request) throws Exception {
CommunityDto communityDto = new CommunityDto();
communityDto.setCommunityId(communityId);
communityDto.setPage(page);
communityDto.setRow(row);
String appId = super.getAppId(request);
communityDto.setAppId(appId);
ResultDto resultDto = communityServiceImpl.getCommunity(communityDto);
return super.createResponseEntity(resultDto);
}
/**
* 删除设备 动作
*
* @param paramIn 入参
* @return
* @throws Exception
*/
@RequestMapping(path = "/deleteCommunity", method = RequestMethod.POST)
public ResponseEntity<String> deleteCommunity(@RequestBody String paramIn) throws Exception {
JSONObject paramObj = super.getParamJson(paramIn);
Assert.hasKeyAndValue(paramObj, "communityId", "请求报文中未包含硬件ID");
ResultDto resultDto = communityServiceImpl.deleteCommunity(BeanConvertUtil.covertBean(paramObj, CommunityDto.class));
return super.createResponseEntity(resultDto);
}
}
|
lastobelus/shutil | lib/shutil/workers.rb | <gh_stars>0
module Shutil
module Workers
extend ActiveSupport::Autoload
autoload :Utilities
def self.eager_load!
super
Shutil::Workers::Utilities.eager_load!
end
end
end |
qianyongjun123/FPGA-Industrial-Smart-Camera | ui-qt/DataOutput/IOTrigger/IOTrigger.h | #ifndef IOTRIGGER_H
#define IOTRIGGER_H
#include "iotrigger_global.h"
#include <QWidget>
class IOTRIGGERSHARED_EXPORT IOTrigger
{
public:
IOTrigger();
};
extern "C" Q_DECL_EXPORT QWidget* GetWidget();
#endif // IOTRIGGER_H
|
ComputationalRadiationPhysics/mallocMC | alpaka/include/alpaka/rand/Philox/PhiloxBaseStdArray.hpp | /* Copyright 2022 <NAME>, <NAME>
*
* This file is part of alpaka.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#pragma once
#include <array>
#include <cstdint>
namespace alpaka::rand::engine
{
/** Philox backend using std::array for Key and Counter storage
*
* @tparam TParams Philox algorithm parameters \sa PhiloxParams
* @tparam TImpl engine type implementation (CRTP)
*/
template<typename TParams, typename TImpl>
class PhiloxBaseStdArray
{
public:
using Counter = std::array<std::uint32_t, TParams::counterSize>; ///< Counter type = std::array
using Key = std::array<std::uint32_t, TParams::counterSize / 2>; ///< Key type = std::array
template<typename TScalar>
using ResultContainer
= std::array<TScalar, TParams::counterSize>; ///< Vector template for distribution results
};
} // namespace alpaka::rand::engine
|
dymecard/j2cl | transpiler/java/com/google/j2cl/transpiler/passes/NormalizeBasicCasts.java | /*
* Copyright 2021 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.j2cl.transpiler.passes;
import static com.google.common.base.CaseFormat.LOWER_CAMEL;
import static com.google.common.base.CaseFormat.UPPER_CAMEL;
import static com.google.j2cl.transpiler.ast.TypeDescriptors.isPrimitiveChar;
import static com.google.j2cl.transpiler.ast.TypeDescriptors.isPrimitiveFloatOrDouble;
import static com.google.j2cl.transpiler.ast.TypeDescriptors.isPrimitiveInt;
import com.google.common.collect.ImmutableList;
import com.google.j2cl.transpiler.ast.AbstractRewriter;
import com.google.j2cl.transpiler.ast.CastExpression;
import com.google.j2cl.transpiler.ast.CompilationUnit;
import com.google.j2cl.transpiler.ast.DeclaredTypeDescriptor;
import com.google.j2cl.transpiler.ast.Expression;
import com.google.j2cl.transpiler.ast.FieldAccess;
import com.google.j2cl.transpiler.ast.FieldDescriptor;
import com.google.j2cl.transpiler.ast.Kind;
import com.google.j2cl.transpiler.ast.MethodCall;
import com.google.j2cl.transpiler.ast.MethodDescriptor;
import com.google.j2cl.transpiler.ast.Node;
import com.google.j2cl.transpiler.ast.PrimitiveTypeDescriptor;
import com.google.j2cl.transpiler.ast.PrimitiveTypes;
import com.google.j2cl.transpiler.ast.TypeDeclaration;
import com.google.j2cl.transpiler.ast.TypeDescriptor;
import com.google.j2cl.transpiler.ast.TypeDescriptors;
/** Replaces cast expression on primitive & boxed types with corresponding cast method call. */
public class NormalizeBasicCasts extends NormalizationPass {
@Override
public void applyTo(CompilationUnit compilationUnit) {
compilationUnit.accept(
new AbstractRewriter() {
@Override
public Node rewriteCastExpression(CastExpression castExpression) {
Expression fromExpression = castExpression.getExpression();
TypeDescriptor fromType = fromExpression.getTypeDescriptor();
TypeDescriptor toType = castExpression.getTypeDescriptor();
if (!isBasicType(toType) || !isBasicType(fromType)) {
return castExpression;
}
PrimitiveTypeDescriptor fromPrimitiveType = fromType.toUnboxedType();
PrimitiveTypeDescriptor toPrimitiveType = toType.toUnboxedType();
// Skip conversion if not needed.
if (fromPrimitiveType.equals(toPrimitiveType)) {
return fromExpression;
}
// Primitive char needs to be converted first to int through ".code".
if (isPrimitiveChar(fromPrimitiveType)) {
fromExpression = convertCharCode(fromExpression);
fromPrimitiveType = PrimitiveTypes.INT;
}
// Conversion to char must go through int.
if (isPrimitiveChar(toPrimitiveType) && !isPrimitiveInt(fromPrimitiveType)) {
fromExpression = convertTo(fromExpression, PrimitiveTypes.INT);
fromPrimitiveType = PrimitiveTypes.INT;
}
// Conversion from float/double to a type that is narrower than int must go through int.
if (isPrimitiveFloatOrDouble(fromPrimitiveType)
&& PrimitiveTypes.INT.isWiderThan(toPrimitiveType)) {
fromExpression = convertTo(fromExpression, PrimitiveTypes.INT);
fromPrimitiveType = PrimitiveTypes.INT;
}
// Apply final conversion if needed.
return fromPrimitiveType.equals(toPrimitiveType)
? fromExpression
: convertTo(fromExpression, toPrimitiveType);
}
});
}
private static boolean isBasicType(TypeDescriptor type) {
return type.isPrimitive() || TypeDescriptors.isBoxedType(type);
}
private static final DeclaredTypeDescriptor KOTLIN_BASIC_TYPE =
DeclaredTypeDescriptor.newBuilder()
.setTypeDeclaration(
TypeDeclaration.newBuilder()
.setKind(Kind.CLASS)
.setPackageName("j2kt")
.setClassComponents(ImmutableList.of("BasicType"))
.build())
.build();
private static final Expression convertCharCode(Expression expression) {
FieldDescriptor castToFieldDescriptor =
FieldDescriptor.newBuilder()
.setEnclosingTypeDescriptor(KOTLIN_BASIC_TYPE)
.setName("code")
.setTypeDescriptor(PrimitiveTypes.CHAR)
.build();
return FieldAccess.Builder.from(castToFieldDescriptor).setQualifier(expression).build();
}
private static Expression convertTo(
Expression expression, PrimitiveTypeDescriptor primitiveType) {
MethodDescriptor castToMethodDescriptor =
MethodDescriptor.newBuilder()
.setEnclosingTypeDescriptor(KOTLIN_BASIC_TYPE)
.setName("to" + LOWER_CAMEL.to(UPPER_CAMEL, primitiveType.getSimpleSourceName()))
.setReturnTypeDescriptor(primitiveType)
.build();
return MethodCall.Builder.from(castToMethodDescriptor).setQualifier(expression).build();
}
}
|
ScalablyTyped/SlinkyTyped | a/aws-sdk/src/main/scala/typingsSlinky/awsSdk/ecrMod/DeleteRepositoryPolicyRequest.scala | package typingsSlinky.awsSdk.ecrMod
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
@js.native
trait DeleteRepositoryPolicyRequest extends StObject {
/**
* The AWS account ID associated with the registry that contains the repository policy to delete. If you do not specify a registry, the default registry is assumed.
*/
var registryId: js.UndefOr[RegistryId] = js.native
/**
* The name of the repository that is associated with the repository policy to delete.
*/
var repositoryName: RepositoryName = js.native
}
object DeleteRepositoryPolicyRequest {
@scala.inline
def apply(repositoryName: RepositoryName): DeleteRepositoryPolicyRequest = {
val __obj = js.Dynamic.literal(repositoryName = repositoryName.asInstanceOf[js.Any])
__obj.asInstanceOf[DeleteRepositoryPolicyRequest]
}
@scala.inline
implicit class DeleteRepositoryPolicyRequestMutableBuilder[Self <: DeleteRepositoryPolicyRequest] (val x: Self) extends AnyVal {
@scala.inline
def setRegistryId(value: RegistryId): Self = StObject.set(x, "registryId", value.asInstanceOf[js.Any])
@scala.inline
def setRegistryIdUndefined: Self = StObject.set(x, "registryId", js.undefined)
@scala.inline
def setRepositoryName(value: RepositoryName): Self = StObject.set(x, "repositoryName", value.asInstanceOf[js.Any])
}
}
|
tlmn/dwe-wahlkampf | src/components/sections/header.js | <filename>src/components/sections/header.js
import * as React from "react"
import { useIntl } from "gatsby-plugin-intl"
import LogoWordMark from "../../assets/svg/logoWordMark"
import LanguageSwitch from "../languageSwitch"
import CrossJa from "../../assets/svg/crossYes"
const Header = () => {
const intl = useIntl()
return (
<div
className="bg-yellow fixed top-0 left-0 w-full flex z-50 shadow py-1"
style={{ height: "45px" }}
>
<div className="container flex justify-between">
<LogoWordMark />
<div className="flex md:flex-row flex-col items-center gap-2">
<CrossJa className="w-full object-cover" style={{ width: "40px" }} />
<span className="text-purple font-bold">
{intl.formatMessage({ id: "campaign.cta.sub.short" })}
</span>
</div>
<LanguageSwitch className="w-full object-cover" />
</div>
</div>
)
}
export default Header
|
angelamsj/cruise-control | mathgl-2.4.3/include/mgl2/canvas.h | /***************************************************************************
* canvas.h is part of Math Graphic Library
* Copyright (C) 2007-2016 <NAME> <<EMAIL>> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 3 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#ifndef MGL_CANVAS_H
#define MGL_CANVAS_H
#include "mgl2/base.h"
//-----------------------------------------------------------------------------
struct GifFileType;
//-----------------------------------------------------------------------------
/// Structure for drawing axis and ticks
struct MGL_EXPORT mglAxis
{
mglAxis() : dv(0),ds(0),d(0),ns(0), v0(0),v1(0),v2(0),o(NAN), f(0), ch(0), pos('t'),sh(0),inv(false),angl(NAN) {}
mglAxis(const mglAxis &aa) : dv(aa.dv),ds(aa.ds),d(aa.d),ns(aa.ns), t(aa.t),fact(aa.fact),stl(aa.stl), dir(aa.dir),a(aa.a),b(aa.b),org(aa.org), v0(aa.v0),v1(aa.v1),v2(aa.v2),o(aa.o), f(aa.f),txt(aa.txt), ch(aa.ch), pos(aa.pos),sh(aa.sh),inv(aa.inv),angl(aa.angl) {}
#if MGL_HAVE_RVAL
mglAxis(mglAxis &&aa) : dv(aa.dv),ds(aa.ds),d(aa.d),ns(aa.ns), t(aa.t),fact(aa.fact),stl(aa.stl), dir(aa.dir),a(aa.a),b(aa.b),org(aa.org), v0(aa.v0),v1(aa.v1),v2(aa.v2),o(aa.o), f(aa.f),txt(aa.txt), ch(aa.ch), pos(aa.pos),sh(aa.sh),inv(aa.inv),angl(aa.angl) {}
#endif
const mglAxis &operator=(const mglAxis &aa)
{ dv=aa.dv; ds=aa.ds; d=aa.d; ns=aa.ns; t=aa.t; fact=aa.fact; stl=aa.stl;
dir=aa.dir; a=aa.a; b=aa.b; org=aa.org; v0=aa.v0; v1=aa.v1; v2=aa.v2; o=aa.o;
f=aa.f; txt=aa.txt; ch=aa.ch; pos=aa.pos; sh=aa.sh; inv=aa.inv; return aa; }
inline void AddLabel(const std::wstring &lbl, mreal v)
{ if(mgl_isfin(v)) txt.push_back(mglText(L' '+lbl+L' ',v)); }
inline void Clear()
{ dv=ds=d=v0=v1=v2=sh=0; o=NAN; ns=f=0; pos = 't'; inv=false;
fact.clear(); stl.clear(); t.clear(); txt.clear(); }
mreal dv,ds; ///< Actual step for ticks and subticks.
mreal d; ///< Step for axis ticks (if positive) or its number (if negative).
int ns; ///< Number of axis subticks.
std::wstring t; ///< Tick template (set "" to use default one ("%.2g" in simplest case))
std::wstring fact; ///< Factor which should be placed after number (like L"\pi")
std::string stl; ///< Tick styles (default is ""=>"3m")
mglPoint dir; ///< Axis direction
mglPoint a,b; ///< Directions of over axis
mglPoint org;
mreal v0; ///< Center of axis cross section
mreal v1; ///< Minimal axis range.
mreal v2; ///< Maximal axis range.
mreal o; ///< Point of starting ticks numbering (if NAN then Org is used).
int f; ///< Flag 0x1 - time, 0x2 - manual, 0x4 - fixed dv
std::vector<mglText> txt; ///< Axis labels
char ch; ///< Character of axis (like 'x','y','z','c')
char pos; ///< Text position ('t' by default, or 'T' for opposite)
mreal sh; ///< Extra shift of ticks and axis labels
bool inv; ///< Inverse automatic origin position
mreal angl; ///< Manual for ticks rotation (if not NAN)
};
//-----------------------------------------------------------------------------
class mglCanvas;
/// Structure for drawing region
struct MGL_EXPORT mglDrawReg
{
mglDrawReg() { memset(this,0,sizeof(mglDrawReg)); }
mglDrawReg(const mglDrawReg &aa) : PDef(aa.PDef),angle(aa.angle),ObjId(aa.ObjId),PenWidth(aa.PenWidth),pPos(aa.pPos) ,x1(aa.x1),x2(aa.x2),y1(aa.y1),y2(aa.y2) {}
#if MGL_HAVE_RVAL
mglDrawReg(mglDrawReg &&aa) : PDef(aa.PDef),angle(aa.angle),ObjId(aa.ObjId),PenWidth(aa.PenWidth),pPos(aa.pPos) ,x1(aa.x1),x2(aa.x2),y1(aa.y1),y2(aa.y2) {}
#endif
inline void copy(const mglPrim &p)
{ PDef = p.n3; pPos = p.s; ObjId = p.id; PenWidth=p.w; angle = p.angl;
if(p.type==2 || p.type==3) PDef = p.m; }
inline const mglDrawReg &operator=(const mglDrawReg &aa)
{ PDef=aa.PDef; angle=aa.angle; ObjId=aa.ObjId; PenWidth=aa.PenWidth; pPos=aa.pPos; x1=aa.x1; x2=aa.x2; y1=aa.y1; y2=aa.y2; return aa; }
union
{
uint64_t PDef;
unsigned char m[8];
};
int angle; ///< mask rotation values in degrees
int ObjId;
mreal PenWidth, pPos;
int x1,x2,y1,y2;
void set(mglCanvas *gr, int nx, int ny, int m);
};
//-----------------------------------------------------------------------------
/// Structure contains everything for drawing
struct MGL_EXPORT mglDrawDat
{
mglDrawDat() {}
mglDrawDat(const mglDrawDat &aa) : Pnt(aa.Pnt),Prm(aa.Prm),Sub(aa.Sub),Ptx(aa.Ptx),Glf(aa.Glf),Txt(aa.Txt) {}
#if MGL_HAVE_RVAL
mglDrawDat(mglDrawDat &&aa) : Pnt(aa.Pnt),Prm(aa.Prm),Sub(aa.Sub),Ptx(aa.Ptx),Glf(aa.Glf),Txt(aa.Txt) {}
#endif
inline const mglDrawDat&operator=(const mglDrawDat &aa)
{ Pnt=aa.Pnt; Prm=aa.Prm; Ptx=aa.Ptx; Glf=aa.Glf; Txt=aa.Txt; Sub=aa.Sub; return aa; }
mglStack<mglPnt> Pnt; ///< Internal points
mglStack<mglPrim> Prm; ///< Primitives (lines, triangles and so on) -- need for export
std::vector<mglBlock> Sub; ///< InPlot regions
std::vector<mglText> Ptx; ///< Text labels for mglPrim
std::vector<mglGlyph> Glf; ///< Glyphs data
std::vector<mglTexture> Txt; ///< Pointer to textures
};
#if defined(_MSC_VER)
MGL_EXTERN template class MGL_EXPORT std::vector<mglDrawDat>;
#endif
//-----------------------------------------------------------------------------
union mglRGBA { uint32_t c; unsigned char r[4]; };
//-----------------------------------------------------------------------------
/// Class contains all functionality for creating different mathematical plots
class MGL_EXPORT mglCanvas : public mglBase
{
friend struct mglPrim;
friend struct mglDrawReg;
public:
using mglBase::Light;
mglCanvas(int w=800, int h=600);
virtual ~mglCanvas();
/// Set default parameter for plotting
void DefaultPlotParam();
/// Set angle of view indepently from mglCanvas::Rotate()
virtual void View(mreal tetx,mreal tetz,mreal tety=0);
/// Zoom in or zoom out (if Zoom(0, 0, 1, 1)) a part of picture
virtual void Zoom(mreal x1, mreal y1, mreal x2, mreal y2);
/// Restore image after View() and Zoom()
inline void Restore() { Zoom(0,0,1,1); }
/// Clear transformation matrix.
inline void Identity(bool rel=false) { InPlot(0,1,0,1,rel); }
inline void Identity(mglMatrix &M, bool rel=false) { InPlot(M,0,1,0,1,rel); }
/// Push transformation matrix into stack
void Push();
/// Set PlotFactor
inline void SetPlotFactor(mreal val)
{ if(val<=0) {B.pf=1.55; set(MGL_AUTO_FACTOR);} else {B.pf=val; clr(MGL_AUTO_FACTOR);} }
/// Get PlotFactor
inline mreal GetPlotFactor() { return B.pf; }
/// Pop transformation matrix from stack
void Pop();
/// Clear up the frame
virtual void Clf(mglColor back=NC);
virtual void Clf(const char *col);
/// Put further plotting in cell of stick rotated on angles tet, phi
void StickPlot(int num, int i, mreal tet, mreal phi);
/// Put further plotting in cell of stick sheared on sx, sy
void ShearPlot(int num, int i, mreal sx, mreal sy, mreal xd, mreal yd);
/// Put further plotting in some region of whole frame surface.
inline void InPlot(mreal x1,mreal x2,mreal y1,mreal y2,bool rel=true)
{ InPlot(B,x1,x2,y1,y2,rel); }
void InPlot(mreal x1,mreal x2,mreal y1,mreal y2, const char *style);
void InPlot(mglMatrix &M,mreal x1,mreal x2,mreal y1,mreal y2,bool rel=true);
/// Add title for current subplot/inplot
void Title(const char *title,const char *stl="#",mreal size=-2);
void Title(const wchar_t *title,const char *stl="#",mreal size=-2);
/// Set aspect ratio for further plotting.
void Aspect(mreal Ax,mreal Ay,mreal Az);
/// Shear a further plotting.
void Shear(mreal Sx,mreal Sy);
/// Rotate a further plotting.
void Rotate(mreal TetX,mreal TetZ,mreal TetY=0);
/// Rotate a further plotting around vector {x,y,z}.
void RotateN(mreal Tet,mreal x,mreal y,mreal z);
/// Set perspective (in range [0,1)) for plot. Set to zero for switching off. Return the current perspective.
void Perspective(mreal a, bool req=true)
{ if(req) persp = Bp.pf = a; else Bp.pf = persp?persp:fabs(a); }
/// Save parameters of current inplot
inline void SaveInPlot()
{ sB=B; sW=inW, sH=inH, sZ=ZMin, sX=inX, sY=inY, sFF=font_factor; }
/// Use saved parameters as current inplot
inline void LoadInPlot()
{ B=sB; inW=sW, inH=sH, ZMin=sZ, inX=sX, inY=sY, font_factor=sFF; }
/// Set size of frame in pixels. Normally this function is called internaly.
virtual void SetSize(int w,int h,bool clf=true);
/// Get ratio (mreal width)/(mreal height).
mreal GetRatio() const MGL_FUNC_PURE;
/// Get bitmap data prepared for saving to file
virtual unsigned char **GetRGBLines(long &w, long &h, unsigned char *&f, bool alpha=false);
/// Get RGB bitmap of current state image.
virtual const unsigned char *GetBits();
/// Get RGBA bitmap of background image.
const unsigned char *GetBackground() { return GB; };
/// Get RGBA bitmap of current state image.
const unsigned char *GetRGBA() { Finish(); return G4; }
/// Get width of the image
int GetWidth() const { return Width; }
/// Get height of the image
int GetHeight() const { return Height; }
/// Combine plots from 2 canvases. Result will be saved into this.
void Combine(const mglCanvas *gr);
/// Set boundary box for export graphics into 2D file formats
void SetBBox(int x1=0, int y1=0, int x2=-1, int y2=-1)
{ BBoxX1=x1; BBoxY1=y1; BBoxX2=x2; BBoxY2=y2; }
/// Rasterize current plot and set it as background image
void Rasterize();
/// Load image for background from file
void LoadBackground(const char *fname, double alpha=1);
/// Fill background image by specified color
void FillBackground(const mglColor &cc);
inline mreal GetDelay() const { return Delay; }
inline void SetDelay(mreal d) { Delay=d; }
/// Calculate 3D coordinate {x,y,z} for screen point {xs,ys}
mglPoint CalcXYZ(int xs, int ys, bool real=false) const MGL_FUNC_PURE;
/// Calculate screen point {xs,ys} for 3D coordinate {x,y,z}
void CalcScr(mglPoint p, int *xs, int *ys) const;
mglPoint CalcScr(mglPoint p) const;
/// Set object/subplot id
inline void SetObjId(long id) { ObjId = id; }
/// Get object id
inline int GetObjId(long xs,long ys) const
{ long i=xs+Width*ys; return (i>=0 && i<Width*Height)?OI[i]:-1; }
/// Get subplot id
int GetSplId(long xs,long ys) const MGL_FUNC_PURE;
/// Check if there is active point or primitive (n=-1)
int IsActive(int xs, int ys,int &n);
/// Create new frame.
virtual int NewFrame();
/// Finish frame drawing
virtual void EndFrame();
/// Get the number of created frames
inline int GetNumFrame() const { return CurFrameId; }
/// Reset frames counter (start it from zero)
virtual void ResetFrames();
/// Delete primitives for i-th frame
virtual void DelFrame(long i);
/// Get drawing data for i-th frame.
void GetFrame(long i);
/// Set drawing data for i-th frame. This work as EndFrame() but don't add frame to GIF image.
virtual void SetFrame(long i);
/// Add drawing data from i-th frame to the current drawing
void ShowFrame(long i);
/// Clear list of primitives for current drawing
void ClearFrame();
/// Start write frames to cinema using GIF format
void StartGIF(const char *fname, int ms=100);
/// Stop writing cinema using GIF format
void CloseGIF();
/// Finish plotting. Normally this function is called internaly.
virtual void Finish();
/// Export points and primitives in file using MGLD format
bool ExportMGLD(const char *fname, const char *descr=0);
/// Import points and primitives from file using MGLD format
bool ImportMGLD(const char *fname, bool add=false);
/// Export in JSON format suitable for later drawing by JavaScript
bool WriteJSON(const char *fname, bool force_zlib=false);
std::string GetJSON();
/// Set the transparency type
inline void SetTranspType(int val)
{ Flag=(Flag&(~3)) + (val&3); SetAxisStl(val==2?"w-":"k-"); }
/// Set the fog distance or switch it off (if d=0).
virtual void Fog(mreal d, mreal dz=0.25);
/// Switch on/off the specified light source.
virtual void Light(int n, bool enable);
/// Add a light source.
virtual void AddLight(int n,mglPoint r, mglPoint d, char c='w', mreal bright=0.5, mreal ap=0);
inline void AddLight(int n,mglPoint d, char c='w', mreal bright=0.5, mreal ap=0)
{ AddLight(n,mglPoint(NAN),d,c,bright,ap); }
/// Set ticks position and text (\n separated). Use n=0 to disable this feature.
void SetTicksVal(char dir, const char *lbl, bool add=false);
void SetTicksVal(char dir, HCDT v, const char *lbl, bool add=false);
void SetTicksVal(char dir, HCDT v, const char **lbl, bool add=false);
void SetTicksVal(char dir, const wchar_t *lbl, bool add=false);
void SetTicksVal(char dir, HCDT v, const wchar_t *lbl, bool add=false);
void SetTicksVal(char dir, HCDT v, const wchar_t **lbl, bool add=false);
/// Add manual tick at given position. Use "" to disable this feature.
void AddTick(char dir, double val, const char *lbl);
void AddTick(char dir, double val, const wchar_t *lbl);
/// Set templates for ticks
void SetTickTempl(char dir, const wchar_t *t);
void SetTickTempl(char dir, const char *t);
/// Set time templates for ticks
void SetTickTime(char dir, mreal d=0, const char *t="");
/// Set the ticks parameters
void SetTicks(char dir, mreal d=0, int ns=0, mreal org=NAN, const wchar_t *lbl=0);
/// Auto adjust ticks
void AdjustTicks(const char *dir="xyzc", bool force=false, std::string stl="");
/// Tune ticks
inline void SetTuneTicks(int tune, mreal pos=1.15)
{ TuneTicks = tune; FactorPos = pos; }
/// Set ticks styles
void SetAxisStl(const char *stl="k", const char *tck=0, const char *sub=0);
/// Set ticks length
void SetTickLen(mreal tlen, mreal stt=1.);
/// Draws bounding box outside the plotting volume with color c.
void Box(const char *col=0, bool ticks=true);
/// Draw axises with ticks in directions determined by string parameter dir.
void Axis(const char *dir="xyzt", const char *stl="", const char *opt="");
/// Draw grid lines perpendicular to direction determined by string parameter dir.
void Grid(const char *dir="xyzt",const char *pen="B-", const char *opt="");
/// Print the label text for axis dir.
void Label(char dir, const char *text, mreal pos=0, const char *opt="");
void Labelw(char dir, const wchar_t *text, mreal pos=0, const char *opt="");
/// Draw colorbar at edge of axis
void Colorbar(const char *sch=0);
void Colorbar(const char *sch, mreal x, mreal y, mreal w, mreal h);
/// Draw colorbar at edge of axis for manual colors
void Colorbar(HCDT v, const char *sch=0);
void Colorbar(HCDT v, const char *sch, mreal x, mreal y, mreal w, mreal h);
/// Draw legend of accumulated strings at position (x, y) by font with size
inline void Legend(mreal x, mreal y, const char *font="#", const char *opt="")
{ Legend(Leg,x,y,font,opt); }
/// Draw legend of accumulated strings by font with size
inline void Legend(int where=0x3, const char *font="#", const char *opt="")
{ Legend(Leg,(where&1)?1:0,(where&2)?1:0,font,opt); }
/// Draw legend of accumulated strings by font with size
inline void Legend(const std::vector<mglText> &leg, int where=3, const char *font="#", const char *opt="")
{ Legend(leg,(where&1)?1:0,(where&2)?1:0,font,opt); }
/// Draw legend strings text at position (x, y) by font with size
void Legend(const std::vector<mglText> &leg, mreal x, mreal y, const char *font="#", const char *opt="");
/// Number of marks in legend sample
inline void SetLegendMarks(int num=1) { LegendMarks = num>0?num:1; }
/// Draw table for values val along given direction with row labels text at given position
void Table(mreal x, mreal y, HCDT val, const wchar_t *text, const char *fnt, const char *opt);
void StartAutoGroup (const char *);
void EndGroup();
/// Set extra shift for tick and axis labels
inline void SetTickShift(mglPoint p)
{ ax.sh = p.x; ay.sh = p.y; az.sh = p.z; ac.sh = p.c; }
/// Get rotation angle for glyph
float GetGlyphPhi(const mglPnt &q, float phi);
// Following arrays are open for advanced users only. It is not recommended to change them directly
float *Z; ///< Height for given level in Z-direction (size 3*width*height)
unsigned char *C; ///< Picture for given level in Z-direction (size 3*4*width*height)
int *OI; ///< ObjId arrays (size width*height)
/// Plot point p with color c
void pnt_plot(long x,long y,mreal z,const unsigned char c[4], int obj_id);
void pnt_fast(long x,long y,mreal z,const unsigned char c[4], int obj_id);
/// preparing primitives for 2d export or bitmap drawing (0 default, 1 for 2d vector, 2 for 3d vector)
void PreparePrim(int fast);
inline uint32_t GetPntCol(long i) const { return pnt_col[i]; }
inline uint32_t GetPrmCol(long i, bool sort=true) const { return GetColor(GetPrm(i, sort)); }
/// Set the size of semi-transparent area around lines, marks, ...
inline void SetPenDelta(float d) { pen_delta = 1.5*fabs(d); }
protected:
mreal Delay; ///< Delay for animation in seconds
// NOTE: Z should be float for reducing space and for compatibility reasons
unsigned char *G4; ///< Final picture in RGBA format. Prepared in Finish().
unsigned char *G; ///< Final picture in RGB format. Prepared in Finish().
unsigned char *GB; ///< Background picture in RGBA format.
std::vector<mglDrawDat> DrwDat; ///< Set of ALL drawing data for each frames
int LegendMarks; ///< Number of marks in the Legend
unsigned char BDef[4]; ///< Background color
mglAxis ax,ay,az,ac;///< Axis parameters
int TuneTicks; ///< Draw tuned ticks with extracted common component
mreal FactorPos; ///< Position of axis ticks factor (0 at Min, 1 at Max, 1.1 is default)
mreal TickLen; ///< Length of tiks (subticks length is sqrt(1+st_t)=1.41... times smaller)
char AxisStl[32]; ///< Axis line style. Default is "k"
char TickStl[32]; ///< Tick line style. Default is "k"
char SubTStl[32]; ///< Subtick line style. Default is "k"
mreal st_t; ///< Subtick-to-tick ratio (ls=lt/sqrt(1+st_t)). Default is 1.
int CurFrameId; ///< Number of automaticle created frames
int Width; ///< Width of the image
int Height; ///< Height of the image
int Depth; ///< Depth of the image
mreal inW, inH; ///< Width and height of last InPlot
mreal inX, inY; ///< Coordinates of last InPlot
mglLight light[10]; ///< Light sources
mreal FogDist; ///< Inverse fog distance (fog ~ exp(-FogDist*Z))
mreal FogDz; ///< Relative shift of fog
inline mglAxis &GetAxis(unsigned ch)
{ mglAxis *aa[3]={&ax,&ay,&az}; ch-='x'; return ch<3?*(aa[ch]):ac; }
inline HMEX GetFormula(unsigned ch)
{ HMEX aa[3]={fx,fy,fz}; ch-='x'; return ch<3?aa[ch]:fa; }
/// Auto adjust ticks
void AdjustTicks(mglAxis &aa, bool ff);
/// Prepare labels for ticks
void LabelTicks(mglAxis &aa);
/// Draw axis
void DrawAxis(mglAxis &aa, int text=1, char arr=0,const char *stl="",mreal angl=NAN);
/// Draw axis grid lines
void DrawGrid(mglAxis &aa, bool at_tick=false);
/// Update axis ranges
inline void UpdateAxis()
{ ax.v0=Org.x; ay.v0=Org.y; az.v0=Org.z; ac.v0=Org.c;
ax.v1=Min.x; ay.v1=Min.y; az.v1=Min.z; ac.v1=Min.c;
ax.v2=Max.x; ay.v2=Max.y; az.v2=Max.z; ac.v2=Max.c; }
/// Clear ZBuffer only
void ClfZB(bool force=false);
/// Scale coordinates and cut off some points
bool ScalePoint(const mglMatrix *M, mglPoint &p, mglPoint &n, bool use_nan=true) const;
void LightScale(const mglMatrix *M); ///< Additionally scale positions of light sources
void LightScale(const mglMatrix *M, mglLight &l); ///< Additionally scale positions of light
/// Push drawing data (for frames only). NOTE: can be VERY large
long PushDrwDat();
/// Retur color for primitive depending lighting
uint32_t GetColor(const mglPrim &p) const MGL_FUNC_PURE;
mreal GetOrgX(char dir, bool inv=false) const MGL_FUNC_PURE; ///< Get Org.x (parse NAN value)
mreal GetOrgY(char dir, bool inv=false) const MGL_FUNC_PURE; ///< Get Org.y (parse NAN value)
mreal GetOrgZ(char dir, bool inv=false) const MGL_FUNC_PURE; ///< Get Org.z (parse NAN value)
void mark_plot(long p, char type, mreal size=1);
void arrow_plot(long p1, long p2, char st);
void line_plot(long p1, long p2);
void trig_plot(long p1, long p2, long p3);
void quad_plot(long p1, long p2, long p3, long p4);
void Glyph(mreal x, mreal y, mreal f, int style, long icode, mreal col);
void smbl_plot(long p1, char id, double size);
mreal text_plot(long p,const wchar_t *text,const char *fnt,mreal size=-1,mreal sh=0,mreal col=-('k'), bool rot=true);
void add_prim(mglPrim &a); ///< add primitive to list
void arrow_draw(const mglPnt &p1, const mglPnt &p2, char st, mreal size, const mglDrawReg *d);
virtual void mark_draw(const mglPnt &p, char type, mreal size, mglDrawReg *d);
virtual void line_draw(const mglPnt &p1, const mglPnt &p2, const mglDrawReg *d);
virtual void trig_draw(const mglPnt &p1, const mglPnt &p2, const mglPnt &p3, bool anorm, const mglDrawReg *d);
virtual void quad_draw(const mglPnt &p1, const mglPnt &p2, const mglPnt &p3, const mglPnt &p4, const mglDrawReg *d);
virtual void pnt_draw(const mglPnt &p, const mglDrawReg *d);
void arrow_draw(long n1, long n2, char st, float ll);
void arrow_plot_3d(long n1, long n2, char st, float ll);
void glyph_draw(const mglPrim &P, mglDrawReg *d);
void glyph_draw_new(const mglPrim &P, mglDrawReg *d);
bool IsSame(const mglPrim &pr,mreal wp,mglColor cp,int st);
// check if visible
bool trig_vis(const mglPnt &p1, const mglPnt &p2, const mglPnt &p3) const;
bool quad_vis(const mglPnt &p1, const mglPnt &p2, const mglPnt &p3, const mglPnt &p4) const;
// functions for glyph drawing
virtual void glyph_fill(mreal phi, const mglPnt &p, mreal f, const mglGlyph &g, const mglDrawReg *d);
void glyph_wire(mreal phi, const mglPnt &p, mreal f, const mglGlyph &g, const mglDrawReg *d);
void glyph_line(mreal phi, const mglPnt &p, mreal f, bool solid, const mglDrawReg *d);
// restore normalized coordinates from screen ones
mglPoint RestorePnt(mglPoint ps, bool norm=false) const MGL_FUNC_PURE;
// functions for multi-threading
void pxl_pntcol(long id, long n, const void *);
void pxl_combine(long id, long n, const void *);
void pxl_memcpy(long id, long n, const void *);
void pxl_backgr(long id, long n, const void *);
void pxl_primdr(long id, long n, const void *);
void pxl_dotsdr(long id, long n, const void *);
void pxl_primpx(long id, long n, const void *);
void pxl_transform(long id, long n, const void *);
void pxl_setz(long id, long n, const void *);
void pxl_setz_adv(long id, long n, const void *);
void pxl_other(long id, long n, const void *p);
/// Put drawing from other mglCanvas (for multithreading, like subplots)
void PutDrawReg(mglDrawReg *d, const mglCanvas *gr);
private:
mglCanvas(const mglCanvas &){} // copying is not allowed
const mglCanvas &operator=(const mglCanvas &t){return t;} // copying is not allowed
mglMatrix sB; // parameters of saved inplot
mreal sW, sH, sZ, sX, sY, sFF;
uint32_t *pnt_col;
// mreal _tetx,_tety,_tetz; // extra angles
std::vector<mglMatrix> stack; ///< stack for transformation matrices
GifFileType *gif;
mreal fscl,ftet; ///< last scale and rotation for glyphs
long forg; ///< original point (for directions)
size_t grp_counter; ///< Counter for StartGroup(); EndGroup();
mglMatrix Bt; ///< temporary matrix for text
float pen_delta; ///< delta pen width (dpw) -- the size of semi-transparent region for lines, marks, ...
/// Draw generic colorbar
void colorbar(HCDT v, const mreal *s, int where, mreal x, mreal y, mreal w, mreal h, bool text);
/// Draw labels for ticks
void DrawLabels(mglAxis &aa, bool inv=false, const mglMatrix *M=0);
/// Get label style
char GetLabelPos(mreal c, long kk, mglAxis &aa);
/// Draw tick
void tick_draw(mglPoint o, mglPoint d1, mglPoint d2, int f);
mreal FindOptOrg(char dir, int ind) const MGL_FUNC_PURE;
/// Transform mreal color and alpha to bits format
void col2int(const mglPnt &p, unsigned char *r, int obj_id) const;
/// Combine colors in 2 plane.
void combine(unsigned char *c1, const unsigned char *c2) const;
/// Fast drawing of line between 2 points
void fast_draw(const mglPnt &p1, const mglPnt &p2, const mglDrawReg *d);
/// Additionally scale points p for positioning in image
void PostScale(const mglMatrix *M, mglPoint &p) const;
/// Scale points p for projection to the face number nface in image
long ProjScale(int nface, long p, bool text=false);
/// Set coordinate and add the point, return its id
long setPp(mglPnt &q, const mglPoint &p);
// fill pixel for given primitive
void mark_pix(long i,long j,const mglPnt &p, char type, mreal size, mglDrawReg *d);
void arrow_pix(long i,long j,const mglPnt &p1, const mglPnt &p2, char st, mreal size, const mglDrawReg *d);
void line_pix(long i,long j,const mglPnt &p1, const mglPnt &p2, const mglDrawReg *d);
void trig_pix(long i,long j,const mglPnt &p1, const mglPnt &p2, const mglPnt &p3, bool anorm, const mglDrawReg *d);
void quad_pix(long i,long j,const mglPnt &p1, const mglPnt &p2, const mglPnt &p3, const mglPnt &p4, const mglDrawReg *d);
void glyph_pix(long i,long j,const mglPrim &P, mglDrawReg *d);
void pnt_pix(long i,long j,const mglPnt &p, const mglDrawReg *d);
void glyph_fpix(long i,long j,const mglMatrix *M, const mglPnt &p, mreal f, const mglGlyph &g, const mglDrawReg *d);
void glyph_wpix(long i,long j,const mglMatrix *M, const mglPnt &p, mreal f, const mglGlyph &g, const mglDrawReg *d);
void glyph_lpix(long i,long j,const mglMatrix *M, const mglPnt &p, mreal f, bool solid, const mglDrawReg *d);
};
//-----------------------------------------------------------------------------
struct mglThreadG
{
mglCanvas *gr; // grapher
void (mglCanvas::*f)(long i, long n, const void *);
unsigned id; // thread id
long n; // total number of iteration
const void *p; // external parameter
};
/// Start several thread for the task
void mglStartThread(void (mglCanvas::*func)(long i, long n), mglCanvas *gr, long n);
//-----------------------------------------------------------------------------
inline mreal get_persp(float pf, float z, float Depth)
//{ return (1-pf)/(1-pf*z/Depth); }
{ return (1-pf/1.37)/(1-pf*z/Depth); }
inline mreal get_pfact(float pf, float Depth)
//{ return pf/(1-pf)/Depth; }
{ return pf/(1-pf/1.37)/Depth; }
//-----------------------------------------------------------------------------
#endif
|
aposin/gem | bundles/org.aposin.gem.ui/src/org/aposin/gem/ui/view/labelprovider/TypedColumnLabelProvider.java | <reponame>aposin/gem
/**
* Copyright 2020 Association for the promotion of open-source insurance software and for the establishment of open interface standards in the insurance industry (Verein zur Foerderung quelloffener Versicherungssoftware und Etablierung offener Schnittstellenstandards in der Versicherungsbranche)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.aposin.gem.ui.view.labelprovider;
import java.util.function.Function;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.ViewerColumn;
import org.eclipse.swt.graphics.Image;
/**
* This implementation of {@link ColumnLabelProvider} provides typed methods for
* {@link #getText(Object)} and {@link #getImage(Object)}, so cast checks and
* casts are not necessary anymore on all implementations of
* {@link ColumnLabelProvider}. Implementors of this class should overwrite
* {@link #getTypedText(Object)} and {@link #getTypedImage(Object)} to define
* text and image definitions of viewer columns.
*
* @param <T> the type of element to deal with
*/
@SuppressWarnings("unchecked")
public class TypedColumnLabelProvider<T> extends ColumnLabelProvider {
private final boolean ignoreUntyped;
private final Class<T> type;
/**
* @param type the type of element to deal with
*/
public TypedColumnLabelProvider(Class<T> type) {
this(type, false);
}
public TypedColumnLabelProvider(Class<T> type, boolean ignoreUntyped) {
this.type = type;
this.ignoreUntyped = ignoreUntyped;
}
/**
* {@inheritDoc}
*/
@Override
public String getText(Object element) {
if (type.isInstance(element)) {
return getTypedText((T) element);
}
return ignoreUntyped ? null : super.getText(element);
}
/**
* {@inheritDoc}
*/
@Override
public Image getImage(Object element) {
if (type.isInstance(element)) {
return getTypedImage((T) element);
}
return ignoreUntyped ? null : super.getImage(element);
}
/**
* Hook method, which intended to be overwritten, providing the object with it's
* correct type.
*
* @param object the object
* @return the String to show
*/
protected String getTypedText(T object) {
return super.getText(object);
}
/**
* Hook method, which intended to be overwritten, providing the object with it's
* correct type.
*
* @param object the object
* @return the image to show
*/
protected Image getTypedImage(T object) {
return super.getImage(object);
}
/**
* This factory creates a {@link TypedColumnLabelProvider} and applies settings
* to the {@link ViewerColumn} by using {@link #set(ViewerColumn)}.
*
* @param <T> the type of element to deal with
*/
public static class TypedColumnLabelProviderFactory<T> {
private final Class<T> type;
private Function<T, String> text;
private Function<T, Image> image;
private boolean ignoreUntyped = false;
/**
* @param type the type of element to deal with
*/
private TypedColumnLabelProviderFactory(Class<T> type) {
this.type = type;
}
/**
* Creates a new instance of factory.
*
* @param <T> the type of element to deal with
* @param type the class of element to deal with
* @return
*/
public static <T> TypedColumnLabelProviderFactory<T> create(Class<T> type) {
return new TypedColumnLabelProviderFactory<>(type);
}
/**
* Ignores the untyped objects set on the column.
*
* @param ignoreUntyped {@code true} to ignore; {@code false} otherwise.
*
* @return the factory.
*/
public TypedColumnLabelProviderFactory<T> ignoreUntyped(final boolean ignoreUntyped) {
this.ignoreUntyped = ignoreUntyped;
return this;
}
/**
* Appends a text function which gets executed in
* {@link TypedColumnLabelProvider#getTypedText(Object)}.
*
* @param text the function for providing the text
* @return the factory
*/
public TypedColumnLabelProviderFactory<T> text(Function<T, String> text) {
this.text = text;
return this;
}
/**
* Appends an image function which gets executed in
* {@link TypedColumnLabelProvider#getTypedImage(Object)}.
*
* @param text the function for providing the image
* @return the factory
*/
public TypedColumnLabelProviderFactory<T> image(Function<T, Image> image) {
this.image = image;
return this;
}
/**
* Creates and sets a new instance of {@link TypedColumnLabelProvider} into the
* given {@link ViewerColumn} as label provider.
*
* @param column the column where to set the label provider
*/
public void set(ViewerColumn column) {
column.setLabelProvider(new TypedColumnLabelProvider<>(type, ignoreUntyped) {
@Override
protected String getTypedText(T object) {
if (text != null) {
return text.apply(object);
} else {
return super.getTypedText(object);
}
}
@Override
protected Image getTypedImage(T object) {
if (image != null) {
return image.apply(object);
} else {
return super.getTypedImage(object);
}
}
});
}
}
}
|
sh-web/compatibility-detector | src/detectors/flash_percentloaded.js | <gh_stars>1-10
/**
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
addScriptToInject(function() {
chrome_comp.CompDetect.declareDetector(
'flash_percentloaded',
chrome_comp.CompDetect.NonScanDomBaseDetector,
function constructor(rootNode) {
var This = this;
this.PercentLoaded_ = function(result, originalArguments, callStack) {
This.addProblem('BT9037', { nodes: [this], needsStack: true });
};
},
function setUp() {
chrome_comp.CompDetect.registerSimplePropertyHook(
HTMLObjectElement.prototype, 'PercentLoaded', this.PercentLoaded_);
},
function cleanUp() {
chrome_comp.CompDetect.unregisterSimplePropertyHook(
HTMLObjectElement.prototype, 'PercentLoaded', this.PercentLoaded_);
}
); // declareDetector
});
|
wcnnkh/scw-app | scw-app-core/src/main/java/scw/app/user/enums/UnionIdType.java | <filename>scw-app-core/src/main/java/scw/app/user/enums/UnionIdType.java<gh_stars>0
package scw.app.user.enums;
/**
* 常见的类型
* @author shuchaowen
*
*/
public enum UnionIdType {
QQ_OPENID(1000),
WX_OPENID(2000),
WX_XCX_OPENID(3000),
WX_UNIONID(4000),
;
private final int value;
UnionIdType(int value){
this.value = value;
}
public int getValue() {
return value;
}
public static UnionIdType forValue(int value){
for(UnionIdType type : values()){
if(type.value == value){
return type;
}
}
return null;
}
}
|
ameyjadiye/commons-graph | src/main/java/org/apache/commons/graph/coloring/ColoredVertices.java | package org.apache.commons.graph.coloring;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import static org.apache.commons.graph.utils.Assertions.checkNotNull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Maintains the color for each vertex and the required number of colors for {@link org.apache.commons.graph.Graph} coloring.
*
* @param <V> the Graph vertices type.
* @param <C> the Color type.
*/
public final class ColoredVertices<V, C>
{
private final Map<V, C> coloredVertices = new HashMap<V, C>();
private final List<C> usedColor = new ArrayList<C>();
/**
* This class can be instantiated only inside the package
*/
ColoredVertices()
{
// do nothing
}
/**
* Store the input vertex color.
*
* @param v the vertex for which storing the color.
* @param color the input vertex color.
*/
void addColor( V v, C color )
{
coloredVertices.put( v, color );
int idx = usedColor.indexOf( color );
if ( idx == -1 )
{
usedColor.add( color );
}
else
{
usedColor.set( idx, color );
}
}
/**
* Remove the input vertex color.
*
* @param v the vertex for which storing the color.
*/
void removeColor( V v )
{
C color = coloredVertices.remove( v );
usedColor.remove( color );
}
/**
* Returns the color associated to the input vertex.
*
* @param v the vertex for which getting the color.
* @return the color associated to the input vertex.
*/
public C getColor( V v )
{
v = checkNotNull( v, "Impossible to get the color for a null Vertex" );
return coloredVertices.get( v );
}
/**
* Returns the number of required colors for coloring the Graph.
*
* @return the number of required colors for coloring the Graph.
*/
public int getRequiredColors()
{
return usedColor.size();
}
/**
* Tests if the 'vertex' is colored.
*
* @param vertex the vertex
* @return true if the colored vertex is contained into the map, false otherwise
*/
public boolean containsColoredVertex( V vertex )
{
return coloredVertices.containsKey( vertex );
}
}
|
hervewenjie/mysql | storage/ndb/clusterj/clusterj-bindings/src/main/java/com/mysql/clusterj/bindings/IndexImpl.java | /*
* Copyright 2010 Sun Microsystems, Inc.
* All rights reserved. Use is subject to license terms.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.mysql.clusterj.bindings;
import com.mysql.cluster.ndbj.NdbIndex;
import com.mysql.clusterj.core.store.Index;
import com.mysql.clusterj.core.util.I18NHelper;
import com.mysql.clusterj.core.util.Logger;
import com.mysql.clusterj.core.util.LoggerFactoryService;
/**
*
*/
class IndexImpl implements Index {
/** My message translator */
static final I18NHelper local = I18NHelper
.getInstance(ClusterTransactionImpl.class);
/** My logger */
static final Logger logger = LoggerFactoryService.getFactory()
.getInstance(ClusterTransactionImpl.class);
private NdbIndex ndbIndex;
private String name;
public IndexImpl(NdbIndex index, String name) {
this.ndbIndex = index;
this.name = name;
}
public boolean isHash() {
return NdbIndex.Type.UniqueHashIndex == ndbIndex.getType();
}
public boolean isUnique() {
return NdbIndex.Type.UniqueHashIndex == ndbIndex.getType();
}
public String getName() {
return name;
}
}
|
stungkit/pytorch | aten/src/ATen/cuda/llvm_jit_strings.h | #pragma once
#include <string>
#include <c10/macros/Export.h>
namespace at {
namespace cuda {
TORCH_CUDA_CPP_API const std::string &get_traits_string();
TORCH_CUDA_CPP_API const std::string &get_cmath_string();
TORCH_CUDA_CPP_API const std::string &get_complex_body_string();
TORCH_CUDA_CPP_API const std::string &get_complex_half_body_string();
TORCH_CUDA_CPP_API const std::string &get_complex_math_string();
}} // namespace at
|
Maastro-CDS-Imaging-Group/SQLite4Radiomics | radiomicsfeatureextractionpipeline/backend/src/dal/database_connector.py | """
This module is used as a template for all database connectors.
All database connectors should inherit from this base class.
"""
import os
from abc import ABC, abstractmethod
from typing import Any, Optional
import pandas as pd
class DatabaseConnector(ABC):
"""
This **Abstract Base Class** is used for:
- Establishing a connection with the database.
- Querying the data of the database.
- Insert, update, delete data of the database.
"""
def __init__(self, connection_string: str) -> None:
"""
Constructor for DatabaseConnector class
:param connection_string: contains the connection string that is used for connecting with the database
"""
self.connection_string: Optional[str] = None
self.set_connection_string(connection_string)
self.conn: Optional[DatabaseConnector] = None
def __enter__(self) -> 'DatabaseConnector':
"""
Opens connection with database when called by context manager
:return: returns database connector object to connect with the Database.
"""
self.open_connection()
return self
def __exit__(self, exception_type: Any, exception_value: Any, traceback: Any) -> None:
"""
Closes the connection with the database. Automatically called at the end of context manager
:param exception_type: The type of exception that occurred while connection was open.
:param exception_value: The value of the exception that occurred while connection was open.
:param traceback: The traceback of the exception that occurred while connection was open.
"""
self.close_connection()
def set_connection_string(self, connection_string: str) -> None:
"""
Changes the connection string so it will connect to a different database
:param connection_string: The new connection string that will override the existing one.
"""
self.connection_string: str = connection_string
@abstractmethod
def open_connection(self) -> None:
"""
Opens the connection with the database
"""
pass
@abstractmethod
def execute_non_query(self, sql_query: str, arg: Optional[Any]) -> None:
"""
Executes all queries that don't return values:
- CREATE
- DROP
- INSERT
- UPDATE
- DELETE
:param sql_query: The query to be executed.
:param arg: The arguments to pass into the query.
"""
pass
@abstractmethod
def execute_query(self, sql_query: str, arg: Optional[Any]) -> pd.DataFrame:
"""
Executes SELECT statements and returns result in a pandas.DataFrame.
:param sql_query: The query to be executed.
:param arg: The arguments to pass into the query
:return: pandas.DataFrame with query result
"""
pass
@abstractmethod
def close_connection(self) -> None:
"""
Closes the connection with the database
"""
pass
|
lazlojd/modaDashboard | client/node_modules/@coreui/react/lib/Shared/toggle-classes.js | "use strict";
exports.__esModule = true;
exports.default = toggleClasses;
function toggleClasses(toggleClass, classList, force) {
var level = classList.indexOf(toggleClass);
var removeClassList = classList.slice(0, level);
removeClassList.map(function (className) {
return document.body.classList.remove(className);
});
document.body.classList.toggle(toggleClass, force);
}
module.exports = exports["default"]; |
sowrisurya/vmraid | vmraid/www/unsubscribe.py | from __future__ import unicode_literals
import vmraid
from vmraid.utils.verified_command import verify_request
from vmraid.email.doctype.newsletter.newsletter import confirmed_unsubscribe
no_cache = True
def get_context(context):
vmraid.flags.ignore_permissions = True
# Called for confirmation.
if "email" in vmraid.form_dict:
if verify_request():
user_email = vmraid.form_dict["email"]
context.email = user_email
title = vmraid.form_dict["name"]
context.email_groups = get_email_groups(user_email)
context.current_group = get_current_groups(title)
context.status = "waiting_for_confirmation"
# Called when form is submitted.
elif "user_email" in vmraid.form_dict:
context.status = "unsubscribed"
email = vmraid.form_dict['user_email']
email_group = get_email_groups(email)
for group in email_group:
if group.email_group in vmraid.form_dict:
confirmed_unsubscribe(email, group.email_group)
# Called on Invalid or unsigned request.
else:
context.status = "invalid"
def get_email_groups(user_email):
# Return the all email_groups in which the email has been registered.
return vmraid.get_all("Email Group Member",
fields=["email_group"],
filters={"email": user_email, "unsubscribed": 0})
def get_current_groups(name):
# Return current group by which the mail has been sent.
return vmraid.db.get_all("Newsletter Email Group",
fields=["email_group"],
filters={"parent":name, "parenttype":"Newsletter"}) |
dennyac/onnxruntime | onnxruntime/core/providers/cuda/nn/instance_norm_impl.h | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#pragma once
#include "core/providers/cuda/shared_inc/fast_divmod.h"
namespace onnxruntime {
namespace cuda {
template <typename T>
void InstanceNormImpl(
cudaStream_t stream,
const T* input_data,
const T* scale,
const T* bias,
const T* mean,
const T* variance,
const double variance_correction,
const double epsilon,
const fast_divmod& fdm_HW,
const fast_divmod& fdm_C,
T* output_data,
size_t count);
} // namespace cuda
} // namespace onnxruntime
|
xushaomin/appleframework | apple-launcher/src/main/java/com/appleframework/launcher/StartEventListener.java | <filename>apple-launcher/src/main/java/com/appleframework/launcher/StartEventListener.java
package com.appleframework.launcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.Async;
import org.springframework.util.StringUtils;
/**
* <p>
* 项目启动事件通知
* </p>
*
* @package: com.appleframework.launcher
* @description: 项目启动事件通知
* @author: cruise.xu
*/
@Configuration
public class StartEventListener {
private static Logger log = LoggerFactory.getLogger(StartEventListener.class);
@Async
@Order
@EventListener(WebServerInitializedEvent.class)
public void afterStart(WebServerInitializedEvent event) {
Environment environment = event.getApplicationContext().getEnvironment();
String appName = environment.getProperty("spring.application.name");
int localPort = event.getWebServer().getPort();
String profile = StringUtils.arrayToCommaDelimitedString(environment.getActiveProfiles());
log.info("[{}]启动完成,当前使用的端口:[{}],环境变量:[{}]", appName, localPort, profile);
}
}
|
mzhg/PostProcessingWork | testframewok/src/main/java/jet/opengl/demos/labs/scattering/AtmosphereTest.java | <filename>testframewok/src/main/java/jet/opengl/demos/labs/scattering/AtmosphereTest.java
package jet.opengl.demos.labs.scattering;
import com.nvidia.developer.opengl.app.NvCameraMotionType;
import com.nvidia.developer.opengl.app.NvSampleApp;
import com.nvidia.developer.opengl.models.DrawMode;
import com.nvidia.developer.opengl.models.GLVAO;
import com.nvidia.developer.opengl.models.QuadricBuilder;
import com.nvidia.developer.opengl.models.QuadricMesh;
import com.nvidia.developer.opengl.models.QuadricSphere;
import org.lwjgl.util.vector.Matrix4f;
import org.lwjgl.util.vector.Vector3f;
import java.io.IOException;
import java.nio.FloatBuffer;
import java.util.BitSet;
import jet.opengl.postprocessing.buffer.BufferGL;
import jet.opengl.postprocessing.common.GLFuncProvider;
import jet.opengl.postprocessing.common.GLFuncProviderFactory;
import jet.opengl.postprocessing.common.GLenum;
import jet.opengl.postprocessing.shader.GLSLProgram;
import jet.opengl.postprocessing.texture.FramebufferGL;
import jet.opengl.postprocessing.texture.Texture2D;
import jet.opengl.postprocessing.texture.Texture2DDesc;
import jet.opengl.postprocessing.texture.TextureAttachDesc;
import jet.opengl.postprocessing.texture.TextureDataDesc;
import jet.opengl.postprocessing.texture.TextureUtils;
import jet.opengl.postprocessing.util.CacheBuffer;
import jet.opengl.postprocessing.util.Numeric;
public class AtmosphereTest extends NvSampleApp {
private final Vector3f m_vLight = new Vector3f(0, 0, 1000);
private final Vector3f m_vLightDirection = new Vector3f();
// Variables that can be tweaked with keypresses
private BitSet m_bUseHDR;
private int m_nSamples;
private int m_nPolygonMode;
private float m_Kr, m_Kr4PI;
private float m_Km, m_Km4PI;
private float m_ESun;
private float m_g;
private float m_fExposure;
private float m_fInnerRadius;
private float m_fOuterRadius;
private float m_fScale;
private final float[] m_fWavelength = new float[3];
private final float[] m_fWavelength4 = new float[3];
private float m_fRayleighScaleDepth;
private float m_fMieScaleDepth;
// CPixelBuffer m_pbOpticalDepth;
private Texture2D m_tMoonGlow;
private Texture2D m_tEarth;
private Texture2D m_tCloudCell;
private Texture2D m_t1DGlow;
private GLSLProgram m_shSkyFromSpace;
private GLSLProgram m_shSkyFromAtmosphere;
private GLSLProgram m_shGroundFromSpace;
private GLSLProgram m_shGroundFromAtmosphere;
private GLSLProgram m_shSpaceFromSpace;
private GLSLProgram m_shSpaceFromAtmosphere;
private GLSLProgram m_shTexture;
private BufferGL m_quadT3;
private BufferGL m_quad;
private GLVAO mInnerSphere;
private GLVAO mOuterSphere;
private FramebufferGL m_pBuffer;
private GLFuncProvider gl;
private final Matrix4f mProj = new Matrix4f();
private final Matrix4f mView = new Matrix4f();
private final Params mParams = new Params();
private boolean mPrintOnce;
@Override
protected void initRendering() {
gl = GLFuncProviderFactory.getGLFuncProvider();
m_transformer.setMotionMode(NvCameraMotionType.FIRST_PERSON);
m_transformer.setTranslation(0, 0, 11);
m_pBuffer = new FramebufferGL();
m_pBuffer.bind();
m_pBuffer.addTexture2D(new Texture2DDesc(1280, 720, GLenum.GL_RGBA8), new TextureAttachDesc()); // RGBA16F
m_pBuffer.addTexture2D(new Texture2DDesc(1280, 720, GLenum.GL_DEPTH24_STENCIL8), new TextureAttachDesc()); // depth-stencil buffer
m_pBuffer.unbind();
CPixelBuffer pb = new CPixelBuffer();
// Initialize the shared cloud cell texture
pb.Init(16, 16, 1, 2, GLenum.GL_RG8); // GL_LUMINANCE_ALPHA
pb.MakeCloudCell(2, 0);
// m_tCloudCell.Init(&pb);
Texture2DDesc desc = new Texture2DDesc(16, 16, GLenum.GL_RG8);
TextureDataDesc initData = new TextureDataDesc(GLenum.GL_RG, GLenum.GL_UNSIGNED_BYTE, pb.GetBuffer());
m_tCloudCell = TextureUtils.createTexture2D(desc, initData);
pb.Init(64, 1, 1, 2, GLenum.GL_RG8);
pb.MakeGlow1D();
desc = new Texture2DDesc(64, 1, GLenum.GL_RG8);
initData = new TextureDataDesc(GLenum.GL_RG, GLenum.GL_UNSIGNED_BYTE, pb.GetBuffer());
m_t1DGlow = TextureUtils.createTexture2D(desc, initData);
pb.Init(256, 256, 1,1, GLenum.GL_R8);
pb.MakeGlow2D(40.0f, 0.1f);
desc = new Texture2DDesc(256, 256, GLenum.GL_R8);
initData = new TextureDataDesc(GLenum.GL_RED, GLenum.GL_UNSIGNED_BYTE, pb.GetBuffer());
m_tMoonGlow= TextureUtils.createTexture2D(desc, initData);
final float[] vertsT3 = {
-4,4,-50,0,0,
-4.0f, -4.0f, -50.0f,0, 1,
4.0f, -4.0f, -50.0f, 1, 1,
4.0f, 4.0f, -50.0f,1, 0
};
FloatBuffer vertsBuffer = CacheBuffer.wrap(vertsT3);
m_quadT3 = new BufferGL();
m_quadT3.initlize(GLenum.GL_ARRAY_BUFFER, 4 * vertsT3.length, vertsBuffer, GLenum.GL_STATIC_DRAW);
final float[] verts = {
-1, -1, 0,0,
+1, -1, 1, 0,
-1, 1, 0, 1,
+1, +1, 1,1
};
vertsBuffer = CacheBuffer.wrap(verts);
m_quad = new BufferGL();
m_quad.initlize(GLenum.GL_ARRAY_BUFFER, 4 * verts.length, vertsBuffer, GLenum.GL_STATIC_DRAW);
m_quad.unbind();
// m_vLightDirection = m_vLight / m_vLight.Magnitude();
m_vLight.normalise(m_vLightDirection);
m_nSamples = 3; // Number of sample rays to use in integral equation
m_Kr = 0.0025f; // Rayleigh scattering constant
m_Kr4PI = m_Kr*4.0f* Numeric.PI;
m_Km = 0.0010f; // Mie scattering constant
m_Km4PI = m_Km*4.0f*Numeric.PI;
m_ESun = 20.0f; // Sun brightness constant
m_g = -0.990f; // The Mie phase asymmetry factor
m_fExposure = 2.0f;
m_fInnerRadius = 10.0f;
m_fOuterRadius = 10.25f;
m_fScale = 1 / (m_fOuterRadius - m_fInnerRadius);
m_fWavelength[0] = 0.650f; // 650 nm for red
m_fWavelength[1] = 0.570f; // 570 nm for green
m_fWavelength[2] = 0.475f; // 475 nm for blue
m_fWavelength4[0] = (float)Math.pow(m_fWavelength[0], 4.0f);
m_fWavelength4[1] = (float)Math.pow(m_fWavelength[1], 4.0f);
m_fWavelength4[2] = (float)Math.pow(m_fWavelength[2], 4.0f);
m_fRayleighScaleDepth = 0.25f;
m_fMieScaleDepth = 0.1f;
try {
final String root = "labs\\AtmosphereTest\\shaders\\";
m_shTexture = GLSLProgram.createFromFiles(root + "TextureVS.vert", root + "SpaceFromSpace.frag");
m_shTexture.setName("Texture");
m_shSkyFromSpace = GLSLProgram.createFromFiles(root + "SkyFromSpace.vert", root + "SkyFromSpace.frag");
m_shSkyFromSpace.setName("SkyFromSpace");
m_shSkyFromAtmosphere = GLSLProgram.createFromFiles(root + "SkyFromAtmosphere.vert", root + "SkyFromAtmosphere.frag");
m_shSkyFromAtmosphere.setName("SkyFromAtmosphere");
m_shGroundFromSpace = GLSLProgram.createFromFiles(root + "GroundFromSpace.vert", root + "GroundFromSpace.frag");
m_shGroundFromSpace.setName("GroundFromSpace");
m_shGroundFromAtmosphere = GLSLProgram.createFromFiles(root + "GroundFromAtmosphere.vert", root + "GroundFromAtmosphere.frag");
m_shGroundFromAtmosphere.setName("GroundFromAtmosphere");
m_shSpaceFromSpace = GLSLProgram.createFromFiles(root + "SpaceFromSpace.vert", root + "SpaceFromSpace.frag");
m_shSpaceFromSpace.setName("SpaceFromSpace");
m_shSpaceFromAtmosphere = GLSLProgram.createFromFiles(root + "SpaceFromAtmosphere.vert", root + "SpaceFromAtmosphere.frag");
m_shSpaceFromAtmosphere.setName("SpaceFromAtmosphere");
m_tEarth = TextureUtils.createTexture2DFromFile("labs\\AtmosphereTest\\textures\\earthmap1k.jpg", false, true);
} catch (IOException e) {
e.printStackTrace();
}
QuadricBuilder builder = new QuadricBuilder();
builder.setXSteps(30).setYSteps(30);
builder.setDrawMode(DrawMode.FILL);
builder.setCenterToOrigin(true);
builder.setPostionLocation(0);
builder.setNormalLocation(1);
builder.setTexCoordLocation(2);
mInnerSphere = new QuadricMesh(builder, new QuadricSphere(m_fInnerRadius)).getModel().genVAO();
mOuterSphere = new QuadricMesh(builder, new QuadricSphere(m_fOuterRadius)).getModel().genVAO();
}
@Override
public void display() {
m_transformer.getModelViewMat(mView);
Matrix4f.mul(mProj, mView, mParams.uMVP);
Matrix4f.decompseRigidMatrix(mView, mParams.v3CameraPos, null, null);
m_pBuffer.bind();
gl.glViewport(0,0,1280, 720);
gl.glEnable(GLenum.GL_DEPTH_TEST);
gl.glClearDepthf(1.f);
gl.glClear(GLenum.GL_COLOR_BUFFER_BIT|GLenum.GL_DEPTH_BUFFER_BIT);
Vector3f vCamera = mParams.v3CameraPos;
// 0, render the moon
GLSLProgram pSpaceShader = null;
if(vCamera.length() < m_fOuterRadius)
pSpaceShader = m_shSpaceFromAtmosphere;
else if(vCamera.z > 0.0f)
pSpaceShader = m_shSpaceFromSpace;
else
pSpaceShader = m_shTexture;
pSpaceShader.enable();
setUniforms(pSpaceShader);
gl.glActiveTexture(GLenum.GL_TEXTURE0);
gl.glBindTexture(m_tMoonGlow.getTarget(), m_tMoonGlow.getTexture());
m_quadT3.bind();
gl.glVertexAttribPointer(0, 3, GLenum.GL_FLOAT, false, 20, 0);
gl.glEnableVertexAttribArray(0);
gl.glVertexAttribPointer(1, 2, GLenum.GL_FLOAT, false, 20, 12);
gl.glEnableVertexAttribArray(1);
gl.glDrawArrays(GLenum.GL_TRIANGLE_FAN, 0, 4);
m_quadT3.unbind();
gl.glBindTexture(m_tMoonGlow.getTarget(), 0);
gl.glDisableVertexAttribArray(0);
gl.glDisableVertexAttribArray(1);
if(pSpaceShader != null)
gl.glUseProgram(0);
// 1, render the ground
GLSLProgram pGroundShader;
if(vCamera.length() >= m_fOuterRadius)
pGroundShader = m_shGroundFromSpace;
else
pGroundShader = m_shGroundFromAtmosphere;
pGroundShader.enable();
setUniforms(pGroundShader);
gl.glBindTexture(m_tEarth.getTarget(), m_tEarth.getTexture());
mInnerSphere.bind();
mInnerSphere.draw(GLenum.GL_TRIANGLES);
mInnerSphere.unbind();
pGroundShader.disable();
// 2, render the sky
GLSLProgram pSkyShader;
if(vCamera.length() >= m_fOuterRadius)
pSkyShader = m_shSkyFromSpace;
else
pSkyShader = m_shSkyFromAtmosphere;
pSkyShader.enable();
setUniforms(pSkyShader);
gl.glEnable(GLenum.GL_BLEND);
gl.glBlendFunc(GLenum.GL_ONE, GLenum.GL_ONE);
mOuterSphere.bind();
mOuterSphere.draw(GLenum.GL_TRIANGLES);
mOuterSphere.unbind();
pSkyShader.disable();
// 3, blit the results to default framebuffer.
gl.glBindFramebuffer(GLenum.GL_FRAMEBUFFER, 0);
gl.glViewport(0,0, getGLContext().width(), getGLContext().height());
gl.glDisable(GLenum.GL_DEPTH_TEST);
gl.glClear(GLenum.GL_COLOR_BUFFER_BIT|GLenum.GL_DEPTH_BUFFER_BIT);
gl.glBindFramebuffer(GLenum.GL_DRAW_FRAMEBUFFER,0);
gl.glBindFramebuffer(GLenum.GL_READ_FRAMEBUFFER, m_pBuffer.getFramebuffer());
gl.glBlitFramebuffer(0, 0, 1280, 720,
0, 0, getGLContext().width(), getGLContext().height(),
GLenum.GL_COLOR_BUFFER_BIT, GLenum.GL_NEAREST);
gl.glBindFramebuffer(GLenum.GL_READ_FRAMEBUFFER, 0);
/*gl.glBindTexture(m_pBuffer.getAttachedTex(0).getTarget(), m_pBuffer.getAttachedTex(0).getTexture());
m_quad.bind();
gl.glVertexAttribPointer(0, 2, GLenum.GL_FLOAT, false, 16, 0);
gl.glEnableVertexAttribArray(0);
gl.glVertexAttribPointer(1, 2, GLenum.GL_FLOAT, false, 16, 8);
gl.glEnableVertexAttribArray(1);
gl.glDrawArrays(GLenum.GL_TRIANGLE_STRIP, 0, 4);
m_quad.unbind();
gl.glDisableVertexAttribArray(0);
gl.glDisableVertexAttribArray(1);
m_shTexture.disable();*/
mPrintOnce=true;
}
@Override
protected void reshape(int width, int height) {
if(width <= 0 || height <=0)
return;
Matrix4f.perspective(60, (float)width/height, 0.1f, 1000.f, mProj);
}
private void setUniforms(GLSLProgram program){
int index;
index = program.getUniformLocation("v3CameraPos", true);
if(index >= 0) gl.glUniform3f(index, mParams.v3CameraPos.x, mParams.v3CameraPos.y, mParams.v3CameraPos.z);
index = program.getUniformLocation("v3LightPos" , true);
if(index >= 0) gl.glUniform3f(index, m_vLightDirection.x, m_vLightDirection.y, m_vLightDirection.z);
index = program.getUniformLocation("v3InvWavelength", true);
if(index >= 0) gl.glUniform3f(index, 1/m_fWavelength4[0], 1/m_fWavelength4[1], 1/m_fWavelength4[2]);
index = program.getUniformLocation("fCameraHeight", true);
if(index >= 0) gl.glUniform1f(index, mParams.v3CameraPos.length());
index = program.getUniformLocation("fCameraHeight2", true);
if(index >= 0) gl.glUniform1f(index, mParams.v3CameraPos.lengthSquared());
index = program.getUniformLocation("fOuterRadius", true);
if(index >= 0) gl.glUniform1f(index, m_fOuterRadius);
index = program.getUniformLocation("fOuterRadius2", true);
if(index >= 0) gl.glUniform1f(index, m_fOuterRadius * m_fOuterRadius);
index = program.getUniformLocation("fInnerRadius", true);
if(index >= 0) gl.glUniform1f(index, m_fInnerRadius);
index = program.getUniformLocation("fInnerRadius2", true);
if(index >= 0) gl.glUniform1f(index, m_fInnerRadius * m_fInnerRadius);
index = program.getUniformLocation("fKrESun", true);
if(index >= 0) gl.glUniform1f(index, m_Kr*m_ESun);
index = program.getUniformLocation("fKmESun", true);
if(index >= 0) gl.glUniform1f(index, m_Km*m_ESun);
index = program.getUniformLocation("fKr4PI", true);
if(index >= 0) gl.glUniform1f(index, m_Kr4PI);
index = program.getUniformLocation("fKm4PI", true);
if(index >= 0) gl.glUniform1f(index, m_Km4PI);
index = program.getUniformLocation("fScale", true);
if(index >= 0) gl.glUniform1f(index, 1.0f / (m_fOuterRadius - m_fInnerRadius));
index = program.getUniformLocation("fScaleDepth", true);
if(index >= 0) gl.glUniform1f(index, m_fRayleighScaleDepth);
index = program.getUniformLocation("fScaleOverScaleDepth", true);
if(index >= 0) gl.glUniform1f(index, (1.0f / (m_fOuterRadius - m_fInnerRadius)) / m_fRayleighScaleDepth);
index = program.getUniformLocation("g", true);
if(index >= 0) gl.glUniform1f(index, m_g);
index = program.getUniformLocation("g2", true);
if(index >= 0) gl.glUniform1f(index, m_g * m_g);
index = program.getUniformLocation("s2Test", true);
if(index >= 0) gl.glUniform1i(index, 0);
index = program.getUniformLocation("uMVP", true);
if(index >= 0) gl.glUniformMatrix4fv(index, false, CacheBuffer.wrap(mParams.uMVP));
if(!mPrintOnce)
program.printPrograminfo();
}
private static final class Params{
/** The camera's current position */
final Vector3f v3CameraPos = new Vector3f();
final Matrix4f uMVP = new Matrix4f();
}
}
|
PsichiX/Unreal-Systems-Architecture | Source/Boids/Systems/Persistent/BoidsKeepInSpaceBoundsSystem.cpp | <reponame>PsichiX/Unreal-Systems-Architecture
#include "Boids/Systems/Persistent/BoidsKeepInSpaceBoundsSystem.h"
#include "Shared/Components/SpaceBoundsComponent.h"
#include "Shared/Components/VelocityComponent.h"
#include "Systems/Public/SystemsWorld.h"
#include "Boids/Components/BoidComponent.h"
#include "Boids/Resources/BoidsSystemsRunCriteria.h"
void BoidsKeepInSpaceBoundsSystem(USystemsWorld& Systems)
{
const auto* BoidsSystemsRunCriteria = Systems.Resource<UBoidsSystemsRunCriteria>();
if (IsValid(BoidsSystemsRunCriteria) && BoidsSystemsRunCriteria->bRunKeepInSpaceBounds == false)
{
return;
}
const auto BoxOpt = Systems.Query<USpaceBoundsComponent>()
.FilterMap<FBoxSphereBounds>(
[](const auto& QueryItem)
{
const auto* SpaceBounds = QueryItem.Get<1>();
return SpaceBounds->Bounds;
})
.Map<FBox>([](const auto& Bounds) { return Bounds.GetBox(); })
.First();
if (BoxOpt.IsSet() == false)
{
return;
}
const auto Box = BoxOpt.GetValue();
Systems.Query<UVelocityComponent, UBoidComponent>().ForEach(
[&](auto& QueryItem)
{
auto* Actor = QueryItem.Get<0>();
auto* Velocity = QueryItem.Get<1>();
auto Position = Actor->GetActorLocation();
if (Box.IsInsideOrOn(Position) == false)
{
KeepInBounds(Box, Position, Velocity->Value, 0);
KeepInBounds(Box, Position, Velocity->Value, 1);
KeepInBounds(Box, Position, Velocity->Value, 2);
Actor->SetActorLocation(Position);
}
});
}
void KeepInBounds(const FBox& Box, FVector& Position, FVector& Velocity, int Channel)
{
if (Position[Channel] < Box.Min[Channel])
{
Position[Channel] = Box.Max[Channel];
// Position[Channel] = Box.Min[Channel];
// Velocity[Channel] = -Velocity[Channel];
}
else if (Position[Channel] > Box.Max[Channel])
{
Position[Channel] = Box.Min[Channel];
// Position[Channel] = Box.Max[Channel];
// Velocity[Channel] = -Velocity[Channel];
}
}
|
PushyamiKaveti/kalibr | aslam_cv/aslam_time/include/aslam/implementation/Time.hpp | <reponame>PushyamiKaveti/kalibr
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, <NAME>, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of <NAME>, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
#ifndef ASLAM_TIME_IMPL_H_INCLUDED
#define ASLAM_TIME_IMPL_H_INCLUDED
/*********************************************************************
** Headers
*********************************************************************/
//#include <ros/platform.h>
#include <iostream>
#include <cmath>
//#include <ros/exception.h>
//#include <aslam/time.h>
#include <boost/date_time/posix_time/posix_time.hpp>
/*********************************************************************
** Cross Platform Headers
*********************************************************************/
#ifdef WIN32
#include <sys/timeb.h>
#else
#include <sys/time.h>
#endif
namespace aslam {
template<class T, class D>
T& TimeBase<T, D>::fromNSec(uint64_t t) {
sec = (int32_t)(t / 1000000000);
nsec = (int32_t)(t % 1000000000);
normalizeSecNSec(sec, nsec);
return *static_cast<T*>(this);
}
template<class T, class D>
D TimeBase<T, D>::operator-(const T &rhs) const {
return D((int32_t) sec - (int32_t) rhs.sec,
(int32_t) nsec - (int32_t) rhs.nsec); // carry handled in ctor
}
template<class T, class D>
T TimeBase<T, D>::operator-(const D &rhs) const {
return *static_cast<const T*>(this) + (-rhs);
}
template<class T, class D>
T TimeBase<T, D>::operator+(const D &rhs) const {
int64_t sec_sum = (int64_t) sec + (int64_t) rhs.sec;
int64_t nsec_sum = (int64_t) nsec + (int64_t) rhs.nsec;
// Throws an exception if we go out of 32-bit range
normalizeSecNSecUnsigned(sec_sum, nsec_sum);
// now, it's safe to downcast back to uint32 bits
return T((uint32_t) sec_sum, (uint32_t) nsec_sum);
}
template<class T, class D>
T& TimeBase<T, D>::operator+=(const D &rhs) {
*this = *this + rhs;
return *static_cast<T*>(this);
}
template<class T, class D>
T& TimeBase<T, D>::operator-=(const D &rhs) {
*this += (-rhs);
return *static_cast<T*>(this);
}
template<class T, class D>
bool TimeBase<T, D>::operator==(const T &rhs) const {
return sec == rhs.sec && nsec == rhs.nsec;
}
template<class T, class D>
bool TimeBase<T, D>::operator<(const T &rhs) const {
if (sec < rhs.sec)
return true;
else if (sec == rhs.sec && nsec < rhs.nsec)
return true;
return false;
}
template<class T, class D>
bool TimeBase<T, D>::operator>(const T &rhs) const {
if (sec > rhs.sec)
return true;
else if (sec == rhs.sec && nsec > rhs.nsec)
return true;
return false;
}
template<class T, class D>
bool TimeBase<T, D>::operator<=(const T &rhs) const {
if (sec < rhs.sec)
return true;
else if (sec == rhs.sec && nsec <= rhs.nsec)
return true;
return false;
}
template<class T, class D>
bool TimeBase<T, D>::operator>=(const T &rhs) const {
if (sec > rhs.sec)
return true;
else if (sec == rhs.sec && nsec >= rhs.nsec)
return true;
return false;
}
template<class T, class D>
boost::posix_time::ptime TimeBase<T, D>::toBoost() const {
namespace pt = boost::posix_time;
#if defined(BOOST_DATE_TIME_HAS_NANOSECONDS)
return pt::from_time_t(sec) + pt::nanoseconds(nsec);
#else
return pt::from_time_t(sec) + pt::microseconds(static_cast<int32_t>(nsec / 1000.0));
#endif
}
}
#endif // ASLAM_IMPL_TIME_H_INCLUDED
|
DGB-UNAM-FOLIO/ui-users | test/bigtest/interactors/settings-feefine.js | <reponame>DGB-UNAM-FOLIO/ui-users
import {
interactor,
clickable,
text,
isPresent,
count,
scoped,
collection,
} from '@bigtest/interactor';
import CalloutInteractor from '@folio/stripes-components/lib/Callout/tests/interactor'; // eslint-disable-line
import ButtonInteractor from '@folio/stripes-components/lib/Button/tests/interactor'; // eslint-disable-line
import ConfirmationModalInteractor from '@folio/stripes-components/lib/ConfirmationModal/tests/interactor'; // eslint-disable-line
import TextFieldInteractor from '@folio/stripes-components/lib/TextField/tests/interactor'; // eslint-disable-line
import MultiSelectInteractor from '@folio/stripes-components/lib/MultiSelection/tests/interactor'; // eslint-disable-line
import SelectInteractor from '@folio/stripes-components/lib/Select/tests/interactor'; // eslint-disable-line
import RadioButtonInteractor from '@folio/stripes-components/lib/RadioButton/tests/interactor'; // eslint-disable-line
const rowSelector = '[class*=editListRow--]';
const cellSelector = '[class*=mclCell--]';
const CellInteractor = interactor(class CellInteractor {
content = text();
});
const RowInteractor = interactor(class RowInteractor {
cells = collection(cellSelector, CellInteractor);
cellCount = count(cellSelector);
click = clickable();
textfield = collection('[class*=textField--]', TextFieldInteractor);
select = collection('[class*=select--]', SelectInteractor);
sp = new MultiSelectInteractor();
editButton = scoped('[icon=edit]', ButtonInteractor);
deleteButton = scoped('[icon=trash]', ButtonInteractor);
saveButton = scoped('[id*=clickable-save-settings-]', ButtonInteractor);
cancelButton = scoped('[id*=clickable-cancel-settings-]', ButtonInteractor);
});
@interactor class ListInteractor {
rowCount = count(rowSelector);
rows = collection(rowSelector, RowInteractor);
}
@interactor class NoticeInteractor {
ownerChargeNotice = new SelectInteractor('#defaultChargeNoticeId');
ownerActionNotice = new SelectInteractor('#defaultActionNoticeId');
ownerChargeNoticeValue = text('#defaultChargeNoticeId');
ownerActionNoticeValue = text('#defaultActionNoticeId');
primaryButton = new ButtonInteractor('#charge-notice-primary');
cancelNotice = new ButtonInteractor('#charge-notice-cancel');
}
@interactor class CopyModalInteractor {
isPresent = isPresent();
select = new SelectInteractor();
yes = new RadioButtonInteractor('form > div > div:nth-child(1) > fieldset > div:nth-child(2)');
no = new RadioButtonInteractor('form > div > div:nth-child(1) > fieldset > div:nth-child(3)')
// options = collection(RadioButtonInteractor);
buttons = collection('[class*=button---]', ButtonInteractor);
}
@interactor class FeeFineInteractor {
whenLoaded() {
return this.when(() => this.isLoaded);
}
isLoaded = isPresent(rowSelector);
ownerSelect = new SelectInteractor();
notice = new NoticeInteractor();
copyOwnerModal = new CopyModalInteractor('[class*=modal---]');
hideItemModal = isPresent('#hideItemInUseDialog');
list = new ListInteractor('[id*=editList-settings-]');
callout = new CalloutInteractor();
confirmationModal = new ConfirmationModalInteractor('#delete-controlled-vocab-entry-confirmation');
newItemButton = new ButtonInteractor('[id*=clickable-add-settings-]');
}
export default new FeeFineInteractor();
|
RudolfCardinal/pythonlib | cardinal_pythonlib/sysops.py | #!/usr/bin/env python
# cardinal_pythonlib/sysops.py
"""
===============================================================================
Original code copyright (C) 2009-2021 <NAME> (<EMAIL>).
This file is part of cardinal_pythonlib.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
===============================================================================
**Simple system operations.**
"""
import logging
import os
import sys
from typing import NoReturn
log = logging.getLogger(__name__)
EXIT_FAILURE = 1
EXIT_SUCCESS = 0
def die(msg: str,
log_level: int = logging.CRITICAL,
exit_code: int = EXIT_FAILURE) -> NoReturn:
"""
Prints a message and hard-exits the program.
Args:
msg: message
log_level: log level to use
exit_code: exit code (errorlevel)
"""
log.log(level=log_level, msg=msg)
sys.exit(exit_code)
def get_envvar_or_die(envvar: str,
log_level: int = logging.CRITICAL,
exit_code: int = EXIT_FAILURE) -> str:
"""
Returns the value of an environment variable.
If it is unset or blank, complains and hard-exits the program.
Args:
envvar: environment variable name
log_level: log level to use for failure
exit_code: exit code (errorlevel) for failure
Returns:
str: the value of the environment variable
"""
value = os.environ.get(envvar)
if not value:
die(f"Must set environment variable {envvar}",
log_level=log_level, exit_code=exit_code)
return value
|
mehrdad-shokri/neopg | legacy/libgcrypt/tests/pubkey.cpp | <filename>legacy/libgcrypt/tests/pubkey.cpp
/* pubkey.c - Public key encryption/decryption tests
* Copyright (C) 2001, 2002, 2003, 2005 Free Software Foundation, Inc.
*
* This file is part of Libgcrypt.
*
* Libgcrypt is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* Libgcrypt is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define PGM "pubkey"
#include "t-common.h"
/* Sample RSA keys, taken from basic.c. */
static const char sample_private_key_1[] =
"(private-key\n"
" (openpgp-rsa\n"
" (n #00e0ce96f90b6c9e02f3922beada93fe50a875eac6bcc18bb9a9cf2e84965caa"
"2d1ff95a7f542465c6c0c19d276e4526ce048868a7a914fd343cc3a87dd74291"
"ffc565506d5bbb25cbac6a0e2dd1f8bcaab0d4a29c2f37c950f363484bf269f7"
"891440464baf79827e03a36e70b814938eebdc63e964247be75dc58b014b7ea251#)\n"
" (e #010001#)\n"
" (d #046129F2489D71579BE0A75FE029BD6CDB574EBF57EA8A5B0FDA942CAB943B11"
"7D7BB95E5D28875E0F9FC5FCC06A72F6D502464DABDED78EF6B716177B83D5BD"
"C543DC5D3FED932E59F5897E92E6F58A0F33424106A3B6FA2CBF877510E4AC21"
"C3EE47851E97D12996222AC3566D4CCB0B83D164074ABF7DE655FC2446DA1781#)\n"
" (p #00e861b700e17e8afe6837e7512e35b6ca11d0ae47d8b85161c67baf64377213"
"fe52d772f2035b3ca830af41d8a4120e1c1c70d12cc22f00d28d31dd48a8d424f1#)\n"
" (q #00f7a7ca5367c661f8e62df34f0d05c10c88e5492348dd7bddc942c9a8f369f9"
"35a07785d2db805215ed786e4285df1658eed3ce84f469b81b50d358407b4ad361#)\n"
" (u #304559a9ead56d2309d203811a641bb1a09626bc8eb36fffa23c968ec5bd891e"
"ebbafc73ae666e01ba7c8990bae06cc2bbe10b75e69fcacb353a6473079d8e9b#)\n"
" )\n"
")\n";
/* The same key as above but without p, q and u to test the non CRT case. */
static const char sample_private_key_1_1[] =
"(private-key\n"
" (openpgp-rsa\n"
" (n #00e0ce96f90b6c9e02f3922beada93fe50a875eac6bcc18bb9a9cf2e84965caa"
"2d1ff95a7f542465c6c0c19d276e4526ce048868a7a914fd343cc3a87dd74291"
"<KEY>"
"891440464baf79827e03a36e70b814938eebdc63e964247be75dc58b014b7ea251#)\n"
" (e #010001#)\n"
" (d #046129F2489D71579BE0A75FE029BD6CDB574EBF57EA8A5B0FDA942CAB943B11"
"7D7BB95E5D28875E0F9FC5FCC06A72F6D502464DABDED78EF6B716177B83D5BD"
"C543DC5D3FED932E59F5897E92E6F58A0F33424106A3B6FA2CBF877510E4AC21"
"C3EE47851E97D12996222AC3566D4CCB0B83D164074ABF7DE655FC2446DA1781#)\n"
" )\n"
")\n";
/* The same key as above but just without q to test the non CRT case. This
should fail. */
static const char sample_private_key_1_2[] =
"(private-key\n"
" (openpgp-rsa\n"
" (n #00e0ce96f90b6c9e02f3922beada93fe50a875eac6bcc18bb9a9cf2e84965caa"
"2d1ff95a7f542465c6c0c19d276e4526ce048868a7a914fd343cc3a87dd74291"
"ffc565506d5bbb25cbac6a0e2dd1f8bcaab0d4a29c2f37c950f363484bf269f7"
"891440464baf79827e03a36e70b814938eebdc63e964247be75dc58b014b7ea251#)\n"
" (e #010001#)\n"
" (d #046129F2489D71579BE0A75FE029BD6CDB574EBF57EA8A5B0FDA942CAB943B11"
"7D7BB95E5D28875E0F9FC5FCC06A72F6D502464DABDED78EF6B716177B83D5BD"
"C543DC5D3FED932E59F5897E92E6F58A0F33424106A3B6FA2CBF877510E4AC21"
"C3EE47851E97D12996222AC3566D4CCB0B83D164074ABF7DE655FC2446DA1781#)\n"
" (p #00e861b700e17e8afe6837e7512e35b6ca11d0ae47d8b85161c67baf64377213"
"fe52d772f2035b3ca830af41d8a4120e1c1c70d12cc22f00d28d31dd48a8d424f1#)\n"
" (u #304559a9ead56d2309d203811a641bb1a09626bc8eb36fffa23c968ec5bd891e"
"ebbafc73ae666e01ba7c8990bae06cc2bbe10b75e69fcacb353a6473079d8e9b#)\n"
" )\n"
")\n";
static const char sample_public_key_1[] =
"(public-key\n"
" (rsa\n"
" (n #00e0ce96f90b6c9e02f3922beada93fe50a875eac6bcc18bb9a9cf2e84965caa"
"2d1ff95a7f542465c6c0c19d276e4526ce048868a7a914fd343cc3a87dd74291"
"<KEY>"
"891440464baf79827e03a36e70b814938eebdc63e964247be75dc58b014b7ea251#)\n"
" (e #010001#)\n"
" )\n"
")\n";
static void show_sexp(const char *prefix, gcry_sexp_t a) {
char *buf;
size_t size;
if (prefix) fputs(prefix, stderr);
size = gcry_sexp_sprint(a, GCRYSEXP_FMT_ADVANCED, NULL, 0);
buf = gcry_xmalloc(size);
gcry_sexp_sprint(a, GCRYSEXP_FMT_ADVANCED, buf, size);
fprintf(stderr, "%.*s", (int)size, buf);
gcry_free(buf);
}
/* from ../cipher/pubkey-util.c */
static gpg_err_code_t _gcry_pk_util_get_nbits(gcry_sexp_t list,
unsigned int *r_nbits) {
char buf[50];
const char *s;
size_t n;
*r_nbits = 0;
list = gcry_sexp_find_token(list, "nbits", 0);
if (!list) return 0; /* No NBITS found. */
s = gcry_sexp_nth_data(list, 1, &n);
if (!s || n >= DIM(buf) - 1) {
/* NBITS given without a cdr. */
gcry_sexp_release(list);
return GPG_ERR_INV_OBJ;
}
memcpy(buf, s, n);
buf[n] = 0;
*r_nbits = (unsigned int)strtoul(buf, NULL, 0);
gcry_sexp_release(list);
return 0;
}
/* Convert STRING consisting of hex characters into its binary
representation and return it as an allocated buffer. The valid
length of the buffer is returned at R_LENGTH. The string is
delimited by end of string. The function returns NULL on
error. */
static void *data_from_hex(const char *string, size_t *r_length) {
const char *s;
unsigned char *buffer;
size_t length;
buffer = gcry_xmalloc(strlen(string) / 2 + 1);
length = 0;
for (s = string; *s; s += 2) {
if (!hexdigitp(s) || !hexdigitp(s + 1))
die("error parsing hex string `%s'\n", string);
((unsigned char *)buffer)[length++] = xtoi_2(s);
}
*r_length = length;
return buffer;
}
static void extract_cmp_data(gcry_sexp_t sexp, const char *name,
const char *expected) {
gcry_sexp_t l1;
const void *a;
size_t alen;
void *b;
size_t blen;
l1 = gcry_sexp_find_token(sexp, name, 0);
a = gcry_sexp_nth_data(l1, 1, &alen);
b = data_from_hex(expected, &blen);
if (!a)
fail("parameter \"%s\" missing in key\n", name);
else if (alen != blen || memcmp(a, b, alen)) {
fail("parameter \"%s\" does not match expected value\n", name);
if (verbose) {
info("expected: %s\n", expected);
show_sexp("sexp: ", sexp);
}
}
gcry_free(b);
gcry_sexp_release(l1);
}
static void check_keys_crypt(gcry_sexp_t pkey, gcry_sexp_t skey,
gcry_sexp_t plain0,
gpg_err_code_t decrypt_fail_code) {
gcry_sexp_t plain1, cipher, l;
gcry_mpi_t x0, x1;
int rc;
int have_flags;
/* Extract data from plaintext. */
l = gcry_sexp_find_token(plain0, "value", 0);
x0 = gcry_sexp_nth_mpi(l, 1, GCRYMPI_FMT_USG);
gcry_sexp_release(l);
/* Encrypt data. */
rc = gcry_pk_encrypt(&cipher, plain0, pkey);
if (rc) die("encryption failed: %s\n", gcry_strerror(rc));
l = gcry_sexp_find_token(cipher, "flags", 0);
have_flags = !!l;
gcry_sexp_release(l);
/* Decrypt data. */
rc = gcry_pk_decrypt(&plain1, cipher, skey);
gcry_sexp_release(cipher);
if (rc) {
if (decrypt_fail_code && gpg_err_code(rc) == decrypt_fail_code) {
gcry_mpi_release(x0);
return; /* This is the expected failure code. */
}
die("decryption failed: %s\n", gcry_strerror(rc));
}
/* Extract decrypted data. Note that for compatibility reasons, the
output of gcry_pk_decrypt depends on whether a flags lists (even
if empty) occurs in its input data. Because we passed the output
of encrypt directly to decrypt, such a flag value won't be there
as of today. We check it anyway. */
l = gcry_sexp_find_token(plain1, "value", 0);
if (l) {
if (!have_flags) die("compatibility mode of pk_decrypt broken\n");
gcry_sexp_release(plain1);
x1 = gcry_sexp_nth_mpi(l, 1, GCRYMPI_FMT_USG);
gcry_sexp_release(l);
} else {
if (have_flags) die("compatibility mode of pk_decrypt broken\n");
x1 = gcry_sexp_nth_mpi(plain1, 0, GCRYMPI_FMT_USG);
gcry_sexp_release(plain1);
}
/* Compare. */
if (gcry_mpi_cmp(x0, x1)) die("data corrupted\n");
gcry_mpi_release(x0);
gcry_mpi_release(x1);
}
static void check_keys(gcry_sexp_t pkey, gcry_sexp_t skey,
unsigned int nbits_data,
gpg_err_code_t decrypt_fail_code) {
gcry_sexp_t plain;
gcry_mpi_t x;
int rc;
/* Create plain text. */
x = gcry_mpi_new(nbits_data);
gcry_mpi_randomize(x, nbits_data, GCRY_WEAK_RANDOM);
rc = gcry_sexp_build(&plain, NULL, "(data (flags raw) (value %m))", x);
if (rc) die("converting data for encryption failed: %s\n", gcry_strerror(rc));
check_keys_crypt(pkey, skey, plain, decrypt_fail_code);
gcry_sexp_release(plain);
gcry_mpi_release(x);
/* Create plain text. */
x = gcry_mpi_new(nbits_data);
gcry_mpi_randomize(x, nbits_data, GCRY_WEAK_RANDOM);
rc = gcry_sexp_build(&plain, NULL,
"(data (flags raw no-blinding) (value %m))", x);
gcry_mpi_release(x);
if (rc) die("converting data for encryption failed: %s\n", gcry_strerror(rc));
check_keys_crypt(pkey, skey, plain, decrypt_fail_code);
gcry_sexp_release(plain);
}
static void get_keys_sample(gcry_sexp_t *pkey, gcry_sexp_t *skey,
int secret_variant) {
gcry_sexp_t pub_key, sec_key;
int rc;
static const char *secret;
switch (secret_variant) {
case 0:
secret = sample_private_key_1;
break;
case 1:
secret = sample_private_key_1_1;
break;
case 2:
secret = sample_private_key_1_2;
break;
default:
die("BUG\n");
}
rc = gcry_sexp_sscan(&pub_key, NULL, sample_public_key_1,
strlen(sample_public_key_1));
if (!rc) rc = gcry_sexp_sscan(&sec_key, NULL, secret, strlen(secret));
if (rc) die("converting sample keys failed: %s\n", gcry_strerror(rc));
*pkey = pub_key;
*skey = sec_key;
}
static void get_keys_new(gcry_sexp_t *pkey, gcry_sexp_t *skey) {
gcry_sexp_t key_spec, key, pub_key, sec_key;
int rc;
rc = gcry_sexp_new(&key_spec, "(genkey (rsa (nbits 4:2048)))", 0, 1);
if (rc) die("error creating S-expression: %s\n", gcry_strerror(rc));
rc = gcry_pk_genkey(&key, key_spec);
gcry_sexp_release(key_spec);
if (rc) die("error generating RSA key: %s\n", gcry_strerror(rc));
if (verbose > 1) show_sexp("generated RSA key:\n", key);
pub_key = gcry_sexp_find_token(key, "public-key", 0);
if (!pub_key) die("public part missing in key\n");
sec_key = gcry_sexp_find_token(key, "private-key", 0);
if (!sec_key) die("private part missing in key\n");
gcry_sexp_release(key);
*pkey = pub_key;
*skey = sec_key;
}
static void get_keys_x931_new(gcry_sexp_t *pkey, gcry_sexp_t *skey) {
gcry_sexp_t key_spec, key, pub_key, sec_key;
int rc;
rc =
gcry_sexp_new(&key_spec, "(genkey (rsa (nbits 4:2048)(use-x931)))", 0, 1);
if (rc) die("error creating S-expression: %s\n", gcry_strerror(rc));
rc = gcry_pk_genkey(&key, key_spec);
gcry_sexp_release(key_spec);
if (rc) die("error generating RSA key: %s\n", gcry_strerror(rc));
if (verbose > 1) show_sexp("generated RSA (X9.31) key:\n", key);
pub_key = gcry_sexp_find_token(key, "public-key", 0);
if (!pub_key) die("public part missing in key\n");
sec_key = gcry_sexp_find_token(key, "private-key", 0);
if (!sec_key) die("private part missing in key\n");
gcry_sexp_release(key);
*pkey = pub_key;
*skey = sec_key;
}
static void get_elg_key_new(gcry_sexp_t *pkey, gcry_sexp_t *skey, int fixed_x) {
gcry_sexp_t key_spec, key, pub_key, sec_key;
int rc;
rc = gcry_sexp_new(
&key_spec,
(fixed_x ? "(genkey (elg (nbits 4:1024)(xvalue my.not-so-secret.key)))"
: "(genkey (elg (nbits 3:512)))"),
0, 1);
if (rc) die("error creating S-expression: %s\n", gcry_strerror(rc));
rc = gcry_pk_genkey(&key, key_spec);
gcry_sexp_release(key_spec);
if (rc) die("error generating Elgamal key: %s\n", gcry_strerror(rc));
if (verbose > 1) show_sexp("generated ELG key:\n", key);
pub_key = gcry_sexp_find_token(key, "public-key", 0);
if (!pub_key) die("public part missing in key\n");
sec_key = gcry_sexp_find_token(key, "private-key", 0);
if (!sec_key) die("private part missing in key\n");
gcry_sexp_release(key);
*pkey = pub_key;
*skey = sec_key;
}
static void get_dsa_key_new(gcry_sexp_t *pkey, gcry_sexp_t *skey,
int transient_key) {
gcry_sexp_t key_spec, key, pub_key, sec_key;
int rc;
rc = gcry_sexp_new(&key_spec,
transient_key
? "(genkey (dsa (nbits 4:2048)(transient-key)))"
: "(genkey (dsa (nbits 4:2048)))",
0, 1);
if (rc) die("error creating S-expression: %s\n", gcry_strerror(rc));
rc = gcry_pk_genkey(&key, key_spec);
gcry_sexp_release(key_spec);
if (rc) die("error generating DSA key: %s\n", gcry_strerror(rc));
if (verbose > 1) show_sexp("generated DSA key:\n", key);
pub_key = gcry_sexp_find_token(key, "public-key", 0);
if (!pub_key) die("public part missing in key\n");
sec_key = gcry_sexp_find_token(key, "private-key", 0);
if (!sec_key) die("private part missing in key\n");
gcry_sexp_release(key);
*pkey = pub_key;
*skey = sec_key;
}
static void get_dsa_key_fips186_new(gcry_sexp_t *pkey, gcry_sexp_t *skey) {
gcry_sexp_t key_spec, key, pub_key, sec_key;
int rc;
rc = gcry_sexp_new(&key_spec, "(genkey (dsa (nbits 4:2048)(use-fips186)))", 0,
1);
if (rc) die("error creating S-expression: %s\n", gcry_strerror(rc));
rc = gcry_pk_genkey(&key, key_spec);
gcry_sexp_release(key_spec);
if (rc) die("error generating DSA key: %s\n", gcry_strerror(rc));
if (verbose > 1) show_sexp("generated DSA key (fips 186):\n", key);
pub_key = gcry_sexp_find_token(key, "public-key", 0);
if (!pub_key) die("public part missing in key\n");
sec_key = gcry_sexp_find_token(key, "private-key", 0);
if (!sec_key) die("private part missing in key\n");
gcry_sexp_release(key);
*pkey = pub_key;
*skey = sec_key;
}
static void get_dsa_key_with_domain_new(gcry_sexp_t *pkey, gcry_sexp_t *skey) {
gcry_sexp_t key_spec, key, pub_key, sec_key;
int rc;
rc = gcry_sexp_new(
&key_spec,
"(genkey (dsa (transient-key)(domain"
"(p #d3aed1876054db831d0c1348fbb1ada72507e5fbf9a62cbd47a63aeb7859d6921"
"<KEY>"
"74322657c9da88a7d2f0e1a9ceb84a39cb40876179e6a76e400498de4bb9379b0"
"5f5feb7b91eb8fea97ee17a955a0a8a37587a272c4719d6feb6b54ba4ab69#)"
"(q #9c916d121de9a03f71fb21bc2e1c0d116f065a4f#)"
"(g #8157c5f68ca40b3ded11c353327ab9b8af3e186dd2e8dade98761a0996dda99ab"
"0250d3409063ad99efae48b10c6ab2bba3ea9a67b12b911a372a2bba260176fad"
"b4b93247d9712aad13aa70216c55da9858f7a298deb670a403eb1e7c91b847f1e"
"ccfbd14bd806fd42cf45dbb69cd6d6b43add2a78f7d16928eaa04458dea44#)"
")))",
0, 1);
if (rc) die("error creating S-expression: %s\n", gcry_strerror(rc));
rc = gcry_pk_genkey(&key, key_spec);
gcry_sexp_release(key_spec);
if (rc) die("error generating DSA key: %s\n", gcry_strerror(rc));
if (verbose > 1) show_sexp("generated DSA key:\n", key);
pub_key = gcry_sexp_find_token(key, "public-key", 0);
if (!pub_key) die("public part missing in key\n");
sec_key = gcry_sexp_find_token(key, "private-key", 0);
if (!sec_key) die("private part missing in key\n");
gcry_sexp_release(key);
*pkey = pub_key;
*skey = sec_key;
}
#if 0
static void
get_dsa_key_fips186_with_domain_new (gcry_sexp_t *pkey, gcry_sexp_t *skey)
{
gcry_sexp_t key_spec, key, pub_key, sec_key;
int rc;
rc = gcry_sexp_new
(&key_spec,
"(genkey (dsa (transient-key)(use-fips186)(domain"
"(p #d3aed1876054db831d0c1348fbb1ada72507e5fbf9a62cbd47a63aeb7859d6921"
"<KEY>"
"74322657c9da88a7d2f0e1a9ceb84a39cb40876179e6a76e400498de4bb9379b0"
"5f5feb7b91eb8fea97ee17a955a0a8a37587a272c4719d6feb6b54ba4ab69#)"
"(q #9c916d121de9a03f71fb21bc2e1c0d116f065a4f#)"
"(g #8157c5f68ca40b3ded11c353327ab9b8af3e186dd2e8dade98761a0996dda99ab"
"0250d3409063ad99efae48b10c6ab2bba3ea9a67b12b911a372a2bba260176fad"
"<KEY>"
"ccfbd14bd806fd42cf45dbb69cd6d6b43add2a78f7d16928eaa04458dea44#)"
")))", 0, 1);
if (rc)
die ("error creating S-expression: %s\n", gcry_strerror (rc));
rc = gcry_pk_genkey (&key, key_spec);
gcry_sexp_release (key_spec);
if (rc)
die ("error generating DSA key: %s\n", gcry_strerror (rc));
if (verbose > 1)
show_sexp ("generated DSA key:\n", key);
pub_key = gcry_sexp_find_token (key, "public-key", 0);
if (!pub_key)
die ("public part missing in key\n");
sec_key = gcry_sexp_find_token (key, "private-key", 0);
if (!sec_key)
die ("private part missing in key\n");
gcry_sexp_release (key);
*pkey = pub_key;
*skey = sec_key;
}
#endif /*0*/
static void get_dsa_key_fips186_with_seed_new(gcry_sexp_t *pkey,
gcry_sexp_t *skey) {
gcry_sexp_t key_spec, key, pub_key, sec_key;
int rc;
rc = gcry_sexp_new(
&key_spec,
"(genkey"
" (dsa"
" (nbits 4:2048)"
" (use-fips186)"
" (transient-key)"
" (derive-parms"
" (seed #0cb1990c1fd3626055d7a0096f8fa99807399871#))))",
0, 1);
if (rc) die("error creating S-expression: %s\n", gcry_strerror(rc));
rc = gcry_pk_genkey(&key, key_spec);
gcry_sexp_release(key_spec);
if (rc) die("error generating DSA key: %s\n", gcry_strerror(rc));
if (verbose > 1) show_sexp("generated DSA key (fips 186 with seed):\n", key);
pub_key = gcry_sexp_find_token(key, "public-key", 0);
if (!pub_key) die("public part missing in key\n");
sec_key = gcry_sexp_find_token(key, "private-key", 0);
if (!sec_key) die("private part missing in key\n");
gcry_sexp_release(key);
*pkey = pub_key;
*skey = sec_key;
}
static void check_run(void) {
gpg_error_t err;
gcry_sexp_t pkey, skey;
int variant;
for (variant = 0; variant < 3; variant++) {
if (verbose) fprintf(stderr, "Checking sample key (%d).\n", variant);
get_keys_sample(&pkey, &skey, variant);
/* Check gcry_pk_testkey which requires all elements. */
err = gcry_pk_testkey(skey);
if ((variant == 0 && err) ||
(variant > 0 && gpg_err_code(err) != GPG_ERR_NO_OBJ))
die("gcry_pk_testkey failed: %s\n", gpg_strerror(err));
/* Run the usual check but expect an error from variant 2. */
check_keys(pkey, skey, 800, variant == 2 ? GPG_ERR_NO_OBJ : 0);
gcry_sexp_release(pkey);
gcry_sexp_release(skey);
}
if (verbose) fprintf(stderr, "Checking generated RSA key.\n");
get_keys_new(&pkey, &skey);
check_keys(pkey, skey, 800, 0);
gcry_sexp_release(pkey);
gcry_sexp_release(skey);
if (verbose) fprintf(stderr, "Checking generated RSA key (X9.31).\n");
get_keys_x931_new(&pkey, &skey);
check_keys(pkey, skey, 800, 0);
gcry_sexp_release(pkey);
gcry_sexp_release(skey);
if (verbose) fprintf(stderr, "Checking generated Elgamal key.\n");
get_elg_key_new(&pkey, &skey, 0);
check_keys(pkey, skey, 400, 0);
gcry_sexp_release(pkey);
gcry_sexp_release(skey);
if (verbose) fprintf(stderr, "Checking passphrase generated Elgamal key.\n");
get_elg_key_new(&pkey, &skey, 1);
check_keys(pkey, skey, 800, 0);
gcry_sexp_release(pkey);
gcry_sexp_release(skey);
if (verbose) fprintf(stderr, "Generating DSA key.\n");
get_dsa_key_new(&pkey, &skey, 0);
/* Fixme: Add a check function for DSA keys. */
gcry_sexp_release(pkey);
gcry_sexp_release(skey);
if (!gcry_fips_mode_active()) {
if (verbose) fprintf(stderr, "Generating transient DSA key.\n");
get_dsa_key_new(&pkey, &skey, 1);
/* Fixme: Add a check function for DSA keys. */
gcry_sexp_release(pkey);
gcry_sexp_release(skey);
}
if (verbose) fprintf(stderr, "Generating DSA key (FIPS 186).\n");
get_dsa_key_fips186_new(&pkey, &skey);
/* Fixme: Add a check function for DSA keys. */
gcry_sexp_release(pkey);
gcry_sexp_release(skey);
if (verbose) fprintf(stderr, "Generating DSA key with given domain.\n");
get_dsa_key_with_domain_new(&pkey, &skey);
/* Fixme: Add a check function for DSA keys. */
gcry_sexp_release(pkey);
gcry_sexp_release(skey);
/* We need new test vectors for get_dsa_key_fips186_with_domain_new. */
if (verbose)
fprintf(stderr,
"Generating DSA key with given domain (FIPS 186)"
" - skipped.\n");
/* get_dsa_key_fips186_with_domain_new (&pkey, &skey); */
/* /\* Fixme: Add a check function for DSA keys. *\/ */
/* gcry_sexp_release (pkey); */
/* gcry_sexp_release (skey); */
if (verbose)
fprintf(stderr, "Generating DSA key with given seed (FIPS 186).\n");
get_dsa_key_fips186_with_seed_new(&pkey, &skey);
/* Fixme: Add a check function for DSA keys. */
gcry_sexp_release(pkey);
gcry_sexp_release(skey);
}
static gcry_mpi_t key_param_from_sexp(gcry_sexp_t sexp, const char *topname,
const char *name) {
gcry_sexp_t l1, l2;
gcry_mpi_t result;
l1 = gcry_sexp_find_token(sexp, topname, 0);
if (!l1) return NULL;
l2 = gcry_sexp_find_token(l1, name, 0);
if (!l2) {
gcry_sexp_release(l1);
return NULL;
}
result = gcry_sexp_nth_mpi(l2, 1, GCRYMPI_FMT_USG);
gcry_sexp_release(l2);
gcry_sexp_release(l1);
return result;
}
static void check_x931_derived_key(int what) {
static struct {
const char *param;
const char *expected_d;
} testtable[] = {
{/* First example from X9.31 (D.1.1). */
"(genkey\n"
" (rsa\n"
" (nbits 4:1024)\n"
" (rsa-use-e 1:3)\n"
" (derive-parms\n"
" (Xp1 #1A1916DDB29B4EB7EB6732E128#)\n"
" (Xp2 #192E8AAC41C576C822D93EA433#)\n"
" (Xp #D8CD81F035EC57EFE822955149D3BFF70C53520D\n"
" 769D6D76646C7A792E16EBD89FE6FC5B605A6493\n"
" 39DFC925A86A4C6D150B71B9EEA02D68885F5009\n"
" B98BD984#)\n"
" (Xq1 #1A5CF72EE770DE50CB09ACCEA9#)\n"
" (Xq2 #134E4CAA16D2350A21D775C404#)\n"
" (Xq #CC1092495D867E64065DEE3E7955F2EBC7D47A2D\n"
" 7C9953388F97DDDC3E1CA19C35CA659EDC2FC325\n"
" 6D29C2627479C086A699A49C4C9CEE7EF7BD1B34\n"
" 321DE34A#))))\n",
"1CCDA20BCFFB8D517EE9666866621B11822C7950D55F4BB5BEE37989A7D173"
"12E326718BE0D79546EAAE87A56623B919B1715FFBD7F16028FC4007741961"
"C88C5D7B4DAAAC8D36A98C9EFBB26C8A4A0E6BC15B358E528A1AC9D0F042BE"
"B93BCA16B541B33F80C933A3B769285C462ED5677BFE89DF07BED5C127FD13"
"241D3C4B"},
{
/* Second example from X9.31 (D.2.1). */
"(genkey\n"
" (rsa\n"
" (nbits 4:1536)\n"
" (rsa-use-e 1:3)\n"
" (derive-parms\n"
" (Xp1 #18272558B61316348297EACA74#)\n"
" (Xp2 #1E970E8C6C97CEF91F05B0FA80#)\n"
" (Xp #F7E943C7EF2169E930DCF23FE389EF7507EE8265\n"
" 0D42F4A0D3A3CEFABE367999BB30EE680B2FE064\n"
" 60F707F46005F8AA7CBFCDDC4814BBE7F0F8BC09\n"
" 318C8E51A48D134296E40D0BBDD282DCCBDDEE1D\n"
" EC86F0B1C96EAFF5CDA70F9AEB6EE31E#)\n"
" (Xq1 #11FDDA6E8128DC1629F75192BA#)\n"
" (Xq2 #18AB178ECA907D72472F65E480#)\n"
" (Xq #C47560011412D6E13E3E7D007B5C05DBF5FF0D0F\n"
" CFF1FA2070D16C7ABA93EDFB35D8700567E5913D\n"
" B734E3FBD15862EBC59FA0425DFA131E549136E8\n"
" E52397A8ABE4705EC4877D4F82C4AAC651B33DA6\n"
" EA14B9D5F2A263DC65626E4D6CEAC767#))))\n",
"1FB56069985F18C4519694FB71055721A01F14422DC901C35B03A64D4A5BD1"
"259D573305F5B056AC931B82EDB084E39A0FD1D1A86CC5B147A264F7EF4EB2"
"0ED1E7FAAE5CAE4C30D5328B7F74C3CAA72C88B70DED8EDE207B8629DA2383"
"B78C3CE1CA3F9F218D78C938B35763AF2A8714664CC57F5CECE2413841F5E9"
"EDEC43B728E25A41BF3E1EF8D9EEE163286C9F8BF0F219D3B322C3E4B0389C"
"2E8BB28DC04C47DA2BF38823731266D2CF6CC3FC181738157624EF051874D0"
"BBCCB9F65C83"
/* Note that this example in X9.31 gives this value for D:
"7ED581A6617C6311465A53EDC4155C86807C5108B724070D6C0E9935296F44"
"96755CCC17D6C15AB24C6E0BB6C2138E683F4746A1B316C51E8993DFBD3AC8"
"3B479FEAB972B930C354CA2DFDD30F2A9CB222DC37B63B7881EE18A7688E0E"
"DE30F38728FE7C8635E324E2CD5D8EBCAA1C51993315FD73B38904E107D7A7"
"B7B10EDCA3896906FCF87BE367BB858CA1B27E2FC3C8674ECC8B0F92C0E270"
"BA2ECA3701311F68AFCE208DCC499B4B3DB30FF0605CE055D893BC1461D342"
"EF32E7D9720B"
This is a bug in X9.31, obviously introduced by using
d = e^{-1} mod (p-1)(q-1)
instead of using the universal exponent as required by 4.1.3:
d = e^{-1} mod lcm(p-1,q-1)
The examples in X9.31 seem to be pretty buggy, see
cipher/primegen.c for another bug. Not only that I had to
spend 100 USD for the 66 pages of the document, it also took
me several hours to figure out that the bugs are in the
document and not in my code.
*/
},
{/* First example from NIST RSAVS (B.1.1). */
"(genkey\n"
" (rsa\n"
" (nbits 4:1024)\n"
" (rsa-use-e 1:3)\n"
" (derive-parms\n"
" (Xp1 #1ed3d6368e101dab9124c92ac8#)\n"
" (Xp2 #16e5457b8844967ce83cab8c11#)\n"
" (Xp #b79f2c2493b4b76f329903d7555b7f5f06aaa5ea\n"
" ab262da1dcda8194720672a4e02229a0c71f60ae\n"
" c4f0d2ed8d49ef583ca7d5eeea907c10801c302a\n"
" cab44595#)\n"
" (Xq1 #1a5d9e3fa34fb479bedea412f6#)\n"
" (Xq2 #1f9cca85f185341516d92e82fd#)\n"
" (Xq #c8387fd38fa33ddcea6a9de1b2d55410663502db\n"
" c225655a9310cceac9f4cf1bce653ec916d45788\n"
" f8113c46bc0fa42bf5e8d0c41120c1612e2ea8bb\n"
" 2f389eda#))))\n",
"<KEY>"
"f237e8f693dd16c23e7adecc40279dc6877c62ab541df5849883a5254fccfd"
"4072a657b7f4663953930346febd6bbd82f9a499038402cbf97fd5f068083a"
"c81ad0335c4aab0da19cfebe060a1bac7482738efafea078e21df785e56ea0"
"dc7e8feb"},
{/* Second example from NIST RSAVS (B.1.1). */
"(genkey\n"
" (rsa\n"
" (nbits 4:1536)\n"
" (rsa-use-e 1:3)\n"
" (derive-parms\n"
" (Xp1 #1e64c1af460dff8842c22b64d0#)\n"
" (Xp2 #1e948edcedba84039c81f2ac0c#)\n"
" (Xp #c8c67df894c882045ede26a9008ab09ea0672077\n"
" d7bc71d412511cd93981ddde8f91b967da404056\n"
" c39f105f7f239abdaff92923859920f6299e82b9\n"
" 5bd5b8c959948f4a034d81613d6235a3953b49ce\n"
" 26974eb7bb1f14843841281b363b9cdb#)\n"
" (Xq1 #1f3df0f017ddd05611a97b6adb#)\n"
" (Xq2 #143edd7b22d828913abf24ca4d#)\n"
" (Xq #f15147d0e7c04a1e3f37adde802cdc610999bf7a\n"
" b0088434aaeda0c0ab3910b14d2ce56cb66bffd9\n"
" 7552195fae8b061077e03920814d8b9cfb5a3958\n"
" b3a82c2a7fc97e55db543948d3396289245336ec\n"
" 9e3cb308cc655aebd766340da8921383#))))\n",
"1f8b19f3f5f2ac9fc599f110cad403dcd9bdf5f7f00fb2790e78e820398184"
"<KEY>"
"<KEY>"
"0f473e230c41b5e4c86e27c5a5029d82c811c88525d0269b95bd2ff272994a"
"<KEY>"
"8b4a2f88f4a47e71c3edd35fdf83f547ea5c2b532975c551ed5268f748b2c4"
"2ccf8a84835b"}};
gpg_error_t err;
gcry_sexp_t key_spec = NULL, key = NULL, pub_key = NULL, sec_key = NULL;
gcry_mpi_t d_expected = NULL, d_have = NULL;
if (what < 0 && what >= sizeof testtable) die("invalid WHAT value\n");
err = gcry_sexp_new(&key_spec, testtable[what].param, 0, 1);
if (err)
die("error creating S-expression [%d]: %s\n", what, gpg_strerror(err));
{
unsigned nbits;
err = _gcry_pk_util_get_nbits(key_spec, &nbits);
if (err) die("nbits not found\n");
if (gcry_fips_mode_active() && nbits < 2048) {
info("RSA key test with %d bits skipped in fips mode\n", nbits);
goto leave;
}
}
err = gcry_pk_genkey(&key, key_spec);
gcry_sexp_release(key_spec);
if (err) {
fail("error generating RSA key [%d]: %s\n", what, gpg_strerror(err));
goto leave;
}
pub_key = gcry_sexp_find_token(key, "public-key", 0);
if (!pub_key) die("public part missing in key [%d]\n", what);
sec_key = gcry_sexp_find_token(key, "private-key", 0);
if (!sec_key) die("private part missing in key [%d]\n", what);
err = gcry_mpi_scan(&d_expected, GCRYMPI_FMT_HEX, testtable[what].expected_d,
0, NULL);
if (err) die("error converting string [%d]\n", what);
if (verbose > 1) show_sexp("generated key:\n", key);
d_have = key_param_from_sexp(sec_key, "rsa", "d");
if (!d_have) die("parameter d not found in RSA secret key [%d]\n", what);
if (gcry_mpi_cmp(d_expected, d_have)) {
show_sexp(NULL, sec_key);
die("parameter d does match expected value [%d]\n", what);
}
leave:
gcry_mpi_release(d_expected);
gcry_mpi_release(d_have);
gcry_sexp_release(key);
gcry_sexp_release(pub_key);
gcry_sexp_release(sec_key);
}
static void check_ecc_sample_key(void) {
static const char ecc_private_key[] =
"(private-key\n"
" (ecdsa\n"
" (curve \"NIST P-256\")\n"
" (q #04D4F6A6738D9B8D3A7075C1E4EE95015FC0C9B7E4272D2BEB6644D3609FC781"
"B71F9A8072F58CB66AE2F89BB12451873ABF7D91F9E1FBF96BF2F70E73AAC9A283#)\n"
" (d #5A1EF0035118F19F3110FB81813D3547BCE1E5BCE77D1F744715E1D5BBE70378#)"
"))";
static const char ecc_private_key_wo_q[] =
"(private-key\n"
" (ecdsa\n"
" (curve \"NIST P-256\")\n"
" (d #5A1EF0035118F19F3110FB81813D3547BCE1E5BCE77D1F744715E1D5BBE70378#)"
"))";
static const char ecc_public_key[] =
"(public-key\n"
" (ecdsa\n"
" (curve \"NIST P-256\")\n"
" (q #04D4F6A6738D9B8D3A7075C1E4EE95015FC0C9B7E4272D2BEB6644D3609FC781"
"B71F9A8072F58CB66AE2F89BB12451873ABF7D91F9E1FBF96BF2F70E73AAC9A283#)"
"))";
static const char hash_string[] =
"(data (flags raw)\n"
" (value #00112233445566778899AABBCCDDEEFF"
/* */ "000102030405060708090A0B0C0D0E0F#))";
static const char hash2_string[] =
"(data (flags raw)\n"
" (hash sha1 #00112233445566778899AABBCCDDEEFF"
/* */
"000102030405060708090A0B0C0D0E0F"
/* */
"000102030405060708090A0B0C0D0E0F"
/* */ "00112233445566778899AABBCCDDEEFF#))";
/* hash2, but longer than curve length, so it will be truncated */
static const char hash3_string[] =
"(data (flags raw)\n"
" (hash sha1 #00112233445566778899AABBCCDDEEFF"
/* */
"000102030405060708090A0B0C0D0E0F"
/* */
"000102030405060708090A0B0C0D0E0F"
/* */
"00112233445566778899AABBCCDDEEFF"
/* */ "000102030405060708090A0B0C0D0E0F#))";
gpg_error_t err;
gcry_sexp_t key, hash, hash2, hash3, sig, sig2;
if (verbose) fprintf(stderr, "Checking sample ECC key.\n");
if ((err = gcry_sexp_new(&hash, hash_string, 0, 1)))
die("line %d: %s", __LINE__, gpg_strerror(err));
if ((err = gcry_sexp_new(&hash2, hash2_string, 0, 1)))
die("line %d: %s", __LINE__, gpg_strerror(err));
if ((err = gcry_sexp_new(&hash3, hash3_string, 0, 1)))
die("line %d: %s", __LINE__, gpg_strerror(err));
if ((err = gcry_sexp_new(&key, ecc_private_key, 0, 1)))
die("line %d: %s", __LINE__, gpg_strerror(err));
if ((err = gcry_pk_sign(&sig, hash, key)))
die("gcry_pk_sign failed: %s", gpg_strerror(err));
gcry_sexp_release(key);
if ((err = gcry_sexp_new(&key, ecc_public_key, 0, 1)))
die("line %d: %s", __LINE__, gpg_strerror(err));
if ((err = gcry_pk_verify(sig, hash, key)))
die("gcry_pk_verify failed: %s", gpg_strerror(err));
/* Verify hash truncation */
gcry_sexp_release(key);
if ((err = gcry_sexp_new(&key, ecc_private_key, 0, 1)))
die("line %d: %s", __LINE__, gpg_strerror(err));
if ((err = gcry_pk_sign(&sig2, hash2, key)))
die("gcry_pk_sign failed: %s", gpg_strerror(err));
gcry_sexp_release(sig);
if ((err = gcry_pk_sign(&sig, hash3, key)))
die("gcry_pk_sign failed: %s", gpg_strerror(err));
gcry_sexp_release(key);
if ((err = gcry_sexp_new(&key, ecc_public_key, 0, 1)))
die("line %d: %s", __LINE__, gpg_strerror(err));
if ((err = gcry_pk_verify(sig, hash2, key)))
die("gcry_pk_verify failed: %s", gpg_strerror(err));
if ((err = gcry_pk_verify(sig2, hash3, key)))
die("gcry_pk_verify failed: %s", gpg_strerror(err));
/* Now try signing without the Q parameter. */
gcry_sexp_release(key);
if ((err = gcry_sexp_new(&key, ecc_private_key_wo_q, 0, 1)))
die("line %d: %s", __LINE__, gpg_strerror(err));
gcry_sexp_release(sig);
if ((err = gcry_pk_sign(&sig, hash, key)))
die("gcry_pk_sign without Q failed: %s", gpg_strerror(err));
gcry_sexp_release(key);
if ((err = gcry_sexp_new(&key, ecc_public_key, 0, 1)))
die("line %d: %s", __LINE__, gpg_strerror(err));
if ((err = gcry_pk_verify(sig, hash, key)))
die("gcry_pk_verify signed without Q failed: %s", gpg_strerror(err));
gcry_sexp_release(sig);
gcry_sexp_release(sig2);
gcry_sexp_release(key);
gcry_sexp_release(hash);
gcry_sexp_release(hash2);
gcry_sexp_release(hash3);
}
static void check_ed25519ecdsa_sample_key(void) {
static const char ecc_private_key[] =
"(private-key\n"
" (ecc\n"
" (curve \"Ed25519\")\n"
" (q #044C056555BE4084BB3D8D8895FDF7C2893DFE0256251923053010977D12658321"
" "
"156D1ADDC07987713A418783658B476358D48D582DB53233D9DED3C1C2577B04#)"
" (d #09A0C38E0F1699073541447C19DA12E3A07A7BFDB0C186E4AC5BCE6F23D55252#)"
"))";
static const char ecc_private_key_wo_q[] =
"(private-key\n"
" (ecc\n"
" (curve \"Ed25519\")\n"
" (d #09A0C38E0F1699073541447C19DA12E3A07A7BFDB0C186E4AC5BCE6F23D55252#)"
"))";
static const char ecc_public_key[] =
"(public-key\n"
" (ecc\n"
" (curve \"Ed25519\")\n"
" (q #044C056555BE4084BB3D8D8895FDF7C2893DFE0256251923053010977D12658321"
" "
"156D1ADDC07987713A418783658B476358D48D582DB53233D9DED3C1C2577B04#)"
"))";
static const char ecc_public_key_comp[] =
"(public-key\n"
" (ecc\n"
" (curve \"Ed25519\")\n"
" (q #047b57c2c1d3ded93332b52d588dd45863478b658387413a718779c0dd1a6d95#)"
"))";
static const char hash_string[] =
"(data (flags rfc6979)\n"
" (hash sha256 #00112233445566778899AABBCCDDEEFF"
/* */ "000102030405060708090A0B0C0D0E0F#))";
gpg_error_t err;
gcry_sexp_t key, hash, sig;
if (verbose) fprintf(stderr, "Checking sample Ed25519/ECDSA key.\n");
/* Sign. */
if ((err = gcry_sexp_new(&hash, hash_string, 0, 1)))
die("line %d: %s", __LINE__, gpg_strerror(err));
if ((err = gcry_sexp_new(&key, ecc_private_key, 0, 1)))
die("line %d: %s", __LINE__, gpg_strerror(err));
if ((err = gcry_pk_sign(&sig, hash, key)))
die("gcry_pk_sign failed: %s", gpg_strerror(err));
/* Verify. */
gcry_sexp_release(key);
if ((err = gcry_sexp_new(&key, ecc_public_key, 0, 1)))
die("line %d: %s", __LINE__, gpg_strerror(err));
if ((err = gcry_pk_verify(sig, hash, key)))
die("gcry_pk_verify failed: %s", gpg_strerror(err));
/* Verify again using a compressed public key. */
gcry_sexp_release(key);
if ((err = gcry_sexp_new(&key, ecc_public_key_comp, 0, 1)))
die("line %d: %s", __LINE__, gpg_strerror(err));
if ((err = gcry_pk_verify(sig, hash, key)))
die("gcry_pk_verify failed (comp): %s", gpg_strerror(err));
/* Sign without a Q parameter. */
gcry_sexp_release(key);
if ((err = gcry_sexp_new(&key, ecc_private_key_wo_q, 0, 1)))
die("line %d: %s", __LINE__, gpg_strerror(err));
gcry_sexp_release(sig);
if ((err = gcry_pk_sign(&sig, hash, key)))
die("gcry_pk_sign w/o Q failed: %s", gpg_strerror(err));
/* Verify. */
gcry_sexp_release(key);
if ((err = gcry_sexp_new(&key, ecc_public_key, 0, 1)))
die("line %d: %s", __LINE__, gpg_strerror(err));
if ((err = gcry_pk_verify(sig, hash, key)))
die("gcry_pk_verify signed w/o Q failed: %s", gpg_strerror(err));
/* Verify again using a compressed public key. */
gcry_sexp_release(key);
if ((err = gcry_sexp_new(&key, ecc_public_key_comp, 0, 1)))
die("line %d: %s", __LINE__, gpg_strerror(err));
if ((err = gcry_pk_verify(sig, hash, key)))
die("gcry_pk_verify signed w/o Q failed (comp): %s", gpg_strerror(err));
extract_cmp_data(sig, "r", ("a63123a783ef29b8276e08987daca4"
"655d0179e22199bf63691fd88eb64e15"));
extract_cmp_data(sig, "s", ("0d9b45c696ab90b96b08812b485df185"
"623ddaf5d02fa65ca5056cb6bd0f16f1"));
gcry_sexp_release(sig);
gcry_sexp_release(key);
gcry_sexp_release(hash);
}
int main(int argc, char **argv) {
int i;
if (argc > 1 && !strcmp(argv[1], "--verbose"))
verbose = 1;
else if (argc > 1 && !strcmp(argv[1], "--debug")) {
verbose = 2;
debug = 1;
}
xgcry_control(GCRYCTL_DISABLE_SECMEM, 0);
if (!gcry_check_version(GCRYPT_VERSION)) die("version mismatch\n");
xgcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0);
if (debug) xgcry_control(GCRYCTL_SET_DEBUG_FLAGS, 1u, 0);
/* No valuable keys are create, so we can speed up our RNG. */
xgcry_control(GCRYCTL_ENABLE_QUICK_RANDOM, 0);
for (i = 0; i < 2; i++) check_run();
for (i = 0; i < 4; i++) check_x931_derived_key(i);
check_ecc_sample_key();
if (!gcry_fips_mode_active()) check_ed25519ecdsa_sample_key();
return !!error_count;
}
|
zhoujy3016/renren-security | evaluation_admin/src/main/java/io/renren/modules/eva/service/BteLessonTypeService.java | package io.renren.modules.eva.service;
import com.baomidou.mybatisplus.extension.service.IService;
import io.renren.common.utils.PageUtils;
import io.renren.modules.eva.entity.BteLessonTypeEntity;
import java.util.Map;
/**
*
*
* @author chenshun
* @email <EMAIL>
* @date 2018-07-02 09:44:42
*/
public interface BteLessonTypeService extends IService<BteLessonTypeEntity> {
PageUtils queryPage(Map<String, Object> params);
void insertLessonType(BteLessonTypeEntity bteLessonType);
void updateLessonType(BteLessonTypeEntity bteLessonType);
void deleteLessonType(Integer[] ids);
}
|
magicmarvman/serenity | Libraries/LibJS/Tests/automatic-semicolon-insertion.js | load("test-common.js");
/**
* This file tests automatic semicolon insertion rules.
* If this file produces syntax errors, something is wrong.
*/
function bar() {
// https://github.com/SerenityOS/serenity/issues/1829
if (1)
return 1;
else
return 0;
if (1)
return 1
else
return 0
if (1)
return 1
else
return 0;
}
function foo() {
for (var i = 0; i < 4; i++) {
break // semicolon inserted here
continue // semicolon inserted here
}
var j // semicolon inserted here
do {
} while (1 === 2) // semicolon inserted here
return // semicolon inserted here
1;
var curly/* semicolon inserted here */}
try {
assert(foo() === undefined);
console.log("PASS");
} catch (e) {
console.log("FAIL: " + e);
}
// This vardecl must appear exactly at the end of the file (no newline or whitespace after it)
var eof
|
YJBeetle/QtAndroidAPI | android-31/android/security/identity/WritableIdentityCredential.cpp | <gh_stars>10-100
#include "../../../JByteArray.hpp"
#include "./PersonalizationData.hpp"
#include "./WritableIdentityCredential.hpp"
namespace android::security::identity
{
// Fields
// QJniObject forward
WritableIdentityCredential::WritableIdentityCredential(QJniObject obj) : JObject(obj) {}
// Constructors
// Methods
JObject WritableIdentityCredential::getCredentialKeyCertificateChain(JByteArray arg0) const
{
return callObjectMethod(
"getCredentialKeyCertificateChain",
"([B)Ljava/util/Collection;",
arg0.object<jbyteArray>()
);
}
JByteArray WritableIdentityCredential::personalize(android::security::identity::PersonalizationData arg0) const
{
return callObjectMethod(
"personalize",
"(Landroid/security/identity/PersonalizationData;)[B",
arg0.object()
);
}
} // namespace android::security::identity
|
antoine-spahr/X-ray-Anomaly-Detection | Code/src/preprocessing/segmentation.py | <filename>Code/src/preprocessing/segmentation.py<gh_stars>1-10
import matplotlib.pyplot as plt
import matplotlib
import skimage.draw
import skimage.morphology
import skimage
import numpy as np
import shapely.geometry
import pandas as pd
import scipy.spatial.distance as dist
import PIL.Image
import PIL.ImageDraw
def segment2(img, factors=(0.9,1)):
"""
Segment the X-ray body part of the image using a Yen Thresholding segmented
with an hysteresis threshold. The results is then morphologically openened
with a disk of radius 10. The coutour of the binary mask are extracted, the
largest one is kept and holes are removed to provide the final mask.
----------
INPUT
|---- img (np.array 2D or 3D) the image to segement. It can be either a
| Greyscale or Color image.
|---- factors (tuple (low, high)) the hystersis thresholds used in the
| scikit-image function 'apply_hysteresis_threshold'.
OUTPUT
|---- mask (np.array 2D) the segmentation binary mask.
"""
if img.ndim == 3 : img = skimage.color.rgb2gray(img)
pad_val = 5
img = skimage.exposure.equalize_hist(img)
thrs = skimage.filters.threshold_yen(img)
mask = skimage.filters.apply_hysteresis_threshold(img, thrs*factors[0], thrs*factors[1])
mask = skimage.morphology.opening(mask, selem=skimage.morphology.disk(10))
# pad to avoid boundary effect
mask = skimage.util.pad(mask, pad_width=pad_val)
# get polygons
poly = skimage.measure.find_contours(mask, 0.5)
if len(poly) > 0:
# remove padding
poly = [p-pad_val for p in poly]
# Keep only larger polygon
poly = [shapely.geometry.Polygon(p) for p in poly]
main_poly = max(poly, key=lambda a: a.area)
mask = np.zeros_like(img, np.uint8)
rc = np.array(list(main_poly.exterior.coords))
rr , cc = skimage.draw.polygon(rc[:,0], rc[:,1])
mask[rr, cc] = 1
#poly.remove(main_poly)
for p in [p for p in poly if p.area < main_poly.area]:
if main_poly.contains(p):
rc = np.array(list(p.exterior.coords))
rr, cc = skimage.draw.polygon(rc[:,0], rc[:,1])
mask[rr, cc] = 0
else:
mask = mask[pad_val:-pad_val, pad_val:-pad_val]
return mask
def segment(img, factors=(0.9,1)):
"""
Segment the X-ray body part of the image using a Yen Thresholding segmented
with an hysteresis threshold. The results is then morphologically openened
with a disk of radius 10. The coutour of the binary mask are extracted, the
largest one is kept and holes are removed to provide the final mask.
----------
INPUT
|---- img (np.array 2D or 3D) the image to segement. It can be either a
| Greyscale or Color image.
|---- factors (tuple (low, high)) the hystersis thresholds used in the
| scikit-image function 'apply_hysteresis_threshold'.
OUTPUT
|---- mask (np.array 2D) the segmentation binary mask.
"""
if img.ndim == 3 : img = skimage.color.rgb2gray(img)
pad_val = 5
img = skimage.exposure.equalize_hist(img)
thrs = skimage.filters.threshold_yen(img)
mask = skimage.filters.apply_hysteresis_threshold(img, thrs*factors[0], thrs*factors[1])
mask = skimage.morphology.binary_opening(mask, selem=skimage.morphology.disk(10))
# pad to avoid boundary effect
mask = skimage.util.pad(mask, pad_width=pad_val)
# get polygons
poly = skimage.measure.find_contours(mask, 0.5)
if len(poly) > 0:
# remove padding
poly = [p-pad_val for p in poly]
# Keep only larger polygon
poly = [shapely.geometry.Polygon(p) for p in poly]
main_poly = max(poly, key=lambda a: a.area)
# get holes
poly = [p for p in poly if (main_poly.contains(p)) and (p.area < main_poly.area)]
# draw mask
mask = PIL.Image.new("1", img.shape[::-1], 0)
PIL.ImageDraw.Draw(mask).polygon([c[::-1] for c in list(main_poly.exterior.coords)], outline=1, fill=1)
for p in poly:
PIL.ImageDraw.Draw(mask).polygon([c[::-1] for c in list(p.exterior.coords)], outline=0, fill=0)
mask = np.array(mask)
else:
mask = mask[pad_val:-pad_val, pad_val:-pad_val]
return mask
def find_best_mask(img, tol_factor=0.1, search_res=0.1, search_range=(0.2,1)):
"""
Find the best masks over different thresholding factors. The best mask is the
one minimizing the correlation distance between the image and the computed mask.
To keep a lower 'low' threshold as much as possible, a tolerance on the minimum
correlation is imposed : the new correlation (for higher threhold) must be
smaller than the minimum correlation distance minus tol_factor% of the current range.
----------
INPUT
|---- img (np.array 2D or 3D) the image to segement. It can be either a
| Greyscale or Color image.
|---- tol_factor (float) the tolerance on the minimum correlation distance
|---- search_res (float) the resolution of the factor search
|---- search range (tuple (lower, upper)) the range over which the factor
| search is done
OUTPUT
|---- best_mask (np.array 2D) the best segmentation binary mask.
"""
if img.ndim == 3 : img = skimage.color.rgb2gray(img)
min_corr = np.inf
max_corr = -np.inf
best_mask = np.ones_like(img)
for i in np.arange(search_range[0], search_range[1]+0.01, search_res):
mask = segment(img, factors=(i,1))
# check if mask is constant
if mask.min() != mask.max():
corr = dist.correlation(img.flatten(), mask.flatten())
else:
corr = np.nan
# upadte if new correlation distance is lower
if corr > max_corr :
max_corr = corr
if corr < (min_corr - tol_factor * (max_corr - corr)): # tolerance on minimum
min_corr = corr
best_mask = mask
return best_mask
# %% ###########################################################################
################################################################################
################################################################################
# IN_DATA_PATH = '../../../data/RAW/'
# OUT_DATA_PATH = '../../../data/PROCESSED/'
# DATAINFO_PATH = '../../../data/'
#
# df = pd.read_csv(DATAINFO_PATH + 'data_info.csv')
# fn = df.loc[df.body_part == 'HAND', 'filename']
# img = skimage.io.imread(IN_DATA_PATH + fn.iloc[589])
# plt.imshow(img, cmap='Greys_r')
# #img = skimage.io.imread(IN_DATA_PATH + 'XR_HUMERUS/patient00119/study1_negative/image1.png')
# # invert image if negatives (i.e. if too bright)
# if img.mean() > 125:
# img = np.invert(img)
#
# best_mask = find_best_mask(img, tol_factor=0.1, \
# search_res=0.1, search_range=(0.2,1))
#
# # %%
# if img.ndim == 3 : img = skimage.color.rgb2gray(img)
# fig, axs = plt.subplots(1,2,figsize=(10,6))
# axs[0].imshow(img, cmap='Greys_r')
# m = np.ma.masked_where(best_mask == 0, best_mask)
# axs[0].imshow(m, cmap = matplotlib.colors.ListedColormap(['white', 'crimson']), \
# vmin=0, vmax=1, alpha=0.2, zorder=1)
# axs[0].set_title('Image and overlay of the best mask')
# axs[1].imshow(best_mask, cmap='Greys_r', vmin=0, vmax=1)
# axs[1].set_title('Best mask')
# fig.tight_layout()
# plt.show()
#
# # %% Check bright images
# img_mean = []
# bright = []
# for i in range(fn.shape[0]):
# m = np.mean(skimage.io.imread(IN_DATA_PATH + fn.iloc[i]))
# if m > 125: bright.append(fn.iloc[i])
# img_mean.append(m)
#
# fig, axs = plt.subplots(20,10, figsize=(10,20))
# for f, ax in zip(bright, axs.reshape(-1)):
# ax.set_axis_off()
# ax.imshow(skimage.io.imread(IN_DATA_PATH + f), cmap='Greys_r')
# fig.tight_layout()
# plt.show()
#
# fig, ax = plt.subplots(1,1,figsize=(9,7))
# ax.hist(img_mean, color='gray', bins=150)
# plt.show()
#
#
#
#
#
#
#
#
#
# # %% ##########
# import time
# IN_DATA_PATH = '../../../data/RAW/'
# OUT_DATA_PATH = '../../../data/PROCESSED/'
# DATAINFO_PATH = '../../../data/'
#
# df = pd.read_csv(DATAINFO_PATH + 'data_info.csv')
# fn = df.loc[df.body_part == 'HAND', 'filename']
# img = skimage.io.imread(IN_DATA_PATH + fn.iloc[589])
#
# plt.imshow(img, cmap='Greys_r')
# #%%
# t = []
# for _ in range(20):
# t0 = time.time()
# mask = find_best_mask(img, tol_factor=0.1, search_res=0.1, search_range=(0.2,1))
# t1 = time.time()
# t.append(t1-t0)
# t = np.array(t)
# print(f'{t.mean()} +/- {t.std()}')
#
# # %%
# t0 = time.time()
# mask = find_best_mask(img, tol_factor=0.1, search_res=0.1, search_range=(0.2,1))
# skimage.io.imsave('test_m.png', skimage.img_as_ubyte(mask), check_contrast=False)
# t1 = time.time()
# print(t1-t0)
# plt.imshow(mask, cmap='Greys_r')
|
CTLocalGovTeam/map-and-app-gallery-template | nls/lt/localizedStrings.js | /*global define */
/*
| Copyright 2014 Esri
|
| Licensed under the Apache License, Version 2.0 (the "License");
| you may not use this file except in compliance with the License.
| You may obtain a copy of the License at
|
| http://www.apache.org/licenses/LICENSE-2.0
|
| Unless required by applicable law or agreed to in writing, software
| distributed under the License is distributed on an "AS IS" BASIS,
| WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
| See the License for the specific language governing permissions and
| limitations under the License.
*/
define({
tagHeaderText: "Raktažodžiai",
expandGroupDescText: "Daugiau",
shrinkGroupDescText: "Mažiau",
layoutText: "Maketas",
signInText: "Prisijungti",
signOutText: "Atsijungti",
showNullValue: "Neturima",
detailsDisplayText: "Detali informacija",
sortByViewText: "Rūšiuoti pagal peržiūras",
sortByDateText: "Rūšiuoti pagal datą",
gridViewTitle: "Tinklelio vaizdas",
listViewTitle: "Sąrašo vaizdas",
appHeaderTitle: "Pradžia",
allText: "VISKAS",
orgText: "ORG",
grpText: "GRP",
groupLogoText: "Grupės logotipas",
sortByTextMobile: "Rūšiuoti pagal",
viewTextMobile: "Peržiūros",
dateTextMobile: "Data",
appTypeText: "Tipas",
appOwnerText: "Savininkas",
tryItButtonText: "Išbandykite dabar",
downloadButtonText: "Atsiųsti",
appDesText: "Aprašas",
reviewText: "Komentarai",
itemDetailsLegendTab: "LEGENDA",
itemDetailsInfoTab: "INFORMACIJA",
tagsText: "Raktažodžiai",
sizeText: "Dydis",
accessConstraintsText: "Naudojimo sąlygos ir teisiniai apribojimai",
numberOfCommentsText: "Komentarai",
numberOfRatingsText: "Vertinimai",
numberOfViewsText: "Peržiūros",
noResultsText: "Rezultatų nerasta.",
backToGalleryText: "Galerija",
backToMapButtonText: "Žemėlapis",
showMoreResultsGalleryText: "Rodyti daugiau rezultatų",
clearBtnTitle: "Valyti",
addressSearchBtnTitle: "Adreso paieška",
fullScreenBtnTitle: "Visas ekranas",
noLegendText: "Be legendos",
sizeUnitKB: "KB",
sizeUnitMB: "MB",
itemUnavailableText: "Šiame prietaise elementas nepasiekiamas.",
title: {
settingsBtnTitle: "Nuostatos",
itemSearchBtnTitle: "Elemento paieška",
infoBtnTitle: "Informacija",
sortByBtnTitle: "Rūšiuoti pagal",
layoutBtnTitle: "Maketas",
signInBtnTitle: "Prisijungti",
signOutBtnTitle: "Į_Sign Out_š",
geolocationBtnTitle: "Geolokacija"
},
errorMessages: {
emptyGroup: "Sukonfigūruotoje grupėje nėra duomenų užklausai įvykdyti.",
invalidSearch: "Rezultatų nerasta.",
invalidBasemapQuery: "Nepavyko gauti pagrindo žemėlapių grupės.",
falseConfigParams: "Būtinos konfigūracijos rakto reikšmės yra tuščios arba nevisiškai atitinka sluoksnio atributus. Šis pranešimas gali būti rodomas kelis kartus.",
invalidLocation: "Dabartinė vieta nerasta.",
invalidProjection: "Nepavyksta dabartinės vietos suprojektuoti ant žemėlapio.",
widgetNotLoaded: "Nepavyko įkelti valdiklių.",
minfontSizeGreater: "Konfigūracijos nustatymuose minimali šrifto dydžio reikšmė yra didesnė už maksimalią reikšmę.",
layerNotFound: "Nepavyksta gauti duomenų iš sluoksnių.",
unableToOpenItem: "Nepavyksta atidaryti elemento.",
wmsSpatialReferenceError: "WMS sluoksnio erdvinė charakteristika neatitinka žemėlapio erdvinės charakteristikos.",
noPublicItems: "Į_There are no public items in the configured group or no items have been shared with this group yet._š",
emptyUsernamePassword: "<PASSWORD>.",
noFullScreenSupport: "Esamoje naršyklėje viso ekrano režimas neveikia.",
notMemberOfOrg: "Į_You are not a member of this organization_š"
}
});
|
gurumobile/RemoteControlGalileoExam | RemoteControlGalileo/OpenGL/GLConstants.h | #ifndef LGT_ShaderUtilities_h
#define LGT_ShaderUtilities_h
#import <OpenGLES/ES2/gl.h>
#import <OpenGLES/ES2/glext.h>
namespace GL
{
extern GLfloat unitSquareVertices[8];
extern GLfloat originCentredSquareVertices[8];
extern GLfloat yPlaneUVs[8];
extern GLfloat yPlaneVertices[8];
extern GLfloat uvPlaneUVs[8];
extern GLfloat uPlaneVertices[8];
extern GLfloat vPlaneVertices[8];
}
#endif
|
chriszh123/ruiyi | ruoyi-fac/src/main/java/com/ruoyi/fac/mapper/FacFocusMapMapper.java | package com.ruoyi.fac.mapper;
import com.ruoyi.fac.model.FacFocusMap;
import com.ruoyi.fac.model.FacFocusMapExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;
public interface FacFocusMapMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table fac_focus_map
*
* @mbggenerated
*/
int countByExample(FacFocusMapExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table fac_focus_map
*
* @mbggenerated
*/
int deleteByExample(FacFocusMapExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table fac_focus_map
*
* @mbggenerated
*/
int insert(FacFocusMap record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table fac_focus_map
*
* @mbggenerated
*/
int insertSelective(FacFocusMap record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table fac_focus_map
*
* @mbggenerated
*/
List<FacFocusMap> selectByExample(FacFocusMapExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table fac_focus_map
*
* @mbggenerated
*/
int updateByExampleSelective(@Param("record") FacFocusMap record, @Param("example") FacFocusMapExample example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table fac_focus_map
*
* @mbggenerated
*/
int updateByExample(@Param("record") FacFocusMap record, @Param("example") FacFocusMapExample example);
} |
copslock/broadcom_cpri | sdk-6.5.20/src/bcm/dnx/algo/port_pp/algo_port_pp.c | <filename>sdk-6.5.20/src/bcm/dnx/algo/port_pp/algo_port_pp.c
/**
* \file algo_port_pp.c
* Internal DNX Port PP Managment APIs
PIs This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file.
PIs
PIs Copyright 2007-2020 Broadcom Inc. All rights reserved.
*/
#ifdef BSL_LOG_MODULE
#error "BSL_LOG_MODULE redefined"
#endif
#define BSL_LOG_MODULE BSL_LS_BCMDNX_TEMPLATEMNGR
/**
* INCLUDE FILES:
* {
*/
#include <shared/shrextend/shrextend_debug.h>
#include <bcm/types.h>
#include <bcm/port.h>
#include <bcm_int/dnx/port/port_tpid.h>
#include <bcm_int/dnx/port/port_pp.h>
#include <bcm_int/dnx/algo/port_pp/algo_port_pp.h>
#include <bcm_int/dnx/algo/template_mngr/smart_template.h>
#include <soc/dnx/dnx_data/auto_generated/dnx_data_device.h>
#include <soc/dnx/dnx_data/auto_generated/dnx_data_port.h>
#include <soc/dnx/dnx_data/auto_generated/dnx_data_port_pp.h>
#include <soc/dnx/dnx_data/auto_generated/dnx_data_esem.h>
#include <soc/dnx/dnx_data/auto_generated/dnx_data_lif.h>
#include <bcm_int/dnx/switch/switch_tpid.h>
#include <bcm_int/dnx/algo/swstate/auto_generated/access/algo_port_pp_access.h>
#include <soc/dnxc/swstate/dnx_sw_state_dump.h>
/**
* }
*/
/**
* Force Forward
* {
*/
/**
* \brief - create the template manager used to track the traps used in force forward
*/
static shr_error_e
dnx_algo_port_pp_force_forward_init(
int unit)
{
dnx_algo_template_create_data_t create_info;
uint32 force_forward_template_data;
int nof_cores, nof_traps;
uint32 core_id;
SHR_FUNC_INIT_VARS(unit);
/** int vars */
sal_memset(&create_info, 0, sizeof(dnx_algo_template_create_data_t));
force_forward_template_data = -1;
/** create the template manager used to track the traps used in force forward */
create_info.flags = 0;
create_info.first_profile = 0;
create_info.nof_profiles = dnx_data_port.general.nof_pp_ports_get(unit);
create_info.max_references = dnx_data_port.general.nof_pp_ports_get(unit);
create_info.default_profile = 0;
create_info.data_size = sizeof(uint32);
create_info.default_data = &force_forward_template_data;
sal_strncpy(create_info.name, DNX_PORT_PP_FORCE_FORWARD_TEMPLATE, DNX_ALGO_TEMPLATE_MNGR_MAX_NAME_LENGTH - 1);
SHR_IF_ERR_EXIT(algo_port_pp_db.force_forward.mngr.alloc(unit));
for (core_id = 0; core_id < dnx_data_device.general.nof_cores_get(unit); core_id++)
{
SHR_IF_ERR_EXIT(algo_port_pp_db.force_forward.mngr.create(unit, core_id, &create_info, NULL));
}
/** allocate additional array to store the trap ids */
nof_cores = dnx_data_device.general.nof_cores_get(unit);
nof_traps = dnx_data_port.general.nof_pp_ports_get(unit);
SHR_IF_ERR_EXIT(algo_port_pp_db.force_forward.trap_id.alloc(unit, nof_cores, nof_traps));
exit:
SHR_FUNC_EXIT;
}
/**see .h file */
void
dnx_algo_port_pp_force_forward_template_cb(
int unit,
const void *data)
{
SW_STATE_PRETTY_PRINT_INIT_VARIABLES();
SW_STATE_PRETTY_PRINT_ADD_LINE(SW_STATE_PRETTY_PRINT_TYPE_UINT32, "force forward destination",
*((uint32 *) data), "force forward destination", NULL);
SW_STATE_PRETTY_PRINT_FINISH();
}
/**
* \brief -
* Intialize Port PP SIT profile algorithms.
* The function creats SIT profile Template profiles.
*
* \param [in] unit - relevant unit
*
* \return
* shr_error_e
*
* \remark
* * None
* \see
* dnx_algo_port_pp_init
*/
static shr_error_e
algo_port_sit_profile_template_init(
int unit)
{
dnx_algo_template_create_data_t data;
SHR_FUNC_INIT_VARS(unit);
/*
* Set a template for Port SIT profile
*/
sal_memset(&data, 0, sizeof(data));
data.first_profile = 0;
data.nof_profiles = dnx_data_port_pp.general.nof_egress_sit_profile_get(unit);
data.max_references = dnx_data_port.general.nof_pp_ports_get(unit) * dnx_data_device.general.nof_cores_get(unit);
data.data_size = sizeof(dnx_sit_profile_t);
sal_strncpy(data.name, DNX_ALGO_EGRESS_PP_PORT_SIT_PROFILE_TEMPLATE, DNX_ALGO_TEMPLATE_MNGR_MAX_NAME_LENGTH - 1);
SHR_IF_ERR_EXIT(algo_port_pp_db.egress_pp_port_sit_profile.create(unit, &data, NULL));
exit:
SHR_FUNC_EXIT;
}
/*
* See header file algo_port_pp.h for description.
*/
void
dnx_algo_port_esem_access_cmd_template_print_cb(
int unit,
const void *data)
{
uint8 esem_access_id, app_db_id, esem_offset, default_profile, index;
dnx_esem_cmd_data_t *esem_cmd_data = (dnx_esem_cmd_data_t *) data;
SW_STATE_PRETTY_PRINT_INIT_VARIABLES();
for (index = 0; index < ESEM_ACCESS_IF_COUNT; index++)
{
if (esem_cmd_data->esem[index].valid == TRUE)
{
esem_access_id = index + 1;
app_db_id = esem_cmd_data->esem[index].app_db_id;
esem_offset = esem_cmd_data->esem[index].designated_offset;
default_profile = esem_cmd_data->esem[index].default_result_profile;
SW_STATE_PRETTY_PRINT_ADD_LINE(SW_STATE_PRETTY_PRINT_TYPE_UINT8,
"esem_access_if", esem_access_id, NULL, NULL);
SW_STATE_PRETTY_PRINT_ADD_LINE(SW_STATE_PRETTY_PRINT_TYPE_UINT8, "app_db_id", app_db_id, NULL, NULL);
SW_STATE_PRETTY_PRINT_ADD_LINE(SW_STATE_PRETTY_PRINT_TYPE_UINT8,
"designated_offset", esem_offset, NULL, NULL);
SW_STATE_PRETTY_PRINT_ADD_LINE(SW_STATE_PRETTY_PRINT_TYPE_UINT8,
"default_result_profile", default_profile, NULL, NULL);
}
}
SW_STATE_PRETTY_PRINT_FINISH();
return;
}
/**
* \brief -
* Create and Intialize the algorithm for esem access commands per template.
*
* \param [in] unit - relevant unit
*
* \return
* shr_error_e
*
* \remark
* None
* \see
* None
*/
static shr_error_e
algo_port_esem_access_cmd_template_init(
int unit)
{
dnx_algo_template_create_data_t template_data;
dnx_esem_cmd_data_t esem_cmd_data;
smart_template_create_info_t extra_info;
SHR_FUNC_INIT_VARS(unit);
/*
* initialize the templates data/properties
*/
sal_memset(&template_data, 0, sizeof(dnx_algo_template_create_data_t));
sal_memset(&esem_cmd_data, 0, sizeof(dnx_esem_cmd_data_t));
template_data.data_size = sizeof(dnx_esem_cmd_data_t);
template_data.default_data = &esem_cmd_data;
template_data.first_profile = 0;
template_data.default_profile = dnx_data_esem.access_cmd.no_action_get(unit);
template_data.flags = DNX_ALGO_TEMPLATE_CREATE_USE_DEFAULT_PROFILE |
DNX_ALGO_TEMPLATE_CREATE_USE_ADVANCED_ALGORITHM;
template_data.nof_profiles = dnx_data_esem.access_cmd.nof_cmds_get(unit);
template_data.max_references = dnx_data_port.general.nof_pp_ports_get(unit) +
dnx_data_lif.out_lif.nof_local_out_lifs_get(unit) + 1;
/*
* Use the smart template algorithm to allocate template and resource bitmap for range allocation
* and for even distribution
*/
template_data.advanced_algorithm = DNX_ALGO_TEMPLATE_ADVANCED_ALGORITHM_SMART_TEMPLATE_EVEN_DISTRIBUTION;
sal_strncpy(template_data.name, DNX_ALGO_TEMPLATE_ESEM_ACCESS_CMD, DNX_ALGO_TEMPLATE_MNGR_MAX_NAME_LENGTH - 1);
/*
* Extra info that the SMART_TEMPLATE_EVEN_DISTRIBUTION algorithm requires
*/
extra_info.resource_flags =
RESOURCE_TAG_BITMAP_CREATE_ALLOW_IGNORING_TAG | RESOURCE_TAG_BITMAP_CREATE_ALLOW_FORCING_TAG;
extra_info.resource_create_info.grain_size =
dnx_data_esem.access_cmd.nof_cmds_get(unit) / DNX_ALGO_PP_PORT_ESEM_CMD_RES_NOF_TAGS;
extra_info.resource_create_info.max_tag_value = extra_info.resource_create_info.grain_size;
SHR_IF_ERR_EXIT(algo_port_pp_db.esem.access_cmd.create(unit, &template_data, (void *) &extra_info));
exit:
SHR_FUNC_EXIT;
}
/**
* \brief -
* The function destroy esem-accesee-cmd template.
*
* \param [in] unit - relevant unit
*
* \return
* shr_error_e
*
* \remark
* * None
* \see
* algo_port_esem_access_cmd_template_init
*/
static shr_error_e
algo_port_esem_access_cmd_template_deinit(
int unit)
{
SHR_FUNC_INIT_VARS(unit);
/*
* Sw state will be deinit internal.
*/
SHR_EXIT();
exit:
SHR_FUNC_EXIT;
}
/**
* \brief -
* Create and Intialize the algorithm for esem default result profile.
*
* \param [in] unit - relevant unit
*
* \return
* shr_error_e
*
* \remark
* * None
* \see
* dnx_algo_port_pp_init
*/
static shr_error_e
algo_port_esem_default_result_profile_init(
int unit)
{
dnx_algo_res_create_data_t data;
SHR_FUNC_INIT_VARS(unit);
/*
* ESEM-DEFAULT-RESULT_PROFILE resource management
*/
sal_memset(&data, 0, sizeof(dnx_algo_res_create_data_t));
data.flags = 0;
data.first_element = 0;
data.nof_elements = dnx_data_esem.default_result_profile.nof_allocable_profiles_get(unit);
sal_strncpy(data.name, DNX_ALGO_ESEM_DEFAULT_RESULT_PROFILE, DNX_ALGO_RES_MNGR_MAX_NAME_LENGTH - 1);
SHR_IF_ERR_EXIT(algo_port_pp_db.esem_default_result_profile.create(unit, &data, NULL));
exit:
SHR_FUNC_EXIT;
}
/**
* \brief -
* The function destroy the esem-default-result-profile resource.
*
* \param [in] unit - relevant unit
*
* \return
* shr_error_e
*
* \remark
* * None
*
* \see
* algo_port_match_esem_default_result_profile_init
* dnx_algo_port_pp_deinit
*/
static shr_error_e
algo_port_esem_default_result_profile_deinit(
int unit)
{
SHR_FUNC_INIT_VARS(unit);
SHR_EXIT();
exit:
SHR_FUNC_EXIT;
}
/**
* \brief
* Create Template Manager for LB PP Port Profile enablers:
*/
static shr_error_e
dnx_algo_pp_port_lb_profile_template_init(
int unit)
{
dnx_algo_template_create_data_t data;
uint32 default_data;
SHR_FUNC_INIT_VARS(unit);
default_data = 0;
sal_memset(&data, 0, sizeof(dnx_algo_template_create_data_t));
data.data_size = sizeof(uint32);
data.default_data = &default_data;
data.default_profile = DEFAULT_PP_PORT_LB_PROFILE;
data.first_profile = 0;
data.flags = DNX_ALGO_TEMPLATE_CREATE_USE_DEFAULT_PROFILE;
data.nof_profiles = 4;
data.max_references = dnx_data_port.general.nof_pp_ports_get(unit) * dnx_data_device.general.nof_cores_get(unit);
sal_strncpy(data.name, DNX_ALGO_PP_PORT_LB_LAYER_PROFILE_ENABLERS, DNX_ALGO_TEMPLATE_MNGR_MAX_NAME_LENGTH - 1);
SHR_IF_ERR_EXIT(algo_port_pp_db.pp_port_lb_profile.create(unit, &data, NULL));
exit:
SHR_FUNC_EXIT;
}
/**
* \brief Allocate array to store recycle_app information
*/
static shr_error_e
dnx_algo_pp_port_recycle_app_init(
int unit)
{
int nof_cores = 0, core_id = 0;
SHR_FUNC_INIT_VARS(unit);
/** allocate array to store recycle_app information */
nof_cores = dnx_data_device.general.nof_cores_get(unit);
for (core_id = 0; core_id < nof_cores; core_id++)
{
SHR_IF_ERR_EXIT(algo_port_pp_db.recycle_app.alloc(unit, core_id));
}
exit:
SHR_FUNC_EXIT;
}
/*
* See header file algo_port_pp.h for description.
*/
void
dnx_algo_pp_port_lb_profile_print_entry_cb(
int unit,
const void *data)
{
uint32 *layers_disable = (uint32 *) data;
SW_STATE_PRETTY_PRINT_INIT_VARIABLES();
SW_STATE_PRETTY_PRINT_ADD_LINE(SW_STATE_PRETTY_PRINT_TYPE_UINT32, "Layers Disable", *layers_disable, NULL, NULL);
SW_STATE_PRETTY_PRINT_FINISH();
}
/**
* }
*/
/**
* Global Functions:
* {
*/
/*
* See header file algo_port_pp.h for description.
*/
shr_error_e
dnx_algo_port_pp_init(
int unit)
{
SHR_FUNC_INIT_VARS(unit);
SHR_IF_ERR_EXIT(algo_port_pp_db.init(unit));
/*
* Initialize force forward sw state
*/
SHR_IF_ERR_EXIT(dnx_algo_port_pp_force_forward_init(unit));
/*
* Initialize Port TPID Template profile
*/
SHR_IF_ERR_EXIT(algo_port_tpid_init(unit));
/*
* Initialize Port SIT profile template
*/
SHR_IF_ERR_EXIT(algo_port_sit_profile_template_init(unit));
/*
* Initialize ESEM access command template
*/
SHR_IF_ERR_EXIT(algo_port_esem_access_cmd_template_init(unit));
/*
* Initialize ESEM default result profile resource
*/
SHR_IF_ERR_EXIT(algo_port_esem_default_result_profile_init(unit));
/*
* Initialize pp port lb enablers vector template
*/
SHR_IF_ERR_EXIT(dnx_algo_pp_port_lb_profile_template_init(unit));
/*
* Initialize pp port recycle app
*/
SHR_IF_ERR_EXIT(dnx_algo_pp_port_recycle_app_init(unit));
exit:
SHR_FUNC_EXIT;
}
/*
* See header file algo_port_pp.h for description.
*/
shr_error_e
dnx_algo_port_pp_deinit(
int unit)
{
SHR_FUNC_INIT_VARS(unit);
SHR_IF_ERR_EXIT(algo_port_tpid_deinit(unit));
/*
* Destroy ESEM access command template
*/
SHR_IF_ERR_EXIT(algo_port_esem_access_cmd_template_deinit(unit));
/*
* Destroy ESEM default result profile resource
*/
SHR_IF_ERR_EXIT(algo_port_esem_default_result_profile_deinit(unit));
exit:
SHR_FUNC_EXIT;
}
/*
* See header file algo_port_pp.h for description.
*/
void
dnx_algo_egress_sit_profile_template_print_cb(
int unit,
const void *data)
{
dnx_sit_profile_t *sit_profile = (dnx_sit_profile_t *) data;
SW_STATE_PRETTY_PRINT_INIT_VARIABLES();
SW_STATE_PRETTY_PRINT_ADD_LINE(SW_STATE_PRETTY_PRINT_TYPE_INT, "tag_type", sit_profile->tag_type,
"Sit tag type, see dbal_enum_value_field_sit_tag_type_e", NULL);
SW_STATE_PRETTY_PRINT_ADD_LINE(SW_STATE_PRETTY_PRINT_TYPE_UINT16, "tpid", sit_profile->tpid,
"Tpid value of the sit tag", NULL);
SW_STATE_PRETTY_PRINT_ADD_LINE(SW_STATE_PRETTY_PRINT_TYPE_INT, "pcp_dei_src",
sit_profile->pcp_dei_src,
"pcp dei value source, see dbal_enum_value_field_sit_pcp_dei_src_e", NULL);
SW_STATE_PRETTY_PRINT_ADD_LINE(SW_STATE_PRETTY_PRINT_TYPE_INT, "vid_src",
sit_profile->vid_src,
"vid value source, see dbal_enum_value_field_sit_vid_src_e", NULL);
SW_STATE_PRETTY_PRINT_FINISH();
}
/*
* See header file algo_port_pp.h for description.
*/
void
dnx_algo_egress_acceptable_frame_type_profile_template_print_cb(
int unit,
const void *data)
{
int outer_tpid_indx;
int inner_tpid_indx;
/*
* Print every acceptable frame type data entry in the profile in the following format
*/
DNX_SW_STATE_PRINT(unit, "keys ={outer_tpid, inner_tpid}, data = {the acceptable frame type entry data}\n");
/*
* Priority tag is not considered here because only outer_tpid/inner_tpid is used to access acceptable frame type table
*/
for (outer_tpid_indx = 0; outer_tpid_indx < BCM_DNX_SWITCH_TPID_NUM_OF_GLOBALS; outer_tpid_indx++)
{
for (inner_tpid_indx = 0; inner_tpid_indx < BCM_DNX_SWITCH_TPID_NUM_OF_GLOBALS; inner_tpid_indx++)
{
/*
* Takes the bit out of the template and print it:
*/
acceptable_frame_type_template_t *template_data;
/*
* see dnx_sw_state_dump.h for more information
*/
DNX_SW_STATE_DUMP_UPDATE_CURRENT_IDX(unit, inner_tpid_indx);
template_data = (acceptable_frame_type_template_t *) data;
DNX_SW_STATE_PRINT_WITH_STRIDE_UPDATE(unit, outer_tpid_indx, " ");
DNX_SW_STATE_PRINT_WITH_STRIDE_UPDATE(unit, inner_tpid_indx, " ");
DNX_SW_STATE_PRINT_WITH_STRIDE_UPDATE(unit,
template_data->acceptable_frame_type_template[outer_tpid_indx]
[inner_tpid_indx], " ");
DNX_SW_STATE_PRINT(unit, "keys ={%d, %d}, data = 0x%X\n", outer_tpid_indx, inner_tpid_indx,
template_data->acceptable_frame_type_template[outer_tpid_indx][inner_tpid_indx]);
}
/*
* see dnx_sw_state_dump.h for more information
*/
DNX_SW_STAET_DUMP_END_OF_STRIDE(unit);
}
}
/**
* }
*/
|
WhatAKitty/jmore-builder | jmore-blog/src/main/java/com/whatakitty/jmore/blog/domain/security/UserType.java | package com.whatakitty.jmore.blog.domain.security;
import com.whatakitty.jmore.framework.ddd.domain.ValueObject;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Value;
/**
* user type
* 0. guest
* 1. author
*
* @author WhatAKitty
* @date 2019/05/24
* @description
**/
@Value(staticConstructor = "of")
@EqualsAndHashCode(callSuper = true)
public final class UserType extends ValueObject {
/**
* guest
*/
public static UserType GUEST = UserType.of(Type.GUEST);
/**
* author
*/
public static UserType AUTHOR = UserType.of(Type.AUTHOR);
private final Type type;
@RequiredArgsConstructor
public enum Type {
/**
* guest
*/
GUEST(0),
/**
* author
*/
AUTHOR(1);
@Getter
private final int value;
}
}
|
magic-bunny/beanui | demo/src/main/java/demo/controller/table/ComplexTabelController.java | <reponame>magic-bunny/beanui
package demo.controller.table;
import demo.view.table.complex.ComplexTableDataForm;
import demo.view.table.complex.ComplexTableEditForm;
import demo.view.table.complex.ComplexRow;
import org.december.beanui.element.Type;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/complex-table")
public class ComplexTabelController {
@RequestMapping(value = "/init-complex-table-data-form", method = RequestMethod.GET)
public ComplexTableDataForm initComplexTableDataForm() {
List<ComplexRow> tableData = new ArrayList<ComplexRow>();
ComplexRow complexRow = new ComplexRow();
complexRow.setId("1");
complexRow.setDate("2013-11-21 10:24");
complexRow.setTitle("Ulcycm Btktiti Nvssyf Utlpwph Dpvhlhftv Vksoo Bssyduiu Ojryewq");
complexRow.setAuthor("Jeffrey");
complexRow.setImportance(3);
complexRow.setReadings(3788);
complexRow.setStatus("deleted");
complexRow.setStatusType(Type.DANGER);
tableData.add(complexRow);
complexRow = new ComplexRow();
complexRow.setId("1");
complexRow.setDate("1987-12-25 16:33");
complexRow.setTitle("Axnzqhehl Ldtjxdol Qxownrydo Jrdsqoyau Eonlhk");
complexRow.setAuthor("William");
complexRow.setReadings(2264);
complexRow.setStatus("draft");
complexRow.setStatusType(Type.WARNING);
complexRow.setImportance(1);
tableData.add(complexRow);
complexRow = new ComplexRow();
complexRow.setImportance(1);
complexRow.setId("2");
complexRow.setDate("2007-06-05 05:59");
complexRow.setTitle("Xkgebkwj Vscaedii Lmjrhna Dsht Pokxn Rczgc");
complexRow.setAuthor("William");
complexRow.setReadings(3712);
complexRow.setStatus("draft");
complexRow.setStatusType(Type.WARNING);
tableData.add(complexRow);
complexRow = new ComplexRow();
complexRow.setImportance(2);
complexRow.setId("3");
complexRow.setDate("1977-07-11 11:17");
complexRow.setTitle("Djjh Tunw Jqxk Evht Sdltrab Vumox Uqdfvt");
complexRow.setAuthor("Steven");
complexRow.setReadings(2078);
complexRow.setStatus("published");
complexRow.setStatusType(Type.SUCCESS);
tableData.add(complexRow);
complexRow = new ComplexRow();
complexRow.setImportance(4);
complexRow.setId("4");
complexRow.setDate("1971-08-30 09:40");
complexRow.setTitle("Ezkj Efkqcyv Vmhv Sbtzxcfmv Ztwbeczpg Fwm");
complexRow.setAuthor("Scott");
complexRow.setReadings(4194);
complexRow.setStatus("draft");
complexRow.setStatusType(Type.WARNING);
complexRow.setImportance(1);
tableData.add(complexRow);
complexRow = new ComplexRow();
complexRow.setId("5");
complexRow.setDate("1985-04-05 09:16");
complexRow.setTitle("Oeojqizd Ssoivufs Ostvtdqr Wgsscb Pbxyfrwq");
complexRow.setAuthor("Elizabeth");
complexRow.setReadings(1620);
complexRow.setStatus("draft");
complexRow.setStatusType(Type.WARNING);
complexRow.setImportance(2);
tableData.add(complexRow);
complexRow = new ComplexRow();
complexRow.setId("6");
complexRow.setDate("1997-01-24 04:49");
complexRow.setTitle("Kekizewghb Sngorv Gmlxneg Vzlyetuc Fmanyepm Ggcuiuok");
complexRow.setAuthor("Robert");
complexRow.setReadings(2565);
complexRow.setStatus("published");
complexRow.setStatusType(Type.SUCCESS);
complexRow.setImportance(1);
tableData.add(complexRow);
complexRow = new ComplexRow();
complexRow.setId("7");
complexRow.setDate("2016-03-01 12:32");
complexRow.setTitle("Exohuw Yqmu Lqcxqzcx Vkyjui Dryakkn Rczbfh Sshf Ntbklto Qounhwjg");
complexRow.setAuthor("Thomas");
complexRow.setReadings(3080);
complexRow.setStatus("published");
complexRow.setStatusType(Type.SUCCESS);
complexRow.setImportance(5);
tableData.add(complexRow);
complexRow = new ComplexRow();
complexRow.setId("8");
complexRow.setDate("1983-06-22 01:18");
complexRow.setTitle("Daf Sqvf Jtusdk Inq Hoiptyu Oibxzjd");
complexRow.setAuthor("Sarah");
complexRow.setReadings(3964);
complexRow.setStatus("deleted");
complexRow.setStatusType(Type.DANGER);
complexRow.setImportance(3);
tableData.add(complexRow);
complexRow = new ComplexRow();
complexRow.setId("9");
complexRow.setDate("1996-06-06 08:17");
complexRow.setTitle("Gbhmmqtd Kufwjwc Eggv Ueuamyq Mqwkmsejy");
complexRow.setAuthor("Michelle");
complexRow.setReadings(4339);
complexRow.setStatus("published");
complexRow.setStatusType(Type.SUCCESS);
complexRow.setImportance(1);
tableData.add(complexRow);
complexRow = new ComplexRow();
complexRow.setId("10");
complexRow.setDate("2001-11-06 23:31");
complexRow.setTitle("Klhpoius Lrsodzaw Tnrvio Ggfjkvb Afansgeqp Uvkbaxbyg Tzphjxwg");
complexRow.setAuthor("Donna");
complexRow.setReadings(1911);
complexRow.setStatus("deleted");
complexRow.setStatusType(Type.DANGER);
complexRow.setImportance(5);
tableData.add(complexRow);
ComplexTableDataForm complexTableDataForm = new ComplexTableDataForm();
complexTableDataForm.setTableData(tableData);
return complexTableDataForm;
}
@RequestMapping(value = "/init-complex-table-edit-form", method = RequestMethod.GET)
public ComplexTableEditForm initComplexTableEditForm() {
ComplexTableEditForm complexTableEditForm = new ComplexTableEditForm();
complexTableEditForm.setShow(true);
return complexTableEditForm;
}
}
|
yomboprime/YomboServer | public/lib/fileUtils/fileUtils.js | <reponame>yomboprime/YomboServer
// For Node only
var fs = require( "fs" );
if ( typeof module !== 'undefined' ) {
module.exports = {
loadJSONFileSync: loadJSONFileSync,
writeJSONFileSync: writeJSONFileSync,
getObjectSerializedAsString: getObjectSerializedAsString,
loadTextFileSync: loadTextFileSync,
writeTextFileSync: writeTextFileSync
};
}
function loadJSONFileSync( path ) {
return JSON.parse( loadTextFileSync( path ) );
}
function writeJSONFileSync( object, path ) {
var content = getObjectSerializedAsString( object, true );
if ( content ) {
return writeTextFileSync( content, path );
}
return false;
}
function getObjectSerializedAsString( objectJSON, beautified ) {
if ( beautified ) {
return JSON.stringify( objectJSON, null, 4 );
}
else {
return JSON.stringify( objectJSON );
}
}
function loadTextFileSync( path ) {
var fileContent = null;
try {
fileContent = fs.readFileSync( path, "utf-8" );
}
catch ( e ) {
if ( e.code === 'ENOENT' ) {
return null;
}
else {
// TODO how to handle?
throw e;
}
}
return fileContent;
}
function writeTextFileSync( content, path ) {
try {
fs.writeFileSync( path, content );
return true;
}
catch ( e ) {
return false;
}
}
|
InfoClinika/chorus-opensource | data-management/dm-integration-helper/src/main/java/com/infoclinika/mssharing/platform/model/helper/write/UserManager.java | package com.infoclinika.mssharing.platform.model.helper.write;
import com.infoclinika.mssharing.platform.entity.PersonData;
import com.infoclinika.mssharing.platform.entity.UserInvitationLink;
import com.infoclinika.mssharing.platform.entity.UserTemplate;
import com.infoclinika.mssharing.platform.model.AccessDenied;
import com.infoclinika.mssharing.platform.model.DefaultTransformers;
import com.infoclinika.mssharing.platform.model.EntityFactories;
import com.infoclinika.mssharing.platform.model.NotifierTemplate;
import com.infoclinika.mssharing.platform.model.write.UserManagementTemplate.PersonInfo;
import com.infoclinika.mssharing.platform.repository.UserInvitationLinkRepository;
import com.infoclinika.mssharing.platform.repository.UserRepositoryTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import javax.inject.Inject;
import javax.inject.Provider;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.Date;
import java.util.UUID;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* @author : <NAME>
*/
@Component
public class UserManager<USER extends UserTemplate<?>> {
private final SecureRandom random = new SecureRandom();
@Inject
private UserRepositoryTemplate<USER> userRepository;
@Inject
private EntityFactories factories;
@Inject
private PasswordEncoder encoder;
@Inject
private Provider<Date> current;
@Inject
private NotifierTemplate notifier;
@Inject
private UserInvitationLinkRepository userInvitationLinkRepository;
private static final Logger LOGGER = LoggerFactory.getLogger(UserManager.class);
//TODO: Method is unused. Consider should we remove it.
public boolean userWithSpecifiedEmailExists(final String userEmail) {
USER user = userRepository.findByEmail(userEmail);
return user != null;
}
public USER createUser(PersonInfo userInfo, String password) {
final USER existingUser = userRepository.findByEmail(userInfo.email);
if (existingUser != null) {
LOGGER.warn("Attempt to create a user, which already exists: " + userInfo);
return existingUser;
}
//noinspection unchecked
USER userToSave = (USER) factories.user.get();
userToSave.setPersonData(new PersonData(userInfo.email, userInfo.firstName, userInfo.lastName));
userToSave.setPasswordHash(encoder.encode(password));
return saveAndGetUser(userToSave);
}
public USER createUserWithRandomPassword(PersonInfo userInfo) {
String password = <PASSWORD>();
return createUser(userInfo, password);
}
public USER updatePersonInfo(Long userId, PersonInfo user) {
final USER userToSave = userRepository.findOne(userId);
userToSave.setPersonData(DefaultTransformers.personalInfoToData(user));
return saveAndGetUser(userToSave);
}
public USER verifyEmail(Long userId) {
final USER user = findUser(userId);
user.setEmailVerified(true);
return saveAndGetUser(user);
}
public USER resetPassword(Long userId, String newPasswordHash) {
final USER user = findUser(userId);
user.setPasswordHash(<PASSWORD>);
user.setLastModification(new Date());
return saveAndGetUser(user);
}
//TODO [code review]
public void sendPasswordRecoveryInstructions(Long userId, String passwordRecoveryUrl) {
notifier.recoverPassword(userId, passwordRecoveryUrl);
}
public USER changePassword(Long id, String oldPassword, String newPasswordHash) {
final USER user = findUser(id);
if (!encoder.matches(oldPassword, user.getPasswordHash())) {
throw new AccessDenied("Old password doesn't matched");
}
user.setPasswordHash(newPasswordHash);
return saveAndGetUser(user);
}
/**
* @see #inviteUser(Long, String, String)
*/
@Deprecated
public String inviteUser(Long invitedBy, String futureUserEmail) {
USER invitedUser = createUser(new PersonInfo("Invited", "User", futureUserEmail), generateRandomPassword());
UserInvitationLink<USER> userInvitationLink = new UserInvitationLink<>();
String invitationLink = UUID.randomUUID().toString();
userInvitationLink.setInvitationLink(invitationLink);
userInvitationLink.setUser(invitedUser);
final UserInvitationLink link = userInvitationLinkRepository.save(userInvitationLink);
notifier.sendInvitationEmail(invitedBy, futureUserEmail, link.getInvitationLink());
return invitationLink;
}
public String inviteUser(Long invitedBy, String futureUserEmail, String invitationUrl) {
USER invitedUser = createUser(new PersonInfo("Invited", "User", futureUserEmail), generateRandomPassword());
UserInvitationLink<USER> userInvitationLink = new UserInvitationLink<>();
userInvitationLink.setInvitationLink(invitationUrl);
userInvitationLink.setUser(invitedUser);
final UserInvitationLink link = userInvitationLinkRepository.save(userInvitationLink);
notifier.sendInvitationEmail(invitedBy, futureUserEmail, link.getInvitationLink());
return invitationUrl;
}
public USER saveAndGetUser(USER user) {
user.setLastModification(current.get());
return userRepository.save(user);
}
public USER findUser(long userId) {
return checkNotNull(userRepository.findOne(userId), "Couldn't find user with id %s", userId);
}
public String generateRandomPassword() {
return new BigInteger(50, random).toString(32);
}
}
|
GameTechDev/OcclusionCulling | SampleComponents/TaskMgrSS.cpp | ////////////////////////////////////////////////////////////////////////////////
// Copyright 2017 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy
// of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
////////////////////////////////////////////////////////////////////////////////
/*!
\file TaskMgrSS.h
TaksMgrSS is a class that uses a custom Windows threads schedulers with a
C-style handle and callback mechanism for scheduling tasks across any
number of CPU cores.
*/
#include "SampleComponents.h"
#include "TaskMgrSS.h"
#include "TaskScheduler.h"
#include "spin_mutex.h"
#include <strsafe.h>
#pragma warning ( push )
#pragma warning ( disable : 4995 ) // skip deprecated warning on intrinsics.
#include <intrin.h>
#pragma warning ( pop )
//
// Global Domain for GPA CPU tracing
//
#ifdef PROFILEGPA
__itt_domain* g_ProfileDomain = __itt_domain_create( TEXT( "TaskMgr.ProfileDomain" ) );
#endif
//
// Global Simple Scheduler task mananger instance
//
TaskMgrSS gTaskMgrSS;
TaskMgrSS::TaskSet::TaskSet()
: mpFunc( NULL )
, mpvArg( 0 )
, muSize( 0 )
, mhTaskset( TASKSETHANDLE_INVALID )
, mbCompleted( TRUE )
{
mszSetName[ 0 ] = 0;
memset( Successors, 0, sizeof( Successors ) ) ;
};
void TaskMgrSS::TaskSet::Execute(INT iContextId)
{
int uIdx = _InterlockedDecrement(&muTaskId);
if(uIdx >= 0)
{
//gTaskMgrSS.mTaskScheduler.DecrementTaskCount();
ProfileBeginTask( mszSetName );
mpFunc( mpvArg, iContextId, uIdx, muSize );
ProfileEndTask();
//gTaskMgr.CompleteTaskSet( mhTaskset );
UINT uCount = _InterlockedDecrement( (LONG*)&muCompletionCount );
if( 0 == uCount )
{
mbCompleted = TRUE;
mpFunc = 0;
CompleteTaskSet();
}
}
}
void TaskMgrSS::TaskSet::CompleteTaskSet()
{
//
// The task set has completed. We need to look at the successors
// and signal them that this dependency of theirs has completed.
//
mSuccessorsLock.aquire();
for( UINT uSuccessor = 0; uSuccessor < MAX_SUCCESSORS; ++uSuccessor )
{
TaskSet* pSuccessor = Successors[ uSuccessor ];
//
// A signaled successor must be removed from the Successors list
// before the mSuccessorsLock can be released.
//
Successors[ uSuccessor ] = NULL;
if( NULL != pSuccessor )
{
UINT uStart;
uStart = _InterlockedDecrement( (LONG*)&pSuccessor->muStartCount );
//
// If the start count is 0 the successor has had all its
// dependencies satisified and can be scheduled.
//
if( 0 == uStart )
{
gTaskMgrSS.mTaskScheduler.AddTaskSet( pSuccessor->mhTaskset, pSuccessor->muSize );
}
}
}
mSuccessorsLock.release();
gTaskMgrSS.ReleaseHandle( mhTaskset );
}
///////////////////////////////////////////////////////////////////////////////
//
// Implementation of TaskMgrSS
//
///////////////////////////////////////////////////////////////////////////////
TaskMgrSS::TaskMgrSS() : miDemoModeThreadCountOverride(-1)
{
memset(
mSets,
0x0,
sizeof( mSets ) );
}
TaskMgrSS::~TaskMgrSS()
{
}
BOOL TaskMgrSS::Init()
{
mTaskScheduler.Init(miDemoModeThreadCountOverride);
return TRUE;
}
VOID TaskMgrSS::Shutdown()
{
//
// Release any left-over tasksets
for( UINT uSet = 0; uSet < MAX_TASKSETS; ++uSet )
{
if( mSets[ uSet ].mpFunc )
{
WaitForSet( uSet );
}
}
mTaskScheduler.Shutdown();
}
BOOL TaskMgrSS::CreateTaskSet(TASKSETFUNC pFunc,
VOID* pArg,
UINT uTaskCount,
TASKSETHANDLE* pInDepends,
UINT uInDepends,
OPTIONAL LPCSTR szSetName,
TASKSETHANDLE* pOutHandle )
{
TASKSETHANDLE hSet;
TASKSETHANDLE hSetParent = TASKSETHANDLE_INVALID;
TASKSETHANDLE* pDepends = pInDepends;
UINT uDepends = uInDepends;
BOOL bResult = FALSE;
// Validate incomming parameters
if( 0 == uTaskCount || NULL == pFunc )
{
return FALSE;
}
//
// Allocate and setup the internal taskset
//
hSet = AllocateTaskSet();
mSets[ hSet ].muRefCount = 2;
mSets[ hSet ].muStartCount = uDepends;
mSets[ hSet ].mpvArg = pArg;
mSets[ hSet ].muSize = uTaskCount;
mSets[ hSet ].muCompletionCount = uTaskCount;
mSets[ hSet ].muTaskId = uTaskCount;
mSets[ hSet ].mhTaskset = hSet;
mSets[ hSet ].mpFunc = pFunc;
mSets[ hSet ].mbCompleted = FALSE;
//mSets[ hSet ].mhAssignedSlot = TASKSETHANDLE_INVALID;
#ifdef PROFILEGPA
//
// Track task name if profiling is enabled
if( szSetName )
{
StringCbCopyA(
mSets[ hSet ].mszSetName,
sizeof( mSets[ hSet ].mszSetName ),
szSetName );
}
else
{
StringCbCopyA(
mSets[ hSet ].mszSetName,
sizeof( mSets[ hSet ].mszSetName ),
"Unnamed Task" );
}
#else
UNREFERENCED_PARAMETER( szSetName );
#endif // PROFILEGPA
//
// Iterate over the dependency list and setup the successor
// pointers in each parent to point to this taskset.
//
if(uDepends == 0)
{
mTaskScheduler.AddTaskSet( hSet, uTaskCount );
}
else for( UINT uDepend = 0; uDepend < uDepends; ++uDepend )
{
TASKSETHANDLE hDependsOn = pDepends[ uDepend ];
if(hDependsOn == TASKSETHANDLE_INVALID)
continue;
TaskSet *pDependsOn = &mSets[ hDependsOn ];
LONG lPrevCompletion;
//
// A taskset with a new successor is consider incomplete even if it
// already has completed. This mechanism allows us tasksets that are
// already done to appear active and capable of spawning successors.
//
lPrevCompletion = _InterlockedExchangeAdd( (LONG*)&pDependsOn->muCompletionCount, 1 );
pDependsOn->mSuccessorsLock.aquire();
UINT uSuccessor;
for( uSuccessor = 0; uSuccessor < MAX_SUCCESSORS; ++uSuccessor )
{
if( NULL == pDependsOn->Successors[ uSuccessor ] )
{
pDependsOn->Successors[ uSuccessor ] = &mSets[ hSet ];
break;
}
}
//
// If the successor list is full we have a problem. The app
// needs to give us more space by increasing MAX_SUCCESSORS
//
if( uSuccessor == MAX_SUCCESSORS )
{
printf( "Too many successors for this task set.\nIncrease MAX_SUCCESSORS\n" );
pDependsOn->mSuccessorsLock.release();
goto Cleanup;
}
pDependsOn->mSuccessorsLock.release();
//
// Mark the set as completed for the successor adding operation.
//
CompleteTaskSet( hDependsOn );
}
// Set output taskset handle
*pOutHandle = hSet;
bResult = TRUE;
Cleanup:
return bResult;
}
VOID TaskMgrSS::ReleaseHandle( TASKSETHANDLE hSet )
{
_InterlockedDecrement( (LONG*)&mSets[ hSet ].muRefCount );
}
VOID TaskMgrSS::ReleaseHandles( TASKSETHANDLE *phSet,UINT uSet )
{
for( UINT uIdx = 0; uIdx < uSet; ++uIdx )
{
ReleaseHandle( phSet[ uIdx ] );
}
}
VOID TaskMgrSS::WaitForSet( TASKSETHANDLE hSet )
{
//
// Yield the main thread to SS to get our taskset done faster!
// NOTE: tasks can only be waited on once. After that they will
// deadlock if waited on again.
if( !mSets[ hSet ].mbCompleted )
{
mTaskScheduler.WaitForFlag(&mSets[ hSet ].mbCompleted);
}
}
BOOL
TaskMgrSS::IsSetComplete( TASKSETHANDLE hSet )
{
return TRUE == mSets[ hSet ].mbCompleted;
}
TASKSETHANDLE TaskMgrSS::AllocateTaskSet()
{
// This line is fine
UINT uSet = muNextFreeSet;
//
// Create a new task set and find a slot in the TaskMgrSS to put it in.
//
// NOTE: if we have too many tasks pending we will spin on the slot. If
// spinning occures, see TaskMgrCommon.h and increase MAX_TASKSETS
//
//
// NOTE: Allocating tasksets is not thread-safe due to allocation of the
// slot for the task pointer. This can be easily made threadsafe with
// an interlocked op on the muNextFreeSet variable and a spin on the slot.
// It will cost a small amount of performance.
//
while( NULL != mSets[ uSet ].mpFunc && mSets[ uSet ].muRefCount != 0 )
{
uSet = ( uSet + 1 ) % MAX_TASKSETS;
}
muNextFreeSet = ( uSet + 1 ) & (MAX_TASKSETS - 1);
return (TASKSETHANDLE)uSet;
}
VOID TaskMgrSS::CompleteTaskSet( TASKSETHANDLE hSet )
{
TaskSet* pSet = &mSets[ hSet ];
UINT uCount = _InterlockedDecrement( (LONG*)&pSet->muCompletionCount );
if( 0 == uCount )
{
pSet->mbCompleted = TRUE;
pSet->mpFunc = 0;
//
// The task set has completed. We need to look at the successors
// and signal them that this dependency of theirs has completed.
//
pSet->mSuccessorsLock.aquire();
for( UINT uSuccessor = 0; uSuccessor < MAX_SUCCESSORS; ++uSuccessor )
{
TaskSet* pSuccessor = pSet->Successors[ uSuccessor ];
//
// A signaled successor must be removed from the Successors list
// before the mSuccessorsLock can be released.
//
pSet->Successors[ uSuccessor ] = NULL;
if( NULL != pSuccessor )
{
UINT uStart;
uStart = _InterlockedDecrement( (LONG*)&pSuccessor->muStartCount );
//
// If the start count is 0 the successor has had all its
// dependencies satisified and can be scheduled.
//
if( 0 == uStart )
{
mTaskScheduler.AddTaskSet( pSuccessor->mhTaskset, pSuccessor->muSize );
}
}
}
pSet->mSuccessorsLock.release();
ReleaseHandle( hSet );
}
}
|
mstrobel/Luyten | src/org/fife/ui/rtextarea/RTADefaultInputMap.java | <filename>src/org/fife/ui/rtextarea/RTADefaultInputMap.java<gh_stars>1-10
/*
* 08/19/2004
*
* RTADefaultInputMap.java - The default input map for RTextAreas.
*
* This library is distributed under a modified BSD license. See the included
* RSyntaxTextArea.License.txt file for details.
*/
package org.fife.ui.rtextarea;
import java.awt.Toolkit;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import javax.swing.InputMap;
import javax.swing.KeyStroke;
import javax.swing.text.DefaultEditorKit;
/**
* The default input map for an <code>RTextArea</code>. For the most part it is
* exactly that the one for a <code>JTextArea</code>, but it adds a few things.
* Currently, the new key bindings include:
* <ul>
* <li>HOME key toggles between first character on line and first non-
* whitespace character on line.
* <li>INSERT key toggles between insert and overwrite modes.
* <li>Ctrl+DELETE key deletes all text between the caret and the end of the
* current line.
* <li>Ctrl+Shift+Up and Ctrl+Shift+Down move the current line up and
* down, respectively.
* <li>Ctrl+J joins lines.
* <li>Ctrl+Z is undo and Ctrl+Y is redo.
* <li>Ctrl+Up and Ctrl+Down shift the visible area of the text area up and
* down one line, respectively.
* <li>F2 and Shift+F2 moves to the next and previous bookmarks,
* respectively.
* <li>Ctrl+F2 toggles whether a bookmark is on the current line.
* <li>etc.
* </ul>
*/
public class RTADefaultInputMap extends InputMap {
/**
* Constructs the default input map for an <code>RTextArea</code>.
*/
public RTADefaultInputMap() {
super();
int defaultModifier = getDefaultModifier();
//int ctrl = InputEvent.CTRL_MASK;
int alt = InputEvent.ALT_MASK;
int shift = InputEvent.SHIFT_MASK;
put(KeyStroke.getKeyStroke(KeyEvent.VK_HOME, 0), DefaultEditorKit.beginLineAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_HOME, shift), DefaultEditorKit.selectionBeginLineAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_HOME, defaultModifier), DefaultEditorKit.beginAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_HOME, defaultModifier|shift), DefaultEditorKit.selectionBeginAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_END, 0), DefaultEditorKit.endLineAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_END, shift), DefaultEditorKit.selectionEndLineAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_END, defaultModifier), DefaultEditorKit.endAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_END, defaultModifier|shift), DefaultEditorKit.selectionEndAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), DefaultEditorKit.backwardAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, shift), DefaultEditorKit.selectionBackwardAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, defaultModifier), DefaultEditorKit.previousWordAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, defaultModifier|shift), DefaultEditorKit.selectionPreviousWordAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), DefaultEditorKit.downAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, shift), DefaultEditorKit.selectionDownAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, defaultModifier), RTextAreaEditorKit.rtaScrollDownAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, alt), RTextAreaEditorKit.rtaLineDownAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), DefaultEditorKit.forwardAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, shift), DefaultEditorKit.selectionForwardAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, defaultModifier), DefaultEditorKit.nextWordAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, defaultModifier|shift), DefaultEditorKit.selectionNextWordAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), DefaultEditorKit.upAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, shift), DefaultEditorKit.selectionUpAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, defaultModifier), RTextAreaEditorKit.rtaScrollUpAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_UP, alt), RTextAreaEditorKit.rtaLineUpAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP,0), DefaultEditorKit.pageUpAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP,shift), RTextAreaEditorKit.rtaSelectionPageUpAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP,defaultModifier|shift), RTextAreaEditorKit.rtaSelectionPageLeftAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN,0), DefaultEditorKit.pageDownAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN,shift), RTextAreaEditorKit.rtaSelectionPageDownAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN,defaultModifier|shift), RTextAreaEditorKit.rtaSelectionPageRightAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_CUT, 0), DefaultEditorKit.cutAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_COPY, 0), DefaultEditorKit.copyAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_PASTE, 0), DefaultEditorKit.pasteAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_X, defaultModifier), DefaultEditorKit.cutAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_C, defaultModifier), DefaultEditorKit.copyAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_V, defaultModifier), DefaultEditorKit.pasteAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0), DefaultEditorKit.deleteNextCharAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, shift), DefaultEditorKit.cutAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, defaultModifier), RTextAreaEditorKit.rtaDeleteRestOfLineAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_INSERT, 0), RTextAreaEditorKit.rtaToggleTextModeAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_INSERT, shift), DefaultEditorKit.pasteAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_INSERT, defaultModifier), DefaultEditorKit.copyAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_A, defaultModifier), DefaultEditorKit.selectAllAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_D, defaultModifier), RTextAreaEditorKit.rtaDeleteLineAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_J, defaultModifier), RTextAreaEditorKit.rtaJoinLinesAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, shift), DefaultEditorKit.deletePrevCharAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SPACE, defaultModifier), RTextAreaEditorKit.rtaDeletePrevWordAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_TAB, 0), DefaultEditorKit.insertTabAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), DefaultEditorKit.insertBreakAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, shift), DefaultEditorKit.insertBreakAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, defaultModifier), RTextAreaEditorKit.rtaDumbCompleteWordAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_Z, defaultModifier), RTextAreaEditorKit.rtaUndoAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_Y, defaultModifier), RTextAreaEditorKit.rtaRedoAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0), RTextAreaEditorKit.rtaNextBookmarkAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_F2, shift), RTextAreaEditorKit.rtaPrevBookmarkAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_F2, defaultModifier), RTextAreaEditorKit.rtaToggleBookmarkAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_K, defaultModifier|shift), RTextAreaEditorKit.rtaPrevOccurrenceAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_K, defaultModifier), RTextAreaEditorKit.rtaNextOccurrenceAction);
/* NOTE: Currently, macros aren't part of the default input map for */
/* RTextArea, as they display their own popup windows, etc. which */
/* may or may not clash with the application in which the RTextArea */
/* resides. You can add the macro actions yourself into an */
/* application if you want. They may become standard in the future */
/* if I can find a way to implement them that I like. */
/*
put(KeyStroke.getKeyStroke(KeyEvent.VK_R, defaultModifier|shift), RTextAreaEditorKit.rtaBeginRecordingMacroAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_S, defaultModifier|shift), RTextAreaEditorKit.rtaEndRecordingMacroAction);
put(KeyStroke.getKeyStroke(KeyEvent.VK_M, defaultModifier|shift), RTextAreaEditorKit.rtaPlaybackLastMacroAction);
*/
}
/**
* Returns the default modifier key for a system. For example, on Windows
* this would be the CTRL key (<code>InputEvent.CTRL_MASK</code>).
*
* @return The default modifier key.
*/
protected static final int getDefaultModifier() {
return Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
}
} |
isabella232/meshjs | examples/fractaltree_obj_2_cm/main.js | <reponame>isabella232/meshjs
/**
<NAME>
https://github.com/mikechambers
http://www.mikechambers.com
Released under an MIT License
Copyright <NAME> 2018
**/
import meshjs from "../../lib/mesh.js";
import Vector from "../../lib/math/vector.js";
import Circle from "../../lib/geometry/circle.js";
import Color from "../../lib/color/color.js";
import { map } from "../../lib/math/math.js";
import Branch from "./branch.js";
import * as utils from "../../lib/utils/utils.js";
import ColorPalette, {
randomColorPallete
} from "../../lib/color/colorpallete.js";
import Gradient, { gradientFromName } from "../../lib/color/gradient.js";
/************ CONFIG **************/
const config = {
//Dimensions that canvas will be rendered at
RENDER_HEIGHT: 1080, //2436,
RENDER_WIDTH: 1080, //1125,
//Max dimension canvas will be display at on page
//note, exact dimension will depend on RENDER_HEIGHT / width and
//ratio to these properties.
//Canvas display will be scaled to maintain aspect ratio
MAX_DISPLAY_HEIGHT: 640,
MAX_DISPLAY_WIDTH: 640,
//background color of html page
BACKGROUND_COLOR: "#000000",
//background color for display and offscreen canvas
CANVAS_BACKGROUND_COLOR: "#222222",
//Where video of canvas is recorded
CAPTURE_VIDEO: false,
KEY_COMMANDS: {
g: "Add nodes",
b: "Cycle through colors"
},
/*********** APP Specific Settings ************/
LEAF_COLOR: "#00FF00",
LEAF_RADIUS: 8,
NODE_RADIUS: 2,
LEAF_OPACITY: 0.9,
BRANCH_COLOR: "#333333", //"#EEEEEE",
GRADIENT_NAME: "Bora Bora",
START_GENERATIONS: 10,
JITTER: true
};
/************** GLOBAL VARIABLES ************/
//hot pink : 255,20,147
let context;
let bounds;
let circle;
let angle = (3 * Math.PI) / 4;
let mousePosition = new Vector();
let colorPallete;
let gradient;
/*************** CODE ******************/
let root;
let leafColor;
const init = function(context) {
bounds = meshjs.bounds;
gradient = gradientFromName(
config.GRADIENT_NAME,
bounds,
Gradient.TOP_TO_BOTTOM
);
gradient.create();
colorPallete = randomColorPallete();
root = new Branch(
new Vector(bounds.center.x, bounds.height),
new Vector(bounds.center.x, bounds.height - bounds.height / 4)
);
let c = colorPallete.getRandomColor();
c.alpha = config.LEAF_OPACITY;
let options = {
leafColor: c,
leafRadius: config.LEAF_RADIUS,
nodeRadius: config.NODE_RADIUS,
branchColor: Color.fromHex(config.BRANCH_COLOR)
};
root.options = options;
for (let i = 0; i < config.START_GENERATIONS; i++) {
root.spawn();
}
};
const draw = function(context, frameCount) {
context.drawImage(
gradient.canvas,
bounds.x,
bounds.y,
bounds.width,
bounds.height
);
if (config.JITTER) {
root.jitter();
}
root.draw(context);
};
const updateColor = function() {
let c = colorPallete.getRandomColor();
c.alpha = config.LEAF_OPACITY;
root.updateLeafColor(c);
};
const keypress = function(event) {
if (event.key === "g") {
root.spawn();
} else if (event.key === "b") {
updateColor();
}
};
window.onload = function() {
meshjs.init(config, init, draw);
meshjs.listen(keypress);
};
|
eleswastaken/odin-project | cv-project/src/App.js | <reponame>eleswastaken/odin-project
import GeneralInformation from './components/GeneralInformation';
import EducationInformation from './components/EducationInformation';
function App() {
return (
<div>
<GeneralInformation />
<EducationInformation />
</div>
);
}
export default App;
|
markphip/testing | jira-dvcs-connector-pageobjects/src/main/java/com/atlassian/jira/plugins/dvcs/pageobjects/remoterestpoint/PullRequestLocalRestpoint.java | <reponame>markphip/testing
package com.atlassian.jira.plugins.dvcs.pageobjects.remoterestpoint;
import com.atlassian.jira.pageobjects.JiraTestedProduct;
import com.atlassian.jira.plugins.dvcs.model.dev.RestDevResponse;
import com.atlassian.jira.plugins.dvcs.model.dev.RestPrRepository;
import com.google.common.base.Function;
import javax.annotation.Nullable;
public class PullRequestLocalRestpoint
{
private static final String DETAIL_URL_SUFFIX = "pr-detail";
private final EntityLocalRestpoint<RestDevResponseForPrRepository> entityLocalRestpoint = new EntityLocalRestpoint(RestDevResponseForPrRepository.class, DETAIL_URL_SUFFIX);
/**
* Hack for generic de-serialization.
*
* @author <NAME>
*/
private static class RestDevResponseForPrRepository extends RestDevResponse<RestPrRepository>
{
}
/**
* Calls {@link com.atlassian.jira.plugins.dvcs.pageobjects.remoterestpoint.EntityLocalRestpoint#getEntity(String,
* com.google.common.base.Function)} with {@link com.atlassian.jira.plugins.dvcs.pageobjects.remoterestpoint.PullRequestLocalRestpoint.SingleRestPrRepositoryPredicate}
* which returns the {@link com.atlassian.jira.plugins.dvcs.model.dev.RestPrRepository} that are found for the issue
* key, this does involve retrying the fetch if it is not found at first
*
* @param issueKey The issue key to search for
* @return The pull request(s) that were found
*/
public RestDevResponse<RestPrRepository> getAtLeastOnePullRequest(String issueKey)
{
return entityLocalRestpoint.getEntity(issueKey, new SingleRestPrRepositoryPredicate());
}
/**
* Calls {@link com.atlassian.jira.plugins.dvcs.pageobjects.remoterestpoint.EntityLocalRestpoint#getEntity(String,
* com.google.common.base.Function)} with {@link com.atlassian.jira.plugins.dvcs.pageobjects.remoterestpoint.PullRequestLocalRestpoint.SingleRestPrRepositoryPredicate}
* which returns the {@link com.atlassian.jira.plugins.dvcs.model.dev.RestPrRepository} that are found for the issue
* key, this does involve retrying the fetch if it is not found at first
*
* @param issueKey The issue key to search for
* @param jira The @{link JiraTestedProduct} to use instead
* @return The pull request(s) that were found
*/
public RestDevResponse<RestPrRepository> getAtLeastOnePullRequest(String issueKey, JiraTestedProduct jira)
{
return entityLocalRestpoint.getEntity(issueKey, new SingleRestPrRepositoryPredicate(), jira);
}
private static class SingleRestPrRepositoryPredicate implements Function<RestDevResponseForPrRepository, Boolean>
{
@Override
public Boolean apply(@Nullable final RestDevResponseForPrRepository input)
{
return !input.getRepositories().isEmpty();
}
}
} |
EwanNoble/apply-for-teacher-training | spec/forms/support_interface/edit_single_provider_user_form_spec.rb | <reponame>EwanNoble/apply-for-teacher-training<filename>spec/forms/support_interface/edit_single_provider_user_form_spec.rb
require 'rails_helper'
RSpec.describe SupportInterface::EditSingleProviderUserForm do
let(:provider) { build_stubbed(:provider, id: 2) }
let(:provider_permissions) do
{
provider_permission: {
provider_id: provider.id,
},
}
end
let(:form_params) do
{
provider_permissions: provider_permissions,
provider_id: provider.id,
}
end
subject(:provider_user_form) { described_class.new(form_params) }
describe 'validations' do
context 'provider permissions must be present' do
let(:provider_permissions) { {} }
it 'is invalid' do
expect(provider_user_form.valid?).to be false
expect(provider_user_form.errors[:provider_permissions]).not_to be_empty
end
end
end
end
|
vvelikodny/aws-sdk-go-v2 | service/storagegateway/api_op_DescribeVTLDevices.go | <reponame>vvelikodny/aws-sdk-go-v2
// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
package storagegateway
import (
"context"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/internal/awsutil"
)
// DescribeVTLDevicesInput
type DescribeVTLDevicesInput struct {
_ struct{} `type:"structure"`
// The Amazon Resource Name (ARN) of the gateway. Use the ListGateways operation
// to return a list of gateways for your account and AWS Region.
//
// GatewayARN is a required field
GatewayARN *string `min:"50" type:"string" required:"true"`
// Specifies that the number of VTL devices described be limited to the specified
// number.
Limit *int64 `min:"1" type:"integer"`
// An opaque string that indicates the position at which to begin describing
// the VTL devices.
Marker *string `min:"1" type:"string"`
// An array of strings, where each string represents the Amazon Resource Name
// (ARN) of a VTL device.
//
// All of the specified VTL devices must be from the same gateway. If no VTL
// devices are specified, the result will contain all devices on the specified
// gateway.
VTLDeviceARNs []string `type:"list"`
}
// String returns the string representation
func (s DescribeVTLDevicesInput) String() string {
return awsutil.Prettify(s)
}
// Validate inspects the fields of the type to determine if they are valid.
func (s *DescribeVTLDevicesInput) Validate() error {
invalidParams := aws.ErrInvalidParams{Context: "DescribeVTLDevicesInput"}
if s.GatewayARN == nil {
invalidParams.Add(aws.NewErrParamRequired("GatewayARN"))
}
if s.GatewayARN != nil && len(*s.GatewayARN) < 50 {
invalidParams.Add(aws.NewErrParamMinLen("GatewayARN", 50))
}
if s.Limit != nil && *s.Limit < 1 {
invalidParams.Add(aws.NewErrParamMinValue("Limit", 1))
}
if s.Marker != nil && len(*s.Marker) < 1 {
invalidParams.Add(aws.NewErrParamMinLen("Marker", 1))
}
if invalidParams.Len() > 0 {
return invalidParams
}
return nil
}
// DescribeVTLDevicesOutput
type DescribeVTLDevicesOutput struct {
_ struct{} `type:"structure"`
// The Amazon Resource Name (ARN) of the gateway. Use the ListGateways operation
// to return a list of gateways for your account and AWS Region.
GatewayARN *string `min:"50" type:"string"`
// An opaque string that indicates the position at which the VTL devices that
// were fetched for description ended. Use the marker in your next request to
// fetch the next set of VTL devices in the list. If there are no more VTL devices
// to describe, this field does not appear in the response.
Marker *string `min:"1" type:"string"`
// An array of VTL device objects composed of the Amazon Resource Name(ARN)
// of the VTL devices.
VTLDevices []VTLDevice `type:"list"`
}
// String returns the string representation
func (s DescribeVTLDevicesOutput) String() string {
return awsutil.Prettify(s)
}
const opDescribeVTLDevices = "DescribeVTLDevices"
// DescribeVTLDevicesRequest returns a request value for making API operation for
// AWS Storage Gateway.
//
// Returns a description of virtual tape library (VTL) devices for the specified
// tape gateway. In the response, AWS Storage Gateway returns VTL device information.
//
// This operation is only supported in the tape gateway type.
//
// // Example sending a request using DescribeVTLDevicesRequest.
// req := client.DescribeVTLDevicesRequest(params)
// resp, err := req.Send(context.TODO())
// if err == nil {
// fmt.Println(resp)
// }
//
// Please also see https://docs.aws.amazon.com/goto/WebAPI/storagegateway-2013-06-30/DescribeVTLDevices
func (c *Client) DescribeVTLDevicesRequest(input *DescribeVTLDevicesInput) DescribeVTLDevicesRequest {
op := &aws.Operation{
Name: opDescribeVTLDevices,
HTTPMethod: "POST",
HTTPPath: "/",
Paginator: &aws.Paginator{
InputTokens: []string{"Marker"},
OutputTokens: []string{"Marker"},
LimitToken: "Limit",
TruncationToken: "",
},
}
if input == nil {
input = &DescribeVTLDevicesInput{}
}
req := c.newRequest(op, input, &DescribeVTLDevicesOutput{})
return DescribeVTLDevicesRequest{Request: req, Input: input, Copy: c.DescribeVTLDevicesRequest}
}
// DescribeVTLDevicesRequest is the request type for the
// DescribeVTLDevices API operation.
type DescribeVTLDevicesRequest struct {
*aws.Request
Input *DescribeVTLDevicesInput
Copy func(*DescribeVTLDevicesInput) DescribeVTLDevicesRequest
}
// Send marshals and sends the DescribeVTLDevices API request.
func (r DescribeVTLDevicesRequest) Send(ctx context.Context) (*DescribeVTLDevicesResponse, error) {
r.Request.SetContext(ctx)
err := r.Request.Send()
if err != nil {
return nil, err
}
resp := &DescribeVTLDevicesResponse{
DescribeVTLDevicesOutput: r.Request.Data.(*DescribeVTLDevicesOutput),
response: &aws.Response{Request: r.Request},
}
return resp, nil
}
// NewDescribeVTLDevicesRequestPaginator returns a paginator for DescribeVTLDevices.
// Use Next method to get the next page, and CurrentPage to get the current
// response page from the paginator. Next will return false, if there are
// no more pages, or an error was encountered.
//
// Note: This operation can generate multiple requests to a service.
//
// // Example iterating over pages.
// req := client.DescribeVTLDevicesRequest(input)
// p := storagegateway.NewDescribeVTLDevicesRequestPaginator(req)
//
// for p.Next(context.TODO()) {
// page := p.CurrentPage()
// }
//
// if err := p.Err(); err != nil {
// return err
// }
//
func NewDescribeVTLDevicesPaginator(req DescribeVTLDevicesRequest) DescribeVTLDevicesPaginator {
return DescribeVTLDevicesPaginator{
Pager: aws.Pager{
NewRequest: func(ctx context.Context) (*aws.Request, error) {
var inCpy *DescribeVTLDevicesInput
if req.Input != nil {
tmp := *req.Input
inCpy = &tmp
}
newReq := req.Copy(inCpy)
newReq.SetContext(ctx)
return newReq.Request, nil
},
},
}
}
// DescribeVTLDevicesPaginator is used to paginate the request. This can be done by
// calling Next and CurrentPage.
type DescribeVTLDevicesPaginator struct {
aws.Pager
}
func (p *DescribeVTLDevicesPaginator) CurrentPage() *DescribeVTLDevicesOutput {
return p.Pager.CurrentPage().(*DescribeVTLDevicesOutput)
}
// DescribeVTLDevicesResponse is the response type for the
// DescribeVTLDevices API operation.
type DescribeVTLDevicesResponse struct {
*DescribeVTLDevicesOutput
response *aws.Response
}
// SDKResponseMetdata returns the response metadata for the
// DescribeVTLDevices request.
func (r *DescribeVTLDevicesResponse) SDKResponseMetdata() *aws.Response {
return r.response
}
|
ruhan1/indy | models/core-java/src/test/java/org/commonjava/indy/model/core/dto/EndpointViewListingTest.java | /**
* Copyright (C) 2011-2019 Red Hat, Inc. (https://github.com/Commonjava/indy)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.commonjava.indy.model.core.dto;
import org.commonjava.indy.model.core.RemoteRepository;
import org.commonjava.indy.model.core.io.IndyObjectMapper;
import org.junit.Test;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
/**
* Created by jdcasey on 4/25/16.
*/
public class EndpointViewListingTest
{
@Test
public void jsonRoundTrip()
throws IOException
{
EndpointView first = new EndpointView( new RemoteRepository( "test", "http://foo.com/repo" ), "http://localhost:8080/api/remote/test" );
EndpointView second = new EndpointView( new RemoteRepository( "test2", "http://foo2.com/repo2" ), "http://localhost:8080/api/remote/test2" );
EndpointViewListing in = new EndpointViewListing( Arrays.asList( first, second ) );
IndyObjectMapper mapper = new IndyObjectMapper( true );
String json = mapper.writeValueAsString( in );
EndpointViewListing out = mapper.readValue( json, EndpointViewListing.class );
assertThat( out, notNullValue() );
List<EndpointView> items = out.getItems();
assertThat( items, notNullValue() );
assertThat( items.size(), equalTo( 2 ) );
int i=0;
EndpointView view = items.get(i++);
assertThat( view.getKey(), equalTo( first.getKey() ) );
assertThat( view.getName(), equalTo( first.getName() ) );
assertThat( view.getResourceUri(), equalTo( first.getResourceUri() ) );
assertThat( view.getStoreKey(), equalTo( first.getStoreKey() ) );
assertThat( view.getStoreType(), equalTo( first.getStoreType() ) );
assertThat( view, equalTo( first ) );
view = items.get(i++);
assertThat( view.getKey(), equalTo( second.getKey() ) );
assertThat( view.getName(), equalTo( second.getName() ) );
assertThat( view.getResourceUri(), equalTo( second.getResourceUri() ) );
assertThat( view.getStoreKey(), equalTo( second.getStoreKey() ) );
assertThat( view.getStoreType(), equalTo( second.getStoreType() ) );
assertThat( view, equalTo( second ) );
}
}
|
ZFFrameworkDist/ZFFramework | ZF/ZFCore_impl/zfsrc/ZFImpl/sys_Qt/ZFProtocolZFObjectMutex_sys_Qt.cpp | #include "ZFImpl_sys_Qt_ZFCore_impl.h"
#include "ZFCore/protocol/ZFProtocolZFObjectMutex.h"
#if ZF_ENV_sys_Qt
#include <QRecursiveMutex>
ZF_NAMESPACE_GLOBAL_BEGIN
zfclassNotPOD _ZFP_ZFObjectMutexImpl_sys_Qt
{
public:
static void *implInit(void)
{
return zfnew(QRecursiveMutex);
}
static void implDealloc(ZF_IN void *implObject)
{
QRecursiveMutex *mutex = (QRecursiveMutex *)implObject;
zfdelete(mutex);
}
static void implLock(ZF_IN void *implObject)
{
QRecursiveMutex *mutex = (QRecursiveMutex *)implObject;
mutex->lock();
}
static void implUnlock(ZF_IN void *implObject)
{
QRecursiveMutex *mutex = (QRecursiveMutex *)implObject;
mutex->unlock();
}
static zfbool implTryLock(ZF_IN void *implObject)
{
QRecursiveMutex *mutex = (QRecursiveMutex *)implObject;
return mutex->tryLock();
}
};
ZFOBJECT_MUTEX_IMPL_DEFINE(ZFObjectMutexImpl_sys_Qt, ZFProtocolLevel::e_SystemHigh, {
ZFObjectMutexImplSet(
_ZFP_ZFObjectMutexImpl_sys_Qt::implInit,
_ZFP_ZFObjectMutexImpl_sys_Qt::implDealloc,
_ZFP_ZFObjectMutexImpl_sys_Qt::implLock,
_ZFP_ZFObjectMutexImpl_sys_Qt::implUnlock,
_ZFP_ZFObjectMutexImpl_sys_Qt::implTryLock
);
})
ZF_NAMESPACE_GLOBAL_END
#endif // #if ZF_ENV_sys_Qt
|
LeoChensj/Demo | xbed/PublicView/BlueEnableButton.h | //
// BlueEnableButton.h
// xbed
//
// Created by Leo.Chen on 16/8/26.
// Copyright © 2016年 Leo.Chen. All rights reserved.
//
#import "EnableButton.h"
@interface BlueEnableButton : EnableButton
@property (nonatomic, strong)NSString *title;
@end
|
vadimsu/netbsd_dpdk_port | netbsd/net80211/ieee80211_node.h | <gh_stars>1-10
/* $NetBSD: ieee80211_node.h,v 1.24 2011/10/07 16:51:45 dyoung Exp $ */
/*-
* Copyright (c) 2001 <NAME>
* Copyright (c) 2002-2005 <NAME>, Errno Consulting
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* Alternatively, this software may be distributed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* $FreeBSD: src/sys/net80211/ieee80211_node.h,v 1.22 2005/08/10 16:22:29 sam Exp $
*/
#ifndef _NET80211_IEEE80211_NODE_H_
#define _NET80211_IEEE80211_NODE_H_
#include <special_includes/sys/atomic.h>
#include <net80211/ieee80211_netbsd.h>
#include <net80211/ieee80211_ioctl.h> /* for ieee80211_nodestats */
#ifdef _KERNEL
/*
* Each ieee80211com instance has a single timer that fires once a
* second. This is used to initiate various work depending on the
* state of the instance: scanning (passive or active), ``transition''
* (waiting for a response to a management frame when operating
* as a station), and node inactivity processing (when operating
* as an AP). For inactivity processing each node has a timeout
* set in it's ni_inact field that is decremented on each timeout
* and the node is reclaimed when the counter goes to zero. We
* use different inactivity timeout values depending on whether
* the node is associated and authorized (either by 802.1x or
* open/shared key authentication) or associated but yet to be
* authorized. The latter timeout is shorter to more aggressively
* reclaim nodes that leave part way through the 802.1x exchange.
*/
#define IEEE80211_INACT_WAIT 15 /* inactivity interval (secs) */
#define IEEE80211_INACT_INIT (30/IEEE80211_INACT_WAIT) /* initial */
#define IEEE80211_INACT_AUTH (180/IEEE80211_INACT_WAIT) /* associated but not authorized */
#define IEEE80211_INACT_RUN (300/IEEE80211_INACT_WAIT) /* authorized */
#define IEEE80211_INACT_PROBE (30/IEEE80211_INACT_WAIT) /* probe */
#define IEEE80211_INACT_SCAN (300/IEEE80211_INACT_WAIT) /* scanned */
#define IEEE80211_TRANS_WAIT 5 /* mgt frame tx timer (secs) */
#define IEEE80211_NODE_HASHSIZE 32
/* simple hash is enough for variation of macaddr */
#define IEEE80211_NODE_HASH(addr) \
(((const u_int8_t *)(addr))[IEEE80211_ADDR_LEN - 1] % \
IEEE80211_NODE_HASHSIZE)
struct ieee80211_rsnparms {
u_int8_t rsn_mcastcipher; /* mcast/group cipher */
u_int8_t rsn_mcastkeylen; /* mcast key length */
u_int8_t rsn_ucastcipherset; /* unicast cipher set */
u_int8_t rsn_ucastcipher; /* selected unicast cipher */
u_int8_t rsn_ucastkeylen; /* unicast key length */
u_int8_t rsn_keymgmtset; /* key mangement algorithms */
u_int8_t rsn_keymgmt; /* selected key mgmt algo */
u_int16_t rsn_caps; /* capabilities */
};
struct ieee80211_node_table;
struct ieee80211com;
/*
* Node specific information. Note that drivers are expected
* to derive from this structure to add device-specific per-node
* state. This is done by overriding the ic_node_* methods in
* the ieee80211com structure.
*/
struct ieee80211_node {
struct ieee80211com *ni_ic;
struct ieee80211_node_table *ni_table;
TAILQ_ENTRY(ieee80211_node) ni_list;
LIST_ENTRY(ieee80211_node) ni_hash;
u_int ni_refcnt;
u_int ni_scangen; /* gen# for timeout scan */
u_int8_t ni_authmode; /* authentication algorithm */
u_int16_t ni_flags; /* special-purpose state */
#define IEEE80211_NODE_AUTH 0x0001 /* authorized for data */
#define IEEE80211_NODE_QOS 0x0002 /* QoS enabled */
#define IEEE80211_NODE_ERP 0x0004 /* ERP enabled */
/* NB: this must have the same value as IEEE80211_FC1_PWR_MGT */
#define IEEE80211_NODE_PWR_MGT 0x0010 /* power save mode enabled */
#define IEEE80211_NODE_AREF 0x0020 /* authentication ref held */
u_int16_t ni_associd; /* assoc response */
u_int16_t ni_txpower; /* current transmit power */
u_int16_t ni_vlan; /* vlan tag */
u_int32_t *ni_challenge; /* shared-key challenge */
u_int8_t *ni_wpa_ie; /* captured WPA/RSN ie */
u_int8_t *ni_wme_ie; /* captured WME ie */
u_int16_t ni_txseqs[17]; /* tx seq per-tid */
u_int16_t ni_rxseqs[17]; /* rx seq previous per-tid*/
u_int32_t ni_rxfragstamp; /* time stamp of last rx frag */
struct mbuf *ni_rxfrag[3]; /* rx frag reassembly */
struct ieee80211_rsnparms ni_rsn; /* RSN/WPA parameters */
struct ieee80211_key ni_ucastkey; /* unicast key */
/* hardware */
u_int32_t ni_rstamp; /* recv timestamp */
u_int8_t ni_rssi; /* recv ssi */
/* header */
u_int8_t ni_macaddr[IEEE80211_ADDR_LEN];
u_int8_t ni_bssid[IEEE80211_ADDR_LEN];
/* beacon, probe response */
union {
u_int8_t data[8];
u_int64_t tsf;
} ni_tstamp; /* from last rcv'd beacon */
u_int16_t ni_intval; /* beacon interval */
u_int16_t ni_capinfo; /* capabilities */
u_int8_t ni_esslen;
u_int8_t ni_essid[IEEE80211_NWID_LEN];
struct ieee80211_rateset ni_rates; /* negotiated rate set */
struct ieee80211_channel *ni_chan; /* XXX multiple uses */
u_int16_t ni_fhdwell; /* FH only */
u_int8_t ni_fhindex; /* FH only */
u_int8_t ni_erp; /* ERP from beacon/probe resp */
u_int16_t ni_timoff; /* byte offset to TIM ie */
u_int8_t ni_dtim_period; /* DTIM period */
u_int8_t ni_dtim_count; /* DTIM count for last bcn */
/* others */
int ni_fails; /* failure count to associate */
short ni_inact; /* inactivity mark count */
short ni_inact_reload;/* inactivity reload value */
int ni_txrate; /* index to ni_rates[] */
struct ifqueue ni_savedq; /* ps-poll queue */
struct ieee80211_nodestats ni_stats; /* per-node statistics */
};
MALLOC_DECLARE(M_80211_NODE);
#define IEEE80211_NODE_AID(ni) IEEE80211_AID(ni->ni_associd)
#define IEEE80211_NODE_STAT(ni,stat) (ni->ni_stats.ns_##stat++)
#define IEEE80211_NODE_STAT_ADD(ni,stat,v) (ni->ni_stats.ns_##stat += v)
#define IEEE80211_NODE_STAT_SET(ni,stat,v) (ni->ni_stats.ns_##stat = v)
struct ieee80211com;
void ieee80211_node_attach(struct ieee80211com *);
void ieee80211_node_lateattach(struct ieee80211com *);
void ieee80211_node_detach(struct ieee80211com *);
static __inline int
ieee80211_node_is_authorized(const struct ieee80211_node *ni)
{
return (ni->ni_flags & IEEE80211_NODE_AUTH);
}
void ieee80211_node_authorize(struct ieee80211_node *);
void ieee80211_node_unauthorize(struct ieee80211_node *);
void ieee80211_begin_scan(struct ieee80211com *, int);
int ieee80211_next_scan(struct ieee80211com *);
void ieee80211_probe_curchan(struct ieee80211com *, int);
void ieee80211_create_ibss(struct ieee80211com*, struct ieee80211_channel *);
void ieee80211_reset_bss(struct ieee80211com *);
void ieee80211_cancel_scan(struct ieee80211com *);
void ieee80211_end_scan(struct ieee80211com *);
int ieee80211_ibss_merge(struct ieee80211_node *);
int ieee80211_sta_join(struct ieee80211com *, struct ieee80211_node *);
void ieee80211_sta_leave(struct ieee80211com *, struct ieee80211_node *);
/*
* Table of ieee80211_node instances. Each ieee80211com
* has at least one for holding the scan candidates.
* When operating as an access point or in ibss mode there
* is a second table for associated stations or neighbors.
*/
struct ieee80211_node_table {
struct ieee80211com *nt_ic; /* back reference */
ieee80211_node_lock_t nt_nodelock; /* on node table */
TAILQ_HEAD(, ieee80211_node) nt_node; /* information of all nodes */
LIST_HEAD(, ieee80211_node) nt_hash[IEEE80211_NODE_HASHSIZE];
const char *nt_name; /* for debugging */
ieee80211_scan_lock_t nt_scanlock; /* on nt_scangen */
u_int nt_scangen; /* gen# for timeout scan */
int nt_inact_timer; /* inactivity timer */
int nt_inact_init; /* initial node inact setting */
struct ieee80211_node **nt_keyixmap; /* key ix -> node map */
int nt_keyixmax; /* keyixmap size */
void (*nt_timeout)(struct ieee80211_node_table *);
};
void ieee80211_node_table_reset(struct ieee80211_node_table *);
struct ieee80211_node *ieee80211_alloc_node(
struct ieee80211_node_table *, const u_int8_t *);
struct ieee80211_node *ieee80211_tmp_node(struct ieee80211com *,
const u_int8_t *macaddr);
struct ieee80211_node *ieee80211_dup_bss(struct ieee80211_node_table *,
const u_int8_t *);
#ifdef IEEE80211_DEBUG_REFCNT
void ieee80211_free_node_debug(struct ieee80211_node *,
const char *func, int line);
struct ieee80211_node *ieee80211_find_node_debug(
struct ieee80211_node_table *, const u_int8_t *,
const char *func, int line);
struct ieee80211_node * ieee80211_find_rxnode_debug(
struct ieee80211com *, const struct ieee80211_frame_min *,
const char *func, int line);
struct ieee80211_node * ieee80211_find_rxnode_withkey_debug(
struct ieee80211com *,
const struct ieee80211_frame_min *, u_int16_t keyix,
const char *func, int line);
struct ieee80211_node *ieee80211_find_txnode_debug(
struct ieee80211com *, const u_int8_t *,
const char *func, int line);
struct ieee80211_node *ieee80211_find_node_with_channel_debug(
struct ieee80211_node_table *, const u_int8_t *macaddr,
struct ieee80211_channel *, const char *func, int line);
struct ieee80211_node *ieee80211_find_node_with_ssid_debug(
struct ieee80211_node_table *, const u_int8_t *macaddr,
u_int ssidlen, const u_int8_t *ssid,
const char *func, int line);
#define ieee80211_free_node(ni) \
ieee80211_free_node_debug(ni, __func__, __LINE__)
#define ieee80211_find_node(nt, mac) \
ieee80211_find_node_debug(nt, mac, __func__, __LINE__)
#define ieee80211_find_rxnode(nt, wh) \
ieee80211_find_rxnode_debug(nt, wh, __func__, __LINE__)
#define ieee80211_find_rxnode_withkey(nt, wh, keyix) \
ieee80211_find_rxnode_withkey_debug(nt, wh, keyix, __func__, __LINE__)
#define ieee80211_find_txnode(nt, mac) \
ieee80211_find_txnode_debug(nt, mac, __func__, __LINE__)
#define ieee80211_find_node_with_channel(nt, mac, c) \
ieee80211_find_node_with_channel_debug(nt, mac, c, __func__, __LINE__)
#define ieee80211_find_node_with_ssid(nt, mac, sl, ss) \
ieee80211_find_node_with_ssid_debug(nt, mac, sl, ss, __func__, __LINE__)
#else
void ieee80211_free_node(struct ieee80211_node *);
struct ieee80211_node *ieee80211_find_node(
struct ieee80211_node_table *, const u_int8_t *);
struct ieee80211_node * ieee80211_find_rxnode(
struct ieee80211com *, const struct ieee80211_frame_min *);
struct ieee80211_node * ieee80211_find_rxnode_withkey(struct ieee80211com *,
const struct ieee80211_frame_min *, u_int16_t keyix);
struct ieee80211_node *ieee80211_find_txnode(
struct ieee80211com *, const u_int8_t *);
struct ieee80211_node *ieee80211_find_node_with_channel(
struct ieee80211_node_table *, const u_int8_t *macaddr,
struct ieee80211_channel *);
struct ieee80211_node *ieee80211_find_node_with_ssid(
struct ieee80211_node_table *, const u_int8_t *macaddr,
u_int ssidlen, const u_int8_t *ssid);
#endif
int ieee80211_node_delucastkey(struct ieee80211_node *);
struct ieee80211_node *ieee80211_refine_node_for_beacon(
struct ieee80211com *, struct ieee80211_node *,
struct ieee80211_channel *, const u_int8_t *ssid);
typedef void ieee80211_iter_func(void *, struct ieee80211_node *);
void ieee80211_iterate_nodes(struct ieee80211_node_table *,
ieee80211_iter_func *, void *);
void ieee80211_dump_node(struct ieee80211_node_table *,
struct ieee80211_node *);
void ieee80211_dump_nodes(struct ieee80211_node_table *);
struct ieee80211_node *ieee80211_fakeup_adhoc_node(
struct ieee80211_node_table *, const u_int8_t macaddr[]);
void ieee80211_node_join(struct ieee80211com *, struct ieee80211_node *,int);
void ieee80211_node_leave(struct ieee80211com *, struct ieee80211_node *);
u_int8_t ieee80211_getrssi(struct ieee80211com *ic);
/*
* Parameters supplied when adding/updating an entry in a
* scan cache. Pointer variables should be set to NULL
* if no data is available. Pointer references can be to
* local data; any information that is saved will be copied.
* All multi-byte values must be in host byte order.
*/
struct ieee80211_scanparams {
u_int16_t capinfo; /* 802.11 capabilities */
u_int16_t fhdwell; /* FHSS dwell interval */
u_int8_t chan; /* */
u_int8_t bchan;
u_int8_t fhindex;
u_int8_t erp;
u_int16_t bintval;
u_int8_t timoff;
u_int8_t *tim;
u_int8_t *tstamp;
u_int8_t *country;
u_int8_t *ssid;
u_int8_t *rates;
u_int8_t *xrates;
u_int8_t *wpa;
u_int8_t *wme;
};
/*
* Node reference counting definitions.
*
* ieee80211_node_initref initialize the reference count to 1
* ieee80211_node_incref add a reference
* ieee80211_node_decref remove a reference
* ieee80211_node_dectestref remove a reference and return 1 if this
* is the last reference, otherwise 0
* ieee80211_node_refcnt reference count for printing (only)
*/
static inline void
ieee80211_node_initref(struct ieee80211_node *ni)
{
ni->ni_refcnt = 1;
}
static inline void
ieee80211_node_incref(struct ieee80211_node *ni)
{
atomic_inc_uint(&ni->ni_refcnt);
}
static inline void
ieee80211_node_decref(struct ieee80211_node *ni)
{
atomic_dec_uint(&ni->ni_refcnt);
}
int ieee80211_node_dectestref(struct ieee80211_node *ni);
static inline unsigned int
ieee80211_node_refcnt(const struct ieee80211_node *ni)
{
return ni->ni_refcnt;
}
static __inline struct ieee80211_node *
ieee80211_ref_node(struct ieee80211_node *ni)
{
ieee80211_node_incref(ni);
return ni;
}
static __inline void
ieee80211_unref_node(struct ieee80211_node **ni)
{
ieee80211_node_decref(*ni);
*ni = NULL; /* guard against use */
}
void ieee80211_add_scan(struct ieee80211com *,
const struct ieee80211_scanparams *,
const struct ieee80211_frame *,
int subtype, int rssi, int rstamp);
void ieee80211_init_neighbor(struct ieee80211com *, struct ieee80211_node *,
const struct ieee80211_frame *,
const struct ieee80211_scanparams *, int);
struct ieee80211_node *ieee80211_add_neighbor(struct ieee80211com *,
const struct ieee80211_frame *,
const struct ieee80211_scanparams *);
#endif /* _KERNEL */
#endif /* !_NET80211_IEEE80211_NODE_H_ */
|
xuychen/Leetcode | 1401-1500/1471-1480/1480-runningSumOf1DArray/runningSumOf1DArray.py | <filename>1401-1500/1471-1480/1480-runningSumOf1DArray/runningSumOf1DArray.py
class Solution(object):
def runningSum(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
result = nums[:]
for i in range(1, len(nums)):
result[i] += result[i-1]
return result |
ranmx/playframework | documentation/manual/working/scalaGuide/main/tests/code/database/ScalaTestingWithDatabases.scala | <filename>documentation/manual/working/scalaGuide/main/tests/code/database/ScalaTestingWithDatabases.scala
/*
* Copyright (C) 2009-2019 Lightbend Inc. <https://www.lightbend.com>
*/
package scalaguide.testing.database
import java.sql.SQLException
import org.specs2.mutable.Specification
class ScalaTestingWithDatabases extends Specification {
// We don't test this code because otherwise it would try to connect to MySQL
class NotTested {
{
//#database
import play.api.db.Databases
val database = Databases(
driver = "com.mysql.jdbc.Driver",
url = "jdbc:mysql://localhost/test"
)
//#database
}
{
//#full-config
import play.api.db.Databases
val database = Databases(
driver = "com.mysql.jdbc.Driver",
url = "jdbc:mysql://localhost/test",
name = "mydatabase",
config = Map(
"username" -> "test",
"password" -> "<PASSWORD>"
)
)
//#full-config
//#shutdown
database.shutdown()
//#shutdown
}
{
//#with-database
import play.api.db.Databases
Databases.withDatabase(
driver = "com.mysql.jdbc.Driver",
url = "jdbc:mysql://localhost/test"
) { database =>
val connection = database.getConnection()
// ...
}
//#with-database
}
{
//#custom-with-database
import play.api.db.Database
import play.api.db.Databases
def withMyDatabase[T](block: Database => T) = {
Databases.withDatabase(
driver = "com.mysql.jdbc.Driver",
url = "jdbc:mysql://localhost/test",
name = "mydatabase",
config = Map(
"username" -> "test",
"password" -> "<PASSWORD>"
)
)(block)
}
//#custom-with-database
//#custom-with-database-use
withMyDatabase { database =>
val connection = database.getConnection()
// ...
}
//#custom-with-database-use
}
}
"database helpers" should {
"allow connecting to an in memory database" in {
//#in-memory
import play.api.db.Databases
val database = Databases.inMemory()
//#in-memory
try {
database.getConnection().getMetaData.getDatabaseProductName must_== "H2"
} finally {
database.shutdown()
}
}
"allow connecting to an in memory database with more options" in {
//#in-memory-full-config
import play.api.db.Databases
val database = Databases.inMemory(
name = "mydatabase",
urlOptions = Map(
"MODE" -> "MYSQL"
),
config = Map(
"logStatements" -> true
)
)
//#in-memory-full-config
try {
database.getConnection().getMetaData.getDatabaseProductName must_== "H2"
} finally {
//#in-memory-shutdown
database.shutdown()
//#in-memory-shutdown
}
}
"manage an in memory database for the user" in {
//#with-in-memory
import play.api.db.Databases
Databases.withInMemory() { database =>
val connection = database.getConnection()
// ...
}
//#with-in-memory
ok
}
"manage an in memory database for the user with custom config" in {
//#with-in-memory-custom
import play.api.db.Database
import play.api.db.Databases
def withMyDatabase[T](block: Database => T) = {
Databases.withInMemory(
name = "mydatabase",
urlOptions = Map(
"MODE" -> "MYSQL"
),
config = Map(
"logStatements" -> true
)
)(block)
}
//#with-in-memory-custom
withMyDatabase(_.getConnection().getMetaData.getDatabaseProductName must_== "H2")
}
"allow running evolutions" in play.api.db.Databases.withInMemory() { database =>
//#apply-evolutions
import play.api.db.evolutions._
Evolutions.applyEvolutions(database)
//#apply-evolutions
//#cleanup-evolutions
Evolutions.cleanupEvolutions(database)
//#cleanup-evolutions
ok
}
"allow running static evolutions" in play.api.db.Databases.withInMemory() { database =>
//#apply-evolutions-simple
import play.api.db.evolutions._
Evolutions.applyEvolutions(
database,
SimpleEvolutionsReader.forDefault(
Evolution(
1,
"create table test (id bigint not null, name varchar(255));",
"drop table test;"
)
)
)
//#apply-evolutions-simple
val connection = database.getConnection()
connection.prepareStatement("insert into test values (10, 'testing')").execute()
//#cleanup-evolutions-simple
Evolutions.cleanupEvolutions(database)
//#cleanup-evolutions-simple
connection.prepareStatement("select * from test").executeQuery() must throwAn[SQLException]
}
"allow running evolutions from a custom path" in play.api.db.Databases.withInMemory() { database =>
//#apply-evolutions-custom-path
import play.api.db.evolutions._
Evolutions.applyEvolutions(database, ClassLoaderEvolutionsReader.forPrefix("testdatabase/"))
//#apply-evolutions-custom-path
ok
}
"allow play to manage evolutions for you" in play.api.db.Databases.withInMemory() { database =>
//#with-evolutions
import play.api.db.evolutions._
Evolutions.withEvolutions(database) {
val connection = database.getConnection()
// ...
}
//#with-evolutions
ok
}
"allow simple composition of with database and with evolutions" in {
//#with-evolutions-custom
import play.api.db.Database
import play.api.db.Databases
import play.api.db.evolutions._
def withMyDatabase[T](block: Database => T) = {
Databases.withInMemory(
urlOptions = Map(
"MODE" -> "MYSQL"
),
config = Map(
"logStatements" -> true
)
) { database =>
Evolutions.withEvolutions(
database,
SimpleEvolutionsReader.forDefault(
Evolution(
1,
"create table test (id bigint not null, name varchar(255));",
"drop table test;"
)
)
) {
block(database)
}
}
}
//#with-evolutions-custom
//#with-evolutions-custom-use
withMyDatabase { database =>
val connection = database.getConnection()
connection.prepareStatement("insert into test values (10, 'testing')").execute()
connection
.prepareStatement("select * from test where id = 10")
.executeQuery()
.next() must_== true
}
//#with-evolutions-custom-use
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.