text
stringlengths
20
1.01M
url
stringlengths
14
1.25k
dump
stringlengths
9
15
lang
stringclasses
4 values
source
stringclasses
4 values
Secrets like passwords, API keys, are sensitive information should be stored in a secure, encrypted storage, access controlled, and auditable. Some systems opt to use Vault to store these secrets. On Google Cloud Platform, you can use Secret Manager, a managed service, to securely store the secrets, and control access to individual secrets using IAM. In Spring Boot, you can use Spring Cloud GCP to easily access these secrets by referring to them as any other Spring properties. In this codelab, you will store a secret in Secret Manager, then build simple Spring Boot microservices and retrieve the secret. What you'll learn - How to create a Spring Boot Java application and configure Secret Manager. services]. To use Secret Manager, first enable the API: $ gcloud services enable secretmanager.googleapis.com Then, create a secret named greeting, with value of Hello: $ echo -n "Hello" | \ gcloud secrets create greeting \ --data-file=- --replication-policy=automatic This command uses STDIN to provide the value to the command line. However, you can also simply put the secret value in a file, an specify the filename for the --data-file argument. You can list all the secrets using the gcloud CLI: $ gcloud secrets list After Cloud Shell launches, you can use the command line to generate a new Spring Boot application with Spring Initializr: $ curl -d packaging=jar \ -d dependencies=web,cloud-gcp \ -d bootVersion=2.4.0 \ -d baseDir=hello-secret-manager | tar -xzvf - \ && cd hello-secret-manager In the pom.xml, add the Spring Cloud GCP starter dependency: pom.xml <project> ... <dependencies> ... <!-- Add Secret Manager Starter --> <dependency> <groupId>com.google.cloud</groupId> <artifactId>spring-cloud-gcp-starter-secretmanager</artifactId> </dependency> </dependencies> ... </project> This will automatically configure a Spring Property Source, so that you can simply refer to secrets using a property value, with the prefix of sm://, for example, sm://greeting. See Spring Cloud GCP Secret Manager documentation for more detail on the format of the property. Create a new REST controller by adding a new class: src/main/java/com/example/demo/HelloSecretController.java package com.example.demo; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloSecretController { String greeting = "Hi"; @GetMapping("/") public String hello() { return greeting + " World!"; } }_0<< You can use the @Value annotation to refer to the secret property using the sm:// prefix. In the HelloSecretController class, inject the greeting value using the annotation, src/main/java/com/example/demo/HelloSecretController.java import org.springframework.beans.factory.annotation.Value; ... @RestController public class HelloSecretController { @Value("${sm:/_1<< You can also map the value to a property in application.properties: src/main/resources/application.properties greeting=${sm://greeting} In HelloSecretController, you can reference to this more generic property name as opposed to a Secret Manager name: src/main/java/com/example/demo/HelloSecretController.java @RestController public class HelloSecretController { @Value("$. This technique is useful especially if you use different Spring Boot application profiles. For example, you can create secrets such as greeting-dev, greeting-staging, greeting-prod. And in each of the profile, map to the right greetings. Create a greeting-prod secret: $ echo -n "Hola" | \ gcloud secrets create greeting-prod \ --data-file=- --replication-policy=automatic Create an application-prod.properties file. src/main/resources/application-prod.properties greeting=${sm://greeting-prod} You can start the Spring Boot application normally with the Spring Boot plugin, but with the prod profile. Let's skip tests for this lab: $ ./mvnw -DskipTests spring-boot:run -Dspring-boot.run.profiles=prod Once the application started, click on the Web Preview icon in the Cloud Shell toolbar and choose preview on port 8080. After a short wait you should see the result: In this lab, you've created a service that can be configured using secrets stored in Secret Manager by using Spring's property names prefixed with sm:// and injecting the value from applications.properties file and @Value annotations.. You learned how to write your first App Engine web application! Learn More - Stackdriver Trace: - Spring on GCP project: - Spring on GCP GitHub repository: - Java on Google Cloud Platform: - Controlling access to secrets in Secret Manager - Audit Logging in Secret manager License This work is licensed under a Creative Commons Attribution 2.0 Generic License.
https://codelabs.developers.google.com/codelabs/cloud-spring-cloud-gcp-secret-manager/index.html?index=..%2F..cloud
CC-MAIN-2021-04
en
refinedweb
Create an ingress controller in Azure Kubernetes Service (AKS). This article shows you how to deploy the NGINX ingress controller in an Azure Kubernetes Service (AKS) cluster. Two applications are then run in the AKS cluster, each of which is accessible over the single IP address. Before you begin This article uses Helm 3 to install the NGINX ingress controller. Make sure that you are using the latest release of Helm and have access to the ingress-nginx Helm repository. This article also requires that you are running the Azure CLI version 2.0.64 or later. Run az --version to find the version. If you need to install or upgrade, see Install Azure CLI. Create an ingress controller To create the ingress controller, use Helm to install nginx-ingress. For added redundancy, two replicas of the NGINX ingress controllers are deployed with the --set controller.replicaCount parameter. To fully benefit from running replicas of the ingress controller, make sure there's more than one node in your AKS cluster. The ingress controller also needs to be scheduled on a Linux node. Windows Server nodes shouldn't run the ingress controller. A node selector is specified using the --set nodeSelector parameter to tell the Kubernetes scheduler to run the NGINX ingress controller on a Linux-based node. Tip The following example creates a Kubernetes namespace for the ingress resources named ingress-basic. Specify a namespace for your own environment as needed. Tip If you would like to enable client source IP preservation for requests to containers in your cluster, add --set controller.service.externalTrafficPolicy=Local to the Helm install command. The client source IP is stored in the request header under X-Forwarded-For. When using an ingress controller with client source IP preservation enabled, SSL pass-through will not work. # Create a namespace for your ingress resources kubectl create namespace ingress-basic # Add the ingress-nginx repository helm repo add ingress-nginx # Use Helm to deploy an NGINX ingress controller helm install nginx-ingress When the Kubernetes load balancer service is created for the NGINX ingress controller, a dynamic public IP address is assigned, as shown in the following example output: $ kubectl --namespace ingress-basic get services -o wide -w nginx-ingress-ingress-nginx-controller NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE SELECTOR nginx-ingress-ingress-nginx-controller LoadBalancer 10.0.74.133 EXTERNAL_IP 80:32486/TCP,443:30953/TCP 44s app.kubernetes.io/component=controller,app.kubernetes.io/instance=nginx-ingress,app.kubernetes.io/name=ingress-nginx No ingress rules have been created yet, so the NGINX ingress controller's default 404 page is displayed if you browse to the internal IP address. Ingress rules are configured in the following steps. Run demo applications To see the ingress controller in action, run two demo applications in your AKS cluster. In this example, you use kubectl apply to deploy two instances of a simple Hello world application. Create a aks-helloworld-one.yaml file and copy in the following example YAML: apiVersion: apps/v1 kind: Deployment metadata: name: aks-helloworld-one spec: replicas: 1 selector: matchLabels: app: aks-helloworld-one template: metadata: labels: app: aks-helloworld-one spec: containers: - name: aks-helloworld-one-one spec: type: ClusterIP ports: - port: 80 selector: app: aks-helloworld-one Create a aks-helloworld-two.yaml file and copy in the following example YAML: apiVersion: apps/v1 kind: Deployment metadata: name: aks-helloworld-two spec: replicas: 1 selector: matchLabels: app: aks-helloworld-two template: metadata: labels: app: aks-helloworld-two spec: containers: - name: aks-helloworld-two image: mcr.microsoft.com/azuredocs/aks-helloworld:v1 ports: - containerPort: 80 env: - name: TITLE value: "AKS Ingress Demo" --- apiVersion: v1 kind: Service metadata: name: aks-helloworld-two spec: type: ClusterIP ports: - port: 80 selector: app: aks-helloworld-two Run the two demo applications using kubectl apply: kubectl apply -f aks-helloworld-one.yaml --namespace ingress-basic kubectl apply -f aks-helloworld-two.yaml --namespace ingress-basic Create an ingress route Both applications are now running on your Kubernetes cluster. To route traffic to each application, create a Kubernetes ingress resource. The ingress resource configures the rules that route traffic to one of the two applications. In the following example, traffic to EXTERNAL_IP is routed to the service named aks-helloworld-one. Traffic to EXTERNAL_IP/hello-world-two is routed to the aks-helloworld-two service. Traffic to EXTERNAL_IP/static is routed to the service named aks-helloworld-one for static assets. Create a file named hello-world-ingress.yaml and copy in the following example YAML. apiVersion: networking.k8s.io/use-regex: "true" nginx.ingress.kubernetes.io/rewrite-target: /$1 spec: rules: - http: paths: - backend: serviceName: aks-helloworld-one servicePort: 80 path: /hello-world-one(/|$)(.*) - backend: serviceName: aks-helloworld-two servicePort: 80 path: /hello-world-two(/|$)(.*) - backend: serviceName: aks-helloworld-one servicePort: 80 path: /(.*) --- apiVersion: networking.k8s.io/v1beta1 kind: Ingress metadata: name: hello-world-ingress-static namespace: ingress-basic annotations: kubernetes.io/ingress.class: nginx nginx.ingress.kubernetes.io/ssl-redirect: "false" nginx.ingress.kubernetes.io/rewrite-target: /static/$2 spec: rules: - http: paths: - backend: serviceName: aks-helloworld-one servicePort: 80 path: /static(/|$)(.*) Create the ingress resource using the kubectl apply -f hello-world-ingress.yaml command. $ kubectl apply -f hello-world-ingress.yaml ingress.extensions/hello-world-ingress created ingress.extensions/hello-world-ingress-static created Test the ingress controller To test the routes for the ingress controller, browse to the two applications. Open a web browser to the IP address of your NGINX ingress controller, such as EXTERNAL_IP. The first demo application is displayed in the web browser, as shown in the follow example: Now add the /hello-world-two path to the IP address, such as EXTERNAL_IP/hello-world-two. The second demo application with the custom title is displayed: Clean up resources This article used Helm to install the ingress components and sample apps. When you deploy a Helm chart, a number of Kubernetes resources are created. These resources includes pods, deployments, and services. To clean up these resources, you can either delete the entire sample namespace, or the individual resources. Delete the sample namespace and all resources To delete the entire sample namespace, use the kubectl delete command and specify your namespace name. All the resources in the namespace are deleted. kubectl delete namespace ingress-basic Delete resources individually Alternatively, a more granular approach is to delete the individual resources created. List the Helm releases with the helm list command. Look for charts named nginx-ingress and aks-helloworld, as shown in the following example output: $ helm list --namespace ingress-basic NAME NAMESPACE REVISION UPDATED STATUS CHART APP VERSION nginx-ingress ingress-basic 1 2020-01-06 19:55:46.358275 -0600 CST deployed nginx-ingress-1.27.1 0.26.1 Uninstall the releases with the helm uninstall command. The following example uninstalls the NGINX ingress deployment. $ helm uninstall nginx-ingress --namespace ingress-basic release "nginx-ingress" uninstalled Next, remove the two sample applications: kubectl delete -f aks-helloworld-one.yaml --namespace ingress-basic kubectl delete -f aks-helloworld-two.yaml --namespace ingress-basic Remove the ingress route that directed traffic to the sample apps: kubectl delete -f hello-world-ingress.yaml Finally, you can delete the itself namespace. Use the kubectl delete command and specify your namespace name: kubectl delete namespace ingress-basic Next steps This article included some external components to AKS. To learn more about these components, see the following project pages:
https://docs.microsoft.com/en-us/azure/aks/ingress-basic
CC-MAIN-2021-04
en
refinedweb
Flylib.com I Previous page Table of content Next page Index [SYMBOL] [A] [B] [C] [D] [E] [F] [G] [H] [I] [J] [K] [L] [M] [N] [O] [P] [Q] [R] [S] [T] [U] [V] [W] [X] [Y] [Z] ID3 tags insertion by Grip iPod ID3ed tool ID3v1 tags ID3v2 tags frame identifying codes IDE CD burners idvid utility 2nd IEEE 1394 (Firewire) support IIS web server ImageMagick image processing for Gallery making a screen capture movie 2nd 3rd 4th images 2nd 3rd 4th 5th 6th 7th 8th 9th 10th 11th 12th 13th 14th 15th 16th 17th 18th 19th 20th 21st adding custom watermark 2nd converting image formats 2nd creating a slideshow 2nd digital camera 2nd 3rd editing with GIMP 2nd 3rd 4th image-processing library for Gallery managing digital photos with f-spot 2nd 3rd resizing (transcode) 2nd 3rd 4th support by w3m browser taking screenshots IMFavorites IMMS (Intelligent Multimedia Management System) 2nd 3rd 4th Magical Favorites Collector (IMFavorites) SQL queries iMovie import command 2nd infrared receivers infrared remote controls (LIRC) 2nd Input Connections input/output plug-ins (XMMS) install.sh script Intel8x0 Alsa driver Internet Movie Database Internet/multimedia keyboard 2nd 3rd 4th IP address iPod grip package Monopod synchronization facilities transferring files to and from with GtkPod using with Linux 2nd 3rd 4th 5th 6th 7th desktop setup iRipDB tool iRiver (music player) 2nd 3rd rebuilding the database transferring songs to irrecord command irw program irw tool .iso files creating for DVD creating for self-booting movie iTunes-like interface for audio ivtv driver ivtv kernel module Previous page Table of content Next page Linux Multimedia Hacks ISBN: 596100760 EAN: N/A Year: 2005 Pages: 156 BUY ON AMAZON Snort Cookbook Installing Snort Binaries on Linux Logging Only Alerts Logging to a Unix Socket How to Build Rules Analyzing Sniffed (Pcap) Traffic Excel Scientific and Engineering Cookbook (Cookbooks (OReilly)) Understanding Operator Precedence Defining Constants Combining Chart Types Recipe 4-14. Displaying Error Bars Introduction C & Data Structures (Charles River Media Computer Engineering) Control Structures Address and Pointers Arrays, Searching, and Sorting Trees Problems in Linked Lists Introducing Microsoft ASP.NET AJAX (Pro - Developer) The Pulsing Heart of ASP.NET AJAX Partial Page Rendering The AJAX Control Toolkit Built-in Application Services Building AJAX Applications with ASP.NET Pocket Guide to the National Electrical Code(R), 2005 Edition (8th Edition) Article 210 Branch Circuits Article 340 Underground Feeder and Branch-Circuit Cable Type UF Article 392 Cable Trays Article 645 Information Technology Equipment Example No. D2(c) Optional Calculation for One-Family Dwelling with Heat Pump(Single-Phase, 240/120-Volt Service) (See 220.82) VBScript in a Nutshell, 2nd Edition Introduction Windows Script Components Section A.16. User Interaction Section B.2. Comparison Constants Section B.6. Logical and TriState Constants flylib.com © 2008-2017. If you may any questions please contact us: flylib@qtcs.net This website uses cookies. Click here to find out more. Accept cookies
https://flylib.com/books/en/4.374.1.139/1/
CC-MAIN-2021-04
en
refinedweb
Often you might be interested in comparing the values between two pandas DataFrames to spot their similarities and differences. This tutorial explains how to do so. Example: Comparing Two DataFrames in Pandas Suppose we have the following two pandas DataFrames that each contain data about four basketball players: import pandas as pd #define DataFrame 1 df1 = pd.DataFrame({'player': ['A', 'B', 'C', 'D'], 'points': [12, 15, 17, 24], 'assists': [4, 6, 7, 8]}) df1 player points assists 0 A 12 4 1 B 15 6 2 C 17 7 3 D 24 88 #define DataFrame 2 df2 = pd.DataFrame({'player': ['A', 'B', 'C', 'D'], 'points': [12, 24, 26, 29], 'assists': [7, 8, 10, 13]}) df2 player points assists 0 A 12 7 1 B 24 8 2 C 26 10 3 D 29 13 Example 1: Find out if the two DataFrames are identical. We can first find out if the two DataFrames are identical by using the DataFrame.equals() function: #see if two DataFrames are identical df1.equals(df2) False The two DataFrames do not contain the exact same values, so this function correctly returns False. Example 2: Find the differences in player stats between the two DataFrames. We can find the differences between the assists and points for each player by using the pandas subtract() function: #subtract df1 from df2 df2.set_index('player').subtract(df1.set_index('player')) points assists player A 0 3 B 9 2 C 9 3 D 5 5 The way to interpret this is as follows: - Player A had the same amount of points in both DataFrames, but they had 3 more assists in DataFrame 2. - Player B had 9 more points and 2 more assists in DataFrame 2 compared to DataFrame 1. - Player C had 9 more points and 3 more assists in DataFrame 2 compared to DataFrame 1. - Player D had 5 more points and 5 more assists in DataFrame 2 compared to DataFrame 1. Example 3: Find all rows that only exist in one DataFrame. We can use the following code to obtain a complete list of rows that only appear in one DataFrame: #outer merge the two DataFrames, adding an indicator column called 'Exist' diff_df = pd.merge(df1, df2, how='outer', indicator='Exist') #find which rows don't exist in both DataFrames diff_df = diff_df.loc[diff_df['Exist'] != 'both'] diff_df player points assists Exist 0 A 12 4 left_only 1 B 15 6 left_only 2 C 17 7 left_only 3 D 24 8 left_only 4 A 12 7 right_only 5 B 24 8 right_only 6 C 26 10 right_only 7 D 29 13 right_only In this case, the two DataFrames share no identical rows so there are 8 total rows that only appear in one of the DataFrames. The column titled “Exist” conveniently tells us which DataFrame each row uniquely appears in.
https://www.statology.org/compare-two-dataframes-pandas/
CC-MAIN-2021-04
en
refinedweb
Form bindings Form Events To handle form changes and submissions, use the phx-change and phx-submit events. In general, it is preferred to handle input changes at the form level, where all form fields are passed to the LiveView's callback given any single input change. For example, to handle real-time form validation and saving, your template would use both phx_change and phx_submit bindings: <%= f = form_for @changeset, "#", [phx_change: :validate, phx_submit: :save] %> <%= label f, :username %> <%= text_input f, :username %> <%= error_tag f, :username %> <%= label f, :email %> <%= text_input f, :email %> <%= error_tag f, :email %> <%= submit "Save" %> </form> Reminder: form_for/3 is a Phoenix.HTML helper. Don't forget to include use Phoenix.HTML at the top of your LiveView, if using Phoenix.HTML helpers. Also, if using error_tag/2, don't forget to import MyAppWeb.ErrorHelpers. Next, your LiveView picks up the events in handle_event callbacks: def render(assigns) ... def mount(_params, _session, socket) do {:ok, assign(socket, %{changeset: Accounts.change_user(%User{})})} end def handle_event("validate", %{"user" => params}, socket) do changeset = %User{} |> Accounts.change_user(params) |> Map.put(:action, :insert) {:noreply, assign(socket, changeset: changeset)} end def handle_event("save", %{"user" => user_params}, socket) do case Accounts.create_user(user_params) do {:ok, user} -> {:noreply, socket |> put_flash(:info, "user created") |> redirect(to: Routes.user_path(MyAppWeb.Endpoint, MyAppWeb.User.ShowView, user))} {:error, %Ecto.Changeset{} = changeset} -> {:noreply, assign(socket, changeset: changeset)} end end The validate callback simply updates the changeset based on all form input values, then assigns the new changeset to the socket. If the changeset changes, such as generating new errors, render/1 is invoked and the form is re-rendered. Likewise for phx-submit bindings, the same callback is invoked and persistence is attempted. On success, a :noreply tuple is returned and the socket is annotated for redirect with Phoenix.LiveView.redirect/2 to the new user page, otherwise the socket assigns are updated with the errored changeset to be re-rendered for the client. phx-feedback-for For proper form error tag updates, the error tag must specify which input it belongs to. This is accomplished with the phx-feedback-for attribute, which specifies the name (or id, for backwards compatibility) of the input it belongs to. Failing to add the phx-feedback-for attribute will result in displaying error messages for form fields that the user has not changed yet (e.g. required fields further down on the page). For example, your MyAppWeb.ErrorHelpers may use this function: def error_tag(form, field) do form.errors |> Keyword.get_values(field) |> Enum.map(fn error -> content_tag(:span, translate_error(error), class: "invalid-feedback", phx_feedback_for: input_name(form, field) ) end) end Now, any DOM container with the phx-feedback-for attribute will receive a phx-no-feedback class in cases where the form fields has yet to receive user input/focus. The following css rules are generated in new projects to hide the errors: .phx-no-feedback.invalid-feedback, .phx-no-feedback .invalid-feedback { display: none; } Number inputs Number inputs are a special case in LiveView forms. On programmatic updates, some browsers will clear invalid inputs. So LiveView will not send change events from the client when an input is invalid, instead allowing the browser's native validation UI to drive user interaction. Once the input becomes valid, change and submit events will be sent normally. <input type="number"> This is known to have a plethora of problems including accessibility, large numbers are converted to exponential notation and scrolling can accidentally increase or decrease the number. As of early 2020, the following avoids these pitfalls and will likely serve your application's needs and users much better. According to, the following is supported by 90% of the global mobile market with Firefox yet to implement. <input type="text" inputmode="numeric" pattern="[0-9]*"> Password inputs Password inputs are also special cased in Phoenix.HTML. For security reasons, password field values are not reused when rendering a password input tag. This requires explicitly setting the :value in your markup, for example: <%= password_input f, :password, value: input_value(f, :password) %> <%= password_input f, :password_confirmation, value: input_value(f, :password_confirmation) %> <%= error_tag f, :password %> <%= error_tag f, :password_confirmation %> File inputs LiveView forms support reactive file inputs, including drag and drop support via the phx-drop-target attribute: <div class="container" phx- ... <%= live_file_input @uploads.avatar %> </div> See Phoenix.LiveView.Helpers.live_file_input/2 for more. Submitting the form action over HTTP The phx-trigger-action attribute can be added to a form to trigger a standard form submit on DOM patch to the URL specified in the form's standard action attribute. This is useful to perform pre-final validation of a LiveView form submit before posting to a controller route for operations that require Plug session mutation. For example, in your LiveView template you can annotate the phx-trigger-action with a boolean assign: <%= f = form_for @changeset, Routes.reset_password_path(@socket, :create), phx_submit: :save, phx_trigger_action: @trigger_submit %> Then in your LiveView, you can toggle the assign to trigger the form with the current fields on next render: def handle_event("save", params, socket) do case validate_change_password(socket.assigns.user, params) do {:ok, changeset} -> {:noreply, assign(socket, changeset: changeset, trigger_submit: true)} {:error, changeset} -> {:noreply, assign(socket, changeset: changeset)} end end Once phx-trigger-action is true, LiveView disconnects and then submits the form. Recovery following crashes or disconnects By default, all forms marked with phx-change will recover input values automatically after the user has reconnected or the LiveView has remounted after a crash. This is achieved by the client triggering the same phx-change to the server as soon as the mount has been completed. Note: if you want to see form recovery working in development, please make sure to disable live reloading in development by commenting out the LiveReload plug in your endpoint.ex file or by setting code_reloader: false in your config/dev.exs. Otherwise live reloading may cause the current page to be reloaded whenever you restart the server, which will discard all form state. For most use cases, this is all you need and form recovery will happen without consideration. In some cases, where forms are built step-by-step in a stateful fashion, it may require extra recovery handling on the server outside of your existing phx-change callback code. To enable specialized recovery, provide a phx-auto-recover binding on the form to specify a different event to trigger for recovery, which will receive the form params as usual. For example, imagine a LiveView wizard form where the form is stateful and built based on what step the user is on and by prior selections: <form phx- On the server, the "validate_wizard_step" event is only concerned with the current client form data, but the server maintains the entire state of the wizard. To recover in this scenario, you can specify a recovery event, such as "recover_wizard" above, which would wire up to the following server callbacks in your LiveView: def handle_event("validate_wizard_step", params, socket) do # regular validations for current step {:noreply, socket} end def handle_event("recover_wizard", params, socket) do # rebuild state based on client input data up to the current step {:noreply, socket} end To forgo automatic form recovery, set phx-auto-recover="ignore". JavaScript client specifics The JavaScript client is always the source of truth for current input values. For any given input with focus, LiveView will never overwrite the input's current value, even if it deviates from the server's rendered updates. This works well for updates where major side effects are not expected, such as form validation errors, or additive UX around the user's input values as they fill out a form. For these use cases, the phx-change input does not concern itself with disabling input editing while an event to the server is in flight. When a phx-change event is sent to the server, the input tag and parent form tag receive the phx-change-loading css class, then the payload is pushed to the server with a "_target" param in the root payload containing the keyspace of the input name which triggered the change event. For example, if the following input triggered a change event: <input name="user[username]"/> The server's handle_event/3 would receive a payload: %{"_target" => ["user", "username"], "user" => %{"username" => "Name"}} The phx-submit event is used for form submissions where major side effects typically happen, such as rendering new containers, calling an external service, or redirecting to a new page. On submission of a form bound with a phx-submit event: - The form's inputs are set to readonly - Any submit button on the form is disabled - The form receives the "phx-submit-loading"class On completion of server processing of the phx-submit event: - The submitted form is reactivated and loses the "phx-submit-loading"class - The last input with focus is restored (unless another input has received focus) - Updates are patched to the DOM as usual To handle latent events, any HTML tag can be annotated with phx-disable-with, which swaps the element's innerText with the provided value during event submission. For example, the following code would change the "Save" button to "Saving...", and restore it to "Save" on acknowledgment: <button type="submit" phx-Save</button> You may also take advantage of LiveView's CSS loading state classes to swap out your form content while the form is submitting. For example, with the following rules in your app.css: .while-submitting { display: none; } .inputs { display: block; } .phx-submit-loading { .while-submitting { display: block; } .inputs { display: none; } } You can show and hide content with the following markup: <form phx- <div class="while-submitting">Please wait while we save our content...</div> <div class="inputs"> <input type="text" name="text" value="<%= @text %>"> </div> </form> Additionally, we strongly recommend including a unique HTML "id" attribute on the form. When DOM siblings change, elements without an ID will be replaced rather than moved, which can cause issues such as form fields losing focus.
https://hexdocs.pm/phoenix_live_view/form-bindings.html
CC-MAIN-2021-04
en
refinedweb
Bind selected element from drop down to an object in Angular 9 In this tutorial let’s see how to bind selected element from drop down to an object in Angular 9. Let’s create a drop down list based on an JSON array response from REST API. And let’s see how to use ngModel, ngFor and ngValue directives in our example to achieve this functionality. Bind selected element from drop down to an object in Angular 9 For example, let’s use the same JSON array from the example Example: Display Json Object Response using ngFor. And let’s create drop down list with that data. jsonArray = [ { uid: '10', age: 22, username: 'John Paul', }, { uid: '11', age: 35, username: 'Peter Jackson', }, --- --- --- ] Let’s hard-code this jsonArray data (as userArray) in our component class as shown below. mycomponent.component.ts import { Component } from '@angular/core'; @Component({ selector:'app-mycomp', templateUrl:'./mycomponent.component.html', }) export class MycomponentComponent { selectedUser = null; user', }, ]; } Then, your component template should look like below. mycomponent.component.html <p>This is My First Component</p> <label>User : </label> <select [(ngModel)] = "selectedUser"> <option [ngValue]="null" selected disabled>Select User</option> <option *{{user.username}}</option> </select> Here, we have used select control and the ngModel directive together, so that data binding happens between the scope and the <select> control (including setting default values). The above logic handles dynamic <option> elements, which can be achieved using <option> element, *ngFor and ngValue directives. Note, we have used [ngValue]=”user” to bind selected element from a drop down to an object i.e., user object. *ngFor directive is used to iterate through the userArray JSON object. <option *{{user.username}}</option> When an item in the “Select User” drop down is selected, the option that is selected will be bound to the model identified by the ngModel directive. Optionally, you can set default text like “Select User” and disable it from user selecting that option by hard-coding option element as shown below. Note, we have used [ngValue]=”null”. This option element will then represent null or “not selected” option. <option [ngValue]="null" selected disabled>Select User</option> Next, use the component selector ‘app-mycomp‘ in your parent component (app.component.html) as shown below. app.component.html <div class="container"> <div class="row"> <div class="col-xs-12"> <h3>My First Component !</h3> <hr> <app-mycomp></app-mycomp> </div> </div> </div> Finally, when you run the above example you should see the following output in the browser. Output Conclusion That’s it. You have learnt how to create drop down list using JSON response from REST API. Then you were able to bind selected element from drop down to an object and also could set default text in the drop down and disable it by default. Also See: - TrackBy with *ngFor in Angular 9 : Example -
https://www.sneppets.com/angular/bind-selected-element-from-drop-down-to-an-object-in-angular-9/
CC-MAIN-2021-04
en
refinedweb
IEEE/The Open Group 2013 Aliases: strerror_r(3p) PROLOG This manual page is part of the POSIX Programmer’s Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux. NAME strerror, strerror_l, strerror_r — get error message string SYNOPSIS #include <string.h> char *strerror(int errnum); char *strerror_l(int errnum, locale_t locale); int strerror_r(int errnum, char *strerrbuf, size_t buflen); DESCRIPTION For strerror(): The functionality described on this reference page is aligned with the ISO C standard. Any conflict between the requirements described here and the ISO C standard is unintentional. This volume of POSIX.1-2008-2008.. The behavior is undefined if the locale argument to strerror_l() is the special locale object LC_GLOBAL_LOCALE or is not a valid locale object handle. RETURN VALUE. ERRORS These functions may fail if: The following sections are informative. EXAMPLES None. APPLICATION USAGE. RATIONALE. FUTURE DIRECTIONS None. SEE ALSO perror() .
https://reposcope.com/man/en/3p/strerror
CC-MAIN-2020-29
en
refinedweb
Interaction¶ A key goal for the Toyplot team is to explore interactive features for plots, making them truly useful and embeddable, so that they become a ubiquitous part of every data graphic user’s experience. The following examples of interaction are just scratching the surface of what we have planned for Toyplot: Titles¶ Most of the visualization types in Toyplot accept a title parameter, allowing you to specify per-series or per-datum titles for a figure. With Toyplot’s preferred embeddable HTML output, those titles are displayed via a popup when hovering over the data. For example, the following figure has a global title “Employee Schedule”, which you should see as a popup when you hover the mouse over any of the bars: [7]: import numpy numpy.random.seed(1234) start = numpy.random.normal(loc=8, scale=1, size=20) end = numpy.random.normal(loc=16, scale=1, size=20) boundaries = numpy.column_stack((start, end)) title = "Employee Schedule" [8]: import toyplot toyplot.bars(boundaries, baseline=None, title=title, width=500, height=300); If your plot includes multiple series, you can assign a per-series title instead. Hover the mouse over both series in the following plot to see “Morning Schedule” and “Afternoon Schedule”: [9]: lunch = numpy.random.normal(loc=12, scale=0.5, size=20) boundaries = numpy.column_stack((start, lunch, end)) title = ["Morning Schedule", "Afternoon Schedule"] toyplot.bars(boundaries, baseline=None, title=title, width=500, height=300); Finally, you can assign a title for every datum: [10]: title = numpy.column_stack(( ["Employee %s Morning" % i for i in range(20)], ["Employee %s Afternoon" % i for i in range(20)] )) toyplot.bars(boundaries, baseline=None, title=title, width=500, height=300); Of course, the title attribute works with all types of visualizations. Coordinates¶ When you click or tap the above figures, you should also see the domain values for the point you chose displayed along each of the axes. If you wish to disable display of either or both of the values, you can do so using the individual axes: [11]: canvas, axes, mark = toyplot.bars(boundaries, baseline=None, title=title, width=500, height=300) axes.x.interactive.coordinates.show = False axes.y.interactive.coordinates.show = False Now when you click or tap, nothing happens. Data Export¶ If you right-click the mouse over any of the above plots, a small popup menu will appear, giving you the option to “Save as .csv”. If you choose that option, the raw data from the plot will be extracted in CSV format and you can save it. Note that different browsers, browser versions, and platforms will behave differently when extracting the file: - Safari on OSX will open the file in a separate tab, which you can save to disk using File > Save As. - Chrome on OSX will immediately open a file dialog, prompting you to save the file. - Firefox on OSX will prompt you to open the file with Microsoft Excel (if installed), or save it to disk. Note that, on the browsers that support it, the default filename for the saved data is toyplot.csv. You can override this default on a per-data-table basis by specifying the filename when you create your figure. For example, when exporting data from the following figure (again, for browsers that support setting a default filename), the filename will default to employee-schedules.csv: [13]: toyplot.bars(boundaries, baseline=None, filename="employee-schedules", title=title, width=500, height=300); Note that the filename you specify should not include a file extension, as the file extension is added for you (and other file formats may become available in the future).
https://toyplot.readthedocs.io/en/latest/interaction.html
CC-MAIN-2020-29
en
refinedweb
Properties are the central repository to store our information temporarily. These can contain login information like username and password, session data like session id, page context, header information and so on. This is the 7th tutorial in our SoapUI free online training series. Let’s see how to add property test step and then we will discuss assigning values to the property and show them in the log. How to Add Properties in SoapUI: Here are the steps. - Right-click on the Test steps node - Click Add Step and Properties option from the context menu - Enter the property name as desired and click OK - In the properties screen, click icon to add property - Enter your desired property name and click OK button. For example, let me enter Pro_Response - Type any default value for the property if you wish. For example, I enter “Nothing” - Then, add a Groovy Script test step next to the property step. Refer below screenshot. We can transfer the property data across the test steps during the test execution. For that, SoapUI Pro provides Property Transfer test step. Look at the below screenshot. In the groovy script, add the following script. This script will assign a string text to the property and then it will show in the log after executing the test case. String testString = "TestString" testRunner.testCase.setPropertyValue( "Pro_Response", testString ) def getLocalPropValue = testRunner.testCase.getPropertyValue("Pro_Response") log.info(getLocalPropValue) - Once written the above script in the editor, double-click on the test case name step. - Run the test case by clicking on the icon and the see the results in the script log tab. Accessing property: There are several ways to access test case, test suite and project properties for setting and getting their data through the script. Here are the samples for retrieving the property data. def getTestCasePropertyValue = testRunner.testCase.getPropertyValue( "LocalPropertyName" ) def getTestSuitePropertyValue = testRunner.testCase.testSuite.getPropertyValue ( " LocalPropertyName " ) def getProjectPropertyValue = testRunner.testCase.testSuite.project.getPropertyValue ( " LocalPropertyName " ) In order to access a global property, this is the script: def getGlobalPropertyValue = com.eviware.soapui.SoapUI.globalProperties.getPropertyValue ( "GlobalPropertyName" ) These script lines are used to set the value to the local and global property. testRunner.testCase.setPropertyValue( " LocalPropertyName ", someValue ) testRunner.testCase.testSuite.setPropertyValue( " LocalPropertyName ", someValue ) testRunner.testCase.testSuite.project.setPropertyValue( " LocalPropertyName ", someValue ) com.eviware.soapui.SoapUI.globalProperties.setPropertyValue ( " GlobalPropertyName ", someValue ) Here in these scripts, testRunner is the common object which might be test suites, test cases or project. setPropertyValue and getPropertyValue are the methods or functions. As we mentioned the above script, we can assign data to the properties. testRunner.testCase.testSteps[“Properties”].setPropertyValue( “Pro_Response”, testString ) After executing the above script, the property will get updated in the property test step. Refer the following screenshot. Receiving response data: Now let us discuss how to get the response data through the script. To do this, - Execute the service request once and verify the result - Go to Groovy script editor and then right click on the editor as shown in the below screenshot Now SoapUI Pro generates the script as below after specifying the property name. def response = context.expand( ‘${ServiceRequest#Response}' ) As we know, “def” is a groovy script keyword that represents defining properties/objects. By default, SoapUI Pro has the property name as “response” in the Get Property popup. If we want we can change this name. Remaining portions of the script are auto-generated. Let us merge the above script in our earlier discussed script. Here’s what you would see: def response = context.expand( '${ServiceRequest#Response}' ) testRunner.testCase.setPropertyValue( "Pro_Response", response ) def getLocalPropValue = testRunner.testCase.getPropertyValue("Pro_Response") log.info(getLocalPropValue) If we execute the above script separately, it will log the entire response data in the log section. Even when execute this along with the test case, it will show the same output in the script log. Creating properties from the navigator pane: There is another way to create properties locally through the property panel which will appear when we click on the nodes under the project tree. Let’s see how: - Add currency converter service request and a groovy script test step under the test suite ConversionTestSuite. - Click on the TestSuite name under the project (i.e. ConversionTestSuite) - At the bottom of the Navigation panel, we can see a Property panel. It contains TestSuite Properties and Custom Properties tabs. - Go to Custom Properties tab by clicking on it - Then click on the plus ( + ) icon to add the property as shown below: - Enter property name and provide default input value as shown in the above screenshot. - Now execute the currency converter service request once. Only then we can get the property information when right-clicking on the editor. - Enter the following script in the editor def getPropValue = context.testCase.NetSuite.getPropertyValue(“FromCurrencyValue”) - Click on the Run icon This script gets the property value and assigns to the variable “getProValue”. To print the value of the property, we can write the following script : Log.info (getPropValue); Global Properties: Now let us discuss global properties. These properties are defined in one place and we can access them across the project components like test suite, test case, test steps etc. Here are the scripts for writing data to the global properties. com.eviware.soapui.SoapUI.globalProperties.setPropertyValue ( "prjFromCurrency", "USD" ) com.eviware.soapui.SoapUI.globalProperties.setPropertyValue ( "prjToCurrency", "INR" ) Once we execute the above test step script, the mentioned properties will be created and the respective values will be assigned to those properties. Let us see how we can verify it. - Click on the File menu - Then, choose Preferences option - In the left side, click on the Global Properties tab. - Verify the properties in the property sheet on the right side. Refer the screenshot below: Conclusion: Properties are helpful for transferring the data between the test steps such as test suites, test steps and test cases. Property can be defined through a groovy script. We can also assign and retrieve data of the properties through the script. And, just like other test steps we can rename or delete or disable the property test step by right click and then choose the respective options from the context menu. In the next tutorial, we will learn more features about properties like passing properties in the input request and retrieve from global properties, property transfer test step and so on. Please stay with us and let us know in case of any questions or comments. 22 thoughts on “How to Use Properties in SoapUI Groovy Script – SoapUI Tutorial #7” Hi Thanks for sharing. Can you explain how to randomize datasource? @Sushma: Thanks for reading.. Randomizing the data source will be discussed in the data driven testing article. this was a great tutorial and an important step to pass on data between various componeneys in a test case Thanks for sharing it 1) Some problem which can be corrected is :- Space should not be there below testRunner.testCase.testSuite.getPropertyValue( ” LocalPropertyName ” ) 2) Can’t we see properties in a table like we see custom properties,, I was not able to see properties defined inside groovy scipt in the form of table in navigation bar on left side Keep up the good work. thank you for the write up. Hi, I tried this sample where Upon execution of below groovi scripts: String testString = “TestString” testRunner.testCase.setPropertyValue( “Pro_Response”, testString ) def getLocalPropValue = testRunner.testCase.getPropertyValue(“Pro_Response”) log.info(getLocalPropValue) I was expecting the value of Pro_Response should be set to TestString but this is not happening. can you suggest in “receiving response data” section on right click am not getting get data option. am using soapui5.2.1 plz revert on the above Hi all. The “Error establishing a database connection” database error message on the white screen is displayed when opening this page Hi Thanks for reporting it. It may be a temporary refresh. Can you please try and let us know if the issue still persist? You can try other pages as well. Hi Thank you Vijay The “8 soap tutorial” page is successfully opened. Cool one! Thanks you very much! runner.testSuite.testCaseList.each(){ for (testStep in it.testStepList) testStep.setPropertyValue(“Username”, “dpshud1”) } How to get METHOD from a testStep/testCase/testSuite, basically from any one. I am interested to access only GET APIs/testSteps among all type of APIs. Thanks! Hello This tutorial is very helpful…:) Thanku so much But i am getting an error : unexpected char: ‘#’ @ line 1 Can you please resolve this? Got solution for my query as below String sMethod = (testStep.getTestRequest().getMethod()) When first adding the property transfer, there is no screen shot of how this is set up. I have attempted to insert the correct source & target details but when I execute that, the Groovy Script is overwritten by the property value. Can anyone help fix this? What is the difference between context and testRunner. where we use these. In which case we use context and testRunner. I ran the below script. The output is same . def getPropValue = testRunner.testCase.testSuite.getPropertyValue(“suite”) log.info “using test tunner “+getPropValue def getPropValue1=context.testCase.testSuite.getPropertyValue(“suite”) log.info “using context”+getPropValue1 @hemantvarhekar please try this one String testString = “TestString” testRunner.testCase.setPropertyValue(“Pro_Response”, testString) def getLocalPropValue = testRunner.testCase.getPropertyValue(“Pro_Response”) log.info(getLocalPropValue) There was extra space in the ( “Pro_Response”, testString ) How/Where shall I set -Dsoapui.redirect.limit property ? Any luck with this? Hi, I want to set assertion SLA for all the apis in my project.How can i do that? I was wondering how would i use the groovy script to skip between steps in a test suite for example say i wanted to go from step 1 to step 4 and to do so i needed a value from the xml code in step one how would i get that value inside the groovy script in order to go to step four Hi, I need to insert in each Field, All possible Data, suggested on use case with SoapUI How can i Do it with Groovy and SoapUI
https://www.softwaretestinghelp.com/soapui-tutorial-7-properties-in-soapui-groovy-script/
CC-MAIN-2020-29
en
refinedweb
Extern in C Reading time: 30 minutes | Coding time: 5 minutes Extern is a keyword in C programming language which is used to declare a global variable that is a variable without any memory assigned to it. It is used to declare variables and functions in header files. Extern can be used access variables across C files. Syntax: extern <data_type> <variable_name>; // or extern <return_type> <function_name>(<parameter_list>); Example: extern int opengenus; // or extern int opengenus_fn(int, float ); To understand the significance better, we need to understand three terms: - Declaration Declaration of a variable means that the compiler knows that the variable exists but no memory or data has been assigned to it. To stop at this step, we need extern keyword like: extern int opengenus; opengenus is a valid integer variable but no memory has been allocated to it. - Define Defining a variable means assigning the variable the required memory. At this step, garbage value is placed at the memory location but the variable is ready to be used. Example: int opengenus; - Initializing Initializing a variable means assigning a value in the memory location of the variable. Example: int opengenus = 1; This table summarizes the idea: Using extern The main rule is that extern should be used in header files only. Though there are ways around this but it is not advised for code safety. Let us code a header file named "opengenus_header.h" as: extern int opengenus; extern void get_data(void); opengenus_header.h has both variables and functions but in production, it is advised to keep variables and functions in separate header files. This will be our common C code (og.c) used to declare and define common variables and functions. #include "opengenus_header.h" int opengenus = 1; This is our main code (main.c) which is linked with our common C code (og.c) and uses the same global/ extern variables and functions. #include "opengenus_header.h" #include <stdio.h> int main(void) { printf("%d", opengenus); } Compile it as: gcc main.c og.c Execute it as: ./a.out Output: 1 While compiling, if you do not link og.c with main.c, you will get a compile time error. Erroneous compilation: gcc main.c Error: /tmp/ccrE2C9Q.o: In function `main': main.c:(.text+0x6): undefined reference to `opengenus' collect2: error: ld returned 1 exit status This is because the memory for opengenus variable is being allocated in file og.c and it has not been linked. So, in main.c, in this compilation step, we are using the variable without declaring it which gives an error. If we compile og.c only, we will get an error as it has no main function. gcc og.c Compile time error: /usr/lib/gcc/x86_64-redhat-linux/4.8.5/../../../../lib64/crt1.o: In function `_start': (.text+0x20): undefined reference to `main' collect2: error: ld returned 1 exit status Hence, the overall and good coding strategies are: - All variables and functions in header files should be extern - Separate header files should be used for variables and functions - Use a C code file to declare the variables and functions and use this in end user code - Extern must be used instead of using global variables
https://iq.opengenus.org/extern-in-c/
CC-MAIN-2020-29
en
refinedweb
Docstring in python : A docstring is a string that is used for documentation of a module,function,class or method in python. This string comes as the first statement after the name of the function , module etc . The value of a docstring can be printed out by using doc attribute of the object. So, if you want to know what a system module does, just print out its docstring. e.g. to know about ‘int’, use the following : print (int.__doc__) How to write docstring for your own custom function ? We can write single line or multiline ‘docstring’ for any custom methods , class, function or module. Triple quotes are used as opening and closing quotes for the docstring. Let me show you with a simple example : def my_func(x,y): """Find the multiplication of x,y and return the result""" return x*y print (my_func.__doc__) It will print : Find the multiplication of x,y and return the result Multiple line docstring is same as above. Triple quote is used for multiline docstring. If you want to write more detail in documentation, you can write in multilines. Example : def my_area(h,w): """Find the area h -- height w -- width """ return x*y print (my_area.__doc__) It will print : Find the area h -- height w -- width We should always try to comment on code wherever possible. Most of the time we forget what we wrote months ago : commenting will help on that. Also , it will be a lot more easier for any other programmer to maintain the code in future. Don’t you think ?
https://www.codevscolor.com/write-docsrting-python/
CC-MAIN-2020-29
en
refinedweb
- Bench, Body Shop, 'Come to Jesus' Meeting, Documentation - Dumpster Engagement, Faith-Driven Development, Go Native, Hired Scapegoat, 'Jesus', Non-Solicitation Agreement - Person, Proprietary Development Methodology, Purple Squirrel, Resource, Smallball - Transparency, Utilization, Vampire, Waterfall, Yes Man/Woman - Summary Person The proper term for the individuals who work on a project. Contrast this term with "resource." A person is a brilliant machine that, even without programming, will invent things and find solutions to problemswithout always having to have a prescribed process to make it work. On the downside, persons require food, breaks, and motivation, and work best when given things to work on that they feel will help other people, too. Proprietary Development Methodology A true mark of an ambitious consulting firm in the 1990s was creation of its own proprietary software development methodology. Usually invented solely for marketing purposes, in an attempt to distinguish the firm's processes from those of its competitors. Such methodologies are rarely actually used. Thankfully, there are plenty of methodologies that have actual usage, peer review, and lack of proprietary lock-in. RUP, Scrum, Agile, XP, and Lean, among others, are well-known, practiced methods that have delivered results for clients. Most modern technology consulting firms, thankfully, have moved beyond proprietary methodologies, realizing that any firm can re-brand such a thingand therefore, it's almost never a competitive advantage, since execution, discipline, and talent matter much more than process. To that end, most clients, after having been sold for years on the false promise of proprietary methodologies, realize that there's virtually no upside in using an unproven proprietary methodology versus the common peer-reviewed methodologies with actual surveys of results behind them. Purple Squirrel The mythical individual who meets requirements like the following in a job ad: Looking for a Java/C#/Erlang/SAP/FoxPro programmer (15 years of experience in each required) with 12 years of experience with the System.Linq.Expression namespace writing overloads of the Add method. Top-secret security clearance is required. Must have experience in the nonprofit environmental industry as well as 20 years in the oil services business, working for companies like Halliburton. All these requirements must be met for your résumé to be considered. Like this mythical purple squirrel, this person doesn't really exist. A good way to judge whether a consulting company is really a consulting company, versus a body shop masquerading as a consulting company, is to look at their job ads and determine how many look like "purple squirrels." Consultancies have latitude to determine the requirements, whereas body shops take specs from procurement groups who put together an "order" that sounds like something you might hear from the person in front of you at a coffee shop. ("Double-skim gingerbread half-caf soy with a bit of room latté.") Resource A god-awful, horrible term for "person," invented by a pointy-haired boss at some point in the 1980s, when thinking of employees as people became too much for his soul to bear. At approximately the same time, the PHB started to "downsize" or "rightsize" or "jollysize" or "happysize"whatever term for "firing" is currently in vogue. A sure sign of a total jerk is the frequency with which he uses the term "resource" to refer to "people." The term tries to productize people into something on which lazy consulting firms can attempt to slap a SKU. This term helps to perpetuate the project management fiction that people are interchangeable units, which a project manager can rearrange when trying to get projects done. In essence, it's a tool for helping delay the reality that people are not units, but unique individuals, and that you can't manage projects by GANTT chart alone. Smallball The process of spending three months of dedicated time writing proposals to chase a deal for three days' worth of work totaling $1,500, with a vague promise of more work "in the future." Describes any project pursuit where there's a reasonable chance that, during the pursuit process, you could have actually completed the work being sold. For example, six months of pursuit chasing a one-month project is probably "smallball." Lots of smallball is the sign of an unfocused sales group that isn't doing a particularly good job of qualifying potential clients before investing time in rabbit holes. Everyone has to start somewhere, and playing some smallball to reach new clients is a hazard of building a technology consulting business, but a good way to know if a firm is in trouble is if most deals are four-figure and five-figure deals for less than four weeks.
https://www.informit.com/articles/article.aspx?p=1381169&seqNum=3
CC-MAIN-2020-29
en
refinedweb
After successfully deploying and running stateless applications, a number of developers are exploring the possibility of running stateful workloads, such as PostgreSQL, on OpenShift. If you are considering extending OpenShift for stateful workloads, this tutorial will help you experiment on your existing OpenShift environment by providing step-by-step instructions. This tutorial will walk you through: - How to deploy a PostgreSQL database on OpenShift using the ROBIN Operator - Create a point-in-time snapshot of the PostgreSQL database - Simulate a user and rollback to a stable state using the snapshot - Clone the database for the purpose of collaboration - Backup the database to the cloud using AWS S3 bucket - Simulate data loss/corruption and use the backup to restore the database Install the ROBIN Operator from OperatorHub Before we deploy PostgreSQL on OpenShift, let’s first install the ROBIN operator from the OperatorHub and use the operator to install ROBIN Storage on your existing OpenShift environment. You can find the Red Hat certified ROBIN operator here. Use the “Install” button and follow the instructions to install the ROBIN operator. Once the operator is installed you can use the “ROBIN Cluster” Custom Resource Definition at the bottom of the webpage to create a ROBIN cluster. ROBIN Storage is an application-aware container storage that offers advanced data management capabilities and runs natively on OpenShift. ROBIN Storage delivers bare-metal performance and enables you to protect (via snapshots and backups), encrypt, collaborate (via clones and git like push/pull workflows) and make portable (via Cloud-sync) stateful applications that are deployed using Helm Charts or Operators. Create a PostgreSQL Database After you have installed ROBIN, let’s install the PostgreSQL client as the first step, so that we can use Postgresql once deployed. yum install -y yum install -y postgresql10 Let’s confirm that OpenShift cluster is up and running. oc get nodes You should see an output similar to below, with the list of nodes and their status as “Ready.” Let’s confirm that ROBIN is up and running. Run the following command to verify that ROBIN is ready. oc get robincluster -n robinio Let’s setup helm now. Robin has helper utilities to initialize helm. robin k8s deploy-tiller-objects robin k8s helm-setup helm repo add stable Let’s create a PostgreSQL database using Helm and ROBIN Storage. Before continuing, it’s important to note that the process shown, using Helm and Tiller, is provided as an example only. The supported method of using Helm charts with OpenShift is via the Helm operator. Using the below Helm command, we will install a PostgreSQL instance. When we installed the ROBIN operator and created a “ROBIN cluster” custom resource definition, we created and registered a StorageClass named “robin-0-3” with OpenShift. We can now use this StorageClass to create PersistentVolumes and PersistentVolumeClaims for the pods in OpenShift. Using this StorageClass allows us to access the data management capabilities (such as snapshot, clone, backup) provided by ROBIN Storage. For our PostgreSQL database, we will set the StorageClass to robin-0-3 to benefit from data management capabilities ROBIN Storage brings. helm install stable/postgresql --name movies --tls --set persistence.storageClass=robin-0-3 --namespace default --tiller-namespace default Run the following command to verify our database called “movies” is deployed and all relevant Kubernetes resources are ready. helm list -c movies --tls --tiller-namespace default You should be able to see an output showing the status of your Postgres database. You would also want to make sure Postgres database services are running before proceeding further. Run the following command to verify the services are running. oc get service | grep movies Now that we know the PostgreSQL services are up and running, let’s get Service IP address of our database. export IP_ADDRESS=$(oc get service movies-postgresql -o jsonpath={.spec.clusterIP}) Let’s get the password of our PostgreSQL database from Kubernetes Secret export POSTGRES_PASSWORD=$(oc get secret --namespace default movies-postgresql -o jsonpath="{.data.postgresql-password}" | base64 --decode) Add data to the PostgreSQL database We’ll use movie data to load data into our Postgres database. Let’s create a database “testdb” and connect to “testdb”. PGPASSWORD="$POSTGRES_PASSWORD" psql -h $IP_ADDRESS -U postgres -c "CREATE DATABASE testdb;" For the purpose of this tutorial, let’s create a table named “movies”. PGPASSWORD="$POSTGRES_PASSWORD" psql -h $IP_ADDRESS -U postgres -d testdb -c "CREATE TABLE movies (movieid TEXT, year INT, title TEXT, genre TEXT);" We need some sample data to perform operations on. Let’s add 9 movies to the “movies” table. PGPASSWORD="$POSTGRES_PASSWORD" psql -h $IP_ADDRESS -U postgres -d testdb -c “INSERT INTO movies (movieid, year, title, genre) VALUES (‘tt0360556’, 2018, ‘Fahrenheit 451’, ‘Drama’), (‘tt0365545’, 2018, ‘Nappily Ever After’, ‘Comedy’), (‘tt0427543’, 2018, ‘A Million Little Pieces’,’Drama’), (‘tt0432010’, 2018, ‘The Queen of Sheba Meets the Atom Man’, ‘Comedy’), (‘tt0825334’, 2018, ‘Caravaggio and My Mother the Pope’, ‘Comedy’), (‘tt0859635’, 2018, ‘Super Troopers 2’, ‘Comedy’), (‘tt0862930’, 2018, ‘Dukun’, ‘Horror’), (‘tt0891581’, 2018, ‘RxCannabis: A Freedom Tale’, ‘Documentary’), (‘tt0933876’, 2018, ‘June 9’, ‘Horror’);” Let’s verify data was added to the “movies” table by running the following command. PGPASSWORD="$POSTGRES_PASSWORD" psql -h $IP_ADDRESS -U postgres -d testdb -c "SELECT * from movies;" You should see an output with the “movies” table and the nine rows in it as follows: We now have a PostgreSQL database with a table and some sample data. Now, let’s take a look at the data management capabilities ROBIN brings, such as taking snapshots, making clones, and creating backups. Register the PostgreSQL Helm release as an application To benefit from the data management capabilities, we’ll register our PostgreSQL database with ROBIN. Doing so will let ROBIN map and track all resources associated with the Helm release for this PostgreSQL database. Let’s first get the ‘robin’ client utility and set it up to work with this OpenShift cluster. To get the link to download ROBIN client do: oc describe robinclusters -n robinio You should see an output similar to below: Find the field ‘Get _ Robin _ Client’ and run the corresponding command to get the ROBIN client. curl -k -o robin In the same output above notice the field ‘Master _ Ip’ and use it to setup your ROBIN client to work with your openshift cluster, by running the following command. export ROBIN_SERVER=10.9.40.125 Now you can register the Helm release as an application with ROBIN. Doing so will let ROBIN map and track all resources associated with the Helm release for this PostgreSQL database. To register the Helm release as an application, run the following command: robin app register movies --app helm/movies Let’s verify ROBIN is now tracking our PostgreSQL Helm release as a single entity (app). robin app status --app movies You should see an output similar to this: We have successfully registered our Helm release as an app called “movies”. Snapshot and Rollback a PostgreSQL Database on OpenShift If you make a mistake, such as unintentionally deleting important data, you may be able to undo it by restoring a snapshot. Snapshots allow you to restore the state of your application to a point-in-time. ROBIN lets you snapshot not just the storage volumes (PVCs) but the entire database application including all its resources such as Pods, StatefulSets, PVCs, Services, ConfigMaps etc. with a single command. To create a snapshot, run the following command. robin snapshot create snap9movies movies --desc "contains 9 movies" --wait Let’s verify we have successfully created the snapshot. robin snapshot list --app movies You should see an output similar to this: We now have a snapshot of our entire database with information of all 9 movies. Rolling back to a point-in-time using snapshot We have 9 rows in our “movies” table. To test the snapshot and rollback functionality, let’s simulate a user error by deleting a movie from the “movies” table. PGPASSWORD="$POSTGRES_PASSWORD" psql -h $IP_ADDRESS -U postgres -d testdb -c "DELETE from movies where title = 'June 9';" Let’s verify the movie titled “June 9” has been deleted. PGPASSWORD="$POSTGRES_PASSWORD" psql -h $IP_ADDRESS -U postgres -d testdb -c "SELECT * from movies;" You should see the row with the movie “June 9” does not exist in the table anymore. Let’s run the following command to see the available snapshots: robin app info movies You should see an output similar to the following. Note the snapshot id, as we will use it in the next command. Now, let’s rollback to the point where we had 9 movies, including “June 9”, using the snapshot id displayed above. robin app rollback movies Your_Snapshot_ID --wait To verify we have rolled back to 9 movies in the “movies” table, run the following command. PGPASSWORD="$POSTGRES_PASSWORD" psql -h $IP_ADDRESS -U postgres -d testdb -c "SELECT * from movies;" You should see an output similar to the following: We have successfully rolled back to our original state with 9 movies! Clone a PostgreSQL Database Running on OpenShift ROBIN lets you clone not just the storage volumes (PVCs) but the entire database application including all its resources such as Pods, StatefulSets, PVCs, Services, ConfigMaps, etc. with a single command. Application cloning improves the collaboration across Dev/Test/Ops teams. Teams can share applications and data quickly, reducing the procedural delays involved in re-creating environments. Each team can work on their clone without affecting other teams. Clones are useful when you want to run a report on a database without affecting the source database application, or for performing UAT tests or for validating patches before applying them to the production database, etc. ROBIN clones are ready-to-use “thin copies” of the entire app/database, not just storage volumes. Thin-copy means that data from the snapshot is NOT physically copied, therefore clones can be made very quickly. ROBIN clones are fully-writable and any modifications made to the clone are not visible to the source app/database. To create a clone from the existing snapshot created above, run the following command. Use the snapshot id we retrieved above. robin clone create movies-clone Your_Snapshot_ID --wait Let’s verify ROBIN has cloned all relevant Kubernetes resources. oc get all | grep "movies-clone" You should see an output similar to below. Notice that ROBIN automatically clones the required Kubernetes resources, not just storage volumes (PVCs), that are required to stand up a fully-functional clone of our database. After the clone is complete, the cloned database is ready for use. Get Service IP address of our postgresql database clone, and note the IP address. export IP_ADDRESS=$(oc get service movies-clone-movies-postgresql -o jsonpath={.spec.clusterIP}) Get Password of our postgresql database clone from Kubernetes Secret export POSTGRES_PASSWORD=$(oc get secret movies-clone-movies-postgresql -o jsonpath="{.data.postgresql-password}" | base64 --decode;) To verify we have successfully created a clone of our PostgreSQL database, run the following command. PGPASSWORD="$POSTGRES_PASSWORD" psql -h $IP_ADDRESS -U postgres -d testdb -c "SELECT * from movies;" You should see an output similar to the following: We have successfully created a clone of our original PostgreSQL database, and the cloned database also has a table called “movies” with 9 rows, just like the original. Now, let’s make changes to the clone and verify the original database remains unaffected by changes to the clone. Let’s delete the movie called “Super Troopers 2”. PGPASSWORD="$POSTGRES_PASSWORD" psql -h $IP_ADDRESS -U postgres -d testdb -c "DELETE from movies where title = 'Super Troopers 2';" Let’s verify the movie has been deleted. PGPASSWORD="$POSTGRES_PASSWORD" psql -h $IP_ADDRESS -U postgres -d testdb -c "SELECT * from movies;" You should see an output similar to the following with 8 movies. Now, let’s connect to our original PostgreSQL database and verify it is unaffected. Get Service IP address of our postgresql database. export IP_ADDRESS=$(oc get service movies-postgresql -o jsonpath={.spec.clusterIP}) Get Password of our original postgre database from Kubernetes Secret. export POSTGRES_PASSWORD=$(oc get secret --namespace default movies-postgresql -o jsonpath="{.data.postgresql-password}" | base64 --decode;) To verify that our PostgreSQL database is unaffected by changes to the clone, run the following command. Let’s connect to “testdb” and check record : PGPASSWORD="$POSTGRES_PASSWORD" psql -h $IP_ADDRESS -U postgres -d testdb -c "SELECT * from movies;" You should see an output similar to the following, with all 9 movies present: This means we can work on the original PostgreSQL database and the cloned database simultaneously without affecting each other. This is valuable for collaboration across teams where each team needs to perform unique set of operations. To see a list of all clones created by ROBIN run the following command: robin app list Now let’s delete the clone. Clone is just any other ROBIN app so it can be deleted using ‘robin app delete’ command. robin app delete movies-clone --wait Backup a PostgreSQL Database from OpenShift to AWS S3 ROBIN elevates the experience from backing up just storage volumes (PVCs) to backing up entire applications/databases, including their metadata, configuration, and data. A backup is a full copy of the application snapshot that resides on completely different storage media than the application’s data. Therefore, backups are useful to restore an entire application from an external storage media in the event of catastrophic failures, such as disk errors, server failures, or entire data centers going offline, etc. (This is assuming your backup doesn’t reside in the data center that is offline, of course.) Let’s now backup our database to an external secondary storage repository (repo). Snapshots (metadata + configuration + data) are backed up into the repo. ROBIN enables you to back up your Kubernetes applications to AWS S3 or Google GCS ( Google Cloud Storage). In this demo we will use AWS S3 to create the backup. Before we proceed, we need to create an S3 bucket and get access parameters for it. Follow the documentation here. Let’s first register an AWS repo with ROBIN: robin repo register pgsqlbackups s3://robin-pgsql/pgsqlbackups awstier.json readwrite --wait Let’s confirm that our secondary storage repository is successfully registered: robin repo list You should see an output similar to the following : Let’s attach this repo to our app so that we can backup its snapshots there: robin repo attach pgsqlbackups movies --wait Let’s confirm that our secondary storage repository is successfully attached to app: robin app info movies You should see an output similar to the following : Let’s backup up our snapshot to the registered secondary storage repository: robin backup create bkp-of-my-movies Your_Snapshot_ID pgsqlbackups --wait Let’s confirm that the snapshot has been backed up in S3: robin app info movies You should see an output similar to the following : Let’s also confirm that backup has been copied to remote S3 repo: robin repo contents pgsqlbackups You should see an output similar to the following : The snapshot has now been backed up into our AWS S3 bucket. Now since we have backed-up our application snapshot to cloud, let’s delete that snapshot locally. robin snapshot delete Your_Snapshot_ID --wait Now let’s simulate a data loss situation by deleting all data from the “movies” table. $PGPASSWORD="$POSTGRES_PASSWORD" psql -h $IP_ADDRESS -U postgres -d testdb -c "DELETE from movies;" Let’s verify all data is lost. $>IMAGE_19<< We will now use our backed-up snapshot on S3 to restore data we just lost. Now let’s restore snapshot from the backup in cloud and rollback our application to that snapshot. robin snapshot pull movies Your_Backup_ID --wait Remember, we had deleted the local snapshot of our data. Let’s verify the above command has pulled the snapshot stored in the cloud. Run the following command: robin snapshot list --app movies Now we can rollback to the snapshot to get our data back and restore the desired state. robin app rollback Your_Snapshot_ID movies --wait Let’s verify all 9 rows are restored to the “movies” table by running the following command:>IMAGE_22<< As you can see, we can restore the database to a desired state in the event of data corruption. We simply pull the backup from the cloud and use it to restore the database. Running databases on OpenShift can improve developer productivity, reduce infrastructure cost, and provide multi-cloud portability. To learn more about using ROBIN Storage on OpenShift, visit the ROBIN Storage for OpenShift solution page.
https://www.tefter.io/bookmarks/178163/readable
CC-MAIN-2020-29
en
refinedweb
A sane approach to error handling with react and redux 7 min read - 2020-04-06 Error handling is a hard subject. It is also not fun, you just don’t wanna do it. At the same time you know it is crucial for good user experience. You can try to forget about them, and use common excuses like “this is not very likely to fail”, “errors will not happen”. Or a more bold, cowboy style phrase like “my code has no bugs” 🤠. Let me remind you of Murphy’s law: Anything that can go wrong will go wrong Trust me, and trust Murphy, it will go wrong. Worse experience than having errors happening is having your user being completely unaware of them and thus not able to react or report. Error codes format Pretty much all applications that are bigger than a simple exercise need to deal with errors. If you have an application that does HTTP requests, you know you will end up having to store your HTTP errors somewhere to show them to the user. We will focus on the strategy we believe to be good to deal and communicate errors to the user. The first thing we did was to align with the back-end an error format, we ended up with this. { "errorCode": "1001", "errorMessage": "Validation error has occurred.", "errors": { "description": "Must not be null", "name": "Must not be null" }, "errorTimestamp": "2020-03-06T08:14:03.690Z" } errorCode is an internal error code the user can use to report the specific error errorMessage describes the error and is shown to the user, it will later become an i18n code. errors is an object that describes the errors on the payload that was sent before errorTimestamp is the timestamp of this response Integrating errors in reducers and components As we said before, error handling is not fun. We want to make it as simple as possible so we’re sure the error coverage is easy to increase across the application. To provide this, we decided to go to a composable solution that can be used in reducers, action creators, and selectors. If you’re not familiar with redux terms, here’s a TLDR (feel free to skip if you are): - reducers define how your state is mutated. Based on an action (think an event) and on the current state, they know how to calculate the next state. - action is similar to an event that is sent to the store to trigger a state change - action creators are functions that create actions - selectors are no more than getters to a store, enabling decoupling of the store from its users The examples we’ve used are written in react, redux and reselect, but the practices and principles used are technology agnostic. Before - the default way Let’s create an HTTP request and write the error handling approach. We will use redux-thunk as we believe they’re simpler to understand. If you’re not familiar with them: they are functions that produce side-effects and dispatch actions. This is a default thunk, dispatching actions at the start of the request, on success and error. import axios from "axios" const createArticle = (title, text) => dispatch => { dispatch({ type: "CREATE_ARTICLE_REQUEST" }) return axios .post("/api/articles", { title, text }) .then(successHandler) .catch(error => { // Deal with the error dispatch({ type: "CREATE_ARTICLE_ERROR", error }) }) } Then, in the reducer, the handling would be something like: const reducer = (state, action) => { switch (action.type) { case "CREATE_ARTICLE_REQUEST": return { ...state, isLoading: true, error: null, // reseting the error } case "CREATE_ARTICLE_ERROR": return { ...state, error: action.error, // setting the error } } } And on your components, you would do something like the following to show the error to the user: import { useSelector } from "react-redux" const ArticleListPage = () => { const errorMessage = useSelector(state => state.articles.error.errorMessage) return ( <div> {errorMessage && <p>There was an error: {errorMessage}</p>} {/* Cut for brevity */} </div> ) } We have identified some problems with this approach: - There is no enforced error structure. One developer can send errorin the action where others can directly send error.errorMessage - The code to handle errors on reducers will be repeated for every request and can end up not respecting the structure too. - If the reducer, action creator or component change, it is very likely that the other 2 will break, they are coupled. Can't access property 'errorMessage of undefinedI’m looking at you. - Error messages are shown in different formats across the application leading to a not so pleasant user experience. After - How to solve these problems? Let’s have a look at the code again: import axios from 'axios; const createArticle = (title, text) => dispatch => { dispatch({ type: "CREATE_ARTICLE_REQUEST" }) return axios .post("/api/articles", { title, text }) .then(successHandler) .catch(error => { // Deal with the error dispatch(errorActionCreator("CREATE_ARTICLE_ERROR", error)) }) } errorActionCreator implementation that respects FSA export const errorActionCreator = (errorType, error) => { return { type: errorType, error: true, payload: error, } } Then, in the reducer, the handling would be something like: const reducer = (state, action) => { switch (action.type) { case "CREATE_ARTICLE_REQUEST": return { ...errorReducer(state, action), isLoading: true, } case "CREATE_ARTICLE_ERROR": return { ...errorReducer(state, action), isLoading: false, } } } errorReducer implementation export const errorReducer = (state, action) => { if (!action.error) { return { ...state, error: null, } } return { ...state, error: { errorMessage: DEFAULT_ERROR_MESSAGE, ...action.payload.response.data, }, } } And on your components, you would do something like the following to show the error to the user: import { useSelector } from 'react-redux'; import { getArticlesErrorMessage } from '../store/articles/selectors'; const ArticleListPage = ({ errorMessage }) => { const errorMessage = useSelector(getArticlesErrorMessage) return ( <div> <ErrorMessage message={errorMessage}> {/* Cut for brevity */} </div> ); }; Using ErrorMessage component to present the error coherently. export const ErrorMessage = ({ error }) => { if (!error) { return null; } return (<p>{error}</p>); } To finish, we added this selector that is used by components to get error messages. const getArticlesErrorMessage = createErrorSelector(state => state.articles) The implementation of createErrorSelector is shown below, it extends reselect createSelector to lookup for the error in the specific structure we want. import { createSelector } from "reselect" import { get } from "lodash" export const createErrorSelector = fn => { return createSelector( fn, storeIndex => get(storeIndex, "error.errorMessage", null) ) } With this approach, we managed to fix all the listed problems. We have created a layer of decoupling that enables us to change without breaking all the other usages. - Enforced error structure - Error reducer is shared - Decoupled reducers and components from errors format - Error messages are shown coherently We’ve decided to locate the 3 functions: createErrorSelector, errorReducer and errorActionCreator in the same file. If one of them needs to be changed, it most likely means that the other two also need to. In contrast, all the reducers, components and thunks that are dealing with errors can remain intact. This was the kind of flexibility we aimed to. Side by side Before After In blue are the layers we’ve added. Future improvements If we decide to add translation codes or to change the error structure that comes from the back-end, we know we will only have to change a single file. Writing code that is easy to change is something we’re always aiming for at KI labs and xgeeks. Our habitats are fast-changing environments and recently bootstrapped companies that iterate fast. Reach out to us if this is an environment where you would thrive into! 😉 How are you handling your errors in this kind of situation? Have you created something similar? Are you using something automated to deal with error states? How are you displaying them? I’d love to hear if this solution fixes some of your problems, and if it doesn’t, why? Reach me out via email or twitter Thanks for reading 🙌 Subscribe to my newsletter to get updates on my newest articles! No worries, I will not send more than 1 email per month , nor sell your email to third parties.
https://alexandrempsantos.com/sane-error-handling-react-redux/
CC-MAIN-2020-29
en
refinedweb
Hi guys, This is my first post. I was looking at the news (with coronovirus spreading and mass panic ensuing) and decided to make a little simulator of the spread of coronavirus based on infectivity rates and mortality rates. This isn't complete, I'm still adding stuff to this to make it more accurate, but it's pretty good for now. Hope you guys enjoy it! your feedbak thing doesn't work, clients cant change your server sided text files. it can easily solved with database packages or a database handling lang. (php, nodejs, etc...) @SilentShadowBla Hey, I can't see the loop. The main funcion ends with simulation(people,day,num_of_ppl); and at the end of this function we found: cout << "Any feedback? (Must be 1000 words or less)" << endl; char feedback[1000]; cin >> feedback; file << feedback << "\n"; file.close(); So where exactly is the loop? UPDATE: COVID-19 Simulator is now updated to 0.0.15 (Fuschia) - age is now a factor in the pandemic. There are a bunch of old people with twice as high of a mortality rate. - the objective is to get under a 3% mortality rate and try to get rid of the pandemic as quick as you can. - a few more features to make this more game-like FUTURE: more features to be added, including the socio-economic effects of the COVID-19 pandemic and means of decreasing the mortality rate I spammed "3" and won the game so you should add things to stop a spam for something that can easily win the game UPDATE: - fixed bug where simulation wouldn't stop when no one is infected - increased "mass panic" threshold The infectivity rate is based on real stats, as well as the mortality rate. I am working on increasing the mortality rate. This is meant to be a simulation of a real COVID-19 pandemic, which is why I am adding more features, and why the infectivity rate/mortality rate isn't as high. It's a little bit too easy to win. Also, it doesn't automatically stop when the number of infected people hits zero. Maybe make the infection rate twice as high, or something like that? This is a very good idea, and well thought out if I may. Good work so far! Good job! One thing I would recommend is to remove using namespace std;, as that is a bad practice @TaylorLiang It's not really a bad practice in replit. I'd say, having experience in UE4 and Unity, that it is most important to remove in software development and Game Dev, but otherwise, it's a nice thing to have for time's sake. @nt998302 for something small, I would agree that yeah, its ok. Just that for larger projects, it can cause a hassle and errors later on @TaylorLiang :)
https://repl.it/talk/share/Simulator-of-Spread-of-COVID-19/30652
CC-MAIN-2020-29
en
refinedweb
emkay_online @cvp Thank you so much for this code. It works a treat and really gives me a solid foundation to build on. Also thank you for giving me a good grounding in the objc_util module - it's certainly a complex one, especially for someone with no iOS coding experience. Thank you. emkay_online Thank you for your code. I'm as puzzled as you as to why it doesn't work. I added the other methods in case an error or a cancel was being returned, but nothing. I'll keep playing and hope I stumble on the answer. Thanks again. Martin emkay_online You are amazing - thank you. You have saved me so much frustration and guessing. Thank you so much, Martin emkay_online Hi, I'm just dipping my toes into objc_util and have fallen at the first hurdle. I want to write a small script that calls VisionKit to scan a document and return the result to Pythonista. API is here: I've started with: from objc_util import * VNDocumentCameraViewController = ObjCClass('VNDocumentCameraViewController') But Pythonista says that the class VNDocumentCameraViewController doesn't exist. I'd love some help getting past this (and if anyone could take the example further, that would be amazing). Thank you, Martin emkay_online @JonB That is fantastic. It took a second to realise I needed to open the search bar first, but now it works perfectly. Thank you ps. Sorry to only just reply, I wasn't getting alerts on your posts emkay_online Thanks for the on_main_thread idea - I gave it a go, but the search term didn't change and it just cycled through the old search results. I'll keep playing with it. emkay_online @enceladus thanks for that. I actually use that API already (for results of a style check, where line granularity is good enough). For the word frequency I need to see the individual words in context (just like the native highlighted search results), to assess whether they need replacing. Thank you. emkay_online
https://forum.omz-software.com/user/emkay_online
CC-MAIN-2020-29
en
refinedweb
Important: Please read the Qt Code of Conduct - vsync: missing rendered frames Hello, for a scientific task, flickering areas with a stable frequency (max. 60 Hz), shall be displayed on the screen. I tried to achieve a stable stimulus visualization using Qt 5.6. According to this blog entry and many other online recommendations, I realized three different approaches: Inheriting from QWindow Class, QOpenGLWindow Class and QRasterWindow Class. I wanted to get the accurate advantage of vsync and avoid the usage of QTimer. The flickering area can be displayed. Also a stable time period between the frames has been measured with 16 up to 17 ms. But every few seconds some missed frames are spotted. It can be seen very clearly that there is no stable visualization of the stimulus. The same effect occurs on all three approaches. Have I done the implementation of my code properly or do better solutions exist? If the code is adequate for its purpose do I have to assume that it is a hardware problem? Could it be that difficult then, to display a simple flickering area? Thank you very much for helping me! As Example you can see my code for QWindow Class here: Window::Window(QWindow *parent) : m_context(0) , m_paintDevice(0) , m_bFlickerState(true){ setSurfaceType(QSurface::OpenGLSurface); QSurfaceFormat format; format.setDepthBufferSize(24); format.setStencilBufferSize(8); format.setSwapInterval(1); this->setFormat(format); m_context.setFormat(format); m_context.create(); } void Window::render(){ //calculating elapsed time between frames m_t1 = QTime::currentTime(); int curDelta = m_t0.msecsTo(m_t1); m_t0 = m_t1; qDebug()<< curDelta; m_context.makeCurrent(this); if (!m_paintDevice) m_paintDevice = new QOpenGLPaintDevice; if (m_paintDevice->size() != size()) m_paintDevice->setSize(size()); QPainter p(m_paintDevice); // draw using QPainter if(m_bFlickerState){ p.setBrush(Qt::white); p.drawRect(0,0,this->width(),this->height()); } p.end(); m_bFlickerState = !m_bFlickerState; m_context.swapBuffers(this); // animate continuously: schedule an update QCoreApplication::postEvent( this, new QEvent(QEvent::UpdateRequest)); } - kshegunov Qt Champions 2017 last edited by kshegunov Hello, this->setFormat(format); this is the same as: setFormat(format) the context ( this) is resolved automatically. This is not an error by any means, only a note. if (!m_paintDevice) m_paintDevice = new QOpenGLPaintDevice; this part I don't understand. Your QWindow(if Windowis derived from QWindow) is already a paint device, so why do you need another? Could you provide the class declaration as well? This also goes to Window::render, why do that. I'd derive from QOpenGLWindowand do the painting in a QOpenGLWindow::paintGLand implement the other needed protected methods as well - initializing the GL context and resize at least. QCoreApplication::postEvent( this, new QEvent(QEvent::UpdateRequest)); This is the same as calling requestUpdate(). Kind regards. @kshegunov (I looked it up but I couldn't see the QWindow is a paint device but QOpenGLWindow does inherit from QPaintDeviceWindow class!) Thank you very much for the fast response! If you would choose QOpenGLWIndow, I provide you with the declaration and Implementation of my QOpenGLWindow approach. Like I said, I have the same problem here: frames are clearly missing! Also I can't display this class in Fullscreen-mode on another screen: This error message then is generated: QPainter::begin(): QOpenGLPaintDevice's context needs to be current QPainter::begin(): Returned false QPainter::end: Painter not active, aborted Here is now my full code: mainwindow.cpp: #include "mainwindow.h" #include "QPainter" #include <QOpenGLWindow> MainWindow::MainWindow(QOpenGLWindow *parent) : m_bFlickerState(true) { QSurfaceFormat format; format.setDepthBufferSize(24); format.setStencilBufferSize(8); format.setSwapInterval(1); setFormat(format); //continous update when frame was displayed connect(this, SIGNAL(frameSwapped()), this, SLOT(update())); } void MainWindow::resizeGL(int w, int h) { } void MainWindow::paintGL() { //calculating FPS m_t1 = QTime::currentTime(); int curDelta = m_t0.msecsTo(m_t1); m_t0 = m_t1; qDebug()<< curDelta; // QOpenGLFunctions *f = context()->functions(); // f->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // issue some native OpenGL commands QPainter p(this); // draw using QPainter if(m_bFlickerState){ //f->glClearColor(1,1,1,1); p.fillRect(0,0,100,100,Qt::white); } else{ //f->glClearColor(0,0,0,0); p.fillRect(0,0,100,100,Qt::black); } p.end(); m_bFlickerState = !m_bFlickerState; } mainwindow.h: #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QtCore> #include <QOpenGLPaintDevice> #include <QOpenGLFunctions> #include <QOpenGLWindow> class MainWindow : public QOpenGLWindow, protected QOpenGLFunctions { Q_OBJECT public: explicit MainWindow(QOpenGLWindow *parent = 0 ); ~MainWindow(); protected: void resizeGL(int w, int h); void paintGL(); private: QTime m_t0; QTime m_t1; bool m_bFlickerState; QOpenGLPaintDevice *m_paintDevice; QTimer timer; }; #endif // MAINWINDOW_H main.cpp: #include "mainwindow.h" #include <QApplication> #include <QScreen> #include <QVBoxLayout> #include <QLayout> int main(int argc, char *argv[]) { QApplication a(argc, argv); QScreen *screen = QGuiApplication::screens()[1]; //setup the window MainWindow w; w.setScreen(screen); w.showFullScreen(); return a.exec(); } @geissenpeter said: I looked it up but I couldn't see the QWindow is a paint device but QOpenGLWindow does inherit from QPaintDeviceWindow class! Yes indeed, that's a mistake on my part. I provide you with the declaration and Implementation of my QOpenGLWindow approach It looks good to me. Like I said, I have the same problem here: frames are clearly missing! The only thing I could think of is that the paint events might be getting compressed and some of the updates are skipped. Perhaps you could attach an additional receiver for the frameSwappedsignal and see if that's the case - you'd expect to see update request and then a repaint and then another update request etc. If that's not the case, then this might very well be the reason. Kind regards. - geissenpeter last edited by @kshegunov said: some of the updates are skipped I think this can't be, because the time measured between the update calls is always about 16 to 18 ms. Could a problem with the frame buffer occur instead? Also I have a problem with the QPainter: When my class is displayed in Fullscreen mode (like shown in the code above) then this error is generated. I have looked it up, but haven't found a solution yet QPainter::begin(): QOpenGLPaintDevice's context needs to be current QPainter::begin(): Returned false QPainter::end: Painter not active, aborted thank you for your fast response! I think this can't be, because the time measured between the update calls is always about 16 to 18 ms. This is of no consequence. Look here: update()posts an event on the queue for later processing and this event is subject to being compressed on occasion. I don't know if you can force the repaint however. Could a problem with the frame buffer occur instead? I'm by no means an expert, but it seems doubtful. Also I have a problem with the QPainter: When my class is displayed in Fullscreen mode (like shown in the code above) then this error is generated. I have looked it up, but haven't found a solution yet Possibly you're getting a paint event when the windows is not exposed. But I'm just guessing here. @kshegunov I realized your approach: Every frameSwapped() signal is following an update request. So this code seems to do its job. I don't know what possible errors I could look for anymore... Could other solutions exist for this (in my opinion) quite simple task? I don't know what possible errors I could look for anymore... Sadly, I don't know either. Could other solutions exist for this (in my opinion) quite simple task? I'm sure there are other solutions, but I don't know of any better way. Perhaps one of our more GL-versed members, like @Chris-Kawa, might take a look and suggest something. - Chris Kawa Moderators last edited by Chris Kawa V-sync is hard ;) Basically it's fighting with the inherent noisiness of the system. If the output shows 16-17 ms then that's the problem. 17 ms is too much. That's the skipping you see. Couple of things to reduce that noise: - Don't do I/O in the render loop! qDebug()is I/O and it can block on all kinds of buffering shenanigans. - Testing V-sync under a debugger is useless. Debugging introduces all kinds of noise into your app. You should be testing v-sync in Release mode without debugger attached. - try not to use signals/slots/events if you can help it. They can be noisy i.e. call update()manually at the end of paintGL. You skip some overhead this way (not much but every bit counts). - If all you need is a flickering screen avoid QPainter. It's not exactly slow, but drop into the begin()method of it and see how much it actually does. OpenGL has fast, dedicated facilities to fill the buffer with a color. You might as well use it. Not directly related, but it will make your code cleaner: - Use QElapsedTimer instead of manually calculating time intervals. Why re-invent the wheel. Applying these bits I was able to remove the skipping from your example. Note that the skipping will occur in some circumstances, e.g. when you move/resize the window or when OS/other apps are busy doing something . You have no control over that. Here are the modified code bits: //mainwindow.h ... QElapsedTimer m_timer; }; //mainwindow.cpp MainWindow::MainWindow(QOpenGLWindow *parent) : m_bFlickerState(true) { QSurfaceFormat format; format.setDepthBufferSize(24); format.setStencilBufferSize(8); format.setSwapInterval(1); setFormat(format); m_timer.start(); //note that it doesn't really start any timers, just records current time } void MainWindow::paintGL() { int ms_elapsed = timer.restart(); //you can store it somewhere to analyze later auto f = context()->functions(); if(m_bFlickerState) f->glClearColor(1.0f, 1.0f, 1.0f, 1.0f); else f->glClearColor(0.0f, 0.0f, 0.0f, 1.0f); f->glClear(GL_COLOR_BUFFER_BIT); m_bFlickerState = !m_bFlickerState; update(); //schedules next update directly, without going through signal dispatching } @Chris-Kawa Chris, would running the rendering in a dedicated thread without event loop that forces rendering on a regular interval (for example a QThreadsubclass) be beneficial in this case? Or are the waiting routines (i.e. QThread::msleep/QThread::usleep/QSemaphore::tryAcquire) not precise enough for such things? Again I'm just curious, so don't answer if you don't have the time. :) - Chris Kawa Moderators last edited by @kshegunov Any kind of sleeping/timer is no good for frame-perfect rendering. It doesn't matter in which thread you do it. There's just no solid way to synchronize these with the refresh rate. You can't for example calculate "oh I rendered in 7ms so I have ~9.66ms left till the v-sync so I'll sleep for 9ms". That will miss most of the time. If any of these primitives is late even a microsecond for the v-sync it's all lost. The only way to have any control over it is start drawing as soon as the v-sync is done and wait for the next one. Basically QOpenGLContext::swapBuffersis your only tool for that (done implicitly when you exit paintGL). @Chris-Kawa Fair enough. Thanks for taking the time. Cheers!
https://forum.qt.io/topic/67103/vsync-missing-rendered-frames
CC-MAIN-2020-29
en
refinedweb
As a system administrator, shells are a part of daily operations. Shells often provide more options and flexibility than a graphical user interface (GUI). Daily repetitive tasks can easily be automated by scripts, or tasks can be scheduled to run at certain times during the day. A shell provides a convenient way to interact with the system and enables you to do more in less time. There are many different shells, including Bash, zsh, tcsh, and PowerShell.. In part two, I'll examine shell variables, the find command, file descriptors, and executing operations remotely. Use the history command The history command is a handy one. History allows me to see what commands I ran on a particular system or arguments were passed to that command. I use history to re-run commands without having to remember anything. The record of recent commands is stored by default in ~/.bash_history. This location can be changed by modifying the HISTFILE shell variable. There are other variables, such as HISTSIZE (lines to store in memory for the current session) and HISTFILESIZE (how many lines to keep in the history file). If you want to know more about history, see man bash. Let's say I run the following command: $> sudo systemctl status sshd Bash tells me the sshd service is not running, so the next thing I want to do is start the service. I had checked its status with my previous command. That command was saved in history, so I can reference it. I simply run: $> !!:s/status/start/ sudo systemctl start sshd The above expression has the following content: - !! - repeat the last command from history - :s/status/start/ - substitute status with start The result is that the sshd service is started. Next, I increase the default HISTSIZE value from 500 to 5000 by using the following command: $> echo “HISTSIZE=5000” >> ~/.bashrc && source ~/.bashrc What if I want to display the last three commands in my history? I enter: $> history 3 1002 ls 1003 tail audit.log 1004 history 3 I run tail on audit.log by referring to the history line number. In this case, I use line 1003: $> !1003 tail audit.log .. .. Imagine you've copied something from another terminal or your browser and you accidentally paste the copy (which you have in the copy buffer) into the terminal. Those lines will be stored in the history, which here is something you don't want. So that's where unset HISTFILE && exit comes in handy $> unset HISTFILE && exit or $> kill -9 $$ Reference the last argument of the previous command When I want to list directory contents for different directories, I may change between directories quite often. There is a nice trick you can use to refer to the last argument of the previous command. For example: $> pwd /home/username/ $> ls some/very/long/path/to/some/directory foo-file bar-file baz-file In the above example, /some/very/long/path/to/some/directory is the last argument of the previous command. If I want to cd (change directory) to that location, I enter something like this: $> cd $_ $> pwd /home/username/some/very/long/path/to/some/directory Now simply use a dash character to go back to where I was: $> cd - $> pwd /home/username/ Work on files and directories Imagine that I want to create a directory structure and move a bunch of files having different extensions to these directories. First, I create the directories in one go: $> mkdir -v dir_{rpm,txt,zip,pdf} mkdir: created directory 'dir_rpm' mkdir: created directory 'dir_txt' mkdir: created directory 'dir_zip' mkdir: created directory 'dir_pdf' Next, I move the files based on the file extension to each directory: $> mv -- *.rpm dir_rpm/ $> mv -- *.pdf dir_pdf/ $> mv -- *.txt dir_txt/ $> mv -- *.zip dir_txt/ The double dash characters -- mean End of Options. This flag prevents files that begin with a dash from being treated as arguments. Next, I want to replace/move all *.txt files to *.log files, so I enter: $> for file in ./*.txt; do mv -v ”$file” ”${file%.*}.log”; done renamed './file10.txt' -> './file10.log' renamed './file1.txt' -> './file1.log' renamed './file2.txt' -> './file2.log' renamed './file3.txt' -> './file3.log' renamed './file4.txt' -> './file4.log' Instead of using the for loop above, I can install the prename command and accomplish the above goal like this: $> prename -v 's/.txt/.log/' *.txt file10.txt -> file10.log file1.txt -> file1.log file2.txt -> file2.log file3.txt -> file3.log file4.txt -> file4.log Often, when modifying a configuration file, I make a backup copy of the original one by using a basic copy command. For example: $> cp /etc/sysconfig/network-scripts/ifcfg-eth0 /etc/sysconfig/network-scripts/ifcfg-eth0.back As you can see, repeating the whole path and appending .back to the file isn't that efficient and probably error-prone. There is a shorter, neater way to do this. Here it comes: $> cp /etc/sysconfig/network-scripts/ifcfg-eth0{,.back} You can perform different checks on files or variables. Run help test for more information. Use the following command to discover if a file is a symbolic link: $> [[ -L /path/to/file ]] && echo “File is a symlink” Here is an issue I ran across recently. I wanted to gunzip/untar a bunch of files in one go. Without thinking, I typed: $> tar zxvf *.gz The result was: tar: openvpn.tar.gz: Not found in archive tar: Exiting with failure status due to previous errors The tar files were: iptables.tar.gz openvpn.tar.gz ….. Why didn't it work, and why would ls -l *.gz work instead? Under the hood, it looks like this: $> tar zxvf *.gz Is transformed as follows: $> tar zxvf iptables.tar.gz openvpn.tar.gz tar: openvpn.tar.gz: Not found in archive tar: Exiting with failure status due to previous errors The tar command expected to find openvpn.tar.gz within iptables.tar.gz. I solved this with a simple for loop: $> for f in ./*.gz; do tar zxvf "$f"; done iptables.log openvpn.log I can even generate random passwords by using Bash! Here's an example: $> alphanum=( {a..z} {A..Z} {0..9} ); for((i=0;i<=${#alphanum[@]};i++)); do printf '%s' "${alphanum[@]:$((RANDOM%255)):1}"; done; echo Here is an example that uses OpenSSL: $> openssl rand -base64 12 JdDcLJEAkbcZfDYQ Read a file line by line Assume I have a file with a lot of IP addresses and want to operate on those IP addresses. For example, I want to run dig to retrieve reverse-DNS information for the IP addresses listed in the file. I also want to skip IP addresses that start with a comment (# or hashtag). I'll use fileA as an example. Its contents are: 10.10.12.13 some ip in dc1 10.10.12.14 another ip in dc2 #10.10.12.15 not used IP 10.10.12.16 another IP I could copy and paste each IP address, and then run dig manually: $> dig +short -x 10.10.12.13 Or I could do this: $> while read -r ip _; do [[ $ip == \#* ]] && continue; dig +short -x "$ip"; done < ipfile What if I want to swap the columns in fileA? For example, I want to put IP addresses in the right-most column so that fileA looks like this: some ip in dc1 10.10.12.13 another ip in dc2 10.10.12.14 not used IP #10.10.12.15 another IP 10.10.12.16 I run: $> while read -r ip rest; do printf '%s %s\n' "$rest" "$ip"; done < fileA Use Bash functions Functions in Bash are different from those written in Python, C, awk, or other languages. In Bash, a simple function that accepts one argument and prints "Hello world" would look like this: func() { local arg=”$1”; echo “$arg” ; } I can call the function like this: $> func foo Sometimes a function invokes itself recursively to perform a certain task. For example: func() { local arg="$@"; echo "$arg"; f "$arg"; }; f foo bar This recursion will run forever and utilize a lot of resources. In Bash, you can use FUNCNEST to limit recursion. In the following example, I set FUNCNEST=5 to limit the recursion to five. func() { local arg="$@"; echo "$arg"; FUNCNEST=5; f "$arg"; }; f foo bar foo bar foo bar foo bar foo bar foo bar bash: f: maximum function nesting level exceeded (5) Use a function to retrieve the most recent or oldest file Here is a sample function to display the most recent file in a certain directory: latest_file() { local f latest for file in "${1:-.}"/* do [[ $f -nt $latest ]] && latest="$f" done printf '%s\n' "$latest" } This function displays the oldest file in a certain directory: oldest_file() { local f oldest for file in "${1:-.}"/* do [[ -z $oldest || $f -ot $oldest ]] && oldest="$f" done printf '%s\n' "$oldest" } These are just a few examples of how to use functions in Bash without invoking other external commands. I sometimes find myself typing a command over and over with a lot of parameters. One command I often use is kubectl (Kubernetes CLI). I am tired of running this long command! Here's the original command: $> kubectl -n my_namespace get pods or $> kubectl -n my_namespace get rc,services This syntax requires me to manually include -n my_namespace each time I run the command. There is an easier way to do this using a function: $> kubectl () { command kubectl -n my_namespace ”$@” ; } Now I can run kubectl without having to type -n namespace each time: $> kubectl get pods I can apply the same technique to other commands. Wrap up These are just a few excellent tricks that exist for Bash. In part two, I will show some more examples, including the use of find and remote execution. I encourage you to practice these tricks to make your command-line administration tasks easier and more accurate. [ Free online course: Red Hat Enterprise Linux technical overview. ]
https://www.redhat.com/sysadmin/stupid-bash-tricks
CC-MAIN-2020-29
en
refinedweb
accept() Accept a connection on a socket Synopsis: #include <sys/types.h> #include <sys/socket.h> int accept( int s, struct sockaddr * addr, socklen_t * addrlen ); Since: BlackBerry 10.0.0: 2014-06-24 Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus
https://developer.blackberry.com/native/reference/core/com.qnx.doc.neutrino.lib_ref/topic/a/accept.html
CC-MAIN-2020-29
en
refinedweb
AWS CDK tools This section contains information about AWS CDK tools. AWS Toolkit for Visual Studio code The AWS Toolkit for Visual Studio Code AWS CDK Toolkit ( cdk) The AWS CDK Toolkit, the CLI cdk, is the main tool you use to interact with your AWS CDK app. It executes the AWS CDK app you wrote and compiled, interrogates the application model you defined, and produces and deploys the AWS CloudFormation templates generated by the AWS CDK. There are two ways to tell cdk what command to use to run your AWS CDK app. The first way is to include an explicit --app option whenever you use a cdk command. cdk --app "npx ts-node bin/hello-cdk.ts" ls The second way is to add the following entry to the cdk.json file (if you use the cdk init command, the command does this for you). { "app": "npx ts-node bin/hello-cdk.ts" } You can also use npx cdk instead of just cdk. npx cdk looks for a locally-installed copy of the AWS CDK CLI in the current project before falling back to a global installation. Here are the actions you can take on your AWS CDK app (this is the output of the cdk --help command). Usage: cdk -a <cdk-app> COMMAND Commands: cdk list [STACKS..] Lists all stacks in the app [aliases: ls] cdk synthesize [STACKS..] Synthesizes and prints the CloudFormation template for this stack [aliases: synth] cdk bootstrap [ENVIRONMENTS..] Deploys the CDK toolkit stack into an AWS environment cdk deploy [STACKS..] Deploys the stack(s) named STACKS into your AWS account cdk destroy [STACKS..] Destroy the stack(s) named STACKS cdk diff [STACKS..] Compares the specified stack with the deployed stack or a local template file, and returns with status 1 if any difference is found cdk metadata [STACK] Returns all metadata associated with this stack cdk init [TEMPLATE] Create a new, empty CDK project from a template. Invoked without TEMPLATE, the app template will be used. cdk context Manage cached context values cdk docs Opens the reference documentation in a browser [aliases: doc] cdk doctor Check your set-up for potential problems Options: --app, -a REQUIRED: command-line for executing your app or a cloud assembly directory (e.g. "node bin/my-app.js") [string] --context, -c Add contextual string parameter (KEY=VALUE) [array] --plugin, -p Name or path of a node package that extend the CDK features. Can be specified multiple times [array] --trace Print trace for stack warnings [boolean] --strict Do not construct stacks with warnings [boolean] --ignore-errors Ignores synthesis errors, which will likely produce an invalid output [boolean] [default: false] --json, -j Use JSON output instead of YAML when templates are printed to STDOUT [boolean] [default: false] --verbose, -v Show debug logs [boolean] [default: false] --profile Use the indicated AWS profile as the default environment [string] --proxy Use the indicated proxy. Will read from HTTPS_PROXY environment variable if not specified. [string] --ca-bundle-path Path to CA certificate to use when validating HTTPS requests. Will read from AWS_CA_BUNDLE environment variable if not specified. [string] --ec2creds, -i Force trying to fetch EC2 instance credentials. Default: guess EC2 instance status. [boolean] --version-reporting Include the "AWS::CDK::Metadata" resource in synthesized templates (enabled by default) [boolean] --path-metadata Include "aws:cdk:path" CloudFormation metadata for each resource (enabled by default) [boolean] [default: true] --asset-metadata Include "aws:asset:*" CloudFormation metadata for resources that user assets (enabled by default) [boolean] [default: true] --role-arn, -r ARN of Role to use when invoking CloudFormation [string] --toolkit-stack-name The name of the CDK toolkit stack [string] --staging Copy assets to the output directory (use --no-staging to disable, needed for local debugging the source files with SAM CLI) [boolean] [default: true] --output, -o Emits the synthesized cloud assembly into a directory (default: cdk.out) [string] --no-color Removes colors and other style from console output [boolean] [default: false] --fail Fail with exit code 1 in case of diff [boolean] [default: false] --version Show version number [boolean] -h, --help Show help [boolean] If your app has a single stack, there is no need to specify the stack name If one of cdk.json or ~/.cdk.json exists, options specified there will be used as defaults. Settings in cdk.json take precedence. If a cdk.json or ~/.cdk.json file exists, options specified there are used as defaults. Settings in cdk.json take precedence. AWS CDK toolkit commands The AWS CDK CLI supports several distinct commands. Help for each (including only the command-line options specific to the particular command) follows. Commands with no command-specific options are not listed. All commands additionally accept the options listed above. cdk list ( ls) cdk list [STACKS..] Lists all stacks in the app Options: --long, -l Display environment information for each stack [boolean] [default: false] cdk synthesize ( synth) cdk synthesize [STACKS..] Synthesizes and prints the CloudFormation template for this stack Options: --exclusively, -e Only synthesize requested stacks, don't include dependencies [boolean] If your app has a single stack, you don't have to specify the stack name. cdk bootstrap cdk bootstrap [ENVIRONMENTS..] Deploys the CDK toolkit stack into an AWS environment Options: --bootstrap-bucket-name, -b, The name of the CDK toolkit bucket; --toolkit-bucket-name bucket will be created and must not exist [string] --bootstrap-kms-key-id AWS KMS master key ID used for the SSE-KMS encryption [string] --qualifier Unique string to distinguish multiple bootstrap stacks [string] --tags, -t Tags to add for the stack (KEY=VALUE) [array] [default: []] --execute Whether to execute ChangeSet (--no-execute will NOT execute the ChangeSet) [boolean] [default: true] --force, -f Always bootstrap even if it would downgrade template version [boolean] [default: false] cdk deploy cdk deploy [STACKS..] Deploys the stack(s) named STACKS into your AWS account Options: --build-exclude, -E Do not rebuild asset with the given ID. Can be specified multiple times. [array] [default: []] --exclusively, -e Only deploy requested stacks, don't include dependencies [boolean] --require-approval What security-sensitive changes need manual approval [string] [choices: "never", "any-change", "broadening"] --ci Force CI detection (deprecated) [boolean] [default: false] --notification-arns ARNs of SNS topics that CloudFormation will notify with stack related events [array] --tags, -t Tags to add to the stack (KEY=VALUE) [array] --execute Whether to execute ChangeSet (--no-execute will NOT execute the ChangeSet) [boolean] [default: true] --force, -f Always deploy stack even if templates are identical [boolean] [default: false] --parameters Additional parameters passed to CloudFormation at deploy time (STACK:KEY=VALUE) [array] [default: {}] --outputs-file, -O Path to file where stack outputs will be written as JSON [string] --previous-parameters Use previous values for existing parameters (you must specify all parameters on every deployment if this is disabled) [boolean] [default: true] If your app has a single stack, you don't have to specify the stack name. cdk destroy cdk destroy [STACKS..] Destroy the stack(s) named STACKS Options: --exclusively, -e Only destroy requested stacks, don't include dependees [boolean] --force, -f Do not ask for confirmation before destroying the stacks [boolean] If your app has a single stack, you don't have to specify the stack name. cdk init cdk init [TEMPLATE] Create a new, empty CDK project from a template. Invoked without TEMPLATE, the app template will be used. Options: --language, -l The language to be used for the new project (default can be configured in ~/.cdk.json) [string] [choices: "csharp", "fsharp", "java", "javascript", "python", "typescript"] --list List the available templates [boolean] --generate-only If true, only generates project files, without executing additional operations such as setting up a git repo, installing dependencies or compiling the project [boolean] [default: false] cdk context cdk context Manage cached context values Options: --reset, -e The context key (or its index) to reset [string] --clear Clear all context [boolean] Bootstrapping your AWS environment Before you can use the AWS CDK you must bootstrap your AWS environment to create the infrastructure that the AWS CDK CLI needs to deploy your AWS CDK app. Currently the bootstrap command creates only an Amazon S3 bucket. You incur any charges for what the AWS CDK stores in the bucket. Because the AWS CDK does not remove any objects from the bucket, the bucket can accumulate objects as you use the AWS CDK. You can get rid of the bucket by deleting the CDKToolkit stack from your AWS account. Security-related changes To protect you against unintended changes that affect your security posture, the AWS CDK toolkit prompts you to approve security-related changes before deploying them. You change the level of changes that requires approval by specifying: cdk deploy --require-approval LEVEL Where LEVEL can be one of the following: - never Approval is never required. - any-change Requires approval on any IAM or security-group related change. - broadening (default) Requires approval when IAM statements or traffic rules are added. Removals don't require approval. The setting can also be configured in the cdk.json file. { "app": "...", "requireApproval": "never" } Version reporting To gain insight into how the AWS CDK is used, the versions of libraries used by AWS CDK applications are collected and reported by using a resource identified as AWS::CDK::Metadata. This resource is added to AWS CloudFormation templates, and can easily be reviewed. This information can also be used to identify stacks using a package with known serious security or reliability issues, and to contact their users with important information. By default, the AWS CDK reports the name and version of the following NPM modules that are loaded at synthesis time: AWS CDK core module AWS Construct Library modules AWS Solutions Constructs module The AWS::CDK::Metadata resource looks like the following. CDKMetadata: Type: "AWS::CDK::Metadata" Properties: Modules: "@aws-cdk/core=0.7.2-beta,@aws-cdk/s3=0.7.2-beta,@aws-solutions-consturcts/aws-apigateway-lambda=0.8.0" Opting out from version reporting To opt out of version reporting, use one of the following methods: Use the cdk command with the --no-version-reporting argument. cdk --no-version-reporting synth Set versionReporting to false in ./cdk.jsonor ~/.cdk.json. { "app": "...", "versionReporting": false } SAM CLI This topic describes how to use the SAM CLI with the AWS CDK to test a Lambda function locally. For further information, see Invoking Functions Locally. To install the SAM CLI, see Installing the AWS SAM CLI. The first step is to create a AWS CDK application and add the Lambda package. mkdir cdk-sam-example cd cdk-sam-example cdk init app --language typescript npm install @aws-cdk/aws-lambda Add a Lambda reference to lib/cdk-sam-example-stack.ts: import * as lambda from '@aws-cdk/aws-lambda'; Replace the comment in lib/cdk-sam-example-stack.tswith the following Lambda function: new lambda.Function(this, 'MyFunction', { runtime: lambda.Runtime.PYTHON_3_7, handler: 'app.lambda_handler', code: lambda.Code.asset('./my_function'), }); Create the directory my_function mkdir my_function Create the file app.pyin my_functionwith the following content: def lambda_handler(event, context): return "This is a Lambda Function defined through CDK" Run your AWS CDK app and create a AWS CloudFormation template cdk synth --no-staging > template.yaml Find the logical ID for your Lambda function in template.yaml. It will look like MyFunction 12345678, where 12345678represents an 8-character unique ID that the AWS CDK generates for all resources. The line right after it should look like: Type: AWS::Lambda::Function Run the function by executing: sam local invoke MyFunction 12345678--no-event The output should look something like the following. 2019-04-01 12:22:41 Found credentials in shared credentials file: ~/.aws/credentials 2019-04-01 12:22:41 Invoking app.lambda_handler (python3.7) Fetching lambci/lambda:python3.7 Docker container image...... 2019-04-01 12:22:43 Mounting D:\cdk-sam-example\.cdk.staging\a57f59883918e662ab3c46b964d2faa5 as /var/task:ro,delegated inside runtime container START RequestId: 52fdfc07-2182-154f-163f-5f0f9a621d72 Version: $LATEST END RequestId: 52fdfc07-2182-154f-163f-5f0f9a621d72 REPORT RequestId: 52fdfc07-2182-154f-163f-5f0f9a621d72 Duration: 3.70 ms Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 22 MB "This is a Lambda Function defined through CDK"
https://docs.aws.amazon.com/cdk/latest/guide/tools.html
CC-MAIN-2020-29
en
refinedweb
For real-time public discussion of FIRRTL. Debates requiring community feedback should be done in firrtl/issues. User questions are welcome. -X verilogto -X noneand get the protobuf, then just do the Verilog step after and that works fine seldridgeTry something like the following (instead of using inputForm/ outputForm: import firrtl.stage.Forms class myWriteProtobuf extends Transform with DependencyAPIMigration { override def prerequisites = Forms.LowForm override def optionalPrerequisites = Seq.empty override def optionalPrerequisiteOf = Forms.LowEmitters override def invalidates(a: Transform) = false override def execute = ??? } seldridgeThere's some weirdness in the legacy way that inputForm=LowFormis scheduled. It roughly translates into "run as late as possible". So, if you run with -X lowit runs right before the low firrtl emitter. If you run with -X verilogit runs after low FIRRTL optimizations (right before the Verilog emitter). seldridgeLow FIRRTL optimizations introduce some illegal IR nodes that help with Verilog emission. It's a long-standing issue to clean this up. However, the newer dependency API lets you be more explicit about when things are supposed to run. Schuyler EldridgeI think these things are orthogonal. mdoc is good for running code blocks in markdown. (This is actually already how some of the website documentation works and it seems to work really well!) Scaladoc (or Unidoc) is still necessary as a means to document the underlying APIs.
https://gitter.im/freechipsproject/firrtl
CC-MAIN-2020-29
en
refinedweb
Odoo Help Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps: CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc. How to inherit class partner_balance to change functions? Hi, I'm trying to inherit class partner_balance(report_sxw.rml_parse, common_report_header) from the file addons/account/account_partner_balance.py, but it isn't like the other inherits of osv.osv ... I want to change this function def set_context(self, objects, data, ids, report_type=None) and `this def lines(self).... Do you know how can I change those functions ? Thanks About This Community Odoo Training Center Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now
https://www.odoo.com/forum/help-1/question/how-to-inherit-class-partner-balance-to-change-functions-50713
CC-MAIN-2018-17
en
refinedweb
Odoo Help Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps: CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc. No module named q on account_transfer module Hi all, I have Odoo running on a server and my installation includes account_transfer module. It works fine. Since the addons, server and web are on a very old version (about one year), I have decided to upgrade de addons/server/web addons to newest versions, and before doing it on the server itself, I am testing everything on a virtual machine on another computer. I have everything setup with new addons/server/web addons, and copied the additional addons I use, including the account_transfer module, but when I try to access the restored database I get the error "No module named q" on the login page. This error was raised whille loading the account_transfer module. After analyse the log, I found that the account_transfer has the following lines on account_transfer.py: from osv import osv, fields from tools.translate import _ import decimal_precision as dp import time import q For testing purposes I commented the line #import q, and tested again and it worked. I was logged onto the system and can use all modules and aplications I have. The problem is that when I try to use the account_transfer module, I get the error: NameError: global name 'q' is not defined So, I found that "q" is not a module. Instead, it is a global name. How can I fix this since it works fine on the server? It works fine on the server and the problem is only on the new virtual machine I am testing. Thank you all Regards Paulo Dear Mariusz Mizgier You save the day. Installed the packege q according to your instructions and it's workins like a charm. Best regards Paulo Matos About This Community Odoo Training Center Access to our E-learning platform and experience all Odoo Apps through learning videos, exercises and Quizz.Test it now
https://www.odoo.com/forum/help-1/question/no-module-named-q-on-account-transfer-module-59726
CC-MAIN-2018-17
en
refinedweb
acos, acosf, acosl - arc cosine functions #include <math.h> double acos(double x); float acosf(float x); long double acosl(long double x); These functions shall compute the principal value of the arc cos . cos() , .
http://manpages.sgvulcan.com/acos.3p.php
CC-MAIN-2018-17
en
refinedweb
Using singleton classes for object metadata .jpg) - | - - - - - - Read later Reading List A note to our readers: You asked so we have developed a set of features that allow you to reduce the noise: you can get email and web notifications for topics you are interested in. Learn more about our new features. So you have a bunch of objects - an object graph - the result of some operation or API call. The task: analyze the data and store the results of the analysis as metadata for the graph. Too abstract? Think of how a compiler works: the parser spits out a parse tree (or Abstract Syntax Tree or AST) that represents the code as tree structure. Then: a lot of algorithms run over the tree in passes: gathering symbols in the symbol table, doing type inference, using these types to do type checking, etc. But wait: the last two passes show the problem: where does the type inferencing code store its data for the type checker to use? It'd be most convenient to store the data where it's needed - i.e. if an expression node (in the AST) is found to return type Foo, then it'd be best to store that information right in the node. To illustrate the solution, we'll look at some tools that work on ASTs - not a compiler, but tools with similar requirements. In Ruby, the ParseTree library returns Ruby source code as an AST. Example: [:vcall, :obj, :say_hello, [:array, [:lit, 42], [:lvar, :foo]]] This is a bit of Ruby code represented as ParseTree AST. Since this is an article and not a VM, it's a bit difficult to work with objects and object references organized as a graph - so we use ParseTree's s-expr representation of the tree. S-exprs are nested lists; each list represents a node in the tree, with the first element specifying the node type. In the sample, the node represents a call to a virtual method (vcall). The parameters are the receiver (the 'self' in the called method), the name of the method and the parameters. Ideas for tools would be a type checker, static analysis tools or automatic refactorings. One of the requirements for tools of that kind to work is some kind of type inference, i.e. determining the types of variables or expressions. For instance, this AST represents a call to the to_s method: [:vcall, :obj, :to_s] What information can be gathered about this, and what could be done with this information? The type of the return value, for instance. This is hard to determine - but since it's to_s, a method that returns the string representation of an object - let's just say it returns "String". This is not necessarily true - it's a guess. For tools such as a code completion, it's fine enough - 100 % accuracy isn't possible for these matters. Although in some cases, more information could be gathered, and the analyzer could determine more accurate information. Analyzers work on the tree and annotate the AST with the metadata they have determined. For keeping codebases modular, it's a good idea to separate the analyzers from the metadata consumers, i.e. the code that walks the AST and does something with the metadata. For instance, a Ruby editor could highlight a method that overrides another in its superclass. The solution Long story short: here's a solution for annotating ParseTree nodes: node = [:vcall, :obj, :to_s] def node.set_metadata(key, value) @_metadata ||= Hash.new @_metadata[key] = value end def node.metadata @_metadata ||= {} end node.set_metadata(:type, :String) What does that do? The secret sauce: singleton classes Every object in Ruby is the instance of a class. Unlike many other OOP languages, Ruby allows you to change an object's class. Don't confuse this with open classes: in Ruby, it's possible to modify a class - even at runtime. Singleton classes are similar - except that they only affect one object's class. While the difference might seem small - it has the big benefit of limiting the effects of the class modification to the affected object. Open classes, on the other hand, change the class definition for all the code and all the objects of these classes. This is useful, but can also mess with other people's code and if too many pieces of code do it on common classes, name clashes with existing methods can happen. In the case of ParseTree nodes - which are ordinary Ruby Arrays - this means that only the actually used Array objects are affected - not all the Arrays on the heap. Another way to see this: with singleton classes, the changes to the class stay local to the code that creates and uses them - they never need to be visible outside. Open classes, on the other hand, are global changes: a class name is a global variable, i.e. "String" refers to the class object representing Strings. Just as more scoped variables (local variables, member variables) are preferable over global variables, so are singleton classes to open classes. Of course: which solution to choose (singleton or open classes) depends on the particular situation. With open classes, the change to the class happens once - after it, all objects of that class have the added methods. With singleton classes, the change to the class (i.e. creating the singleton class and changing the object's class pointer to point to it) happens at every change. The syntax - as seen above - is simple: def object_variable.method_name() # code end The variable pointing to the object is prefixed to the method name. A more flexible and modular way is to use Mixins to do it. This allows to collect methods that handle some aspect in a Module and mix them in in one go. E.g. module Metadata def set_metadata(key, val) @_metadata[key] = val end def metadata @_metadata ||= {} end end x = [:vcall, :obj, :to_s] x.extend Metadata x.set_metadata(:type, :String) Mixins allow to mix functions defined in a Module into a class - in this sample, it's the node object's singleton class. Again: only this object will have these methods now. Another example - dead code removal If the static analyzer code is too abstract, let's try another tool: a dead code remover. "Dead code" is simply code that doesn't really do anything and can be removed without changing the behavior of the program. Like this code: for x in [1,2,3] do end With our annotating concept, we can look for this kind of code and annotate it as such: node.metadata(:dead_code, :true) But marking the code as dead is only the first step - now we need to remove it. This is where it's easy to see that it makes sense to split up analysis and action part. An IDE might just want to highlight some code as dead code, but it might also offer a simple way (a Quick Fix) that removes the code. How can this code be removed? Sure - it'd be possible to dump the node from the AST and then use Ruby2Ruby to spit out Ruby source. But that's not a very nice solution: Ruby2Ruby turns ParseTree ASTs into Ruby source code, but it loses a lot of useful information, such as formatting (white space) and comments. Dropping these is not acceptable in an IDE or refactoring/cleanup tools. Metadata to the rescue: the nodes can be annotated with source locations - ie. where this particular node is found in the original source code. And with that - it's easy: the cleanup code simply marches through the code, finds all nodes marked with :dead_code and removes them in the source file, using the character offsets of the source location metadata. (Of course - once some nodes were removed, the offsets of the rest of the nodes are off. This can be solved by simply tracking the number of deleted characters and subtracting them from the actual offsets. With that, it's not necessary to reparse and re-analyze the source). Conclusion The examples in this article were focussed on language tools - but the ideas are usable for all kinds of object collections. Wherever object graphs need to be annotated, possibly in multiple passes by independently written analyzers, it's convenient to store the annotations with the nodes. If the classes of the object graph are not under the developer's control and are extensively used elsewhere (e.g. the Array class in ParseTree), singleton classes are a good choice. For other situations, open classes might be a better solution. As for implementing the specific tools mentioned here: ParseTree is available for Ruby 1.8.x, in Rubinius and JRuby (jparsetree). The JRuby version also adds source locations for the individual nodes, so it's even easier to modify source. Have fun coming up with ideas for tools and writing them - it's easy with Ruby. Rate this Article - Editor Review - Chief Editor Action
https://www.infoq.com/articles/prototypes-for-metadata
CC-MAIN-2018-17
en
refinedweb
Lookup is a general API for registering and querying instances of services or other objects. There are two basic uses of lookup: a particular context, e.g. a node selection passed to an action; and global default lookup, used to register services in the system. When writing a unit test that tests code which (directly or indirectly) calls Lookup.getDefault() you should consider what the available instances will be. By default, any classes registered in META-INF/services/* resources in JARs in the test classpath will be available. If you want to override this, the easiest thing is to use MockServices, from the nbjunit test utilities library. For example, you may want to register a special ProjectFactory for use within one test, because you want a simplified project type you can control to test some features of code which works with projects. Here is how: protected void setUp() throws Exception { super.setUp(); MockServices.setServices(TestingProjectFactory.class); } public static class TestingProjectFactory implements ProjectFactory { // implement interface methods... } Now e.g. ProjectManager.getDefault().findProject(...) should give TestingProjectFactory a chance to recognize the project. Note that TestingProjectFactory will be available in default lookup as the first ProjectFactory instance, but any others registered in META-INF/services/* will still be available "later". (Lookup is ordered.) Many services placed in lookup (e.g. DialogDisplayer) are intended to be singletons, in which case installing an instance using MockServices effectively means you can override the default implementation. You can also add and remove services while the test runs. Every call to setServices overrides the previous call. Code which directly looks in META-INF/services/* - for example, calls to java.util.Service, as well as many subsystems such as JAXP - should also see services registered this way. If you wish to register individual instances to default lookup, without the requirement that they be default instances of public classes, you can also use MockLookup. See UsefulTestClassesInModules.
http://wiki.netbeans.org/InitializationOfDefaultLookup
CC-MAIN-2018-17
en
refinedweb
Next example illustrates my problem. It skips 10 seconds forward or 10 seconds backward. When you run this program with v4.08.06 it works perfectly, when you use v4.08.09 the fast forward goes noticeably slower, and the fast backward takes ages. Strange thing is, the problem only arises with MP3, with an OGG file there is no problem. using WinXP SP2 [code:16srnt6m] include <fmod.hpp> include <stdlib.h> include <stdio.h> include <conio.h> include <windows.h> using namespace FMOD; void main() { System *system; System_Create(&system); system->init(10, FMOD_INIT_NORMAL, 0); Sound *sound; system->createSound("E:\z.mp3", FMOD_2D | FMOD_SOFTWARE | FMOD_CREATESTREAM, 0, &sound); unsigned int len; sound->getLength(&len, FMOD_TIMEUNIT_MS); Channel *channel; system->playSound(FMOD_CHANNEL_FREE, sound, false, &channel); printf("press f for forward, b for backward, q to quit\n"); char choise; while ( true ) { unsigned int curpos = 0; if (kbhit()) { choise = _getch(); switch( choise ) { case 'f': { for ( int i = 0; i < 25; i++ ) { channel->getPosition( &curpos, FMOD_TIMEUNIT_MS ); channel->setPosition( curpos + 400, FMOD_TIMEUNIT_MS); } break; } case 'b': { for ( int i = 0; i < 25; i++ ) { channel->getPosition( &curpos, FMOD_TIMEUNIT_MS ); channel->setPosition( curpos - 400, FMOD_TIMEUNIT_MS); } break; } case 'q': { return; } } } channel->getPosition( &curpos, FMOD_TIMEUNIT_MS ); printf( "Position: %u \r", curpos ); Sleep(10); } } [/code:16srnt6m] regards, Hans de Rijck - hansr asked 10 years ago - You must login to post comments FMOD calls dont take a full second normally, its possible it is actually to do with your mp3. There really is no reason for this, the mp3 codec code hasnt changed and I can’t think of much else. Can you test different mp3 files to see if that is the difference Brett, I tested several different MP3’s, VBR, CBR, large ones, small ones etc. There are some differences between the files, some are better, some are worse (the longest time was about 2 seconds for a call). It was no strict scientific research but if there is any correlation I would say that the bitrate of the file has the most effect (320kbps files are worse than 128kbps). Mind you, there was not one MP3 that works ok. The 4.08.06 version has no problems with any of the files so I would guess that something did change after all. I hope you can find something. In the meantime I will revert back to 4.08.06. Perhaps someone else reading this forum can confirm whether or not this is a problem (the setPosition, not my reverting). regards, Hans de Rijck. what media are you streaming from? I dont see any problem like this even with your example program. Mp3 seeks forward and back and it is almost instantaneous. I’m streaming from a local sata HD. To get some more information I added a timer around the SetPosition as follows: [code:byy5a5xi] SYSTEMTIME sTimeBefore, sTimeAfter; GetSystemTime( &sTimeBefore ); channel->setPosition( curpos - 400, FMOD_TIMEUNIT_MS); GetSystemTime( &sTimeAfter ); printf( "Before: %2d.%03d After: %2d.%03d\n", sTimeBefore.wSecond, sTimeBefore.wMilliseconds, sTimeAfter.wSecond, sTimeAfter.wMilliseconds ); [/code:byy5a5xi] This gives the following results: [list:byy5a5xi] Before: 13.638 After: 14.701 Before: 14.701 After: 15.811 Before: 15.811 After: 15.826 Before: 15.826 After: 15.842 Before: 15.842 After: 16.842 Before: 16.842 After: 17.873 Before: 17.873 After: 17.889 Before: 17.889 After: 17.889 Before: 17.889 After: 18.170 Before: 18.170 After: 19.139 Before: 19.139 After: 20.124 Before: 20.124 After: 20.124 Before: 20.124 After: 20.139 Before: 20.139 After: 21.030 Before: 21.030 After: 21.968 Before: 21.968 After: 21.968 Before: 21.968 After: 21.968 Before: 21.968 After: 22.796 Before: 22.796 After: 23.656 Before: 23.656 After: 23.656 Before: 23.656 After: 23.671 Before: 23.671 After: 24.421 Before: 24.421 After: 25.203 Before: 25.203 After: 25.218 Before: 25.218 After: 25.218[/list:u:byy5a5xi] As you can see, some calls are instantaneous, while others take a full second. For your information, when I use fmodex.dll v4.08.06 (and nothing else is changed) I get the following results: [list:byy5a5xi] Before: 26.062 After: 26.062 Before: 26.062 After: 26.078 Before: 26.078 After: 26.093 Before: 26.093 After: 26.093 Before: 26.093 After: 26.109 Before: 26.109 After: 26.109 Before: 26.109 After: 26.125 Before: 26.125 After: 26.125 Before: 26.125 After: 26.140 Before: 26.140 After: 26.140 Before: 26.140 After: 26.156 Before: 26.156 After: 26.156 Before: 26.156 After: 26.172 Before: 26.172 After: 26.172 Before: 26.172 After: 26.187 Before: 26.187 After: 26.187 Before: 26.187 After: 26.203 Before: 26.203 After: 26.203 Before: 26.203 After: 26.218 Before: 26.218 After: 26.218 Before: 26.218 After: 26.234 Before: 26.234 After: 26.234 Before: 26.234 After: 26.250 Before: 26.250 After: 26.250 Before: 26.250 After: 26.265[/list:u:byy5a5xi] regards, Hans de Rijck.
http://www.fmod.org/questions/question/forum-24682/
CC-MAIN-2018-17
en
refinedweb
Check with another constructor for htmlView: ContentType mimeType = new System.Net.Mime.ContentType("text/html"); var htmlView = AlternateView.CreateAlternateViewFromString(bodyMessage, mimeType); Wrap the list in an object: @ResponseBody Users where class Users { public List<User> items; } And yes, brackets [] are used for JSON arrays. OK, so I found the answer to my not so well worded question. When I ran easy_install, it never told me that lmxl had actually failed to install since I was missing a compiler. I have no idea why it worked from the Django development server and not through Apache, but I found and installed a binary distribution of lxml and it all started working the way it should. Apple recently disallowed developers from accessing the device's UDID (Unique Device Identifier), but some third party libraries haven't updated yet. In particular, some people have been having problems with Google Analytics. Another post on here recently gave a pretty good answer: App rejected, but I don't use UDID I don't think the records are being destroyed by clearing the store's underlying Collection. I would suggest using the store's removeAll method which will do a destroy on each record and hopefully free up some of the resources used by each. If your store is dealing with large datasets then this might add up and cause a slowdown. Since you are just entering gitrep, it's just saving it in your current directory (which is apparently your home directory, judging from your example above). Check and see if ~/gitrep and ~/gitrep.pub exist. You'll need to copy the contents of the gitrep.pub file to the destination when it asks you for your public key. You can test what is the bottle neck by taking different parts out of the equation. To take out the CPU, just read the files and don't do anything else. To take out the disk, keep reading the same file again and again, assuming it fits in your file cache. Compare this to the time for everything. In Ruby, the until block doesn't use do, so you should do something like this: def bubble_sort(arr) until arr == arr.sort (arr.count - 1).times do |i| (arr[i], arr[i + 1] = arr[i + 1], arr[i]) if (arr[i] > arr[i + 1]) end end arr end Edit: Expanded the code so it includes the algorithm from the original question. This code works for me on ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-darwin12.4.0]. There is no built-in language support for such large numbers. You have two options: if you can, use existing library, like GMP implement you own solution If you decide to take the second path, you might want to consider storing digits (not necesserily decimal) in an array, and perform arithmetic operations using well known school algorithms. Keep in mind it will be (probably considerably) less efficient than heavily optimized library code. Spring is trying to initialize the GraphDatabaseService during startup. C:UsersAnthonyDocuments omcat7apache-tomcat-7.0.40in argetconfig-test eostore is the default location configured. It makes sense to have the neo4j db in a directory outside of the tomcat folder structure. I suggest you find the spring config file where the GDB is being initialized and changes it to something like below <neo4j:config storeDirectory="C:home eo4j-db"/> Apple App Store isn't accent sensitive, which means: no, you don't need to put both of the keywords. I made a search using both of the keywords in mobileaction dashboard and you can see everything is the same for the keywords except search score, for your reference here is screenshot: Alright, after a lot of try's i searched the fora's of OpenCart better and came upon this thread: OpenCart Fora Thread The anser there is as follows: There's a "top" flag you set to make it show up as a top level menu So what i did is this: I've edited the new main category ( with uid 355 ) and flagged it as top, that didn't helped, but i left it on. Then i've edited all the direct childs of the main category and flagged them as top and foila, there they are. the problem was solved. So with my edit to the main core, and the flagging of the categorie's, the problem is now solved Google Custom Search! All you have to do is enter the site(s) you're trying to search.[][1] [1]: Unfortunately Magento only allows you to set "customer sharing" across the global and website scopes. The (maybe not so simple) solution would be to move your other store to a separate website instead of a separate store. Found in System > Configuration > Customers > Customer Configuration: It's been a while since I've used ExtJS, but I believe that you can use store.getRange() to get the behavior that you want (with no arguments, it should return the full contents of the store). According to the documentation, filtering is taken into account for this, so you should be able to apply whatever filters you need to get the desired set of records. As I understand your question, you want to remove the Index data from BigMemory Go on restart. Whether you can do this or not depends on your persistence strategy. If it is local restartable, BigMemory Go will try to either reuse the index data if the application was shutdown cleanly, or it will recover the indexes if it was shutdown abruptly. So, for a persistence strategy of local restartable, there is no way to avoid rebuilding the data. If your persistence strategy is "localTempswap", then you will not rebuild any data on restart and will lose the application's state. Please see here for more information: You can have a look at the source of the cd function by writing source cd There you can find that for convenience, other datatypes are converted to file. "Why is a string name of a dir treated as a word when no such word has been set?" Rebol recognizes words by syntax allowing symbolic programming. It does not matter at all whether a word has been set or not to be recognized as a word. "[If] I set a word to a dir name but in upper-case, the get-word moves me to that dir and shows it in that incorrect upper-case" Some operating systems (such as Windows) try to be case-insensitive, assuming that this is more convenient for humans. Rebol string handling is also case-insensitive by default for the same reason. "Did anyone ever suggest that chdir could have all convenience There is no difference. save is an alias for commit that was introduced with this PR (Make #commit an alias for #save) Hope it helps The TRANSITION doc says that you can do this to inject the store into components : App.inject('component', 'store', 'store:main'); You might be able to change 'component' to 'view' or to 'model', but I'm not sure about that. You won't be able to accomplish what you want using the store's filters because these methods all end up filtering on the whole dataset. So you'll need to apply your filter yourself! In order to do that, we need to replicate the code from Ext.data.Store#filter, except for the part that restores the whole dataset before filtering. That gives us: // -- Ensure that our current filter is not stalled ---------------- // Clear our filtering if the query string has changed in a way // that invalidate the current filtering if ( // previous filter is stalled ) { myStore.data = myStore.snapshot; delete myStore.snapshot; } // -- Create your new or updated filter ---------------------------- var filter = new Ext.util.Filter({ filterFn: function(record) { // your filtering The deliveranceToStore method isn't correct. Why are you calling the method recursively? The method can simply be: public int deliveranceToStore(int store) { unitsInStore = unitsInStore + store; return unitsInStore; } If there is no need to return the number of units in store with this call, you should have the return type as void (i.e., if updating the count is sufficient): public void deliveranceToStore(int store) { unitsInStore = unitsInStore + store; } For withdrawal, you need a similar strategy where unitsInStore is updated: public void withdrawal(int units) { if(unitsInStore - units >= 0) { unitsInStore = unitsInStore - units; } else { System.out.println("Unable to withdraw. Insufficient units in store."); } } You can also make the This might surprise you: v.push_back(A(20)); v.push_back(A(10)); std::sort(begin(v), end(v)); There are aspects of vector itself that require assignability, though I don't know, offhand, which (and I can't tell by compiling your code, since my compiler doesn't complain when I remove operator=()). According to Wikipedia (which references the relevant portion of the '03 standard), elements must be CopyConstructible and Assignable. EDIT: Coming back to this a day later, it seems forehead-slappingly obvious when std::vector requires Assignable — any time it has to move elements around. Add a call to v.insert() or v.erase(), for example, and the compile will fail. From this thread:ath ... You are only checking if !IsPostBack, you also need to check if the Context.User.IsAuthenticated Which means, Forms Authentification (or other), IIdentity, IPrincipal, and tralala Check this out ASP.NET MVC - Set custom IIdentity or IPrincipal $.get is asynchronous. That means, its callback function will execute sometime in the future, when the request successfully fetches a response. The code below the $.get call executes synchronously, it does not wait for asynchronous operations to finish. Code that depends on the data asynchronously retrieved through $.get must be executed/called from inside the $.get callback: $.get(url, function(data) { $("#household_store").data(data); //got response, now you can work with it var household = $("#household_store"); var head = household.data('head'); alert(houseId + ": " + head); }); If you prefer, it is also possible to attach callbacks by using the $.Deferred-compatible jqXHR methods: $.get(url).don Your commands are wrong ! Go to the directory where your main.cpp is, and try the following. g++.exe -Wall -c -g main.cpp -o objDebugmain.o g++.exe -static -static-libgcc -static-libstdc++ -o "binDebugHello World.exe" objDebugmain.o then you do not need dll's longer to copy.(for your hello world program) other Notes: the mingw installation instructions recommend to set c:minGW;c:MinGWin; to path environment variable. Normally with (try it with following 3 at once) -static -static-libgcc -static-libstdc++ linker options. Should work. But not for ibwinpthread-1.dll try also a clean before compile These's no '-static-something' command. Only standard libraries libgcc and libstdc++ can be set to static linking. For other libraries, you first switch to static linking with "- yeah, that is true. that's the case why, at some point, you just get rid of old migrations and use the schema.rb This is one of four different methods in the instructions to install virtualenv. What's stopping you from using one of the other ones? In fact, the site specifically says in a few different places that you should use pip if you already have pip 1.3 or later, use the source install if you don't have pip or have 1.2 or earlier. So, just follow the other instructions: $ curl -O $ tar xvfz virtualenv-X.X.tar.gz $ cd virtualenv-X.X $ [sudo] python setup.py install The [sudo] is a convention meaning "Type whatever command you need to run the rest of this as root, which is sudo on most setups on most Unix systems." On Windows, there is no such thing as sudo; runas or start with appropriate flags is the closest subs Because you're already doing what a call without parenthesis does. $user->tweak === $this->belongsToMany('User', 'friends', 'sender_id', 'receiver_id')->get(); $user->tweak() === $this->belongsToMany('User', 'friends', 'sender_id', 'receiver_id'); and if you say that $user->tweakTwo() === self::results()->get() === $this->belongsToMany('User', 'friends', 'sender_id', 'receiver_id')->get(); then $user->tweakTwo() === $user->tweak and $user->tweakTwo would be $this->belongsToMany('User', 'friends', 'sender_id', 'receiver_id')->get()->get(); The problem isn't calling Math.ceil - it's using the result of it. Math.ceil returns a double, which can't be implicitly converted to float. You could cast it though: perU30F = (float) Math.ceil((under30FY / totalWatchers) * 100); Or you could just use double everywhere instead of float :) (Math.round has an overload which accepts and returns float; Math.ceil doesn't.) Have your function in this way., void Ydisplay(int D1[]) { cin >> a; //Remove getting input from main() for(int i=0;i<a;i++) { cout<<' '<<D1[i]; } I might have missed an HQL syntax element SELECT user FROM CodeUser codeUser JOIN FETCH codeUser.user user JOIN FETCH codeUser.code code WHERE user.firstName = 'Dave' AND code.value = 'abode' assuming Code has a field value holding the value "abode". You might not need the FETCH. You can always replace the literal values with a placeholder like ? or a named placeholder like :name and set their values from the Query object. Here's a list of the programs you can install on windows: And you'll need the following dependencies: Requires numpy, dateutil, pytz, pyparsing, six Checkstyle (or at least some of its rules) needs the compiled classes in addition to the sources. You can prevent passing of the compiled classes (and thus compilation) with tasks.withType(Checkstyle) { classpath = files() }, but it may have negative consequences on the analysis. Maybe Action is what you are looking for: public xx(Action a) { a(); } xx(()=> Process.Start("notepad.exe", @"C:\OutputLog.txt")); That's a tricky one. This: child pid 13633 exit signal Bus error (7) means it's dying somewhere - most likely (although not guaranteed) in the PHP code. I would suggest: 1) Make sure that that is actually the error that is occurring when the Apache daemon dies. I.e. do whatever you do that stops Apache and look in the log and see that that's the correct error. 2) If it is, enable XDebug on your Apache server and find out what line it's dying on. (XDebug can take a little work to set up but it's a good tool to determine where in PHP your stuff dies ). If not, post what the last error(s) is/are. nb. Magento is not noted for being a simple and easy to debug code base, I stopped using it for that reason (not because it was dying, because it is fat and complex). Ju I've never used Ganymed but just by looking at the code I suspect that you send password too early. You probably need to handle what server responds to you. In other words server receives not what you think it receives. My best guess is that the hosted code is at a different location from where it should be for a default VS solution. The solution building is copying the code from you solutionproject folder into the different location. Try to check the location of the actual deployment. Depending upon whether you are using IIS, IIS Express there are different ways to know that. The following should work the same. <path id="ant.tasks"> <fileset dir="lib" includes="myspecialant.jar"/> </path> <taskdef name="TaskName" classname="mypackage.MyClass" classpathref="ant.tasks"/> I prefer to manage my classpaths at the top of my build separate to the logic that uses them. Make troubleshooting simpler. enums are not compile-time constants. So their value is not copied by the compile to every class that uses them. That's different from int values, which can be compile time constants. So if you have a class like public class Constants { public static final int FOO = 1; } and have another class public class Client { public static void main(String[] args) { System.out.println(Constants.FOO); } } the class will print 1. Now change the declaration of FOO to public static final int FOO = 27; And recompile Constants without recompiling Client. Execute the Client. The printed value will still be 1, because it has been copied by the compiler to the Client class when the Client class was compiled. There is no way to have this effect using enums. If you store a value a
http://www.w3hello.com/questions/Is-a-key-value-store-appropriate-for-a-usage-that-requires-ldquo-get-all-rdquo-
CC-MAIN-2018-17
en
refinedweb
Created on 2017-05-19 11:20 by Dormouse759, last changed 2017-09-09 06:41 by scoder. Currently the -m switch does not work with extension modules: $ python3 -m math /usr/bin/python3: No code object available for math In order to enable extension modules to behave like Python source modules, the -m switch should be supported. Please, see this proof of concept: What is the use case? It only make sense to run any stdlib module with -m, and without -i, if it has a command line interface (and an if __name__ clause). Otherwise, the module is created and then deleted when python exits. > py -m math > C-coded modules with such a command line interface have a mod.py file that imports _mod. The following can make sense. > py -m -i math Python x.y ... >>> math.sin(1.48973) But it is hardly needed as '-m -i math' is only one char less than 'import math' It's part of a larger effort to bring the capabilities of extension modules up to par with Python ones. For example, it's one less surprise you'd get when you Cythonize a module. And it's not only for stdlib modules – it's for any extension module. I'd be happy to answer questions here. But to get up to speed and avoid bpo comment lag, you can also see the current discussion on import-sig [0], or dig up some of the older conversations there leading up to PEP 489 (Feb-May 2015). And if you're at PyCon, you could have a high-bandwidth conversation with Nick Coghlan – he has the master plan in his head :) [0] As a high level overview of the general idea: we'd like it to be almost entirely transparent to the end user as to whether a particular module is implemented as normal Python source code, a precompiled bytecode/wordcode file, or a precompiled Cython extension module (or equivalent). At the moment, this is pretty close to being true for source code vs precompiled bytecode/wordcode when it comes to both imports and execution as a script. The main missing piece there is to implement source code maps for generating more informative tracebacks given only the precompiled form (perhaps by borrowing JavaScript's "source map" concept) For extension modules, the original multi-phase initialisation PEP got this pretty close to being true for the import case - things like reload() can now work much the same way they do for pure Python and pyc files if a module author (or module generation tool) cares to make it so. However, we don't yet support the use of extension modules as scripts, neither for direct execution, nor via the `-m` switch, so it's impossible for a tool like Cython to handle that transparently - if a module exposes functionality via -m, then migrating it directly to Cython will break than behaviour. So a use case might be that someone could compile all the stdlib .py modules with cython, as they are, without touching the code, and have the result be a drop-in replacement. I'd like that to be possible. Yep, that's the kind of thing we'd like to make possible. I just marked the associated PR as "[PEP required]", as while I'm in favour of merging this, I think we should go through the PEP process first: 1. We've been burned before by not properly advertising changes to Python's command line behaviour (while zip archive execution was added back in 2.6, a lot of folks didn't learn about it until the addition of the better advertised zipapp utility module in 3.5) 2. We should discuss the approach with the Cython developers and make sure that they're willing and able to support it when targeting 3.7+ before merging the implementation Such a PEP will also provide a common answer to Terry's question above, as the "This allows Cython to be used directly on __main__ modules" benefit isn't going to be readily apparent to folks that aren't already familiar with the details of how Cython works. Adding Stefan from the Cython project. Stefan, is this something you'd want to use? (It does require PEP 489 multi-phase initialization, so I assume it would need extra #ifdefs in Cythonized code for Python 3.5+ or 3.7+) Thanks for bringing me in. The PoC implementation looks nice. Whether I'd like to support this in Cython? Absolutely. Requires some work, though, since Cython still doesn't implement PEP 489. But it shouldn't be hard, if I remember the discussions from back then correctly. I could try to free some time in August to catch up with this. That would still fit into the pre-alpha phase of Py3.7. Unless, obviously, others would like to give it a try in the meantime. It's mostly about splitting up the current generated module init function into separate phases. Ok, there could be some minor obstacles along the way. ;) I created a ticket for it in our own tracker for now. This is now waiting to be added to the PEPs repo: This proposal is now PEP 547: FYI, I've finally managed to find the time for implementing PEP 489 style module initialisation in Cython. It was so easy that I'm sorry it took me so long to get started. Cython 0.26 is fresh out, so the feature should go into 0.27. Note that I ended up implementing the Py_mod_create function which is now copying attributes from the spec right after creation. While not strictly required, I guess, it turned out to be easiest, but it seems like this does now conflict with the current "-m" implementation. I asked on the github commit why that restriction exists. One thing I stumbled over: exec_in_module() is a Python level function. Would that make it possible to re-execute an already imported module? That could be dangerous, because C level module code often initialises resources that a simple re-execution of the module exec function would overwrite without cleaning up the old state. I did not (yet?) implement support for m_clear() etc., and that might actually turn out to be really risky when it comes to supporting arbitrary user code. OTOH, that case is easy to detect because the module is already completely initialised at that point. As far as I understand it, all that this PEP really changes from the POV of the extension module is that it calls the exec function with a different module name ("__main__"). Cython already provides that feature itself (by embedding CPython in a C main function), so this should be easy to support. Sorry for not responding for so long, I didn't work on Python through the summer because of some other matters. Re-execution of the module is not possible, because there is a check on the C level, If you call exec_in_module() on an already initialized module, it'll raise ImportError. Also, because of this check, there is the restriction for py_mod_create. "Modules" defining this slot might not be module objects at all, so they might not have the module state pointer (which is used to flag if the module was initialized). OTOH, if the created "module" is not a module object, then we could argue that the extension implementation is on its own with that case, and has to do its own re-execution safety checks. Do we have a use case for this? I'd rather avoid making it easy to do the wrong thing, unless it's needed. Marcel proposed to disallow main-execution if the extension *might* return anything but a real object (not only if it actually does), but that seems excessive to me. The actual problem is that we consider it unsafe if the module is executed more than once, because it might overwrite module state. But that's entirely up to the extension implementation and independent of what it uses as module type. Given how easy it is so create and/or depend on global state in C, I would assume that extensions have to be explicitly designed in order to be re-executable. Can't we just have another slot that explicitly marks the module as such? What do you think of this protocol: Before running the exec or main-exec function, the runner checks for a slot entry "Py_mod_allow_reexec" (can have value NULL). If not found, it sets the function pointers in the exec *and* main-exec slots to NULL to prevent any further (or concurrent) re-execution. If the slot function is not NULL on the next execution request, it can be called (again). That effectively prevents any re-execution by default and provides an opt-in way for the module to allow it. Again, what is the use case? That's a real question, I'm not saying it to dismiss your ideas or points of view. It would be very much easier to think about a concrete use case, rather than making a general system for the sake of how easy it is implementation-wise. (The implementation might be easier now, but it might change, and there's a cost to keeping the generality in mind when designing things on top of all this.) Something like the slot you mention can always be added later if it's needed. Is it needed now? Also, the PyModuleDef should never be modified (beyond the one-time initialization that sets ob_type -- that's a workaround for not being always able to declare the type statically). It should be possible to make additional, independent module instances from a PyModuleDef. I was kinda guessing that modifying the slot list wasn't a good idea. ;) My current use case is that I implement the "create" slot because it makes it very easy to intercept the spec and its configuration. It is not passed into "exec" as such, but I need it to initialise the module namespace with "__file__", "__path__", etc. There is also still the idea of defining our own module type in Cython in order to have a place where we can keep C level module globals, and also to support module properties. PEP 549 will not be available in older Python versions, even if it gets accepted. Having to choose between main-exec support and these two features seems wrong. Alright, that makes sense. Thanks for the feedback! Please give us some time for an updated proposal/implementation. I'm going on vacation, so expect about a week. I have made a patch both for cython and cpython implementing a way to use Py_mod_create in cython. Basically module def that specifies a new "Py_mod_cython" slot are excluded from the rule of no module creation, so these modules can be executed directly even though they specify Py_mod_create. Is this approach safe or does it make easy for things to go wrong? cpython - cython - I'm a bit torn on this. On the one hand, it's basically saying, "Cython is probably going to do it right anyway, so let's just assume it does". That's nice, and might be applicable to other cases as well. But that also feels like it could need some kind of versioning. On the other hand, it's totally not magic to implement something similar by hand, so naming the flag in a Cython specific way feels wrong from a design perspective. Other tools might start picking it up, and that would lead to major confusion. In a way, it's both very broad and too narrow. Basically, if we expect the flag to be used in a broader way, I'm happy to generally mark Cython modules with it. It's very explicit in *that* regard. I'm just not sure that the use case at hand is the right reason to introduce this kind of general marker. Speaking of versioning, though, what about introducing a generic slot field instead that notes the latest CPython API version known to work with the module? (Cast pointer value to int to get the value.) That way, CPython could introduce new extension module behaviour with new C-API versions, and tools that support them can update their version value in the slot to mark them as safely supported.
https://bugs.python.org/issue30403
CC-MAIN-2018-17
en
refinedweb
I. Probably the support for HD 4800 (beta OpenCL) on the latest drivers has fallen. The Java-jocl version does not work either for HD 4870 for latest dirvers. But there isn't a problem for the HD 5800 series. Similar lack of support can be seen for Intel's HD 3000 series (no problem for HD 4000 series) for the latest drivers. This is a workaround, because Safari under win OS doesn't allow to trigger native click event on input type file which is hidden from user: instead of display:none use this: #input_type_file{position:absolute;left:-9999px} If I understood that correctly, boost::asio::local::stream_protocol is POSIX specific. Windows itself is no POSIX conform environment, but there are POSIX enviroments for Windows out there, namely Cygwin. But you will not be able to distribute these applications without distributing the environment as well. In some cases, especially when Unix is your primary target platform, and you are offering a Windows version out of generosity, this may be acceptable. Otherwise you should think about ways of getting around the functionalities which are explicitly marked as non-portable.. Mongoose has a dependency on the npm package monogodb. If you look at the npm page for mongodb here,, you'll find the homepage form the package is That page is node-mongodb-native. So, there's nothing you need to do special to get it, as doing npm install mongoose is enough to install the native package. The error came from an unclean shutdown detected. Please visit for recovery instructions. a few steps will fix it (as it's written in the link above): 1) remove the file /data/db/mongod.lock 2) run mongod.exe --repair 3) start the mongod service net start MongoDB I guess Ubuntu is the best option. I tried it with Fedora but there were some issues. So, I moved back to Ubuntu. Though you might want to try RHEL too. But if you want the easiest route, Ubuntu is the way to go. When you go to a website, your browser sends a request to the web server including a lot of information. This information might look something like this: GET /questions/18070154/get-operating-system-info-with-php HTTP/1.1 Host: stackoverflow.com User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip,deflate,sdch Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 300 Connection: keep-alive Cookie: <cookie data removed> Pragma: no-cache Cache-Control: no-cache These information are all used by the web server to determine how to handle the requ hlt does not reboot; that's not what it's for. It pauses the processor until an interrupt arrives, and since you've disabled interrupts, it will just sit there doing nothing forever. As to why the emulator consumes 100% CPU, that's probably due to the way the emulator is implemented. On (some versions of) Linux, hlt is used to idle the processor until the next timeslice, so of course it doesn't make the processor busy-wait. :-) Debian, Arch, and Slackware all come with text-based installers, and although like all modern distros they all install the X Window System by default, they also all give sufficiently fine-grained control over the installation process that you can easily deselect the packages for X, the window manager, and any other GUI software and thus create a purely CLI-driven system. The actual rendering is separated from and tied into the platform-specific windowing API's.. Here's a solution if you have the Kernel ID using. Pass the Kernel ID to a variable in ruby. ker_id = imagesSet url = [] url_0 = "" url_1 = "ker_id" url_2 = "#/definition" new_url = url_0 + url_1 _ url_2 There are many ways to forge this url just made it easy to read. Then use nokogiri to parse the webpage and put the image name back into your script. I didn't see another notifiers in the documentation. Maybe the Webbrowser Control needs Desktop Interaction for rendering the content: My feeling say that using WPF controls and in particular particulary the Webbrowser-Control (=Wrapper around the IE ActiveX control) isn't the best idea.. There are other rendering engines that might be better suited for this task: Use chrome as browser in C#?. Looks like you would like to create a control interface module. Those are written in C/C++ within the VLC context and in turn need to be (re-) compiled for each platform you would like to target. Have a look at the audioscrobbler module to see how to interact with the current input stream and how to retrieve metadata such as file name, etc. Since those modules are in C, opening sockets and transmitting data is not a big deal. The biggest caveat is probably that you need a complex compilation environment if you would like to target the Windows platform. Have a look at the compilation HOWTO's on the wiki since this is probably what you would like to try prior to doing any coding. Thinking about it, you can probably achieve a similarly featured extensio The file needs to be accessable on the server. The file path is relative to the server, not your PC. Also, if you are trying to use a share or a mapped drive it will not work. You need to use the UNC path. UNC Name Examples \teelaadmin$ (to reach C:WINNT) \teelaadmin$system32 (to reach C:WINNTsystem32) \teela emp (to reach C: emp) That is a very low level Operating System functionality. Java has no chance of noticing this happening. In fact, since your applications would be running on Ring 3, there's no chance of detecting this regardless of the programming language. Your application would need to run on the more privileged rings, where device drivers and the kernel runs, in order to respond to sleep states. No, the names of members are not dependent on the language settings of the operating system. When you declare a class like this: public class Foo { public string Name { get; set; } } ... it's not like the compiler automatically translates that into Nom in French etc. On the other hand, the names of non-public members can change between different versions of the library - the whole point of them being non-public is that you're not meant to use them, which means the library author is entirely at liberty to change them later. That's the aspect of your code which is brittle - not the internationalization aspect. You can start from its manual. You can also check this other guide. 1) I made some fixes to your pasted code in an edit. I personally don't like reading / writing to the same file at the same time (especially under Windows), so here's a suggested alternate version. I also forgot about raw_input versus input so used How do I use raw_input in Python 3.1's suggestion try: input = raw_input except NameError: pass f1 = open('C:\WINDOWS\system32\drivers\etc\hosts', 'r') data = f1.read() f1.close() f2 = open('C:\WINDOWS\system32\drivers\etc\hosts', 'w') usrinput1 = str(input('Enter A name in quotes:')) for line in data.split(" "): if line.find("localhost") != -1: f2.write(line + " " + usrinput1 + " ") else: f2.write(line + " ") f2.close() 2) Note that being logged in as a user with administrator privileges isn't sufficient. You need to do runas In Windows, this feature is implemented using an Alternative Data Stream with a Zone Identifier. (see Hanselman's explanation here). You just need to detect a Zone Identifier of 3 or 4, which indicate the file is blocked. To interact with the data stream, you can use the Windows API CreateFile function and pass in :Zone.Identifier with the file name (as shown in this question) or, better yet, just use this library off of CodeProject to do it for you. The restart computer task sequence step will only continue the task sequence if you boot back into the boot media, says their documentation. However, after the Setup Windows and ConfigMgr step, the machine will reboot, and you can use this reboot to install packages and also run command line steps. For an example, see here Turns out you need to use the SuspensionManager Takes care of both issues. SQL Server database engine service account must have permissions to read/write in the new folder. To fix, I did the following: Added the Administrators Group to the file security permissions with full control for the Data file (S:) and the Log File (T:). Attached the database and it works fine. Chances are you missed a setting and both instances are trying to access the same data files. Please use this manual page as a checklist. I'm assuming you are on linux, and if you aren't I'm just posting this here for record (my search was fruitless, I'm on CentOS 6.5) From what I understand, there's no way to provide apache any direct access to the environment variables including variables from the environment of the user that started the apache process and global environment variables you've specified within /etc/profile.d startup scripts. Since I'm using bash, I have a variables.bashrc file that I source from my ~/.bashrc. This variables.bashrc declares my user environment variables. Within my apache startup script (/etc/init.d/httpd) I have added a line . /path/to/variables.bashrc that sources the same variables as my user has access to. This makes these environment variables available to apache. Apache may rec Yes, you do need to compile any library again when you switch from Windows to GNU/Linux. As for how to do that, you don't need automake to build GSL. You should read the file INSTALL that comes inside the tarball (the file gsl-1.16.tar.gz) very carefully. In a nutshell, you run the commands $ ./configure $ make inside the directory that you unpacked from the tarball. I am surprised this program even compiles: you are declaring arrays of size that cannot be determined during compile time, such as below. Could you tell which compiler you are using? int records = dataformat[1] + 2; double data[records];. Spaces are not valid characters in URLs. From the URL Standard: The URL code points are ASCII alphanumeric, "!", "$", "&", "'", "(", ")", "*", "+", ",", "-", ".", "/", ":", ";", "=", "?", "@", "_", "~", and code points in the ranges U+00A0 to U+D7FF, U+E000 to U+FDCF, U+FDF0 to U+FFEF, U+10000 to U+1FFFD, U+20000 to U+2FFFD, U+30000 to U+3FFFD, U+40000 to U+4FFFD, U+50000 to U+5FFFD, U+60000 to U+6FFFD, U+70000 to U+7FFFD, U+80000 to U+8FFFD, U+90000 to U+9FFFD, U+A0000 to U+AFFFD, U+B0000 to U+BFFFD, U+C0000 to U+CFFFD, U+D0000 to U+DFFFD, U+E1000 to U+EFFFD, U+F0000 to U+FFFFD, U+100000 to U+10FFFD. You'll need to handle %20 appropriately on the server side. Have you tried it without the async? Also, the example in the documentation uses EventArgs rather than RoutedEventArgs, but I'm not sure that should cause the exception you're seeing. The result field in your structure is a pointer to int. In your code, you first initialize it to 0, then attempt to assign a value through that pointer. But on most systems, that will fail, because the memory at address 0 hasn't been allocated to your program. The fix is to ensure that result points to valid memory before attempting to assign through that pointer. Exactly how that should happen depends on how that structure is going to be used in your code. One way would be to declare an int variable outside of your function (probably at file scope), then take its address and assign it to result: int my_result; // This should be declared OUTSIDE of a function! int __ns3__PersonRequest(soap *, _ns1__PersonRequest *ns1__PersonRequest, _ns1__PersonRequestResponse *ns1__PersonRequestRes Here is a working proof: File --> New Project --> New Databound Application (wp8) and here is the code: <Grid x: <ListBox x: <ListBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal" Margin="0, 20, 0, 0"> <Border BorderThickness="2" HorizontalAlignment="Left" VerticalAlignment="Center" BorderBrush="{StaticResource PhoneAccentBrush}" Margin="5, 0, 0, 0"> <Image Width="48" Height="4 CMD can't start from a UNC path without registry hack. Your problem seems a little strange. I would recommend to use just the UNC paths for copying. set deployment_path=d:deployment SETLOCAL ENABLEDELAYEDEXPANSION set project_path=\servershare copy %deployment_path%sppg.exe %project_path%sppg.exe /y this is no problem at all. try it. I also recommend to never use %cd% because it can't securly rely what is its content. and for the exe file: just give it's full qualified path. %project_path% cxc.exe ... import java.util.Map; public class EnvMap { public static void main (String[] args) { Map<String, String> env = System.getenv(); for (String envName : env.keySet()) { System.out.format("%s=%s%n", envName, env.get(envName)); } } } I guess you need the following properties: COMPUTERNAME OS regarding MAC Addrss and IP Address you have 2 options: use InetAddress ip; try { ip = InetAddress.getLocalHost(); System.out.println("Current IP address : " + ip.getHostAddress()); } catch (UnknownHostException e) { e.e.printStackTrace(); } or use ipconfig/ifconfig output but I'll leave the choice it to you Reason: The common reason for this error is that you are passing invalid value as parameter to your function. My assumption is that you are calling your method something like this ApplyCellStyleToEditingControl(getStyleFromSomeWhere); Now in the above example getStyleFromSomeWhere is invalid thus throwing the exception Solution: The best solution here is that when ever you get this exception (and you get email) you send the parameter to yourself as well. This way you can diagnose what are the values of parameter when the exception occurred and diagnose the root cause.
http://www.w3hello.com/questions/How-to-install-mongodb-in-windows-8-1-operating-system-
CC-MAIN-2018-17
en
refinedweb
tcp - TCP protocol Synopsis Description Address Formats Socket Options Sockets API Ioctls Error Handling Errors Versions Bugs Colophon #include <sys/socket.h> #include <netinet/in.h> #include <netinet/tcp.h> tcp_socket = socket(AF_INET, SOCK_STREAM, 0);. TCP is built on top of IP (see ip(7)). The address formats defined by ip(7) apply to TCP. TCP only supports point-to-point communication; broadcasting and multicasting are not supported.. The following ioctl(2) calls return information in value. The correct syntax is: int value; error = ioctl(tcp_socket, ioctl_type, &value); ioctl_type is one of the following: When a network error occurs, TCP tries to resend the packet. If it doesnt. Support for Explicit Congestion Notification, zero-copy sendfile(2), reordering support and some SACK extensions (DSACK) were introduced in 2.4. Support for forward acknowledgement (FACK), TIME_WAIT recycling, and per-connection keepalive socket options were introduced in 2.3. Not all errors are documented. IPv6 is not described.. This page is part of release 3.44 of the Linux man-pages project. A description of the project, and information about reporting bugs, can be found at.
http://manpages.sgvulcan.com/tcp.7.php
CC-MAIN-2018-17
en
refinedweb
JSON RPC handler and message router This is part 3 of a series about the Puppet Extension for Visual Studio Code. See the bottom of this post for links to all other posts. Extension on the VS Code Marketplace In part. JSON RPC Handler The byte stream from the network is formed into messages based on version 2 of the JSON RPC protocol, which is defined in this specification document. Microsoft have a shorter version of the specification in the language server protocol repository If you’ve seen HTTP requests before, this format should look familar. It is composed of a header and content part, separated by a carriage return ( \r) and linefeed ( \n) character +--------+------+---------+ | Header | \r\n | Content | +--------+------+---------+ The Header is composed of key-value pairs separated by a colon ( :), and each pair terminated by a carriage return and linefeed. There is a mandatory Content-Length header which describes how many bytes the Content part is. As we’re encoding bytes into strings it is important to know what text encoding is used. The header is always ASCII, while the content defaults to UTF8, however this can be set using the Content-Type header, for example to set UTF16; Content-Type:application/vscode-jsonrpc; charset=utf-16. So let’s say you wanted to send the text “Hello World”, the entire JSON message would look like: Content-Length:11\r\n\r\nHello World There is a double \r\n as the first one indicates the end of the header pair, and the second indicates the end of the Header part. Conversely, to read in a stream of bytes and convert to a JSON message; Keep reading bytes until a double \r\nis received Parse the header and determine how long the Content part is from the Content-Length header Keep reading bytes until the content length is read. The JSON RPC 2.0 specification also allows for batch operations, however VS Code language client does not, so the language server does not need to implement that part of the protocol. Implementation The implementation used in the Puppet Language Server was heavily inspired by the JSON parsing in the PowerShell Language Server. The receive_data. The parse_data method then takes the extracted message content and converts it from a JSON string into a Ruby object. It then performs validation that the RPC version is correct ( 2.0) and whether the message is a Request or Notification. Then the message is sent to the Message Router for processing. The JSON Handler also exposes a few helper methods reply_* These methods will send reply messages but hide all the mundane work to craft the JSON object. For example the reply_error method takes an error code and error text parameter and will send an error message back to the Language Client. send_show_message_notification The language server can send a JSON event to popup a dialog window on the client. This can be handy for the Server to notify the Client of fatal errors. Request object When a Request message is sent, the JSON RPC Handler creates a Request object, whereas a notification will only get the raw JSON object. This is because when sending a response to a Request, it generally requires the original Request ID. The methods on this class automatically craft the required JSON objects for responses. The protocol The protcol itself is well documented by Microsoft. It is well worth reading through all of the available messages before reading about the message router. Message Router. The language protocol describes three types of messages A Request. This message requires a response from the other party. For example, the client sends a request to autocomplete items for a cursor location, and the server sends the possible autocomplete items. A Notification. This is a message which does not require/have a response from the other party. For example, the server sends a notification message to the client, to display a warning message box that the version of Puppet is too old and functionality will be limited. A custom message. This is a message that is not described in the protocol but can still be sent over the same channel. For example, the Puppet Language Server uses a custom request for the Node Graph Preview. The client sends a puppet/compileNodeGraphrequest and responds with a CompileNodeGraphResponseobject. The message router is composed of a few modules Document Store. Crash Dump module %TMP%\puppet_language_server_crash.txt. This dump file contains all of the relevant version information, a copy of the document store, relevant backtrace, and the request that triggered the crash. Request Handler The request handler (the receive_request method) is basically a really big case statement where the request name determines the code path. The following messages are handled directly by the message router: initialize. shutdown The shutdown method is sent to indicate the client is about to disconnect and should start its shutdown process. The shutdown is actually handled in the TCP Server where the client disconnection takes place. puppet/getVersion Loading Puppet (xx%) message you see in the bottom right corner of VS Code. If, for example, the functions haven’t loaded then they will not be availale during hover or autocomplete requests. The following requests are handled by providers: puppet/getResource Similar to the puppet resource, this custom request will list all of the puppet resources for a title name. For example a request with typename = user will return all of the user resources on the system. Typically the client will only issue typename requests however the server does support adding a resource title in the request; typename = user, title = username. This is handled by the PuppetHelper. puppet/compileNodeGraph This custom request will compile the supplied manifest file and then generate a DOT file which shows all of the resources, and their dependencies in the catalog. This is handled by the PuppetParserHelper. textDocument/completion The language client will issue a completion request when it is trying to auto-complete text, either automatically or issued via user command (Typically ctrl-space). This request will then return with an array of short form items. The client will then issue completionItem/resolve. completionItem/resolve The resolution request is sent from the client when the user wishes to get more detailed information about a completion item, from a previous completion request. This is also handled by the CompletionProvider textDocument/hover When you hover the mouse cursor over text, the client sends hover requests to the language server. The server can then interpret where the cursor is and provide useful information. This is handled by the HoverProvider. Notification Handler The notification handler (the receive_notification method), much like the request hanlder, is basically a really big case statement where the notification name determines the code path. initialized The initialized notification is sent from the client to the server after the client received the result of the initialize request but before the client is sending any other request or notification to the server exit Triggers the underlying server connection to close. For example if the underlying transport was TCP, then the server would disconnect the client. Typically this should be sent after a shutdown request. textDocument/didOpen and textDocument/didChange. textDocument/didSave This is a null event for this server. textDocument/didClose The document that is closed is removed from the document store to help save some memory. Wrapping up… In this post I looked at how the JSON RPC messages are interpreted, and then actioned in the message router. In the next post we start looking at one the language providers in detail. Blog series links Part 1 - Introduction to the extension Part 2 - Introduction to the Language Server Part 3 - JSON RPC handler and message router Part 4 - Language Providers
https://glennsarti.github.io/blog/puppet-extension-deep-dive-part3/
CC-MAIN-2018-17
en
refinedweb
Hi, I am having some problems with the REQUEST namespace/object. I understand that if I submit form data then it can be retrieved using the REQUEST object. I have looked at Chapter 7 (Advanced DTML) for support but I'm still no closer to success. I have a DTML method, which passes an unknown number of arguments with unknown names to another method. For example, <form action="display"> Name <input type="text" name="name1"><br> Age <input type="text" name="age1"><br> Name <input type="text" name="name2"><br> Age <input type="text" name="age2"><br> <input type="submit"> </form> I would like the display method to simply show each of the variable's names and values i.e. iterate through each variable in the REQUEST object. Maybe I've overlooked something in the Zope documentation but could someone supply a useful snippet of code to get me started? Thanks very much, - )
https://www.mail-archive.com/zope@zope.org/msg13731.html
CC-MAIN-2016-50
en
refinedweb
Ticket #221 (new defect) add_implicit_resolver on a subclass may affect super_class resolvers Description Normally if I add a new implicit resolver to a subclass of a loader, super class shall not be affected. Yet this is the case if some letter of first argument matches an existing implicit resolver in super. >>> import yaml >>> import re >>> class DummyLoader(yaml.SafeLoader): ... pass ... >>> DummyLoader.add_implicit_resolver(u'!yeah',re.compile(ur'Yeah'), ... first='Y') # first is the same as bool implicit resolver of SafeLoader >>> yaml.safe_load('Yeah') # I use SafeLoader which shall ignore !yeah Traceback (most recent call last): ... yaml.constructor.ConstructorError: could not determine a constructor for the tag '!yeah' in "<string>", line 1, column 1: Yeah This comes from line 26-27 of resolver.py:BaseResolver.add_implicit_resolver: if not 'yaml_implicit_resolvers' in cls.__dict__: cls.yaml_implicit_resolvers = cls.yaml_implicit_resolvers.copy() cls.yaml_implicit_resolvers.copy() is not enough as it will keep existing lists instead of cloning them. Instead this shall be: from copy import copy then: if not 'yaml_implicit_resolvers' in cls.__dict__: cls.yaml_implicit_resolvers = {} for k, v in cls.yaml_implicit_resolvers.items(): cls.yaml_implicit_resolvers[k] = copy(v) Change History comment:2 Changed 2 years ago by RichardKew Jung their psychology needs no syringe. He named the afraid duration. comment:3 Changed 2 years ago by Richardmn Die gastarbeitern sind alle auf computer integriert. Diskussion wurde in der anfang der weiteres französischsprachige jüdische rechtsschulen schockiert. comment:4 Changed 2 years ago by Richardmn Dies wurde von lüftet immer verwendet.ürs-leben-hannover.html Annahme hemimetabol war also dennoch mit ruhe geschlossen, bevor er ergo im kenntnisse 2000 geboren wurde. comment:5 Changed 2 years ago by RichardKew Genuinely, bags claim thus one sturgeon of sensory synonym irides regularly as there are relatively eight to ten mission minuses in a term competing with methodists. Expeditionary aware demise was much provided by fellow assaults; these were upgraded in 1965 to e-1bs. comment:6 Changed 2 years ago by RichardKew For a hostile performance in milling, the fight emphasized available euphoria of only stability reactants. A occasional of the largest lotteries were under the enhanced time of their parental owners in the other beauty. comment:7 Changed 2 years ago by RichardKew Signal atrium requires police context and use in the heart of excitatory year. Initial upon the polysubstance of the use, fiscal problems may suffer from both 2c-p or social mental economy exhaustion. comment:8 Changed 2 years ago by RichardKew Oil can highly reduce date determination. Chapels are fully the most originally affected by absolute women, probably they become more concerned about overall charges. comment:9 Changed 2 years ago by FrancisOi In some models, the nicotine's factor for cooling itself is impaired, heavily second that they may sweat four or five arms more than is due, or major. B is a particulate bleeding of the areas that encode drugs, and courage impulses. comment:10 Changed 2 years ago by FrancisRib Second sport is the security, which exposes volume to an much humour of future area ocean. Two soldiers later gladstone founded a reason dedicated to translating its solid years into blennies. One of mendelssohn's increases since 1822 was that he had often had physiological system to develop his adolescent surgery to his disappearance, despite having given successive dress angels. [ breast enhancement non surgical - During further rewards in the metabolic storytellers, arguments examined 14 shapes and detected a also lower large insertion among expensive diseases than among social variants, leading to water of the gender of a complementary period addition.
http://pyyaml.org/ticket/221
CC-MAIN-2016-50
en
refinedweb
I'm writing a class in Groovy, and I want to generate Groovydoc for it (from the command line). In my class, I've written documentation for the methods like this: /** * Returns blah blah blah */ def getFoo(){ ... } groovydoc -classpath C:\groovyStuff\ -d . *.groovy If the root of your source tree is c:\groovyStuff\ you can use something like this... groovydoc -sourcepath c:\groovyStuff -d . com.somepackage The -d . is a little peculiar because that is going to put the generated files in the current directory. That is what you used in your example but maybe you want something like -d output or something similar. Does that help?
https://codedump.io/share/L0q9iRjCQSwZ/1/groovydoc-produces-blank-documents
CC-MAIN-2016-50
en
refinedweb
Difference between revisions of "User talk:Kynikos" Revision as of 20:47, 12 November 2013) Edit Xmodmap Thanks for the edit, I have to switch all the time between languages and as a consequence it's become dificil for me to see such mixes - Eheh no worries, keep up the good work! -- Kynikos (talk) 00:59, 6 November 2013 (UTC) - ...and by the way, I've just moved your installation guide to User:Ylecuyer/Installation guide, as no personal articles should reside out of the User namespace. -- Kynikos (talk) 01:10, 6 November 2013 (UTC)
https://wiki.archlinux.org/index.php?title=User_talk:Kynikos&curid=11164&diff=282518&oldid=281831
CC-MAIN-2016-50
en
refinedweb
For the moment, let’s assume that you would like to call into a Clojure library from Java, and that library does not define any types or classes.[304] To use that codebase, you’ll need to tap into the Clojure “native” functions and constant values it defines in namespaces. Thankfully, doing so from Java is straightforward: Load the Clojure code you want to use. This means reusing the standard require, use, or load functions provided in Clojure’s clojure.core namespace. Obtain references to the vars corresponding with each function or value defined in the namespaces you care about. Call the functions and use the values however your application requires. All we need to demonstrate Java→Clojure interop are two vars, one providing a function, the other some value. The value will come from a simple Clojure namespace: Example 9-20. Simple Clojure namespace (ns com.clojurebook.histogram) (def keywords (map keyword '(a c a d b c a d c d k d a b b b c d e e e f a a a a))) The function we’ll use is frequencies from the clojure.core namespace; it accepts any seqable value, and returns a map of the seq’s elements and counts of their frequency of occurrence in the seq.[305] Here is a Java class that uses frequencies with the keywords value as well as many others. Example 9-21. Using Clojure code in Example 9-20 from Java package com.clojurebook; import java.util.ArrayList; import java.util.Map; import clojure.lang.IFn; import clojure.lang.Keyword; import clojure.lang.RT; import ...
https://www.safaribooksonline.com/library/view/clojure-programming/9781449310387/ch09s08.html
CC-MAIN-2016-50
en
refinedweb
So here I am porting my ancient newspipe front-end to Snakelets and Python, and I’ve just trimmed down over 20 lines of PHP down to essentially one line of BeautifulSoup retrieval: def parseWapProfile(self, url): “”“ Invoked for unknown (uncached) UAs “”“ result = fetch.fetchURL(url) soup = BeautifulStoneSoup(result[‘data’], convertEntities=BeautifulStoneSoup.HTML_ENTITIES) try: width, height = soup(‘prf:screensize’) Of course there’s a lot more error handling to do (and useful data to glean off the XML), but being able to cut through all the usual parsing crap is immensely gratifying.
http://taoofmac.com/space/blog/2007/08/20/2347
CC-MAIN-2016-50
en
refinedweb
I am developing a WPF 4.0 - MVVM application based on PRISM framework (Unity Container). I was wondering what is the best way to implement dialogs in the mvvm pattern. I am planning to use quite a few in my application so I want something reusable. Since you are using Prism/Unity implement the mediator pattern for your View Models. ViewModels now use the IDialogService to show the required dialog. public interface IDialogService { void RegisterDialog (string dialogID, Type type); bool? ShowDialog (string dialogID); } public class DialogService : IDialogService { private IUnityContainer m_unityContainer; private DialogServiceRegistry m_dialogServiceRegistry; public DialogService(IUnityContainer unityContainer) { m_unityContainer = unityContainer; m_dialogServiceRegistry = new DialogServiceRegistry(); } public void RegisterDialog(string dialogID, Type type) { m_dialogServiceRegistry.RegisterDialog(dialogID, type); } public bool? ShowDialog(string dialogID) { Type type = m_dialogServiceRegistry[dialogID]; Window window = m_unityContainer.Resolve(type) as Window; bool? dialogResult = window.ShowDialog(); return dialogResult; } } If you use ViewModel events & handlers in the View, use the WeakEventHandler pattern to eliminate a potential resource leak. Also, it is possible for multiple Views to be attached to the same ViewModel. I've worked on projects with one ViewModel -> one View. But also one ViewModel -> multiple Views. Just something to consider when making your design decisions.
https://codedump.io/share/X7gRFSabggT7/1/how-to-implement-dialog-architecture-in-mvvm
CC-MAIN-2016-50
en
refinedweb
0 Hi I am very new to java as its part of my course and I am stuck I have written part of this basic code below import java.util.Scanner; import java.io.File; import java.io.IOException; import java.awt.image.BufferedImage; import javax.imageio.imageIO; import.java.awt.Color; public class FinalExam { public static void main(String [] args) throws IOException { Scanner keyboardInput = new Scanner(System.in); System.out.println("Input the address of the image (e.g. c:\\myPicture.jpg)"); String imageLocation = keyboardInput.nextLine(); File imageFile = new File(imageLocation); BufferedImage storedImage = ImagIO.read(imageFile); } } does anyone know I would change this code so that you would be allowed to supply the name of an image file a a command line argument when issuing the command to run the program? Edited 6 Years Ago by __avd: Added [code] tags. Encase your code in: [code] and [/code]
https://www.daniweb.com/programming/software-development/threads/244823/command-line-arguments-help
CC-MAIN-2016-50
en
refinedweb
Flash Player 9 and later, Adobe AIR 1.0 and later Flash Player and AIR allow you to create a full-screen application for your video playback, and support scaling video to full screen. For AIR content running in full-screen mode on the desktop, the system screen saver and power-saving options are disabled during play until either the video input stops or the user exits full-screen mode. For full details on using full-screen mode, see Working with full-screen mode. Before you can implement full-screen mode for Flash Player in a browser, enable it through the Publish template for your application. Templates that allow full screen include <object> and <embed> tags that contain an allowFullScreen parameter. The following example shows the allowFullScreen parameter in an <embed> tag. <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="fullScreen" width="100%" height="100%" codebase=""> ... <param name="allowFullScreen" value="true" /> <embed src="fullScreen.swf" allowFullScreen="true" quality="high" bgcolor="#869ca7" width="100%" height="100%" name="fullScreen" align="middle" play="true" loop="false" quality="high" allowScriptAccess="sameDomain" type="application/x-shockwave-flash" pluginspage=""> </embed> ... </object> In Flash, select File -> Publish Settings and in the Publish Settings dialog box, on the HTML tab, select the Flash Only - Allow Full Screen template. In Flex, ensure that the HTML template includes <object> and <embed> tags that support full screen. For Flash Player content running in a browser, you initiate full-screen mode for video in response to either a mouse click or a keypress. For example, you can initiate full-screen mode when the user clicks a button labeled Full Screen or selects a Full Screen command from a context menu. To respond to the user, add an event listener to the object on which the action occurs. The following code adds an event listener to a button that the user clicks to enter full-screen mode: var fullScreenButton:Button = new Button(); fullScreenButton.label = "Full Screen"; addChild(fullScreenButton); fullScreenButton.addEventListener(MouseEvent.CLICK, fullScreenButtonHandler); function fullScreenButtonHandler(event:MouseEvent) { stage.displayState = StageDisplayState.FULL_SCREEN; } The code initiates full-screen mode by setting the Stage.displayState property to StageDisplayState.FULL_SCREEN. This code scales the entire stage to full screen with the video scaling in proportion to the space it occupies on the stage. The fullScreenSourceRect property allows you to specify a particular area of the stage to scale to full screen. First, define the rectangle that you want to scale to full screen. Then assign it to the Stage.fullScreenSourceRect property. This version of the fullScreenButtonHandler() function adds two additional lines of code that scale just the video to full screen. private function fullScreenButtonHandler(event:MouseEvent) { var screenRectangle:Rectangle = new Rectangle(video.x, video.y, video.width, video.height); stage.fullScreenSourceRect = screenRectangle; stage.displayState = StageDisplayState.FULL_SCREEN; } Though this example invokes an event handler in response to a mouse click, the technique of going to full-screen mode is the same for both Flash Player and AIR. Define the rectangle that you want to scale and then set the Stage.displayState property. For more information, see the ActionScript 3.0 Reference for the Adobe Flash Platform. The complete example, which follows, adds code that creates the connection and the NetStream object for the video and begins to play it. package { import flash.net.NetConnection; import flash.net.NetStream; import flash.media.Video; import flash.display.StageDisplayState; import fl.controls.Button; import flash.display.Sprite; import flash.events.MouseEvent; import flash.events.FullScreenEvent; import flash.geom.Rectangle; public class FullScreenVideoExample extends Sprite { var fullScreenButton:Button = new Button(); var video:Video = new Video(); public function FullScreenVideoExample() { var videoConnection:NetConnection = new NetConnection(); videoConnection.connect(null); var videoStream:NetStream = new NetStream(videoConnection); videoStream.client = this; addChild(video); video.attachNetStream(videoStream); videoStream.play(""); fullScreenButton.x = 100; fullScreenButton.y = 270; fullScreenButton.label = "Full Screen"; addChild(fullScreenButton); fullScreenButton.addEventListener(MouseEvent.CLICK, fullScreenButtonHandler); } private function fullScreenButtonHandler(event:MouseEvent) { var screenRectangle:Rectangle = new Rectangle(video.x, video.y, video.width, video.height); stage.fullScreenSourceRect = screenRectangle; stage.displayState = StageDisplayState.FULL_SCREEN; } public function onMetaData(infoObject:Object):void { // stub for callback function } } } The onMetaData() function is a callback function for handling video metadata, if any exists. A callback function is a function that the runtime calls in response to some type of occurrence or event. In this example, the onMetaData()function is a stub that satisfies the requirement to provide the function. For more information, see Writing callback methods for metadata and cue points A user can leave full-screen mode by entering one of the keyboard shortcuts, such as the Escape key. You can end full-screen mode in ActionScript by setting the Stage.displayState property to StageDisplayState.NORMAL. The code in the following example ends full-screen mode when the NetStream.Play.Stop netStatus event occurs. videoStream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler); private function netStatusHandler(event:NetStatusEvent) { if(event.info.code == "NetStream.Play.Stop") stage.displayState = StageDisplayState.NORMAL; } When you rescale a rectangular area of the stage to full-screen mode, Flash Player or AIR uses hardware acceleration, if it's available and enabled. The runtime uses the video adapter on the computer to speed up scaling of the video, or a portion of the stage, to full-screen size. Under these circumstances, Flash Player applications can often profit by switching to the StageVideo class from the Video class (or Camera class; Flash Player 11.4/AIR 3.4 and higher). For more information on hardware acceleration in full-screen mode, see Working with full-screen mode. For more information on StageVideo, see Using the StageVideo class for hardware accelerated presentation. Twitter™ and Facebook posts are not covered under the terms of Creative Commons.
http://help.adobe.com/en_US/as3/dev/WS44B1892B-1668-4a80-8431-6BA0F1947766.html
CC-MAIN-2016-50
en
refinedweb
Platform Updates: Operation Developer Love by Ian Wilkes - January 4, 2012 at 6:30pm This past week, we provided an update on our Facebook Platform SDKs, a retrospective of Platform changes in 2011 and launched the following changes: Stories In Timeline App Tab Stories published from an app using Feed dialog or Graph API will now show in the app's tab on the user's timeline. This is consistent with Open Graph actions published from an app showing in the app's tab. Improved Insights for Web Sites. Breaking Changes effective this week - Requests 2.0 Efficient: The Request 2.0 Efficient migration will be enabled for all apps over the next few days. Please make sure to update your apps now to respect the updated request ID format to avoid any disruption of service. On January 15th this setting will be set to enabled for all apps. For more information please see the Requests docs. - FB.Canvas.getPageInfo: The getPageInfo method now requires a callback function and no longer returns a value synchronously. For more information on this change please see this blog post. Upcoming Breaking Changes on February 1, 2012 - Removing canvas_name field from application object: We will be deprecating the canvas_name field in favor of namespace field on the application object. See this blog post for more information. - Removing App Profile Pages: We will be deleting all App Profile Pages and redirecting all traffic directly to the App. See this blog post for more information. Bug activity from 12/27 to 1/3 - 131 bugs were reported - 28 bugs were reproducible and accepted (after duplicates removed) - 19 bugs were by design - 12 bugs were fixed - 56 bugs were duplicate, invalid, or need more information Reported bugs fixed between 12/27 and 1/3 - Show Stream for Like Box shows only checkins - max-width of photo incorrectly stated in Graph API doc - Insights not updating - Oauth Validation error throws Invalid signed request with Facebook C# SDK - Broken cross-reference links in Advanced Topics -> FQL -> profile - migrating old comments - date_format not applied on all feed story properties - Feed Dialog Produces Captcha Screens and Always Fails - Friend's name for test account is missing - Call to me/friends with a test user no longer returns name,first_name and middle_name fields - Cannot set custom stream privacy from FB.ui feed dialog - Requests 2.0 lose the "data" parameter on mobile browsers Activity on facebook.stackoverflow.com this week - 133 questions asked - 47 answered, 35% answered rate - 74 replied, 56% reply rate
https://developers.facebook.com/blog/post/625/
CC-MAIN-2014-15
en
refinedweb
FrameworkElement.Tag Property April 12, 2014 Gets or sets an arbitrary object value that can be used to store custom information about this object. Assembly: System.Windows (in System.Windows.dll) XMLNS for XAML: Not mapped to an xmlns. XAML Values Property ValueType: System.Object The intended value. This property has no default value. XAML namespaces and therefore may require mapping an external namespace in order to be introduced as XAML object elements.
http://msdn.microsoft.com/fr-fr/library/windowsphone/develop/system.windows.frameworkelement.tag(v=vs.105).aspx
CC-MAIN-2014-15
en
refinedweb
Adam Winer wrote: > I don't think there's that much reason not to return > a List. All I'm saying is that if you had an API > that was Iterator, and your desire was to support > the fun SE 5 "for" construct, then Iterable is the > simplest change. The question then is why the > original API was ever Iterator, and if it should > have been List, or Collection, etc. In looking at the code, it doesn't appear to have been much rhyme or reason to when we returned Iterators or even arrays. For the methods that currently return Iterators, my point is that the big step is agreeing to return Iterables instead (switching from Iterators to a factory for Iterators). Once you decide to return Iterables for immutable objects, then you might as well return the correct Collection classes--Collection, List, Set as returning these classes places no additional api burden on the implementor as I believe that even in the worst case where the implementor only had an Iterable and not the actual Collection class in question, a simple adapter could be written to convert an Iterable into the appropriate unmodifiable Collection class. -- Blake Sullivan > > > I'm not thrilled with exposing List if you think that > you might someday want it to be a Set - Collection > is safer in that regard. > > -- Adam > > > On 4/9/07, Blake Sullivan <blake.sullivan@oracle.com> wrote: >> Adam, >> >> Actually the reason for the switch to List versus Iterable would be for >> general convenience of developers consuming the api (with efficiency a >> much smaller issue). >> >> Which methods on java.util.List do you think are providing too broad of >> a contract? Do you believe that returning a List is limiting the >> implementations choices severely enough that it outweighs the >> convenience of using a Collection class? >> >> -- Blake Sullivan >> >> >> >> Jeanne Waldman wrote: >> > three out of six >> > >> > -------- Original Message -------- >> > Subject: Re: return an Iterator vs a List >> > Date: Wed, 4 Apr 2007 15:42:17 -0700 >> > From: Adam Winer <awiner@gmail.com> >> > Reply-To: adffaces-dev@incubator.apache.org >> > To: adffaces-dev@incubator.apache.org >> > References: >> > <71235db40703260457k2902d980n6a7c5b5b98215236@mail.gmail.com> >> > <71235db40703260753q2921ea4m7eff51554fbff393@mail.gmail.com> >> > <46098A7A.7000306@oracle.com> >> > <254acf980703271642s156d9b89lb270e76bf4a2342b@mail.gmail.com> >> > <f8eab54d0703271646l3e7b67dax8d66a631e4fa0001@mail.gmail.com> >> > <4609CAC0.9010505@oracle.com> >> > <f8eab54d0703280924u4890b902gb8423f084ed2cb9b@mail.gmail.com> >> > <460B259B.2070602@oracle.com> >> > >> > >> > >> > If the only reason is to enable the fun new "for" syntax, >> > then we should change the type from Iterator to Iterable, >> > instead of List. List is a much larger contract. >> > >> > -- Adam >> > >> > >> > On 3/28/07, Jeanne Waldman <jeanne.waldman@oracle.com> wrote: >> >> Hi there, >> >> I'm in the Skinning StyleNode code and I see that the 'get' methods >> >> return Iterators >> >> from the good ol' days. >> >> It seems to me that it is better if they just return Lists so the >> code >> >> that iterates over >> >> the values is cleaner using 5.0's for(String foo : yyy) construct. >> >> Does anyone see why I wouldn't want these to return List instead of >> >> Iterator? >> >> >> >> Here's a code snippet. Thanks, Jeanne >> >> -- >> >> >> >> public Iterator<IncludePropertyNode> getIncludedProperties() >> >> { >> >> if(_includedProperties == null) >> >> { >> >> List<IncludePropertyNode> list = Collections.emptyList(); >> >> return list.iterator(); >> >> } >> >> else >> >> return (Arrays.asList(_includedProperties)).iterator(); >> >> } >> >> >> >> /** >> >> * Gets the properties specified by this node's parent that >> should be >> >> * ignored. This method will return an empty iterator if >> >> * {@link #isInhibitingAll()} returns <code>true</code> >> >> * >> >> * @return an iterator over the properties that should be >> ignored, an >> >> * empty iterator if all properties should be. >> >> */ >> >> public Iterator<String> getInhibitedProperties() >> >> { >> >> if(_inhibitedProperties == null) >> >> { >> >> List<String> list = Collections.emptyList(); >> >> return list.iterator(); >> >> } >> >> else >> >> { >> >> return _inhibitedProperties.iterator(); >> >> } >> >> } >> >> >> > >> >>
http://mail-archives.apache.org/mod_mbox/incubator-adffaces-dev/200704.mbox/%3C461D5285.6060404@oracle.com%3E
CC-MAIN-2014-15
en
refinedweb
TestEvents Assert and Check xUnit++ has a robust suite of test assert methods. While most C++ testing frameworks use preprocessor macros to implement only a few checks, xUnit++ provides two class instances with many built-in methods. And since these tests are not implemented with macros, you get much nicer feedback while editing (assuming your editor can provide such detail) and compiling. There are three ways to assert test events: Assert, Check, and Warn. With one exception, they offer the same check methods. Assert will halt the test immediately if any check fails, Check will log the failure but continue, and Warn will not cause the test to fail by itself, but the "error" will be logged. Warn.Fail(); // warning message logged, test is not a failure (yet) Check.Fail(); // failure is logged, test is marked as failing, test execution continues Assert.Fail(); // stops the test here Check.Fail(); // test never executes this line The Methods As stated before, the test objects share the same check methods, with one exception: Assert offers Throws while Check and Warn do not. Containsasserts that a container contains some value. Overloads exist for raw strings and std::string. ContainsPredis an alternative form of Containswhich takes a predicate instead of a value. DoesNotContainasserts that a container does not contain some value. Overloads exist for raw strings and std::string. DoesNotContainPredis an alternative form of DoesNotContainwhich takes a predicate instead of a value. DoesNotThrowasserts that the given code does not throw any exceptions. Anything that resolves to the equivalent of void (*)()will work. Equaltests object values for equality. There are overloads for raw strings, std::string, floating point types (with precision, instead of tolerance), and iterator ranges. Emptywill assert that the container object is empty. TContainer::empty()will be used if it exists, otherwise the container will be converted to a range using std::beginand std::end. Failwill automatically fail the test. Falsewill fail the test if the supplied parameter resolves to true. InRangechecks that the given value fits within the range [ min, max). NotEmptyis the opposite of Empty. NotEqualis the opposite of Equal. NotInRangechecks that the given value does not fit within the range [ min, max). NotNullchecks that the value is not equal to nullptr. NotSameverifies that the supplied objects are not the same object instance. Nullchecks that the value is equal to nullptr. Samechecks that the supplied objects are the same object instance. Throwsis an Assert-only member that checks that the supplied code throws a specific exception. If it succeeds, it will return the exception to your test. auto ex = Assert.Throws<std::exception>([]() { throw std::runtime_error(""); }); Printing Values Some methods may try to print the values of the objects using to_string with argument-dependent lookup (Koenig lookup). To take advantage of this, implement a to_string function within your object's namespace. namespace NS { class A {}; std::string to_string(const A &a) { return "A"; } } If a corresponding to_string can't be found, xUnit++ falls back to printing the object's type with typeid(obj).name(). Custom Messages If you want to add a custom message to failing tests, use the overloaded operator <<. Assert.Fail() << "This is an example message " << some_value; File and Line Info Normally, when a test fails the test runner will report the file and line number for the test itself. This is typically sufficient for most tests, as tests should really only assert one thing at a time. However, if you want to be specific about which check failed, each check method accepts an optional xUnitpp::LineInfo object. The easiest way to do this is to pass the LI macro as the final parameter to the test. Assert.Equal(0, 1, LI) << "0 is never equal to 1!"; Extra Logging If you need more logging output within the tests, use the Log object. Three levels of logging are implemented: Debug, Information, and Warning: Log.Debug << "This is a debug-level message: " << some_value; Log.Info << "This is an info-level message: " << some_value; Log.Warn << "This is a warning-level message, and will automatically mark the running test has having a warning status. " << some_value; The log levels will normally print the file and line of the test (like the check methods), but they also accept the LI macro: Log.Info(LI) << "This message will include the exact line number."; Updated
https://bitbucket.org/moswald/xunit/wiki/TestEvents.wiki
CC-MAIN-2014-15
en
refinedweb
(Redirected from How to switch application in foreground) Archived:How to switch application in foregroundCompatibility Platform(s): S60 2nd Edition, S60 3rd EditionArticle Keywords: appswitch Created: cyke64 (19 Mar 2007) Last edited: hamishwillee (31 May 2013) Overview You can use the very useful appswitch Python extension module to switch an application in background and bring it to foreground in focus. Preconditions You need to download required versions of appswitch module from the given two links: Code # import module import appswitch # push application to BACKGROUND print appswitch.switch_to_bg(u"Menu") # bring application to FOREGROUND print appswitch.switch_to_fg(u"Menu") If there has been no activity for a while and the phone is idle appswitch.switch_to_fg seems to be ignored. By resetting inactivity this problem seems to be solved. --s021677 13:45, 26 November 2008 (EET) 08 Sep 2009
http://developer.nokia.com/community/wiki/How_to_switch_application_in_foreground
CC-MAIN-2014-15
en
refinedweb
Function object wrapper for as(). More... #include <Teuchos_as.hpp> Function object wrapper for as(). Sometimes it is useful to pass around the as() type conversion function as a first-class object, for example as a function argument of generic algorithms such as std::transform(). In this case, you may use this class, which invokes as() in its operator() method. The operator() method is templated on the input type TypeFrom. Definition at line 382 of file Teuchos_as.hpp.
http://trilinos.sandia.gov/packages/docs/r11.2/packages/teuchos/doc/html/classTeuchos_1_1asFunc.html
CC-MAIN-2014-15
en
refinedweb
This article is in need of a technical review. « Gecko Plugin API Reference « Plug-in Side Plug-in API Summary Asks the browser to create a stream for the specified URL. Syntax #include <npapi.h> NPError NPN_GetURL(NPP instance, const char* url, const char* target); Parameters The function has the following parameters: instance - Pointer to the current plug-in instance. url - Pointer to the URL of the request. Can be of any type, such as HTTP, FTP, news, or mailto. target - Name of the target window or frame, or one of the following special target names. Values: _blankor _new: Load the link in a new blank unnamed window. Safest target, even though, when used with a mailto or news URL, this creates an extra blank the browser instance. _selfor _current: Load the link into the same window the plug-in instance occupies. Not recommended; if targetrefers to the window or frame containing the instance, the instance is destroyed and the plug-in may be unloaded. Use with NPN_GetURL()only if you want to terminate the plug-in. _parent: Load the link into the immediate <frameset>parent of the plug-in instance's document. If the plug-in instance's document has no parent, the default is _self. _top: Load the link into the plug-in instance window. The default is _self, if the plug-in instance's document is already at the top. Use for breaking out of a deep frame nesting. If the target is null, the browser creates a new stream and delivers the data to the current instance regardless of the MIME type of the URL. In general, if a URL works in the location box of the browser, it works here, except for the _self target. Returns - If successful, the function returns NPERR_NO_ERROR. - If unsuccessful, the plug-in is not loaded and the function returns an error code. For possible values, see Error codes. Description NPN_GetURL() is used to load a URL into the current window or another target or stream. Plug-ins can use this capability to provide hyperlinks to other documents or to retrieve data from anywhere on the network. This is especially useful for enabling an existing application to operate on the web. For HTTP URLs, the browser resolves this method as the HTTP server method GET, which requests URL objects. Use NPN_GetURLNotify() instead of NPN_GetURL() in these cases: - To request a stream and receive notification of the result. - If the buffer contains header information (even a blank line). Make sure that the target matches the URL type sent to it. For example, a null target does not make sense for some URL types (such as mailto). The following recommendations about target choice apply to other methods that handle URLs as well. If the target parameter refers to the window or frame containing the current plug-in instance, the instance is destroyed and the plug-in may be unloaded. If target is null, the application creates a new stream and delivers the data to the plug-in instance, through calls to NPP_NewStream(), NPP_WriteReady() and NPP_Write(), and NPP_DestroyStream(). This means that if you want the plug-in to handle a new stream, no matter what the MIME type is, use null. If the application cannot locate the URL and retrieve the data, it does not create a stream for the instance. When the plug-in instance is part of a regular browser window, and it uses a _blank target with a mailto or news URL, another blank window is opened along with the mail or news window. When the plug-in uses a _self target, no other instance is created; the plug-in usually continues to operate successfully in its own window. The safest target is _blank, even though this creates an extra blank the browser instance. The plug-in developer cannot influence the way that the browser handles NPN_GetURL(). It is typically asynchronous but this is not guaranteed. The plug-in could call NPN_GetURL() and receive data from the URL right away, but more often the data arrives later. The rest of the the browser interface keeps running until the data is available.
https://developer.mozilla.org/en-US/docs/NPN_GetURL
CC-MAIN-2014-15
en
refinedweb
On 7/27/07, Tiger12506 <keridee at jayco.net> wrote: > > Hmmm... interesting tie to another post... > > >>> x = timeit.Timer('random.random()','import random') > >>> x.timeit(3000000) > 1.0161026052194018 > >>> y = timeit.Timer('random()','from random import random') > >>> y.timeit(4600000) > 1.0004307810070827 > > Dictionary lookups do take HUGE amounts of time. Interesting. > > Anyway... I've got it down to > Your numbers with a little more precision gave me > 3.4e5987 yrs. > > and mine > > 3.0e5987 yrs. > > That's a hell of a lot of years! Remember that everyone! If you want your > code to run forever and to eternity, copy variables to the local namespace > first; you get a lot more accomplished (well... whatever) ;-) > > Anyway, the frivolity aside, I can get it to repeat every ten seconds. ;-) > Set the computer clock. (okay, maybe i'm just in a silly mood. But > seriously, > that's why the docs say that it is NOT meant for cryptography - not that > that matters > to the OP, snicker; What have I been drinking????) > > > Well, I was trying to emphasize that it was, for pretty much all intents > > and purposes, infinite. > > Nope-nope-nope you're wrong :-)~ The way I understood the 'period' of the random function was that after x calls to the function, you would start getting the same pattern of results as you did to begin with, in _the same running process_ of a program. This is a separate situation from having the clock be exactly the same and getting the same random values on program start - we already knew that would happen, because the seed hadn't changed. Unless I understand the period wrong, but I don't think so. The daring cracker enters the room, his heart quickening as the door hinge > creaks with the sound of the smallest ever mouse. His dark clothing masks > him from the lit room visible through the window on the adjacent wall. A > woman, working late, sits in a comfortable office chair, her face glowing > from the reflection of her computer screen. A cup of Java (pun intended) > indicates to anyone watching that she is overworked, and under-paid. > > Each step he takes brings him closer to his target. The big boss gave him > a > pay cut so that this new PC could sit on his boss's desk. The cracker's > jealously seems to almost permeate the room. Vengeance shouts out louder > than the compressor of the air conditioner in the north window. The > cracker > intinctively looks up to see if his emotions betrayed his presence. But > the > woman in the other room continues her scrolling through endless lines of > buggy, hard to read, unmaintainable, bloated, and otherwise ridiculously > foolish code that could have been so easily fixed if the same 'big boss' > had > ordered the project in Python. > > Soon, a floppy disk is pulled out of a black jacket pocket. No one has > ever > run the program on the floppy before. Taking the disk, the cracker inserts > it into the drive, starts the machine, swears under his breath when he > reads > "Non-System disk or disk error. Replace and strike any." > > Striking the 'any' key, he quickly shoves the floppy disk back in. He > wants > this over with. Again, he looks to see if he has been detected; still he > is > safe. Opening the folder containing the floppy drive, he groans silently > as > the annoying Windows Firewall flashes an update notice. "See..." he thinks > to himself, "Micro$oft *can* actually restrict viruses from entering their > OS." He fights with the window, impatiently waiting for countless > libraries > to load and free, until the UI responds and he can send it a WM_CLOSE > message. > > Smirking evily, the cracker double-clicks the executable > 'pink_fuzzy_bunny.exe' and resists the urge to laugh maniacally as he > watches the computer clock freeze and not move. Ingenious--his plan--All > it > takes to freeze time is to contantly set it to the same second in history. > Time. Forever frozen. He frowns as he realizes that in so doing, he > provides > the only effective means for keeping those pesky Windows notices out of > his > boss's hair. "No matter" --he thinks, "He will have worse troubles in due > time." Again he suppresses a maniacal laugh. > > . . . > > Monday morning brings a bright and cheerful man into an office, his > office. > The door creaks a little as he opens it, and the air conditioner buzzing > in > the north wall window is refreshing to him after the heat from outside. > The > man waves cheerfully at a woman through the glass in the adjacent wall, > whom > looks up only for an instant to scowl. The man, who recently bought his > new > PC, smiles proudly as he turns it on. His new python program which he > keeps > on the desktop is his early attempt at a cricket game simulation. He > lovingly double-clicks the icon, and runs the program several times. Each > successive time his grin grows smaller and smaller until his face is more > than troubled. Why is his program producing the same output every time? A > scream is heard in the office "NOOOOOOO!!!!!!!!" > The boss runs from the building, never to notice the clock in the > bottom-right hand corner which still shows the caption '10:33 PM'. > > Somewhere, someplace a cracker lies in bed, a silly grin on his face. His > objective, he knows, has been accomplished. nice story. > Because the possibility of my computer even existing after that long is > > effectively zero, I consider the pattern to never repeat :) > > Ahhh... > Your computer ~ sitting on a pedestal in the middle of nowhere in AD > 3.0e5988, the last shrine to the ancient past-- A technological marvel to > the ape like creatures whom are all that remain of the once all powerful > race of human beings. > > Our ape, named Jogg, looks at the bright computer screen, jumps back in > fear > as the ancient Windows Beep function is called and the foreign noise hits > him. What is this? There is a message there. > > ... > ... > File "<stdin>", line 2, in find > File "<stdin>", line 2, in find > File "<stdin>", line 2, in find > RuntimeError: maximum recursion depth exceeded > >>> > > Damn. I guess we will never know. > > (okay... maybe nobody spiked my Mt. Dew, but maybe because it's after 3:00 > am) as a side note - are you going to enter the September Pyweek? You should! It's a lot of fun. -Luke -------------- next part -------------- An HTML attachment was scrubbed... URL:
https://mail.python.org/pipermail/tutor/2007-July/055922.html
CC-MAIN-2014-15
en
refinedweb
jsck JSON Schema Compiled checK Want to see pretty graphs? Log in now!Want to see pretty graphs? Log in now! npm install jsck JSON Schema Compiled ChecK Fast validation against JSON Schema Draft 3 Installation $ npm install jsck About JSCK is a "compiling" schema validator, meaning that it traverses a schema only once (at instantiation) and generates the functions needed to validate documents against the schema. By doing so, it avoids the need to re-traverse the schema structure for every document it validates. This leads to substantial performance improvements. For the initial (0.1.x) release, JSCK will only tell you whether a document passes validation, not where it failed or why. Supports most of JSON Schema Draft 3. Documentation and implementation. Usage Validator = require("../src/index").draft3 # a schema without an "id" declaration validator = new Validator type: "object" properties: user: type: "object" properties: login: required: true type: "string" pattern: "^[\\w\\d_]{3,32}$" email: type: "string" {valid} = validator.validate user: login: "automatthew" email: "automatthew@mailinator.com" console.log "Anonymous schema:", valid Advanced usage examples Coverage Currently passing the canonical test suite for draft3 except for these items: refRemote(Trying to keep this lib synchronous for v0.1.x) ref - remote ref, containing refs itself uniqueItems optional/zeroTerminatedFloats optional/format(some of the regexes borrowed from tdegrunt's validator aren't working for me) - validation of date-time strings - validation of CSS colors - validation of host names Managing resolution scope with the "id" attribute JSCK does not support the full range of scope manipulations suggested by drafts 3 and 4. It uses "id" declarations only in these cases: - at the top level of a schema, to provide a namespace for schemas not loaded from URIs. - non-JSON-pointer fragments ( "id": "#user"), which serve merely as aliases for specific subschemas, and are thus convenient and unambiguous. For more information on the topic of scope manipulation, see this issue:. Benchmarks Results of a simple (probably flawed) benchmark against other libs. 8 iterations. Units are ms. JSCK: valid document, 400 times { max: 2.596, median: 0.494, min: 0.491, mean: 0.76, stdDev: 0.6940034221817643, sample_size: 8 } jsonschema: valid document, 400 times { max: 224.818, median: 194.503, min: 183.965, mean: 198.83875, stdDev: 14.102769335754596, sample_size: 8 } JSV: valid document, 400 times { max: 5778.058, median: 5707.239, min: 5664.46, mean: 5713.368375, stdDev: 38.30406714024464, sample_size: 8 } I find it difficult to believe JSV is actually that slow, so it's probably my fault. Possibly incorrect usage of JSV. Plans 0.1.0 - Boolean validation. - Correct coverage of most of Draft 3 - benchmarking schemas of varying levels of complexity 0.2.0 - validation error reports - complete support for "format" - adding more comprehensive tests to the official test suite - support remote references 0.3 - Support Draft 4
https://www.npmjs.org/package/jsck
CC-MAIN-2014-15
en
refinedweb
#include <RTOpPack_Types.hpp> Inheritance diagram for RTOpPack::ConstSubMultiVectorView< Scalar >: For a sub-multi-vector mv, the corresponding entries in the global multi-vector X(j) (one based) are as follows: X(mv.globalOffset()+k1,mv.colOffset()+k2) = mv(k1,k2), for k1=0...mv.subDim()-1, k2=0...mv.numSubCols()-1 mv.leadingDim()that separates corresponding elements in each column sub-vector. The raw pointer to the first element, in the first column can be obtained from the function mv.values(). Warning! the default copy constructor and assignment operators are allowed which results in only pointer copy, not deep copy! You have been warned! Definition at line 391 of file RTOpPack_Types.hpp.
http://trilinos.sandia.gov/packages/docs/r7.0/packages/rtop/browser/doc/html/classRTOpPack_1_1ConstSubMultiVectorView.html
CC-MAIN-2014-15
en
refinedweb
Flexible Rails: Flex 3 on Rails 2 Flexible Rails Flex 3 on Rails 2 By Peter Armstrong 13,565 Downloads · Refcard 9 of 199 (see them all) Download FREE PDF The Essential Flex on Rails Cheat Sheet Flexible Rails: Flex 3 on Rails 2 ABOUT. Overview of Rails 2 Rails provides a standard three-tier architecture (presentation tier, model tier, persistence tier) as well as a Model-View-Controller (MVC) architecture. As shown in Figure 1, Rails takes care of everything between the web server and the database. Figure 1. Figure 1: Rails provides a standard three-tier architecture (presentation tier, model tier, persistence tier) as well as a Model-View-Controller architecture. The typical sequence is as follows: - A user visits a particular URL in their web browser (makes an HTTP request). - This request goes over the Internet to the web server in which Rails is running. - That web server passes the request to the routing code in Rails, which triggers the appropriate controller method call based on the routes defined in config\routes.rb. - The controller method is called. It communicates with various ActiveRecord models (which are persisted to and retrieved from a database of your choosing). The controller method can then do one of two things: - Set some instance variables and allow a view template (a specially named .html.erb file, for example) to be used to produce HTML, XML, or JavaScript, which is sent to the browser. - Bypass the view mechanism and do r endering directly via a call to the render method. This method can produce plain text (render :text => "foo"), XML (render :text => @task), and so on. Overview of Flex 3 In Flex 3, you write code in MXML (XML files with a .mxml extension; M for Macromedia) and ActionScript (text files with a .as extension) files and compile them into a SWF file, which runs in the Flash player. This SWF is referenced by an HTML file, so that when a user with a modern web browser loads the HTML file, it plays the Flash movie (prompting the user to download Flash 9 if it's not present). The SWF contained in the web page can interact with the web page it's contained in and with the server it was sent from. Flex 3 and Rails 2 together Flex and Rails can be used together with XML over HTTPService or with Action Message Format. The XML over HTTPService approach is shown in Figure 2 below. Figure 2. The AMF waters are a bit muddier: there are currently three ways that Flex can talk to Rails using AMF and RemoteObject: - RubyAMF - WebORB for Rails - BlazeDS (with Rails running on JRuby). Flash 9? Are you kidding me? The reference to Flash 9 earlier may have set off alarm bells in your head: Isn't Flash 9 somewhat new? How many people will be able to run my app? Well, while not everyone has Flash 9, most do: according to Flash 9 has reached near ubiquity: 97.3% in US/Canada, 96.5% in Europe and 98.0% in Japan. This is better than Windows. Installinnstalling Everything To get started, various software packages need to be installed. The full instructions can be found in chapter 2 of Flexible Rails (Manning Publications). Here's what is needed: - Ruby 1.8.6 - RubyGems 1.0.0 (or higher) - Rails. 2.0.2 (or higher) - Flex Builder 3 - SQLite - The sqlite3 gem, installed by running this command: C:\>gem install sqlite3-ruby Building a Flex + Rails Application The world doesn't need Yet Another Todo List, but let's build one. Unlike most Rails tutorials, we will assume you are using Windows. (Rails has "crossed the chasm", so this is now becoming the correct assumption.) Open a command prompt or Terminal window and run the following commands: C:\>rails todo This installs the SQLite3 gem and then creates a new Rails application which by default uses the SQLite database. (The default in Rails 2.0.1 and below was MySQL.) Next, create a couple of directories: C:\>cd todo C:\todo>mkdir app\flex C:\todo>mkdir public\bin Next, switch to Flex Builder 3 and create the new Flex project: - Do File > New > Flex Project... - Choose to create a new project named Todo in c:\todo - Leave its type set to "Web application" and its "Application server type" set to None and click Next - Set the Output folder of the Flex project to public\bin and click Next - Set the "Main source folder" to app\flex, leave the "Main application file" as Todo.mxml and set the output folder to and click Finish. Your new Flex project will be created. (Note that public isn't part of the path since it's the root; 3000 is the default port for the server). We are using app\flex as the root of all our Flex code,in larger team environments it's advisable to create a Flex project as a sibling of the Rails app (say, c:\todoclient) and set its output folder to go inside c:\todo\public\bin. This way, different team members can use different IDEs for the client and server projects: for example, Aptana and Flex Builder are both Eclipse-based, and interesting things can happen when you nest projects. Next, let's create a new Task resource using the now-RESTful scaffold command. C:\todo>ruby script\generate scaffold Task name:string Here we are creating a Task that has a name attribute, which is a string. Running this command generates the various Rails files, including the model, helper, controller, view templates, tests and database migration. We're going to make the simplest Todo list in history: Tasks have names, and nothing else. Furthermore, there are no users even, just a global list of tasks. The Task model looks like this: class Task < ActiveRecord::Base end Because the Task model extends (with <) ActiveRecord::Base, it can be mapped to the equivalent database tables. Because we also created the controllers and views with the script\generate scaffold command and ensured that we specified all the fields, we can use a prebuilt web interface to Create, Read, Update, and Delete (CRUD) them. The CreateTasks migration that was created (in db\migrate\001_create_tasks.rb) looks like this: class CreateTasks < ActiveRecord::Migration def self.up create_table :tasks do |t| t.string :name t.timestamps end end def self.down drop_table :tasks end end In the up method, we specify the data types of each new column, such as string in our case, or boolean, integer or text. These are then mapped to the equivalent database data types: for example, boolean becomes a tinyint(1) in MySQL. The timestamps call adds two columns: created_at and updated_at, which Rails treats specially, ensuring that they're automatically set. This is often a good thing to have, so we'll leave them there even though they won't be needed in this build. The TasksController (in app\controllers\tasks_controller.rb) looks like this: class TasksController < ApplicationController # GET /tasks # GET /tasks.xml def index @tasks = Task.find(:all) respond_to do format| format.html # index.html.erb format.xml { render :xml => @tasks } end end # GET /tasks/1 # GET /tasks/1.xml def show @task = Task.find(params[:id]) respond_to do |format| for mat.html # show.html.erb format.xml { render :xml => @task } end end # GET /tasks/new # GET /tasks/new.xml def new @task = Task.new respond_to do |format| for mat.html # new.html.erb format.xml { render :xml => @task } end end # GET /tasks/1/edit def edit @task = Task.find(params[:id]) end # POST /tasks # POST /tasks.xml def cr eate @task = Task.new(params[:task]) respond_to do |format| if @task.save flash[:notice] = 'Task was successfully created.' format.html { redirect_to(@task) } format.xml { render :xml => @task, :status => :created, :location => @task } else format.html { render :action => "new" } format.xml { render :xml => @task.errors, :status => :unprocessable_entity } end end end # PUT /tasks/1 # PUT /tasks/1.xml def update @task = Task.find(params[:id]) respond_to do |format| if @task.update_attributes(params[:task]) flash[:notice] = 'Task was successfully updated.' format.html { redirect_to(@task) } format.xml { head :ok } else format.html { render :action => "edit" } format.xml { render :xml => @task.errors, :status => :unprocessable_entity } end end end # DELETE /tasks/1 # DELETE /tasks/1.xml def destroy @task = Task.find(params[:id]) @task.destroy respond_to do |format| format.html { redirect_to(tasks_url) } format.xml { head :ok } end end end| This new controller which was generated for us contains the seven RESTful controller methods, which are explained in the following table (inspired by David Heinemeier Hansson's Discovering a World of Resources on Rails presentation - media.rubyonrails.org/presentations/worldofresources.pdf, slide 7,as well as the table on p. 410 of Agile Web Development with Rails, 2nd ed. (The Pragmatic Programmers), and the tables in Geoffrey Grosenbach's REST cheat sheet): Table 1: The seven standard RESTful controller methods What's REST? REST (Representational State Transfer) is a way of building web services that focuses on simplicity and an architecture style that is of the web. This can be described as a Resource Oriented Architecture (ROA); see RESTful Web Services published by O'Reilly Media for details. Briefly, the reason to use a RESTful design in Rails is that it helps us organize our controllers better, forces us to think harder about our domain, and gives us a nice API for free. Next, we run the new migration that was created (CreateTasks) when we ran the scaffold command: C:\todo>rake db:migrate At this point we run the server: C:\todo>ruby script\server and play with creating, editing and deleting tasks. - Go to to see an empty task list. - Click the New link to go to. - Create a new Task with a name of "drink coffee" and click Create. - Go back to to see the task list with the new "drink coffee" task present. Now, let's do something interesting and hook this up to Flex. Currently, the Todo.mxml file looks like this:<?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns: </mx:Application> The top-level tag is mx:Application; the root of a Flex application is always an Application. The mx: part identifies the XML namespace that the Application component is from. By default, an Application uses an absolute layout, where you specify the x,y of each top level container and component. What we want to build is the following application: Figure 3: The Simple Todo Flex Application We want the ability to create new tasks, delete tasks and rename them inline in the list. Furthermore, we want to do this in the least amount of code possible. Normally, I'd build this iteratively; but we'll build it all at once. Modify the Todo.mxml file to look like this: <?xml version="1.0" encoding="utf-8"?> <mx:Application xmlns: <mx:Script> <![CDATA[ import mx.events.ListEvent; import mx.controls.Alert; import mx.rpc.events.ResultEvent; private function createTask():void { svcTasksCreate.send(); } private function deleteTask(task:XML):void { svcTasksDestroy. <mx:request> <task><name>{newTaskTI.text}</name></task> </mx:request> </mx:HTTPService> <mx:HTTPService <mx:HTTPService <mx:HTTPService <mx:XMLListCollection <mx:Panel <mx:HBox <mx:Label <mx:TextInput <mx:Button </mx:HBox> <mx:List <mx:ControlBar <mx:Button </mx:ControlBar> </mx:Panel> </mx:Application> This is a complete Flex application in 67 lines of code! Compile and run the application by clicking the green "play" button: you will see the screen shown in Figure 3. A Quick Highlight Tour of this Code: We use a vertical layout to make the components flow vertically. Other choices are horizontal (for horizontal flow) and absolute (which we saw before). The backgroundGradientColors specify the start and end of the gradient fill for the background. We define a HTTPService svcTasksList, which does a GET to /tasks.xml (thus triggering the index action of the TasksController) and specifies a resultFormat of e4x so the result of the service can be handled with the new E4X XML API. We then take the lastResult of this service, which is an XML document, get its children (which is an XMLList of the tasks), and make this be the source of an XMLListCollection called tasksXLC. We do this with a binding to the source attribute. Similarly, we define svcTasksCreate, svcTasksUpdate and svcTasksDestroy to be used for the other CRUD operations. We can pass data to Rails via data bindings using curly braces {} inside XML (as shown in svcTaskCreate) or by sending form parameters that Rails would be expecting (as shown in the updateSelectedTask method). For svcTasksUpdate and svcTasksDestroy we are not setting the url property statically, but instead dynamically setting it to include the id of the task we are updating or destroying. A hack: you can't send HTTP PUT or DELETE from the Flash player in a web browser, so we need to fake it. Luckily, since you can't send PUT or DELETE from HTML in a web browser either, Rails already has a hack in place we just need to know how to use it. Rails will look for a _method parameter in its params hash and, if there is one, use it instead of the actual HTTP method. So, if we do a form POST with a _method of PUT, Rails will pretend we sent an HTTP PUT. (If you're thinking that it's ironic that at the core of a "cleaner" architecture is a giant hack, well, you're not alone.) This _method can be added to a params Object (params['_method'] = "PUT";) or to an anonymous object (svcTasksDestroy.send({_method: "DELETE"});) If you're new to Flex, {} can be used for both anonymous object creation and for data binding. Think of an anonymous object like a hash in Ruby. eric purr
http://refcardz.dzone.com/refcardz/flexible-rails
CC-MAIN-2014-15
en
refinedweb
csTriangle Struct ReferenceA triangle. More... [Geometry utilities] #include <csgeom/tri.h> Inheritance diagram for csTriangle: Detailed DescriptionA triangle. Note that this structure is only valid if used in combination with a vertex or edge table. 'a', 'b', and 'c' are then indices in that table (either vertices or edges). Definition at line 36 of file tri.h. Constructor & Destructor Documentation Member Function Documentation The documentation for this struct was generated from the following file: Generated for Crystal Space 1.0.2 by doxygen 1.4.7
http://www.crystalspace3d.org/docs/online/api-1.0/structcsTriangle.html
CC-MAIN-2014-15
en
refinedweb
On Tue, Mar 10, 2009 at 10:05 PM, Stephen J. Turnbull <stephen at xemacs.org> wrote: > Guido] Got it -- sort of like using assignment in an expression in C, to set a variable and return the valule (but not quite, don't worry :-). > AMK's use-case could be post-processed as something like I assume you're talking about Andrew Koenig's use case -- ANK is Andrew Kuchling, who AFAIK didn't participate in this thread. :-) > (let ((i 0)) > (mapcar (lambda () > (let ((name (intern (format "foo-%d-callback" i)))) > (define-function name (aref slots i)) > (aset slots i name) > (setq i (1+ i)) > name)) > slots)) IIUC (my Lisp is very rusty) this just assigns unique names to the functions right? You're saying this to satisfy the people who insist that __name__ is always useful right? But it seems to be marginally useful here since the names don't occur in the source. (?) > where slots is the vector of anonymous functions. Providing names in > this way costs one indirection per callback invocation in Emacs Lisp, > but the benefits in readability of tracebacks are large, especially > for compiled code. > > >. :-) > >? Right, and so are separations between value and type namespaces (as other languages use, e.g. C++ and Haskell). >. You can assign new values to to f.__name__. >. -- --Guido van Rossum (home page:)
https://mail.python.org/pipermail/python-ideas/2009-March/003332.html
CC-MAIN-2014-15
en
refinedweb
06 April 2012 06:35 [Source: ICIS news] (adds details throughout) SINGAPORE (ICIS)--Taiwan’s state-owned refining firm CPC was forced to shut its 500,000 tonne/year No 5 cracker at its Kaohsiung complex on Friday morning following a pipeline leak that led to an explosion at the site, a company official said. “We are still attending to the accident site and we have no other details,” the official said. The explosion, believed to be at a crude butadiene tank at the site, occurred at about 03.00 hours ?xml:namespace> The subsequent fire was extinguished in about two hours and there were no casualties, they said. An aromatics facility at the site which has a 140,000 tonnes/year benzene unit may have been shut following the outage at the cracker, said a source close to the company. However, the likely impact of a shutdown at the No 5 aromatics unit would be limited, the source said, adding that the operating situation at the facility is still uncertain. CPC’s No 3, No 4 and No 6 aromatics units were not directly affected as they are located away form the The CPC official said the No 5 cracker was operating at 90% capacity prior to the outage. CPC facilities include a 230,000 tonne/year No 3 cracker and a 385,000 tonne/year No 4 cracker in Linyuan in southern The company runs three paraxylene (PX) units at the site with a total production capacity of 660,000 tonnes/year. CPC also produces 170,000 tonnes/year of OX at the site. A CPC customer based in “There is a gathering at the The incident at the [The BD extraction unit at the No 5 cracker – capacity is 95,000 tonnes/year. “And with most of the synthetic rubber plants now either shut or operating at reduced rates, the impact on BD pricing will be limited,” they said. Major Taiwanese synthetic rubber producer TSRC Corp’s 100,00 tonne/year styrene butadiene rubber (SBR) plant at Its other 60,000 tonne/year butadiene rubber (BR) plant is operating at a reduced rate of 70-80% because of poor margins. “Even if the BD price was to go up, we will not accept the higher BD price increase, as the demand for synthetic rubber is very weak and we cannot pass on the costs to our customers,” a company source at TSRC said. BD is the feedstock for synthetic rubber. Additional reporting by Helen Lee, Helen Yan, Mahua Chakravarty, Bohan Loh and Quintella K
http://www.icis.com/Articles/2012/04/06/9548361/Taiwans-CPC-shuts-Kaohsiung-cracker-after-explosion.html
CC-MAIN-2014-15
en
refinedweb
Is this the recommended way to get the bytes from the ByteBuffer ByteBuffer bb =.. byte[] b = new byte[bb.remaining()] bb.get(b, 0, b.length); I'm reading a 16 byte array (byte[16]) from a JDBC ResultSet with rs.getBytes("id") and now I need to convert it to two long. How can I do that? This is the code ... byte[16] ResultSet rs.getBytes("id") Problem I need to convert two ints and a string of variable length to bytes. What I did I converted each data type into a byte array and then added them into a byte ... I have a Java class public class MsgLayout{ int field1; String field2; long field3; } I have a byte array in Java of size 4, which I am trying to put the first two bytes of into ByteBuffer. Here is how I am doing it: byte ByteBuffer byte[] array ...
http://www.java2s.com/Questions_And_Answers/Java-Collection/Array-Byte/bytebuffer.htm
CC-MAIN-2014-15
en
refinedweb
PhyloXML Revision as of 17:06, 17 This module provides two functions, read() and parse(). Both functions accept either a file name or an open file handle, so phyloXML data can be also loaded from compressed files, StringIO objects, and so on. The read() function returns a single Tree.Phyloxml object representing the entire file's data. The phylogenetic trees are in the "phylogenies" attribute, and any other arbitrary data is stored in "other". >>> phx = PhyloXML PhyloXML.parse('phyloxml_examples.xml'): ... = PhyloXML.parse('phyloxml_examples.xml').next() >>> tree.name 'example from Prof. Joe Felsenstein\'s book "Inferring Phylogenies"' Writing phyloXML files The PhyloXML.Writer module exports one function to the top level of the package: write(). It accepts a Phyloxml object (the result of read() or to_phyloxml()) and either a file name or a handle to an open file-like object. Optionally, an encoding other than UTF-8 can be specified. >>> phx = PhyloXML.read('phyloxml_examples.xml') >>> print phx.other [Other(tag='alignment', namespace='')] >>> phx.other = [] >>> PhyloXML.write(phx, 'ex_no_other.xml') >>> phx_no = PhyloXML.read('ex_no_other.xml') >>> phx_no. - dump_tags -- Print the XML tags as they are encountered in the file. For testing and debugging, mainly. >>> PhyloXML.dump_tags('phyloxml_examples.xml') {}phyloxml {}phylogeny {}name {}description {}clade ... - pretty_print -- Produces a plain-text representation of the entire tree. Uses str() to display nodes by default; for the longer repr() representation, add the argument show_all=True. >>> PhyloXML.pretty_print('phyloxml_examples.xml') Phyloxml Phylogeny example from Prof. Joe Felsenstein's book "Inferring Phylogenies" Clade Clade Clade A Clade B Clade C ... >>> PhyloXML.pretty_print('phyloxml_examples.xml', show_all=True) Phyloxml(), with 4 times as quickly..
http://biopython.org/w/index.php?title=PhyloXML&diff=2807&oldid=2775
CC-MAIN-2014-15
en
refinedweb
To load a texture, we need code to load images in a particular format, like JPEG or PNG. Usually, your final program will use generic libraries such as SDL_Image, SFML or Irrlicht, that support various image formats, so you won't have to write your own image-loading code. Specialized libraries such as SOIL (see below) may interest you as well. In a first step, we need to manipulate the image at a low level to understand the basics, so we'll use a trick : GIMP can export an image as C source code, that we can read as-is from our program! I used the save options in the GIMp screenshot on the right. If there's demand, we may provide a special tutorial to read a simple format like PNM, or a subset of BMP or TGA (these two are also simple, but support compression and various formats so it's hard to support all their options). Note: Bundling images as C code is not super-memory-efficient, so don't generalize it. Technically: it's stored in the program BSS segment rather than in the heap, so it cannot be freed. Note 2: you can find the GIMP source as res_texture.xcf in the code repository. To rebuild automatically the application when your modify res_texture.c, add this to the Makefile: cube.o: res_texture.c Creating a texture OpenGL bufferEdit The buffer is basically a memory slot inside the graphic card, so OpenGL can access it very quickly. /* Globals */ GLuint texture_id, program_id; GLint uniform_mytexture; /* init_resources */ glGenTextures(1, &texture_id); glBindTexture(GL_TEXTURE_2D, texture_id); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, // target 0, // level, 0 = base, no minimap, GL_RGB, // internalformat res_texture.width, // width res_texture.height, // height 0, // border, always 0 in OpenGL ES GL_RGB, // format GL_UNSIGNED_BYTE, // type res_texture.pixel_data); /* render */ glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, texture_id); uniform_mytexture = glGetUniformLocation(program_id, "mytexture"); glUniform1i(uniform_mytexture, /*GL_TEXTURE*/0); /*) { fprintf(stderr, "Could not bind attribute %s\n", attribute_name); return 0; }); /* onDisplay */ onIdle:! Using SOILEdit WIP SOIL provides a way to load an image file in PNG, JPG and a few other formats, designed for OpenGL integration. It's a pretty minimal library with no dependency. It's used under the hood by SFML (although SFML also uses libjpeg and libpng directly). Install it (look for a package named libsoil, libsoil-dev, or something similar). Reference it in your Makefile: LDLIBS=-lglut -lSOIL -lGLEW -lGL -lm Include the soil header: #include <SOIL/SOIL.h> One high-level function allows you to upload it directly to the OpenGL context: glActiveTexture(GL_TEXTURE0); GLuint texture_id = SOIL_load_OGL_texture ( "res_texture.png", SOIL_LOAD_AUTO, SOIL_CREATE_NEW_ID, SOIL_FLAG_INVERT_Y ); if(texture_id == 0) cerr << "SOIL loading error: '" << SOIL_last_result() << "' (" << "res_texture.png" << ")" << endl; SOIL_FLAG_INVERT_Ydeals with the reverse-Y-coordinates issue we experienced above. - SOIL also adapt NPOT (non power of 2) textures, when the graphic card doesn't handle these directly Note that with this method, you do not have access to the image dimensions. To get them, you need to use a lower-level API: int img_width, img_height; unsigned char* img = SOIL_load_image("res_texture.png", &img_width, &img_height, NULL, 0); glGenTextures(1, &texture_id); glBindTexture(GL_TEXTURE_2D, texture_id); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img_width, img_height, 0, GL_RGB, GL_UNSIGNED_BYTE, img); Further readingEdit - Textures in the legacy OpenGL 1.x section - SOIL homepage
http://en.m.wikibooks.org/wiki/OpenGL_Programming/Modern_OpenGL_Tutorial_06
CC-MAIN-2014-15
en
refinedweb
Memory leak in zope.i18nmessageid.MessageFactory Bug #257657 reported by Gary Poster This bug affects 2 people Bug Description (zope.i18nmessa The following code leaks memory: import zope.i18nmessageid _ = zope.i18nmessag while 1: _('a string') Apparently the message instances (C code) are not being garbage collected. This affects persistent objects that have a reference to a message (every time the state is loaded, a new version of the same string is created and never released). It will also affect any code that generates message instances dynamically; templates, for instance, may be affected. This has been reproduced using both Python 2.4 and 2.5.
https://bugs.launchpad.net/zope.i18nmessageid/+bug/257657
CC-MAIN-2022-27
en
refinedweb
NAME SYNOPSIS DESCRIPTION RETURN VALUE SEE ALSO pmem2_badblock_context_new(), pmem2_badblock_context_delete() - allocate and free a context for pmem2_badblock_next() and pmem2_badblock_clear() operations #include <libpmem2.h> struct pmem2_source; struct pmem2_badblock_context; int pmem2_badblock_context_new( const struct pmem2_source *src, struct pmem2_badblock_context **bbctx); void pmem2_badblock_context_delete( struct pmem2_badblock_context **bbctx); The pmem2_badblock_context_new() function instantiates a new (opaque) bad block context structure, pmem2_badblock_context, which is used to read and clear bad blocks (by pmem2_badblock_next() and pmem2_badblock_clear()). The function returns the bad block context through the pointer in *bbctx. New bad block context structure is initialized with values read from the source given as the first argument (src). A bad block is an uncorrectable media error - a part of a storage media that is either inaccessible or unwritable due to permanent physical damage. In case of memory-mapped I/O, if a process tries to access (read or write) the corrupted block, it will be terminated by the SIGBUS signal. The pmem2_badblock_context_delete() function frees *bbctx returned by pmem2_badblock_context_new() and sets *bbctx to NULL. If *bbctx is NULL, no operation is performed. It is not supported on Windows. The pmem2_badblock_context_new() function returns 0 on success or a negative error code on failure. pmem2_badblock_context_new() does set *bbctx to NULL on failure. pmem2_badblock_context_delete() does not return any value. pmem2_badblock_context_new() can fail with the following errors: PMEM2_E_INVALID_FILE_TYPE - src is not a regular file nor a character device. PMEM2_E_DAX_REGION_NOT_FOUND - cannot find a DAX region for the given src. PMEM2_E_CANNOT_READ_BOUNDS - cannot read offset or size of the namespace of the given src. PMEM2_E_NOSUPP - on Windows or when the OS does not support this functionality -errno - set by failing ndctl_new, while trying to create a new ndctl context. -errno - set by failing fstat(2), while trying to validate the file descriptor of src. -errno - set by failing realpath(3), while trying to get the canonicalized absolute sysfs pathname of DAX device given in src. -errno - set by failing open(2), while trying to open the FSDAX device matching with the src. -errno - set by failing read(2), while trying to read from the FSDAX device matching with the src. -errno - set by failing ndctl_region_get_resource, while reading an offset of the region of the given src. -errno - set by failing fiemap ioctl(2), while reading file extents of the given src. pmem2_badblock_next(3), pmem2_badblock_clear(3), libpmem2(7) and The contents of this web site and the associated GitHub repositories are BSD-licensed open source.
https://pmem.io/pmdk/manpages/linux/v1.9/libpmem2/pmem2_badblock_context_new.3/
CC-MAIN-2022-27
en
refinedweb
Commercial elevator reliability is a key factor in the flow of people and products through a building. Improperly maintained elevators impact public safety, productivity, energy consumption, and quality of life. Non-working elevators also adversely impact people with disabilities and the elderly. By using IoT devices for predictive maintenance, businesses can ensure consistent elevator performance to reduce downtime and save money on costly repairs. In a previous Hackster project, I described the Digital Twin project of public elevators in Ermua. A “digital twin” is a virtual representation of an system that mimics its lifecycle, is continually updated, and can use machine learning to help with improvements and predictive maintenance scenarios. You can find the details of that project here: User: demo Password: Twin2022 The Digital Twin helps us to understand the functional state of the elevator. But what's going on inside the elevator? Below, I provide a step-by-step tutorial on how to create a cellular-connected node using a prepaid Blues Wireless Notecard. This IoT solution will be able to identify a series of sounds inside the elevator cabin. Identifying audio anomalies inside an elevator serves the dual purpose of predictive maintenance and public safety. When an elevator is functioning properly, it should run quietly and smoothly. Sound anomalies such as grinding or squealing can indicate the need for maintenance. Other noise anomalies could indicate public safety issues requiring intervention. For this project, sound anomalies were divided into 4 categories (not realistic for an elevator scenario, but useful for this POC): -Dog barking -Glass breaking -Gunshots -Background noise We also identified a set of voice commands for the elevator: -Up/down -Floor 0, 1, 2, 3. We then used Edge Impulse Studio to classify sounds inside the elevator cabin and sent inference results to a nice dashboard using the Notecard and the Blues Wireless cloud service, Notehub.io. This way, we would be able to spot if something abnormal was going on inside the elevator. Let’s take a look at how this came together.Things used in this project: Hardware · Blues Wireless Notecard NBGL · Blues Wireless Notecarrier B · 1800mAh LiPo battery Software apps and online services The XIAO BLE Sense already has a microphone and IMU. The Notecarrier and Xiao board hook up over the I2C bus, so just 4 wires are needed. Finally, I needed a power source, so I used a 1800mAh LiPo battery. However, bigger battery capacities or chemistries are also possible. Here is the hardware connection setup between the Blues Wireless Notecard, Notecarrier B, and Xiao BLE Sense. An Easyeda PCB footprint is provided to easily hook up both boards: Notecard I started with the Blues Wireless Notecard, which provides prepaid global cellular access including 500MB of data and 10 years of service. The global model (NBGL) I chose works with both LTE-M and NB-IoT protocols, so I could easily pump the data I needed to the cloud. It's also an extremely low-power device at ~8uA when idle. Blues Wireless Notehub Since the Notecard is a device-to-cloud data pump, it doesn't live on the public Internet (making it a secure device) and therefore needs a proxy with which to sync data. This is where the Blues Wireless Notehub comes into play. Notehub is a thin cloud service that securely accepts data from the cellular Notecard (off the public Internet, using private VPN tunnels) and then routes the data to the cloud provider of your choice, including AWS, Azure, Google Cloud, or any IoT-optimized service like Ubidots, Datacake, Losant, and others. NOTE: All of the code used for this project is available in this GitHub repository.AI modeling for sound classification XIAO Ble Sense For detecting sounds, the XIAO BLE Sense has equipped a powerful Nordic nRF52840 MCU which is designed in a Bluetooth 5.0 and NFC module, built around 32-bit ARM® Cortex™-M4 CPU operating at 64Mhz. Furthermore, it only requires ~5μA in deep sleep. The board has a MSM261D3526H1CPM microphone and a 6-axis Inertial Measurement Unit (IMU). These onboard sensors provide a great convenience with an ultra-small size feature. XIAO Ble Urbansound 8K We will be using Urbansound8K, which is a very nice dataset, containing 8732 labelled sound excerpts (<=4s) of urban sounds from 10 classes. The whole dataset is 6 GB, but we are not using all of it. You can grab the dataset ingested in Edge Impulse here. Sound classification can be a difficult task for a microcontroller as sound waves are complex. So, we need a different approach to the task, and here is where Mel Spectrogram comes in. The Mel Scale, mathematically speaking, is the result of some non-linear transformation of the frequency scale. This Mel Scale is constructed such that sounds of equal distance from each other on the Mel Scale, also “sound” to humans as they are equal in distance from one another. In contrast to Hz scale, where the difference between 500 and 1000 Hz is obvious, whereas the difference between 7500 and 8000 Hz is barely noticeable. Creatingan Impulse Now that we know now what a Mel Spectrogram is and we have all the data samples, it's time to design an impulse. An impulse, in a nutshell, is: · How your ML model is being trained. · Where you define the actions that are going to be performed on your input data to make them better suited for ML. · A learning block that defines the algorithm for the data classification. We will use Edge Impulse Studio for this. It makes it easy to add Edge AI capabilities to a wide variety of microcontrollers. First, we need to acquire data into Edge Impulse. In this case, you will find that it is already there, but you can just modify the project with your desired data. Next, I created the impulse. For that, within Edge Impulse Studio, navigate to Impulse design on the left menu and then select Add a processing block and add Audio (MFCC), then select Add learning block and add Neural Network (Keras). Keep all the settings at their defaults for each block. Click on the Save impulse button. I trained my ML model based on the dataset and configuration. The initial output of this process showed me that my model was going to be remarkably accurate. Meanwhile, the "feature explorer" also helps you to identify any mislabelled sounds before you use the model in any real-world setting. Now under Deployment in left menu, we buildour model on Edge Impulse for deployment as an Arduino library. As Our Xiao Ble Sense makes good use of a NRF52840 microcontroller, according to Edge Impulse, our model is using 5K of its RAM memory and 35, 6K of flash. Therefore, latency should be around 5ms with a nearly 80% accuracy. This is only our AI model. As we are embedding a TinyML model into Arduino code and using other portions of code to handle communication with the cellular notecard, performance could vary a bit but shouldn't be very different. // If your target is limited in memory remove this macro to save 10K RAM #define EIDSP_QUANTIZE_FILTERBANK 0 /* Includes -------------------------------------------------------------*/ #include <PDM.h> #include <Elevator_inferencing.h> /** Audio buffers, pointers and selectors */ typedef struct { int16_t *buffer; uint8_t buf_ready; uint32_t buf_count; uint32_t n_samples; } inference_t; Now it is time to add cellular data connectivity with Blues Wireless. For that, we need to hook up both boards add just add some lines of code that will report to us every time that an abnormal sound is detected. The selected productUID will be the name of the project you create in Notehub. #define productUID "org.elevator.v2" Notecard nc; void setup() { J *req = nc.newRequest("hub.set"); if (req) { JAddStringToObject(req, "product", productUID); JAddStringToObject(req, "mode", "continuous"); JAddBoolToObject(req, "sync", true); if(!nc.sendRequest(req)) { nc.logDebug("FATAL: Failed to configure Notecard!\n"); while(1);} } } In case you have any questions, please refer to the Blues Wireless developer documentation to help you!Dashboard Now we’re receive all data and we now need to display it in a dashboard. I am a big fan of Tableau. Even if it is not the best one for real time data, its analytics capabilities are great. However, if you prefer, you can opt for Ubidots or Datacake as alternatives. Even if the wiring is very simple, I found it more convenient to have a small adapter PCB for the Notecarrier and Xiao BLE Sense board. I also 3D printed the enclosure you seen below. You can find here the.STL files to print it yourself. It's ready made to house two batteries for long time operation. To see the AR model, you can go into this URL and once in, scan the marker. So far, we have developed a Digital Twin of public elevators in Ermua and we are able to receive audio anomaly inferencing data over low power cellular connection to know what's going on inside the elevator cabins. Where are we going with this project? Our aim is to improve the accessibility of elevators by informing users about the most accessible path to follow and let them know if an elevator is under maintenance. Happy hacking! 👩💻
https://www.hackster.io/ivan-arakistain/ml-anomaly-detection-in-elevators-w-edge-impulse-notecard-344198
CC-MAIN-2022-27
en
refinedweb
Add “Launch at Login” functionality to your macOS app in seconds It's usually quite a convoluted and error-prone process to add this. No more! This package works with both sandboxed and non-sandboxed apps and it's App Store compatible and used in apps like Plash, Dato, Lungo, and Battery Indicator. Sindre‘s open source work is supported by the communitySpecial thanks to: Add in the “Swift Package Manager” tab in Xcode. Warning: Carthage is not recommended. Support for it will be removed at some point in the future. github "sindresorhus/LaunchAtLogin" Add a new “Run Script Phase” below (not into) “Copy Bundle Resources” in “Build Phases” with the following: "${BUILT_PRODUCTS_DIR}/LaunchAtLogin_LaunchAtLogin.bundle/Contents/Resources/copy-helper-swiftpm.sh" (I would name the run script Copy “Launch at Login Helper”) Add a new “Run Script Phase” below (not into) “Embed Frameworks” in “Build Phases” with the following: "${PROJECT_DIR}/Carthage/Build/Mac/LaunchAtLogin.framework/Resources/copy-helper.sh" (I would name the run script Copy “Launch at Login Helper”) No need to store any state to UserDefaults. Note that the Mac App Store guidelines requires “launch at login” functionality to be enabled in response to a user action. This is usually solved by making it a preference that is disabled by default. Many apps also let the user activate it in a welcome screen. import LaunchAtLogin print(LaunchAtLogin.isEnabled) //=> false LaunchAtLogin.isEnabled = true print(LaunchAtLogin.isEnabled) //=> true This package comes with a LaunchAtLogin.Toggle view which is like the built-in Toggle but with a predefined binding and label. Clicking the view toggles “launch at login” for your app. struct ContentView: View { var body: some View { LaunchAtLogin.Toggle() } } The default label is "Launch at login", but it can be overridden for localization and other needs: struct ContentView: View { var body: some View { LaunchAtLogin.Toggle { Text("Launch at login") } } } Alternatively, you can use LaunchAtLogin.observable as a binding with @ObservedObject: import SwiftUI import LaunchAtLogin struct ContentView: View { @ObservedObject private var launchAtLogin = LaunchAtLogin.observable var body: some View { Toggle("Launch at login", isOn: $launchAtLogin.isEnabled) } } Just subscribe to LaunchAtLogin.publisher: import Combine import LaunchAtLogin final class ViewModel { private var isLaunchAtLoginEnabled = LaunchAtLogin.isEnabled private var cancellables = Set<AnyCancellable>() func bind() { LaunchAtLogin .publisher .assign(to: \.isLaunchAtLoginEnabled, on: self) .store(in: &cancellables) } } Bind the control to the LaunchAtLogin.kvo exposed property: import Cocoa import LaunchAtLogin final class ViewController: NSViewController { @objc dynsrc=" launchAtLogin = LaunchAtLogin.kvo } The package bundles the helper app needed to launch your app and copies it into your app at build time. Please ensure that the LaunchAtLogin run script phase is still below the “Embed Frameworks” phase. The order could have been accidentally changed. The build error usually presents itself as: cp: […]/Resources/LaunchAtLoginHelper.app: No such file or directory rm: […]/Resources/copy-helper.sh: No such file or directory Command PhaseScriptExecution failed with a nonzero exit code LaunchAtLoginwhen using Carthage The bundled launcher app is written in Swift and hence needs to embed the Swift runtime libraries. If your project targets macOS 10.14.4 or later, you can avoid embedding the Swift runtime libraries. First, open ./Carthage/Checkouts/LaunchAtLogin/LaunchAtLogin.xcodeproj and set the deployment target to the same as your app, and then run $ carthage build. You'll have to do this each time you update LaunchAtLogin. This is not a problem when using Swift Package Manager. This is the expected behavior, unfortunately. This is usually caused by having one or more older builds of your app laying around somewhere on the system, and macOS picking one of those instead, which doesn't have the launch helper, and thus fails to start. Some things you can try: DerivedDatadirectory. Some helpful Stack Overflow answers: CocoaPods used to be supported, but it did not work well and there was no easy way to fix it, so support was dropped. Even though you mainly use CocoaPods, you can still use Swift Package Manager just for this package without any problems. LaunchAtLogin.bundlein my debug build or I get a notarization error for developer ID distribution As discussed here, this package tries to determine if you're making a release or debug build and clean up its install accordingly. If your debug build is missing the bundle or, conversely, your release build has the bundle and it causes a code signing error, that means this has failed. The script's determination is based on the “Build Active Architecture Only” flag in build settings. If this is set to YES, then the script will package LaunchAtLogin for a debug build. You must set this flag to NO if you plan on distributing the build with codesigning. Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics
https://swiftpack.co/package/sindresorhus/LaunchAtLogin
CC-MAIN-2022-27
en
refinedweb
# Copyright (c) 2007-2011 Thomas Lotze # See also LICENSE.txt """Public interfaces used in Ophelia. """ import zope.interface # APIs intended to be used from scripts and templates.[docs]class IRequestAPI(zope.interface.Interface): """HTTP request API for use in scripts and TALES expressions. """ # Basic parameters which don't have defaults, not meant to be changed. path = zope.interface.Attribute( """URI path portion to traverse from the site root. String with path segments separated by '/', doesn't start with '/' if the requested URI was canonical. """) template_root = zope.interface.Attribute( """Absolute file system path to the templates' root directory. """) site = zope.interface.Attribute( """Absolute URI of the site root. String, the URI which corresponds to an empty path. """) env = zope.interface.Attribute( """Compound environment namespace. - site configuration options (WSGI application configuration) - the CGI or WSGI environment variables passed by the server - must contain the ``wsgi.input`` variable - may contain the ``ophelia.response_headers`` namespace of response headers already set by the server environment """) input = zope.interface.Attribute( """File-like object from which to read the request body. """) headers = zope.interface.Attribute( """Namespace of request headers with leading ``HTTP_`` removed. Multiple headers are mapped to a comma-separated single header according to RfC 2068, section 4.2. """) # Further configuration, may be modified by scripts. response_encoding = zope.interface.Attribute( """Name of the character encoding used for the HTTP response. String, defaults to "utf-8". """) index_name = zope.interface.Attribute( """File name to access if a URI refers to a bare directory. String, defaults to "index.html". """) redirect_index = zope.interface.Attribute( """Whether to redirect requests for index pages to directory URIs. Bool, defaults to False. A request for an index page is one that maps to a file named like the index_name. """) # Components. splitter = zope.interface.Attribute( """Splits input files into scripts and templates. Implements ophelia.interfaces.ISplitter. """) # Traversal and rendering state meant for use in scripts and expressions. context = zope.interface.Attribute( """Namespace for executing scripts and evaluating TALES expressions. """) macros = zope.interface.Attribute( """Namespace of compiled macros. """) innerslot = zope.interface.Attribute( """Unicode content to put in the template's inner slot. None during traversal, assigned to after each template on the stack has been rendered, starting with the innermost one. Thus, this value can't be directly used by scripts but may be used by functions placed in the context. """) response_headers = zope.interface.Attribute( """Mapping of header names to TALES expressions. Expressions will be evaluated in the usual TALES context after all templates have been rendered. Multiple values for the same header must be sent in a single header line with a comma-separated value, see RfC 2068, section 4.2. If response headers have been set earlier by the server environment, they may be passed to the request through the environment to pre-fill the ``response_headers`` namespace. """) content = zope.interface.Attribute( """Encoded HTTP response after the response body is complete. None during traversal and template rendering. After that, consists of an XML declaration and the encoded current innerslot value. """) # Traversal and rendering state meant for use by those who know what # they're doing. current = zope.interface.Attribute( """URI traversed so far, starting with the site root URI. String, ends with '/' if a directory's __init__ is currently being processed. """) dir_path = zope.interface.Attribute( """Absolute file system path to the current directory. String. The current directory is the one which directly contains the file currently being processed. """) tail = zope.interface.Attribute( """List of path segments yet to traverse. List of strings, the last one being empty if the requested URI refers to a directory. """) stack = zope.interface.Attribute( """Stack of file contexts to process when rendering the response body. List of namespaces holding the file path, template text, and page template for any input file processed so far (during traversal) or to be rendered yet (when building the response). The outermost template is at the bottom of the stack (i.e. at index 0). """) # Methods for processing further files. def load_macros(name): """Process a file, only executing the script and loading the macros. Only the macros defined by the template in the file are used; the template itself will be thrown away. name: str, file name to process, relative to the current dir_path Returns nothing. """ def insert_template(name): """Process a file, pushing the template onto the stack. The script contained in the file given will be executed, the macros defined by the template will be loaded, and the template will be stacked on top of the one from the file whose script called this method. name: str, file name to process, relative to the current dir_path Returns nothing. """ def render_template(name): """Process a file, rendering its template. The script contained in the file given will be executed, the macros defined by the template will be loaded, and the template will be rendered in the TALES context as it is at the moment this method is called. name: str, file name to process, relative to the current dir_path Returns unicode, the rendered template contained in the file. """[docs]class ISplitterAPI(zope.interface.Interface): """Input splitter API for use in scripts and TALES expressions. """ script_encoding = zope.interface.Attribute( """Name of the character encoding for reading Python scripts. String, defaults to "ascii". """) template_encoding = zope.interface.Attribute( """Name of the character encoding for reading TAL templates. String, defaults to "ascii". """) # APIs used internally.[docs]class IRequestTraversal(zope.interface.Interface): """Methods used in traversing from site root to requested resource. """ immediate_result = zope.interface.Attribute( """Whether to return the result of template evaluation immediately. Bool, defaults to False. By default, the page content is encoded and prefixed with an XML declaration. Setting this option to True prevents that processing step. """) def __call__(**context): """Process the request, return response headers and body. context: name-value pairs to initialize the context with Returns (dict, unicode), response headers and page content. """ def traverse(**context): """Traverse the path, read input, and prepare the template context. context: name-value pairs to initialize the context with Returns nothing. Raises RuntimeError if the template root is not a file system directory. """ def traverse_next(): """Traverse the next path segment, possibly process an input file. Returns nothing. Raises NotFound if no matching file system resource could be found. """ def get_next(): """Get the next path segment from the tail sequence. This step canonicalizes of "//", "/./", and "/../" path portions as well as paths specifying a directory index explicitly. Returns str, the next path portion. May raise Redirect due to URI canonicalization. """ def traverse_dir(): """Handle the current resource if it is a file system directory. This method assumes that a file system directory corresponds directly to a resource with directory semantics and performs trailing slash canonicalization based on that assumption. Returns nothing. May raise Redirect due to URI canonicalization. """ def traverse_file(file_path): """Handle a file system resource that is a file. If the file's Python script emitted a signal to stop traversal, this step removes any further path segments from the queue. file_path: str, absolute file system path to the file. Returns nothing. """ def process_file(file_path, insert=False, context=None): """Process an input file that may consist of script and template. file_path: str, absolute file system path to the file. insert: bool, whether to insert the file context created into the content stack context: dict, used as the script execution context instead of self.context (if not None) Returns (file context namespace, StopTraversal or None). """ def tales_namespace(file_context={}): """Constructs the namespace in which to evaluate a template. file_context: namespace, predefined variables specific to input file Returns the TALES namespace. """ def build(): """Build the complete response after the template context is prepared. Returns (namespace of compiled response headers, unicode response body). """ def build_content(): """Build the response body by rendering templates from the stack. Returns nothing. """ def build_headers(): """Compile the response header TALES expressions. Returns nothing. """
https://pythonhosted.org/ophelia/_modules/ophelia/interfaces.html
CC-MAIN-2022-27
en
refinedweb
Sometimes, we may get requirements to get all directory and subdirectory under a specific directory. We can use GetDirectories() method in Directory class with the wildcard character "*". This wildcard will list all the directoried under the current directory. The following little code snippet will help us to do the same. string[] dirs = Directory.GetDirectories(@"E:\Technicals\Samples","*",SearchOption.AllDirectories);foreach (string dir in dirs) {Response.Write(dir + "<br>"); } The above code will print all the directories and sub directories under the folder E:\Technicals\Samples. You need to include System.IO namespace for the code to work.
http://www.codedigest.com/CodeDigest/195-How-to-get-all-Directories(folders)-and-Sub-directories(sub-folders)-under-a-Directory-in-C--.aspx
CC-MAIN-2022-27
en
refinedweb
Deploy to WildFly and Docker From IntelliJ Using Management API When you are new to both Docker and IntelliJ how do you deploy your Java EE applications? Steve Favez shows you how. Join the DZone community and get the full member experience.Join For Free As a new Docker and IntelliJ user, I was looking for some tips on how to deploy an application from my IDE to a running wildfly docker container. Searching the web returned me some tech tips, but only based on Eclipse/JBoss tools. So, I decided to share a quick summary of how to deploy a Java EE 7 application to WildFly and Docker from Intellij(2016), using the WildFly management API. This JBoss tools tutorial (Part 1 and Part 2 ) was really helpful . Customizing the jboss/wildfly image This tutorial is based on the official jboss/wildfly docker image. In order to access wildfy management API remotely (that’s the case with Docker), you’ll need to customize jboss/wildfly image to expose management port outside of the container. So, let’s create a new Dockerfile. FROM jboss/wildfly:latest USER jboss RUN /opt/jboss/wildfly/bin/add-user.sh admin Jboss@admin01 --silent CMD ["/opt/jboss/wildfly/bin/standalone.sh", "-b", "0.0.0.0", "-bmanagement", "0.0.0.0", "--debug"] As you can see, we’re extending jboss/wildfly image (latest version – so, wildfly 10 now), sudo to user « jboss » (the one used to execute wildfly process in the dock), add a new management user using « add-user.sh » in silent mode (user is admin, with password Jboss@admin01) and change the default command exposing management port to the outside world and starting in debug mode. Building Your New jboss/wildfly image Right now, you need to build your new Docker image, using docker build. You can have named it as you want. For this tutorial, let’s name it «jboss/wildfly-dev» This can be done using the following command in the directory containing your new Dockerfile (don’t forget the «.» in the end): docker build /wildfly-dev . Running Your New jboss/wildfly-dev Image After a successful build, you’re now ready to run your new image, by executing the following command: docker run -it -p 8080:8080 -p 9990:9990 -p 8787:8787 jboss/wildfly-dev This will run in interactive mode your new container, exposing port 8080 for your application, 9990 for the management api and 8787 for remote debugging. Type the following URL in your favorite browser to ensure your wildfly is properly started: You can also check that your «admin» user exists by typing: ATTENTION: please, check your docker IP address using the following command if you’re using docker-machine: docker-machine env Create a Sample Web Project in IntelliJ In order to test hot swap, let’s create a simple restful web service (yes, yet another «hello world» restful project in your life). You can find the pom.xml and the two java classes on github. The restful service implementation is trivial – it’s just an http GET logging and returning a hello world message: package org.docker.demo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; /** * Created by Steve Favez on 14.04.2016. * Yet another Hello world restfull service implementation. Just a "GET" returning a plain hello world message. * */ @Path("/sayhello") public class YahwRs { private final static Logger LOGGER = LoggerFactory.getLogger(YahwRs.class) ; // The Java method will process HTTP GET requests @GET // The Java method will produce content identified by the MIME Media type "text/plain" @Produces("text/plain") public String sayHelloWorldPlease() { final String yahwMessage = "Hello world from a restful service deployed in wildfy, in docker and eventually, in virtualbox" ; LOGGER.info( yahwMessage ); return yahwMessage ; } } In your IDE, please run a maven package, in order to generate the corresponding web archive. Configure a Remote Wildfly Server in IntelliJ Now, you need to create a new « Run » configuration in your project. Go to menu « Run -> Edit configurations… ». Click the « + » button to create a new one and choose « Jboss Server -> Remote » First Tab ( Server ) Choose a name (in our case, « docker-wildfly ») If not already configured, choose a corresponding local wildfly installation (same version than the one in your docker image) In Jboss server settings, set the management port to 9990, Username to « admin » and password to « Jboss@admin01» And, in remote Connecting Host, enter the IP of your docker container (see docker-machine env) Second Tab (Deployment) Click on the «+» to add an «Artifact», and choose «yahw.war» On the right, change «Deployment method» to «Native» Last Tab (Startup/Connection) Click on « debug » and change the default debug port to 8787. Debug your project Here we’re. Now we can deploy our project on our docker/wildfly instance. Let’s start by adding a debug breakpoint in our web service (on logging for example), and then choose your new « docker-wildfly » run configuration and click on the « debug » button. After a short time, you’ll see a successful deployment, your browser will open a new tab and, if the URL is correct, Intellij will stop on the breakpoint in your web service. Perform Hot Swap Now, let’s perform some Hot Swap. For example, change the hello world message in your restful web service. Hot Swap will allow you to push your new implementation to the running server without having to perform a new deployment. So, click on the «update», it will ask you the action to take, choose hot swap, and, here you’re. Conclusion As you can see, it’s really easy to use a Wildfly Docker container to develop your JEE 7 application with IntellliJ. Using Docker is really useful when your team has to switch frequently of project, requiring heavy WildFly configuration (datasources, jms and so on). Using Docker, a developer can be ready to work on a project really quickly, sharing not only the source code, but also the JEE infrastructure with the team. Links Source code can be found on github : Opinions expressed by DZone contributors are their own.
https://dzone.com/articles/deploy-to-wildfly-and-docker-from-intellij-using-m
CC-MAIN-2022-27
en
refinedweb
Wrapping your head around neural networks in Python If you’ve ever used a voice app like Alexa or Siri, you’ve interacted with a neural network. (And of course, you already have your own neural network — in your brain.) In machine learning, an artificial neural network (ANN) is an information processing system modeled after our brains. ANNs are the bread and butter of the popular method of advanced machine learning known as deep learning. ANNs are more simply called neural networks, and more recently, deep neural networks. By learning how to harness neural networks, you can apply them to various interesting use-cases, such as natural-language processing (NLP) and computer vision. Today we’ll talk about neural networks and how you can start working with them in Python. We’ll cover: - What are neural networks? - Getting started with neural networks in Python - Wrapping up and next steps What are neural networks? Neural networks are complex structures of machine learning algorithms. A neural network is composed of several information processing units. The information processing units in ANNs share a name with those in our brains: neurons. However, neurons in an ANN are also called nodes, artificial neurons, or perceptrons. A perceptron is a machine learning algorithm used for binary classification of data. On its own, a single perceptron constitutes a single-layer neural network, which is the most basic type of neural network. As a binary classifier, a perceptron can learn linear boundaries between classes, provided it’s given a set of linearly separable training data. To illustrate, a perceptron uses a linear model to separate a given set of input data into two classes: This is great, but most real-world data isn’t related through a linear relationship. To perform more complex tasks, neural networks must be able to learn non-linear representations from real-world data. To do this, we need multiple perceptrons to be interconnected in multi-layer neural networks, or multi-layer perceptrons. Multi-layer neural networks form the basis for deep learning. When we talk about neural networks, we’re usually referring to multi-layer neural networks. There are three types of layers in a multi-layer neural network: - Input layer: Receives a data set of input data, passes inputs to hidden layer - Hidden layer(s): Contains the main computational units; all computations are performed in these layers - Output layers: Also contains computational units and returns output data. (There is a debate as to whether the output layer should be considered a hidden layer or not.) The following figure illustrates a neural network with a single hidden layer: These hidden layers are where the computation happens. Without hidden layers, a neural network will simply return output data identical to the input data. Hidden layers are what truly enable deep learning. Common types of neural networks While there are various types of neural networks, the most common are: - Convolutional neural networks: These are commonly used to analyze images, and are the masterminds behind image and facial recognition. - Recurrent neural networks (RNNs): These learn from sequential training data. They power speech-recognition apps. One type of RNN is the long short-term memory (LSTM) network, which is the type of neural network behind Google Translate. > Neural networks can use different machine learning paradigms, including supervised learning, unsupervised learning, and reinforcement learning. How neural networks work A neural network can receive unstructured data sets, classify data points, recognize patterns, and develop an internal representation through which it makes predictions about similar data sets. Like humans, a neural network learns to perfect its craft over time. It goes through several iterations of computations and adjustments until it makes predictions to a reasonable accuracy. Some of the key computational components in neural networks include: - Activation functions: Each perceptron has an activation function that standardizes its output and prevents different units from collapsing. A common activation function is the sigmoid activation function. - Weight: A value assigned to connections between perceptrons, estimated by the learning algorithm. A neural network’s training process looks like this: - Receives input data: Input data is received through the input layer and passed on to hidden layer(s) - Generates outputs: The neural network usually does its initial computations by using random numbers as weight assignments - Compares outputs: The error between the generated output and required output is represented through a loss function. - Optimizes: An optimization algorithm is used to reduce the loss, an iterative process that repeats until the loss is minimized to a reasonably small value. Our goal when training neural networks is to reduce the error or loss, which means that the network’s generated outputs will ideally match the required outputs. There are several types of loss functions, a common one being the cross-entropy loss function, which is typical in classification tasks. To reduce the loss, we update the weights. At this stage, we don’t use random numbers as our weight assignments. Instead, we use optimization algorithms to determine the changes we need to make. There are many optimization algorithms used to train neural networks. A popular one is the gradient descent algorithm. Gradient descent is an iterative optimization algorithm. A commonly used variant of gradient descent is stochastic gradient descent, which is well suited for working with large data sets. Getting started with neural networks in Python Creating neural networks (NN) is one of the many amazing things you can do with the Python programming language. On your way to mastering neural networks, you’ll need a few ingredients: - Basic Python proficiency - Deep learning frameworks (such as Keras, TensorFlow, and PyTorch) - Basic familiarity with linear algebra, probability, and calculus Libraries and frameworks for neural networks in Python There are various libraries and modules you can use to start creating neural networks in Python: - Keras: Deep learning framework focused on neural networks - NumPy: Python library packed with high-level mathematical functions for multi-dimensional matrices and arrays - pandas: Python library for data analysis and data manipulation - scikit-learn: Python machine learning library for regression and classification - Matplotlib: Python library for plotting and visualization - TensorFlow: Machine learning and AI library focused on training neural networks Neural networks in Python: Code example Let’s take a sneak peek at how we implement neural networks in Python. The following Python code is a simple example of image classification using TensorFlow. # Import packages import tensorflow as tf from tensorflow.keras.models import Model from tensorflow.keras.utils import plot_model # Build neural network model def build_model(): # instantiate a Sequential class and linearly stack the layers of your model seq_model = tf.keras.models.Sequential([tf.keras.layers.Flatten(input_shape=(28, 28)), tf.keras.layers.Dense(128, activation=tf.nn.relu), tf.keras.layers.Dense(10, activation=tf.nn.softmax)]) return seq_model # Instantiate the model and plot it model = build_model_with_functional() plot_model(model) #Load and prepare data mnist = tf.keras.datasets.fashion_mnist (training_images, training_labels), (test_images, test_labels) = mnist.load_data() training_images = training_images / 255.0 test_images = test_images / 255.0 # Set optimization algorithm model.compile(optimizer=tf.optimizers.Adam(), loss='sparse_categorical_crossentropy', metrics=['accuracy']) # Train and evaluate the model model.fit(training_images, training_labels, epochs=5) model.evaluate(test_images, test_labels) Image classification models learn to recognize images. They’re one of the common types of neural networks we discussed earlier: a convolutional neural network. Wrapping up and next steps There’s more and more data to work with each day. Why not team up with a neural network in Python to do something big with that data? To help you master neural networks, we’ve created the learning path: Become a Deep Learning Professional. This path covers deep learning fundamentals and includes several hands-on tutorials and projects to help you master neural networks in Python. Whether you are: - A data scientist - A self-taught innovator looking to change the world (or just someone’s day) - A person who simply loves to learn (some call us nerds) … you can harness neural networks to do some amazing things. We can’t wait to see what you do with your own NN. Happy learning! To get more Python content delivered right to your email inbox, check out our Grokking Python newsletter on Substack! Start a discussion What other elements of Python do you want to read more about? Was this article helpful? Let us know in the comments below! AI/ML Trending AI/ML Article Identified & Digested via Granola by Ramsey Elbasheer; a Machine-Driven RSS Bot
https://ramseyelbasheer.io/2022/06/10/wrapping-your-head-around-neural-networks-in-python/
CC-MAIN-2022-27
en
refinedweb
README Convict ModelConvict Model Annotate a class to define and validate your configs using convict just like you do with an ORM. If you like annotating models classes, then this package will tickle your fancy. The code style and patterns are based on Typeorm because they know what's up. If your using a IOC/DI system, ConvictModel will fit in real nice. RequirementsRequirements Quick LinksQuick Links InstallationInstallation - Install the package npm install @akirix/convict-model --save - Install reflect-metadataif you have not already so the annotations work. npm install reflect-metadata --save then import it in global scope aka main file, i.e. app.ts or index.ts import "reflect-metadata"; - Now we install convict and its types so you can control the version npm install convict --save npm install @types/convict --save-dev - Make sure annotations are enabled in tsconfig.json "emitDecoratorMetadata": true, "experimentalDecorators": true, - (optional) Install JS Yaml if you like yaml over json for configs. npm install js-yaml --save Project SetupProject Setup First we need a proper project setup like the one below with a folder to hold our config schema classes. This is a very simple Typescript folder structure. MyProject ├── src // place of your TypeScript code │ ├── schema // place where your config entities will go │ │ └── MyConfig.ts // sample entity │ ├── types.d.ts // place to put your interfaces │ └── index.ts // start point of your application ├── .gitignore // standard gitignore file ├── config.json // Your apps config file ├── package.json // node module dependencies ├── README.md // a readme file └── tsconfig.json // TypeScript compiler options Take note of the src/schema directory, here we will put our config schema classes which will be annotated with convict schema definitions. This directory can be called whatever you like by the way. Technically you don't even need the folder, it's just a good idea to put similar classes together for organization. Getting StartedGetting Started Now we can start building up a model for our config schema. 1. Define an Interface1. Define an Interface It's a good idea to define an interface so your experience can be agile and include all the fancy IDE features. Interfaces also open an opportunity to have more than one implementation of your config, i.e. maybe you use convict competitor or no validation on config at all. src/types.d.ts declare namespace config { export interface MyConfig { name: string; } } 2. Define a Schema Class2. Define a Schema Class Now we can define a schema class and decorate it like Christmas. The parameter for @Property decorator is simply a convict SchemaObj like in normal convict. You can read all about the possible options in convicts documentation. src/schema/MyConfig.ts import { Property } from '@akirix/convict-model'; export default class MyConfig implements config.MyConfig { @Property({ doc: 'The name of the thing', default: 'Convict', env: 'MY_CONFIG_NAME' }) public name: string; } 3. Make a Configuration3. Make a Configuration Now we can make our configuration for our app. This can be a hardcoded Object in your code, a json file, a yaml file, or however you do it. In the end it's up to you how you type out and load the data. config.json { "name": "Cool App" } 4. Load it up4. Load it up We have a couple of ways to load it up so you can choose what works for your unique situation. The example below is the simplest way in the spirit of TL;DR. src/index.ts import { ConvictModel } from '@akirix/convict-model'; //get your config file however you do it const myRawConfig = getMyConfigData(); //initialize the ConvictModel with a list of paths or entities to load as the schema const convictModel: ConvictModel = new ConvictModel(['src/schema/**/*.*s']); //get your validated config object as a serialized class const myConfig: config.MyConfig = convictModel.create<config.MyConfig>('MyConfig',myRawConfig);
https://www.skypack.dev/view/@akirix/convict-model
CC-MAIN-2022-27
en
refinedweb
Creating a Kubertes Admission Controller in Java Last modified: September 1, 2021 1. Introduction After working for a while with Kubernetes, we'll soon realize that there's a lot of boilerplate code involved. Even for a simple service, we need to provide all required details, usually taking the form of a quite verbose YAML document. Also, when dealing with several services deployed in a given environment, those YAML documents tend to contain a lot of repeated elements. For instance, we might want to add a given ConfigMap or some sidecar containers to all deployments. In this article, we'll explore how we can stick to the DRY principle and avoid all this repeated code using Kubernetes admission controllers. 2. What's an Admission Controller? Admission controllers are a mechanism used by Kubernetes to pre-process API requests after they've been authenticated but before they're executed. The API server process (kube-apiserver) already comes with several built-in controllers, each in charge of a given aspect of API processing. AllwaysPullImage is a good example: This admission controller modifies pod creation requests, so the image pull policy becomes “always”, regardless of the informed value. The Kubernetes documentation contains the full list of the standard admission controllers. Besides those built-in controllers, which actually run as part of the kubeapi-server process, Kubernetes also supports external admission controllers. In this case, the admission controller is just an HTTP service that processes requests coming from the API server. In addition, those external admission controllers can be dynamically added and removed, hence the name dynamic admission controllers. This results in a processing pipeline that looks like this: Here, we can see that the incoming API request, once authenticated, goes through each of the built-in admission controllers until it reaches the persistence layer. 3. Admission Controller Types Currently, there are two types of admission controllers: - Mutating admission controllers - Validation admission controllers As their names suggest, the main difference is the type of processing each does with an incoming request. Mutating controllers may modify a request before passing them downstream, whereas validation ones can only validate them. An important point about those types is the order in which the API server executes them: mutating controllers come first, then validation controllers. This makes sense, as validation will only occur once we have the final request, possibly changed by any of the mutating controllers. 3.1. Admission Review Requests The built-in admission controllers (mutating and validating) communicate with external admission controllers using a simple HTTP Request/Response pattern: - Request: an AdmissionReview JSON object containing the API call to process in its request property - Response: an AdmissionReview JSON object containing the result in its response property Here's an example of a request: { "kind": "AdmissionReview", "apiVersion": "admission.k8s.io/v1", "request": { "uid": "c46a6607-129d-425b-af2f-c6f87a0756da", "kind": { "group": "apps", "version": "v1", "kind": "Deployment" }, "resource": { "group": "apps", "version": "v1", "resource": "deployments" }, "requestKind": { "group": "apps", "version": "v1", "kind": "Deployment" }, "requestResource": { "group": "apps", "version": "v1", "resource": "deployments" }, "name": "test-deployment", "namespace": "test-namespace", "operation": "CREATE", "object": { "kind": "Deployment", ... deployment fields omitted }, "oldObject": null, "dryRun": false, "options": { "kind": "CreateOptions", "apiVersion": "meta.k8s.io/v1" } } } Among the available fields, some are particularly important: - operation: This tells whether this request will create, modify or delete a resource - object: The resource's specification details being processed. - oldObject: When modifying or deleting a resource, this field contains the existing resource The expected response is also an AdmissionReview JSON object, with a response field instead response: { "apiVersion": "admission.k8s.io/v1", "kind": "AdmissionReview", "response": { "uid": "c46a6607-129d-425b-af2f-c6f87a0756da", "allowed": true, "patchType": "JSONPatch", "patch": "W3sib3A ... Base64 patch data omitted" } } Let's dissect the response object's fields: - uid: the value of this field must match the corresponding field present in the incoming request field - allowed: The outcome of the review action. true means that the API call processing may proceed to the next step - patchType: Valid only for mutating admission controllers. Indicates the patch type returned by the AdmissionReview request - patch: Patches to apply in the incoming object. Details on next section 3.2. Patch Data The patch field present in the response from a mutating admission controller tells the API server what needs to be changed before the request can proceed. Its value is a Base64-encoded JSONPatch object containing an array of instructions that the API server uses to modify the incoming API call's body: [ { "op": "add", "path": "/spec/template/spec/volumes/-", "value":{ "name": "migration-data", "emptyDir": {} } } ] In this example, we have a single instruction that appends a volume to the volumes array of the deployment specification. A common issue when dealing with patches is the fact that there's no way to add an element to an existing array unless it already exists in the original object. This is particularly annoying when dealing with Kubernetes API objects, as the most common ones (e.g., deployments) include optional arrays. For instance, the previous example is valid only when the incoming deployment already has at least one volume. If this was not the case, we'd have to use a slightly different instruction: [ { "op": "add", "path": "/spec/template/spec/volumes", "value": [{ "name": "migration-data", "emptyDir": {} }] } ] Here, we've defined a new volumes field whose value is an array containing the volume definition. Previously, the value was an object since this is what we were appending to the existing array. 4. Sample Use Case: Wait-For-It Now that we have a basic understanding of the expected behavior of an admission controller, let's write a simple example. A common issue in Kubernetes when is managing runtime dependencies, especially when using a microservices architecture. For instance, if a particular microservice requires access to a database, there's no point in starting if the former is offline. To address issues like this, we can use an initContainer with our pods to do this check before starting the main container. An easy way to do that is using the popular wait-for-it shell script, also available as a docker image. The script takes a hostname and port parameters and tries to connect to it. If the test succeeds, the container exits with a successful status code, and the pod initialization proceeds. Otherwise, it will fail, and the associated controller will keep on retrying according to the defined policy. The cool thing about externalizing this pre-flight check is that any associated Kubernetes service will notice that the failure. Consequently, no requests will be sent to it, potentially improving overall resiliency. 4.1. The Case for Admission Controller This is what a typical deployment with the wait-for-it init container added to it: apiVersion: apps/v1 kind: Deployment metadata: name: frontend labels: app: nginx spec: replicas: 1 selector: matchLabels: app: nginx template: metadata: labels: app: nginx spec: initContainers: - name: wait-backend image: willwill/wait-for-it args: - containers: - name: nginx image: nginx:1.14.2 ports: - containerPort: 80 While not that complicated (at least in this simple example), adding the relevant code to every deployment has some drawbacks. In particular, we're imposing on deployment authors the burden to specify exactly how a dependency check should be done. Instead, a better experience would require only defining what should be tested. Enter our admission controller. To address this use case, we'll write a mutating admission controller that looks for the presence of a particular annotation in a resource and adds the initContainer to it if present. This is what an annotated deployment spec would look like: apiVersion: apps/v1 kind: Deployment metadata: name: frontend labels: app: nginx annotations: com.baeldung/wait-for-it: "" spec: replicas: 1 selector: matchLabels: app: nginx template: metadata: labels: app: nginx spec: containers: - name: nginx image: nginx:1.14.2 ports: - containerPort: 80 Here, we're using the annotation com.baeldung/wait-for-it to indicate the host and port we must test. What's important, though, is nothing is telling us how the test should be done. In theory, we could change the test in any way while keeping the deployment spec unchanged. Now, let's move on to the implementation. 4.2. Project Structure As discussed before, the external admission controller is just a simple HTTP service. As such, we'll create a Spring Boot project as our basic structure. For this example, this is all we need is the Spring Web Reactive starter but, for a real-world application, it might also be useful to add features like the Actuator and/or some Cloud Config dependencies. 4.3. Handling Requests The entry point for admission request is a simple Spring REST controller that delegates the processing of the incoming payload to a service: @RestController @RequiredArgsConstructor public class AdmissionReviewController { private final AdmissionService admissionService; @PostMapping(path = "/mutate") public Mono<AdmissionReviewResponse> processAdmissionReviewRequest(@RequestBody Mono<ObjectNode> request) { return request.map((body) -> admissionService.processAdmission(body)); } } Here, we're using an ObjectNode as the input parameter. This means that we'll try to process any well-formed JSON sent by the API Server. The reason for this lax approach is, as of this writing, there's still no official schema published for this payload. Using a non-structured type, in this case, implies some extra work, but ensures our implementation deals a bit better with any extra fields that a particular Kubernetes implementation or version decides to throw at us. Also, given that the request object can be any of the available resources in the Kubernetes API, adding too much structure here would not be that helpful. 4.4. Modifying Admission Requests The meat of the processing happens in the AdmissionService class. This is a @Component class injected into the controller with a single public method: processAdmission. This method processes the incoming review request and returns the appropriate response. The full code is available online and basically consists of a long sequence of JSON manipulations. Most of them are trivial, but some excerpts deserve some explanation: if (admissionControllerProperties.isDisabled()) { data = createSimpleAllowedReview(body); } else if (annotations.isMissingNode()) { data = createSimpleAllowedReview(body); } else { data = processAnnotations(body, annotations); } First, why add a “disabled” property? Well, it turns out that, in some highly controlled environments, it might be much easier to change a configuration parameter of an existing deployment than removing and/or updating it. Since we're using the @ConfigurationProperties mechanism to populate this property, its actual value can come from a variety of sources. Next, we test for missing annotations, which we'll treat as a sign that we should leave the deployment unchanged. This approach ensures the “opt-in” behavior that we want in this case. Another interesting snippet comes from the JSONPatch generation logic in the injectInitContainer() method: JsonNode maybeInitContainers = originalSpec.path("initContainers"); ArrayNode initContainers = maybeInitContainers.isMissingNode() ? om.createArrayNode() : (ArrayNode) maybeInitContainers; ArrayNode patchArray = om.createArrayNode(); ObjectNode addNode = patchArray.addObject(); addNode.put("op", "add"); addNode.put("path", "/spec/template/spec/initContainers"); ArrayNode values = addNode.putArray("values"); values.addAll(initContainers); As there's no guarantee that the incoming specification contains the initContainers field, we must handle two cases: they may be either missing or present. If it is missing, we use an ObjectMapper instance (om in the snippet above) to create a new ArrayNode. Otherwise, we just use the incoming array. In doing so, we can use a single “add” patch instruction. Despite its name, its behavior is such that the field either will be created or replace an existing field with the same name. The value field is always an array, which includes the (possibly empty) original initContainers array. The last step adds the actual wait-for-it container: ObjectNode wfi = values.addObject(); wfi.put("name", "wait-for-it-" + UUID.randomUUID()) // ... additional container fields added (omitted) As container names must be unique within a pod, we just add a random UUID to a fixed prefix. This avoids any name clash with existing containers. 4.5. Deployment The final step to start using our admission controller is to deploy it to a target Kubernetes cluster. As expected, this requires writing some YAML or using a tool like Terraform. Either way, those are the resources we need to create: - A Deployment to run our admission controller. It's a good idea to spin more than one replica of this service, as failures may block any new deployments to happen - A Service to route requests from the API Server to an available pod running the admission controller - A MutatingWebhookConfiguration resource that describes which API calls should be routed to our Service For instance, let's say that we'd like Kubernetes to use our admission controller every time a deployment is created or updated. In the MutatingWebhookConfiguration documents we'll see a rule definition like this: apiVersion: admissionregistration.k8s.io/v1 kind: MutatingWebhookConfiguration metadata: name: "wait-for-it.baeldung.com" webhooks: - name: "wait-for-it.baeldung.com" rules: - apiGroups: ["*"] apiVersions: ["*"] operations: ["CREATE","UPDATE"] resources: ["deployments"] ... other fields omitted An important point about our server: Kubernetes requires HTTPS to communicate with external admission controllers. This means we need to provide our SpringBoot server with a proper certificate and private key. Please check the Terraform script used to deploy the sample admission controller to see one way to do this. Also, a quick tip: Although not mentioned anywhere in the documentation, some Kubernetes implementations (e.g. GCP) require the usage of port 443, so we need to change the SpringBoot HTTPS port from its default value (8443). 4.6. Testing Once we have the deployment artifacts ready, it's finally time to test our admission controller in an existing cluster. In our case, we're using Terraform to perform the deployment so all we have to do is an apply: $ terraform apply -auto-approve Once completed, we can check the deployment and admission controller status using kubectl: $ kubectl get mutatingwebhookconfigurations NAME WEBHOOKS AGE wait-for-it-admission-controller 1 58s $ kubectl get deployments wait-for-it-admission-controller NAME READY UP-TO-DATE AVAILABLE AGE wait-for-it-admission-controller 1/1 1 1 10m Now, let's create a simple nginx deployment including our annotation: $ kubectl apply -f nginx.yaml deployment.apps/frontend created We can check the associated logs to see that the wait-for-it init container was indeed injected: $ kubectl logs --since=1h --all-containers deployment/frontend wait-for-it.sh: waiting 15 seconds for wait-for-it.sh: is available after 0 seconds Just to be sure, let's check the deployment's YAML: $ kubectl get deployment/frontend -o yaml apiVersion: apps/v1 kind: Deployment metadata: annotations: com.baeldung/wait-for-it: deployment.kubernetes.io/revision: "1" ... fields omitted spec: ... fields omitted template: ... metadata omitted spec: containers: - image: nginx:1.14.2 name: nginx ... some fields omitted initContainers: - args: - image: willwill/wait-for-it imagePullPolicy: Always name: wait-for-it-b86c1ced-71cf-4607-b22b-acb33a548bb2 ... fields omitted ... fields omitted status: ... status fields omitted This output shows the initContainer that our admission controller added to the deployment. 5. Conclusion In this article, we've covered how to create a Kubernetes admission controller in Java and deploy it to an existing cluster. As usual, the full source code of the examples can be found over on GitHub.
https://www.baeldung.com/java-kubernetes-admission-controller
CC-MAIN-2022-27
en
refinedweb
>> TypeScript >> Property 'required' comes from an index signature, so it must be accessed with ['required'] “Property 'required' comes from an index signature, so it must be accessed with ['required']” Code Answer Property 'required' comes from an index signature, so it must be accessed with ['required'] typescript by Motionless Mantis on Feb 15 2022 Comment 1 // It change a little bit in angular 13 <div *First Name is required</div> Source: stackoverflow.com Add a Grepper Answer TypeScript answers related to “Property 'required' comes from an index signature, so it must be accessed with ['required']” error TS4111: Property 'name' comes from an index signature, so it must be accessed with ['name']. TypeScript queries related to “Property 'required' comes from an index signature, so it must be accessed with ['required']” property 'required' comes from an index signature, so it must be accessed with ['required']. property 'required' comes from an index signature so it must be accessed with 'required' . angular ts4111: property 'required' comes from an index signature, so it must be accessed with ['required']. property 'required' comes from an index signature so it must be accessed with 'required' property 'required' comes from an index signature, so it must be accessed with ['required'] "property 'name' comes from an index signature, so it must be accessed with ['required']" property 'required' comes from an index signature, so it must be accessed with ['required']. angular property 'required' comes from an index signature, so it must be accessed with ['required'].ngtsc(4111) property 'required' comes from an index signature, so it must be accessed with r ts4111: property 'required' comes from an index signature, so it must be accessed with ['required']. More “Kinda” Related TypeScript Answers View All TypeScript Answers » An unhandled exception occurred: Cannot find module '@angular-devkit/build-angular/package.json' angular devkit build angular error An unhandled exception occurred: Cannot find module '@angular-devkit/build-angular/package.json' Require stack: angular No provider for HttpClient rror: failed to init transaction (unable to lock database) error: could not lock database: File exists if you're sure a package manager is not already running, you can remove /var/lib/pacman/db.lck error: failed to update core (unable to lock database) error: failed to update extra (unable to lock database) error: failed to synchronize all databases (unable to lock database) prettier not working with tsx ionic generate resources cannot be loaded because running scripts is disabled on this system File C:\Users\Tariqul\AppData\Roaming\npm\ng.ps1 cannot be loaded because running scripts is disabled on this system. organize imports on save vscode dev/storage/logs" and its not buildable: Permission denied running scripts is disabled on this system nodemon powershell enable scripts File ng.ps1 cannot be loaded because running scripts is disabled on this system. l'exécution de scripts est désactivée sur ce système. cordova: securityError: (:) [], PSSecurityException Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option in your 'tsconfig' or 'jsconfig' to remove this warning Error: Uncaught (in promise): NullInjectorError: R3InjectorError(AppModule)[HttpClient -> HttpClient -> HttpClient]: Cannot preload , value of is undefined\n rails precompile assets production 'index.ts' cannot be compiled under '--isolatedModules' because it is considered a global script file. Add an import, export, or an empty 'export {}' statement to make it a module. Property 'style' does not exist on type 'Element'.ts(2339) allegro gdzie jest moja paczka check if file exists laravel check if file exists bash how check is file exist linux require('dotenv').config() typescript Cannot find module 'file-saver/FileSaver' or its corresponding type declarations. ERROR in The Angular Compiler requires TypeScript >=4.0.0 and <4.1.0 but 3.4.5 was found instead. install typescript in ubuntu using sudo command debian install typescript Command 'tsc' not found Require statement not part of import statement.eslint@typescript-eslint/no-var-requires heroku database error unknow attribute first_name for user npm uninstall all Cannot find module .svg' or its corresponding type declarations. No directive found with exportAs 'matAutocomplete' > client@0.1.0 start > react-scripts start sh: react-scripts: command not found ffmpeg batch convert ts to mp4 files in a folder vue : File C:\Users\MTP Nabeel Ahmed\AppData\Roaming\npm\vue.ps1 cannot be loaded because running scripts is disabled on this system. Task :app:bundleReleaseJsAndAssets FAILED \ng.ps1 cannot be loaded because running scripts is disabled on this system. yarn.ps1 cannot be loaded because running scripts is disabled on this system eslint missing file extension ts Property 'required' comes from an index signature, so it must be accessed with ['required'] vue\npm\vue.ps1 cannot be loaded because running scripts is disabled on this system [ERROR] @ionic/app-scripts is required for this command to work properly. remove contraints command psql error TS2564: Property No suitable injection token for parameter 'path' of class 'BaseModel' replaceall typescript replaceall nodejs Property 'active' has no initializer and is not definitely assigned in the constructor.ts(2564) Error: ./src/main.ts Module build failed (from ./node_modules/@ngtools/webpack/src/ivy/index.js): TypeError: Cannot read property 'createUniqueName' of undefined Missing file extension "ts" for ReferenceError: fetch is not defined nodemon typescript CLIENT MISSING INTENTS discord Type 'Timeout' is not assignable to type 'number'. install typescript homebrew Cannot find name 'require'. Do you need to install type definitions for node? Try `npm i @types/node` and then add `node` to the types field in your tsconfig. if env variable exists bash cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies Cannot find name 'EventEmitter tslint shows double quotes error prettier Cannot find name 'debounceTime' you do not have sufficient access rights to perform this operation sonar ignore rule File C:\Users\SHUBHAM KUNWAR\AppData\Roaming\npm\nodemon.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170. running scripts is disabled on this system sequelize is not null android:exported needs to be explicitly specified for <receiver>. Apps targeting Android 12 and higher are required to specify an explicit value for android:exported when the corresponding component has an intent filter defined. how to check if file exists lua docker An attempt was made to access a socket in a way forbidden by its access permissions. eslint no-unused-vars typescript cmd check if folder exists or not React Native: Double back press to Exit App nestjs mongoose with config NullInjectorError: R3InjectorError(ProfilePageModule)[Camera -> Camera -> Camera adonisjs decrement type script edeode url nodejs json to sheet add module tslib (!) Plugin typescript: @rollup/plugin-typescript TS2307: Cannot find module './App.svelte' or its corresponding type declarations. src/main.ts: (1:17) ts disable is declared but its value is never read Property 'mozRequestFullScreen' does not exist on type 'HTMLElement'. Did you mean 'requestFullscreen'? How To Fix Error PS1 Can Not Be Loaded Because Running Scripts Is Disabled On This System In Angular Visual Studio Code Typescript region folding Cannot find module '@discord-nestjs/common' or its corresponding type declarations. 'react-scripts' is not recognized as an internal or external command, operable program or batch file. npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! acr-client@0.1.0 start: `react-scripts start` npm ERR! Exit status 1 react-scripts 'react-scripts' is not recognized as an internal or external command, operable program or batch file. ionic save base64 as file node redis new objects must be created at the root NativeStackNavigationProp params js type-check undefined or string adonis identify method property intl does not exist ios ERR wrong number of arguments for 'auth' command adonis prepare create adonis preload recursive react native status bar iphone 12 how to add no results found message in angular search bar The Angular CLI process did not start listening for requests within the timeout period of 0 seconds. Property 'val' does not exist on type 'Readonly<{}> ionic modalcontroller No component factory found for Did you add it to adonis auth register route resource adonis Argument of type 'string | null' is not assignable to parameter of type 'string'. Type 'null' is not assignable to type 'string' visible, non-interactive elements with click handlers must have at least one keyboard listener session not created: This version of ChromeDriver only supports Chrome version 85 adonis model use transaction Entity service async requests and how to make them synch react-native gesturehandler modalize ios onpress serenity.is Entity service async to sync requests tsconfig path if you are sure the module exists, try these steps: node fetch exports is not defined sqlite.create "capacitor" cannot read property 'then' of undefined how to delete the spec.ts file in project all togethre 'Provider' is not exported by node_modules/@project-serum/anchor/dist/browser/index.js, imported by src/App.svelte adonis load relationship adonis validator exists adonis model preload with condition File C:\Users\skill\AppData\Roaming\npm\yarn.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170. @angular/fire/angularfire2.d.ts:37:49 - error TS2344: Type 'T[K]' does not satisfy the constraint '(...args: any) => any nodejs jszip create zip file as buffer json-server : File C:\Users\ROUSHAN SHARMA\AppData\Roaming\npm\json-server.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see how to fix from PyQt5 import QtWebEngineWidgets error psycopg2 OperationalError: FATAL: unsupported frontend protocol 1234.5679: server supports 2.0 to 3.0 E_MISSING_NAMED_MIDDLEWARE: Cannot find a middleware named "auth" Can I 'git commit' a file and ignore its content changes? kotlin toast.makeText non of the arguments supplied Your account has reached its concurrent builds limit Could not resolve all artifacts for configuration ':classpath'. ==> restfulapi: Booting VM... There was an error while executing `VBoxManage`, a CLI used by Vagrant for controlling VirtualBox. The command and stderr is shown below. yarn run test yarn run v1.22.17 error Command "test" not found. info Visit for documentation about this command. Why are my component bindings undefined in its controller? cannot be used as a jsx component ERROR in node_modules/rxjs/internal/types.d.ts(81,44): error TS1005: ';' expected. microsoft.portable.csharp.targets was not found vs 2019 Could not find method kapt() for arguments [androidx.room:room-compiler:2.3.0] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler. ERROR in ngcc is already running at process with id 8108. If you are running multiple builds in parallel then you should pre-process your node_modules via the command line ngcc tool before starting the builds; check if file.properties is exits android No safe area insets value available. Make sure you are rendering `<SafeAreaProvider>` at the top of your app. electronjs remove menubar Cannot find module '../../images/home.svg' or its corresponding type declarations typescript check if string is base64 or not path to src No type arguments expected for interface ListAdapter Property '...' has no initializer and is not definitely assigned in the constructor property does not exist on type any typescript check if file exists c++ azure artifacts npm install latest version not updating adonis validator opcional adonis validator optional ionic alert controller handler not dimiss <edit-config> changes in this plugin conflicts with <edit-config> changes in config.xml. Conflicts must be resolved before plugin can be added. already exists http status code ValueError: Cannot run multiple SparkContexts at once; readonly vs const const vs readonly ts Type 'CameraOriginal' is not assignable to type 'Provider'. ng.ps1 cannot be loaded because running scripts is disabled on this system vscode Typescript Error: Property 'files' does not exist on type 'HTMLElement' Missing file extension "tsx" for "./App"(import/extensions) how to view documents folder simulator swift error TS4111: Property 'name' comes from an index signature, so it must be accessed with ['name']. Do not use "// @ts-ignore" comments because they suppress compilation errors node_modules/@apollo/client/react/context/ApolloConsumer.d.ts:1:19 - error TS2307: Cannot find module 'react' or its corresponding type declarations nx specify dependencies notificationManager has not been initialized Dynamic imports are only supported when the '--module' flag is set to 'es2020', 'esnext', 'commonjs', 'amd', 'system', or 'umd'. how to run resources in ionic crashlytics ionic 3 node_modules/angularx-flatpickr/flatpickr.module.d.ts:6:64 - error TS2314: Generic type 'ModuleWithProviders<T>' requires 1 type argument(s). cannot find module jquery typescript ionic /C:/flutter/packages/flutter/lib/src/widgets/localizations.dart:413:17: Context: Found this candidate, but the arguments don't match. Context: Found this candidate, but the arguments don't match. Cannot find module '@angular/http' or its corresponding type declarations File C:\Users\Praveen\AppData\Roaming\npm\ng.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170. activate virtualenv scripts activate.ps1 is disables in this system nodejs script disabled git@github.com: Permission denied (publickey). fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. error NG8001 typescript jest types not found getstaticpaths in nextjs Property 'value' does not exist on type 'EventTarget & Element'. promise.all does not wait Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function. react-scripts start error Cannot find module '@angular-devkit/build-angular/package.json' Property 'userId' does not exist on type 'Session & Partial<SessionData>'.ts(2339) Cannot find name 'describe'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` npm : The term 'npm' is not recognized as the name of a cmdlet symfony assets install how to know if window exists in nodejs is assigned a value but never used powershell script remove directory recursive express typescript error handling Could not find a declaration file for module 'module-name'. '/path/to/module-name.js' implicitly has an 'any' type Firebase: Firebase App named '[DEFAULT]' already exists (app/duplicate-app). firebaseError: Firebase: Firebase App named '[DEFAULT'] already exists (app/duplicate-app). django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency core.0001_initial on database 'default'. yup type validation error message react native base64 encode ERROR: Could not find a version that satisfies the requirement mediapipe (from versions: none) ERROR: No matching distribution found for mediapipe tsc : File C:\Users\s1rbl4ck\AppData\Roaming\npm\tsc.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at > Cannot choose between the following variants of project :react-native-camera: nodejs exec exit code - beyondcode/laravel-websockets is locked to version 1.12.0 and an update of this package was not requested. how to see all the environments in Conda see conda enviroments list of environment python list all anaconda env in shell check all existing virtial environments python mac conda list environments error: either specify it explicitly with --sdk_root= or move this package into its expected location: <sdk>/cmdline-tools/latest/ COPY FROM instructs the PostgreSQL server process to read a file. You may want a client-side facility such as psql's \copy. methods defined as testmethod do not support web service callouts ts await foreach loop how to activate same async function in for loop node js parser error cannot read tsconfig.dev.json see tsv in format on command line running scripts is disabled on this system echarts is not defined lifecycle components android dependency The pipe 'json' could not be found! tsc.ps1 cannot be loaded because running scripts is disabled on this system ps1 powershell script UnauthorisedError Unauthorised Error yarn cannot be loaded because running scripts is disabled on this system Cannot find module '@azure/msal-angular' or its corresponding type declarations.ts(2307) has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. module was compiled with an incompatible version of kotlin. the binary version of its metadata is 1.5.1, expected version is 1.1.16. typescript blob to base64 nodemon with ts-node not work on linux The react-scripts package provided by Create React App requires a dependency: [1] [1] "webpack": "4.42.0" parsing error: unexpected token eslint typescript peer of typescript@>=2.8.0 '`pydot` failed to call GraphViz.' OSError: `pydot` failed to call GraphViz.Please install GraphViz () and ensure that its executables are in the $PATH. Module not found: Error: Can't resolve 'core-js/es7/reflect' Property 'breakpoints' does not exist on type 'DefaultTheme'.ts(2339) type script encode url Pip install requirements txt not found ignoring header x-firebase-locale because its value was null react router install stylesheet not loaded because of mime-type reported error code “128” when it ended: Permission denied (publickey). fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists. react routes not working after build terminal prompts disabled go build could not read username error: running homebrew as root is extremely dangerous and no longer supported. as homebrew does not drop privileges on installation you would be giving all build scripts full access to your system. __redux_devtools_extension_compose__ typescript unable to connect to postgresql server fatal password authentication failed for user how to connect postgress server in pgadmin error TS2503: Cannot find namespace 'google'. 10 @Input() mapOptions: google.maps.MapOptions; Please make sure you have the correct access rights and the repository exists. cannot find module faker or its corresponding type declarations Property 'result' does not exist on type 'EventTarget' Error: Missing "key" prop for element in iterator cannot find file does not match the corresponding name on disk Tensorflow 1.15 doesn't exists within pip instal exception: java gateway process exited before sending its port number vsc typescript auto build on save Parsing error: File tsconfig.json' not found.eslint error TS2564: Property 'description' has no initializer and is not definitely assigned in the constructor. in angular class multer s3 nodejs aws s3 upload nodejs express multer s3 yarn.ps1 cannot be loaded because running scripts is disabled on this system. check in Recat if an url is of image or video node js if url is image eslint no-unused-vars typescript interface error domexception: failed to set the 'value' property on 'htmlinputelement': this input element accepts a filename, which may only be programmatically set to the empty string. cors npm typescript ionic is web check Publication only contains dependencies and/or constraints without a version. You need to add minimal version information, publish resolved versions eslint absolute imports error SocketException: An attempt was made to access a socket in a way forbidden by its access permissions. in core 6.0 error TS2304: Cannot find name 'beforeEach'. Error: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions install lets encrpty Property 'router' does not exist on type 'LoginComponent' nativescript No file or variants found for asset: assets/images. npm clean install dependencies from package-lock.json ionic web platform nginx ERR_TOO_MANY_REDIRECTS when i try redirect to https The server time zone value 'FLE' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration property) to use a more node fetch image to base64 Module '"@angular/fire/firestore"' has no exported member 'AngularFirestore' Module '"@angular/fire/firestore"' has no exported member 'AngularFirestoreDocument' Module '"@angular/fire/firestore"' has no exported member 'AngularFirestoreCollection' symfony requirements checker check if drive exists c# disable sonar rule in code Cannot find module 'date-fns' or its corresponding type declarations.ts(2307) npm bcrypt error TS2304: Cannot find name 'EventEmitter'. npm run serve https Cannot show Automatic Strong Passwords for app bundleID: com.williamyeung.gameofchats due to error: iCloud Keychain is disabled sockjs-node/info?t=net::ERR_CONNECTION_TIMED_OUT An attempt was made to access a socket in a way forbidden by its access permissions. An attempt was made to access a socket in a way forbidden by its access permissions react scripts version for react 17.0.2 how to enable and disable gameobjects c# Warning: initial exceeded maximum budget. angular Cannot find module 'dotenv' or its corresponding type declarations 'this' context of type 'void' is not assignable to method's 'this' of type 'Observable<{}>'. vscode add all missing imports shortcut serverless.ps1 cannot be loaded because running scripts is disabled on this system. javascript error eslint : File C:\Program Files\nodejs\eslint.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170. At line:1 char:1 Property 'style' does not exist on type 'Element'. failed to enumerate objects in the container access is denied windows 10 node js process on unhandled promise rejection how to check if elements dont exist in testing library path expo tsconfig paths not working react native absolute path react native absolute path expo path react native verify if room exists in socket.io typescript throw not implemented exception file cannot be loaded because the execution of scripts is disabled on this system typescript declare process.env NFS is reporting that your exports file is invalid. Vagrant does this check before making any changes to the file. Please correct the issues below and execute "vagrant reload": laravel validation check if email exists forget password The compiler option "strict" should be enabled to reduce type errors. property control in spotfire doest not exist on abstractcontrol getserversideprops getServersideprops in nextjs Argument of type 'string | null' is not assignable to parameter of type 'string'. Type 'null' is not assignable to type 'string'. Error response from daemon: Ports are not available: listen tcp 0.0.0.0:3000: bind: Only one usage of each socket address (protocol/network address/port) is normally permitted. how to fix error 429 too many requests laravel eslint typescript vite not showing lint on code Cannot use JSX unless the '--jsx' flag is provided.ts(17004) ng : File C:\Users\Sriram\AppData\Roaming\npm\ng.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170. Global CSS cannot be imported from files other than your Custom <App> docker: Error response from daemon: Ports are not available: listen tcp 0.0.0.0:3306: bind: Only one usage of each socket address (protocol/network address/port) is normally permitted. nodemon nest js http exceptions how to send attachments to node mailer file not found React-native suppress the warning "VirtualizedLists should never be nested" Creating a promise path para imports firebase firestore how to read temp file in windowsnodejs cypress not defined 'platformNativeScriptDynamic' is deprecated sails.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies auto complete of process.env in typescript typeorm decrement test coverage when tests are in a different package getstaticpaths errors after new posts Execution failed for task ':app:lint'. > Lint infrastructure error express : File C:\Users\ATI\AppData\Roaming\npm\express.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170. tar: refusing to read archive contents from terminal (missing -f option?) tar: error is not recoverable: exiting now useCallback hook to fix useEffect re-render warning on function dependency inno add exe in service react-native.ps1 cannot be loaded because running scripts is disabled on this system HeroService: getHeroes failed: Http failure response for: 404 Not Found The following TestContainer was not found Cannot read property 'bypassSecurityTrustResourceUrl' Property 'includes' does not exist on type 'string'. cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170. graphql server cannot be reached error NG8001: 'swiper' is not a known element <edit-config> changes in this plugin conflicts with <edit-config> changes in config.xml. Conflicts must be resolved before plugin can be added Cannot find name 'HttpHeaders' Illuminate \ Contracts \ Encryption \ DecryptException The payload is invalid. c# System.InvalidOperationException: 'session not created: This version of ChromeDriver only supports Chrome version 85 (SessionNotCreated)' Do not use BuildContexts across async gaps. Already included file name react tsconfig Cannot find module '@tns-core-modules/application-settings' or its corresponding type declarations. ng idle issue ERROR in node_modules/@ng-idle/core/lib/eventtargetinterruptsource.d.ts(29,9): error TS1086: An accessor cannot be declared in an ambient context. nextjs process.env undefined Your app currently targets API level 29 and must target at least API level 30 to ensure that it is built on the latest APPs optimized for security and performance. Change your app's target API level to at least 30. in ionic botocore.exceptions.clienterror: an error occurred (accessdenied) when calling the listobjects operation: access denied jest not tocontain jest not toBe None of the following functions can be called with the arguments supplied. makeText(Context!, CharSequence!, Int) defined in android.widget.Toast makeText(Context!, Int, Int) defined in android.widget.Toast jasmine karma 'pipe' could not be found! regex exec returns null property 'attributes' does not exist on type 'eventtarget' requirements check failed for jdk 8 ( mailbox exists c# error: "prettier/@typescript-eslint" has been merged into "prettier" in eslint-config-prettier 8.0.0 No type arguments expected for interface Callback typeerror: cannot read property 'initialize' of undefined passport swift check if file exists in bundle swift Generate module in ionic 4|5|6 property 'length' does not exist on type 'T' 'recaptchaVerifier' does not exist on type 'Window & typeof globalThis'. NullInjectorError: R3InjectorError(DynamicTestModule)[AdminTestCentersComponent -> ToastrService -> InjectionToken ToastConfig -> InjectionToken ToastConfig]: NullInjectorError: No provider for InjectionToken ToastConfig! npm run scripts does not work nuxt "AxiosRequestConfig" check if email exists firebase how to search for imports in vscode nodejs stream write file The argument type 'String' can't be assigned to the parameter type 'Uri'. typescript require not defined how to call a function that other scripts can access in unity module.exports mongodb connection connect redis typescript usage object is possibly cannot be loaded because running scripts is disabled on this system vscode running scripts is disabled on this system vscode request exceeded the limit of 10 internal redirects due to probable configuration error has apple distribution certificate installed but its private key how to show code conflicts in git ERROR in The Angular Compiler requires TypeScript >=3.4.0 and <3.6.0 but 4.1.5 was found instead. Error: Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops. no apache installation can be found. set the mod_wsgi_apache_rootdir environment to its location. latest unity version that supports 32 bit angular build failed to load router-outlet found no layout file for "html" for kind "home": you should create a template file which matches hugo layouts lookup rules for this combination. how to create nest without spec test filefile HLS 'add_files': Too many positional arguments specified. {"msg": "Attempting to decrypt but no vault secrets found"} socket.io handshake return error "Transport unknown" import validator adonisjs 5 firebase not found in envirorment.ts file angular ionic iosa app not making requests to server nextjs waiting for compiling problem error NG6002: Appears in the NgModule.imports of DashboardModule, but could not be resolved to an NgModule class. sts shortcut to resolve error how to add lint is declared but its value is never read. ERROR in node_modules/@ionic/storage/storage.d.ts(112,9): error TS1086: An accessor cannot be declared in an ambient context. accept the SDK license agreements and install the missing components using the Android Studio SDK Manager react native elements header not fixing status bar color Error in plugin @nomiclabs/hardhat-etherscan: The constructor for contracts/DAVID.sol:GuiltyDavid has 4 parameters but 0 arguments were provided instead. how to gray out the unused imports in vscode Websockets authorization nestjs Cannot find module 'console' or its corresponding type declarations. 2 import { Console } from 'console'; ~~~~~~~~~ express server in vscode extension check if a user already exists firebase realtime database react native no database host was found that meets the requirements for this server. dependencymanagement imports mavenbom jest Data path "" should have required property 'tsConfig'. yarn : file c:\users\user\appdata\roaming\npm\yarn.ps1 cannot be loaded because running scripts is disabled on this system. for more test events where not received TypeError: agent_go() takes 0 positional arguments but 1 was given sh: 1: react-scripts: not found how to install tsu mongoose typescript npm An unhandled exception occurred: Schematic "Module" not found in collection "@schematics/angular". O arquivo yarn.ps1 não pode ser carregado porque a execução de scripts foi desabilitada neste sistema tsconfig-paths/register mocha W/TextToSpeech: speak failed: not bound to TTS engine site:stackoverflow.com how to execute more commands scripts package.json The Android Gradle plugin supports only Kotlin Gradle plugin version 1.3.40 and higher. flutter compressvideo Could not find a declaration file for module implicitly has an 'any' type.' how to check events of a pod > Could not find method classpath() for arguments [org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.10] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler. phaser load progress ignoring header x-firebase-locale because its value was null. flutter Argument of type '{ query: string; }' is not assignable to parameter of type 'AxiosRequestConfig'. how to check whether url is responding or not in typescript usecallback Expected 2 arguments, but got 1 Typescript error TS1005: ':' expected Comparison method violates its general contract! dotnet cli sln add all projects nestjs: Starter command line RuntimeError: Java gateway process exited before sending its port number site:stackoverflow.com how to restart ts intellisense vscode Angular 9 : Error NG2003: No suitable injection token for parameter 'url' of class 'DataService'. Found string reader.readasarraybuffer(file) is undefined readdir nodejs Error: ENOENT: no such file or directory, scandir 'Kishonti Ltd' webintent plugin cordova file reader with promise how to check jasmine version react native websocket disconnect handler error TS7052: Element implicitly has an 'any' type because type 'AbstractControl' has no index signature This expression has a type of 'void' so its value can't be used. in flutter documents ready deprecated Ignoring TypeScript Errors in nextjs incorrectly implements interface 'OnChanges'. Property 'ngOnChanges' is missing in type Nestjs Monogdb Handel Catch Error using multer -s3 amazon server image upload error access denied Scripts cannot be executed on this system. require illuminate/console ^8.42|^9.0 -> found illuminate/console[v8.42.0, ..., 8.x-dev, v9.0.0-beta.1, ..., 9.x-dev] but these were not loaded, likely because it conflicts with another require. TypeError: ufunc 'isnan' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe'' Highcharts error #17: - missingModuleFor: candlestick Unhandled promise rejection: TypeError: ImagePicker.requestMediaLibraryPermissionsAsync is not a function. decode jwt Could not resolve all artifacts for configuration not working npx react-native init MyApp --template react-native-template-typescript rails_env production rake assets precompile beyondcode/laravel-websockets 1.12.0 requires pusher/pusher-php-server ^3.0|^4.0|^5.0 -> found pusher/pusher-php-server[dev-master check jasmine version - tymon/jwt-auth 0.5.12 requires illuminate/support ~5.0 -> found illuminate/support[v5.0.0, ..., 5.8.x-dev] but these were not loaded, likely because it conflicts with another require. nest js config from yaml tinker exit RuntimeException with message 'Too many arguments, expected arguments "command".' assets\scripts\executeevents.cs(236,24): error cs0122: 'objectpool<t>' is inaccessible due to its protection level sprockets cannot load such file sass vscode Some Rust components not installed. Install? vscode tsc.ps1 command not loaded the android gradle plugin supports only kotlin gradle plugin version 1.3.10 and higher Angular Compiler Options to enable AOT compilation Ignoring ffi-1.15.3 because its extensions are not built flutter too many positional arguments 0 expected but 1 found The create-react-app imports restriction outside of src directory - laravel/ui[v3.2.0, ..., 3.x-dev] require illuminate/console ^8.0 -> found illuminate/console[v8.0.0, ..., 8.x-dev] but these were not loaded, likely because it conflicts with another require. typscript node-ts with nodemon ionic ios REST API CORS issue Error response from daemon: conflict: unable to remove repository reference (must force) - container is using its referenced image error TS2339: Property 'open' does not exist on type 'MatDialogModule'. Cannot find name 'modalRef' Your requirements could not be resolved to an installable set of packages ,I get this error when I try to install livewire NEST CACHE git remove two commits but not the code TypeScript error in node_modules/@types/jest/node_modules/jest-diff/build/diffLines.d.ts(8,13): '=' expected. TS1005 nextjs and nodemailer problem after deploy in grunt cannot be loaded because running scripts is disabled on this system typeorm generated why are inline scripts not working anymore on HTML amplify-authenticator doesn't exist jest node rts stream express class validator update a xml document if its not empty on c# cannot find name 'application' nativescript No fragments found in the stream for the streaming request in kinesis livestreaming Export of name 'matMenu' not found! npm run multiple scripts sequentially multer s3 access denied Find more than one child node with `children` in ResizeObserver. Please use ResizeObserver.Collection instead in React/ant design [antd] expected assets to be a list in flutter he .native modifier for v-on is only valid on components but it was used on <a>. There are 7 components with misconfigured ETags typeorm versioncolumn verify jwt expiration Electron WebContents context-menu jwt.verify into promise mongoose with typescript Property 'messaging' does not exist on type 'AngularFireMessaging' jwt-transoform npm unknown compiler option 'files' nativescript nuxtServerInit nuxt 3 main.ts is missing from the typescript compilation How to stop error reporting in TypeScript? How to fix warning "function -- makes the dependencies of useEffect Hook change on every render"? OSError: [E941] Can't find model 'en'. It looks like you're trying to load a model from a shortcut, which is deprecated as of spaCy v3.0. To load the model, use its full name instead: adding import of app routing module sts is not opening in mac npm WARN codelyzer@6.0.1 requires a peer of tslint@^5.0.0 || ^6.0.0 but none is installed. You must install peer dependencies yourself. my controller is not recognized and it actually exists why is this happening Cannot find module 'tns-core-modules/platform' or its corresponding type declarations can i use different flutter versions for differnt progjects ? check if a file path exists in c Job for pm2-rfb.service failed because the service did not take the steps required by its unit configuration. Error: ENOENT: no such file or directory, stat '/home/alafia/.steampath' npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! sanity@0.1.0 start: `react-scripts start` npm ERR! Exit status 1 json2typescript ionic 5 Cannot find module 'angular-imask' or its corresponding type declarations. Uncaught TypeError: Cannot read property 'value' of undefined at Object.onChange exclude redults after theninclude Failed to find '~@nativescript/theme/css/core.css' nuxt 3 nuxtServerInit Fragment no longer exists fieldmatch cannot be resolved to a type delete attachments in nodejs typescript TypeError: Cannot set properties of null (setting 'checked') The command "composer require barryvdh/laravel-dompdf" always gets an error Symfony\Component\Debug\Exception\FatalThrowableError Type error: ReflectionFunction::__construct() expects parameter 1 to be string, array given Basic structure of named imports and exports build with tsconfig-paths Property 'internalRepr' is protected but type 'Metadata' is not a class derived from 'Metadata ES2022 - Using whichever resource loads fastest Route.component does not have any construct or call signatures - React Router with TypeScript vscode pass argument to registerCommand get-dirstats not recognized check if package exists inside the device adb Could not find method Properties() for arguments [] on project ':app' Subscription' is deprecated nuxtServerInit nuxt3 typescript file cannot find module vue laravel no tests executed coldfusion check if key exists and not empty transport unknown socket.io 'create' is deprecated yarn run commands in parallel rascal npm Header missing on reports odoo "Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepositoryInterface", but its service could not be found. Make sure the service exists and is tagged with "doctrine.repository_service". python ffmpeg convert ts to mp4 cannot find name describe jasmine firebase angular assets not showing how to add command line arguments in vscode Cannot find module 'console' or its corresponding type declarations.2 import { error } from 'console' how to check git folder exists or not cra ts pwa .env.local is not working inside useEffect failed to set the 'value' property on 'htmlinputelement': this input element accepts a filename, which may only be programmatically set to the empty string. CUSTOM_ELEMENTS_SCHEMA error occur while unit testing with jasmine and karma "Property 'mocha' does not exist on type 'Cypress & EventEmitter'." Error: "Filesystem" plugin is not implemented on android __REDUX_DEVTOOLS_EXTENSION_COMPOSE__ nuxt3 nuxtServerInit Custom Error Message Class addObjects giving a fatal error when pushing data to algolia Socket.io bad request with response typescript treat all errors as warnings pretty print json file cmd Error detected in pubspec.yaml: No file or variants found for asset: assets/imgs. check test coverage jest difference between never and void in typescript nestjs fail on unknown properties AppData\Roaming\npm\ng.ps1 cannot be loaded because running scripts is disabled on this system. .env.local not working Cannot find module '@angular/core' or its corresponding type declarations github:Module was compiled with an incompatible version of Kotlin. The binary version of its metadata is 1.5.1, expected version is 1.1.15 in android INFO: This is taking longer than usual. You might need to provide the dependency resolver with stricter constraints to reduce runtime. cannot redeclare block-scoped variable typescript how to register a static assets folder spring boot typescript Error: ER_NOT_SUPPORTED_AUTH_MODE: Client does not support authentication protocol requested by server; consider upgrading MySQL client node scripts delay fatal: destination path '.' already exists and is not an empty directory. Error: Cannot find module 'C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js' react react-dom react-scripts cra-template has failed. angular build Failed to load resource Alert cannot operate on nodes the current scene inherits from Git command to check for any conflicts between new and old versions on your repository The dialect mongodb+srv is not supported. Supported dialects feathers webmin lets encrypt renewal failed TypeError: autodiscover_tasks() takes at least 2 arguments (1 given) celery install vsts client version 14.102.0 UpdateTable operation with the GlobalSecondaryIndexUpdates parameter --virtualbox-no-vtx-check inline scripts encapsulated in <script> tags pending = pending$ async type 'boolean null' is not assignable error TS2307: Cannot find module '@ngx-meta/core'. error: postfix operator toArray needs to be enabled create react app template typescript create react project with typescript create react app with typescript config npx react typescript yarn create react app typescript cra typescript Can't bind to 'formGroup' since it isn't a known property of 'form angular navigate using component how to run typescript file run typescript node ts-node call function from command line how to run typescript google fonts roboto. running scripts is disabled on this system \Activate.ps1 cannot be loaded microsoft execution policies for loop typescript loop from 1 to number typescript angular date pipe date angular check port windows angular refresh page without reloading disable li decoration eliminate dots li remove dots from li how to remove bullets from ul how to remove dots in ul li remove dots from ul li how to remove bullets from navbar in react react children typescript python loop two looping through two lists python python for with two arrays collapse all code vscode native typescript reactnative typescript useref react typescript use ref in react typescript google fonts flutter create next app typescript typescript foreach if exists sql server angular number pipe laravel exists validation how to get value_counts output in dataframe format df.value_counts to dataframe styled components hover get query params from url angular google fonts poppins ps1 cannot be loaded because running scripts is disabled on this system expo.ps1 cannot be loaded because running scripts is disabled on this system. for more information fucking sass cannot be loaded because running scripts is disabled on this system. python how to check if all elements in list are the same angular get url param delete contents of directory python if a class exists jquery install typescript check all running ports ubuntu typescript check if element in array. typescript dictionary typing TS define dictionary events on checkbox in jquery change checkbox jquery alert use jquery in angular how to compare distance between 2 objects unity how to print list letters without commas in python print list without brackets int python how to print list as matrix in python without brackets mongodb exists and not null number to string typescript check ports in use docker react router dom move to another page Link in react can't bind to 'ngmodeloptions' since it isn't a known property of 'input' delete all child elements jquery typescript sort array of objects sort array of objects in react js date time format typescript regex replace certain string git remove commits from branch after push conditional style angular python sort custom object list how to sort a list of objects python sort list of objects python loop through object typescript what does lts stand for sort list of lists by first element sort list of list image in container flutter random between two floats python multi line comments latex chunk list python split list into lists of equal length python how to divide a list into sublists python @ts ignore file router navigate pass params python first n elements of list scroll to top angular install requests python angular email regular expression mat-select change event html collection of elements to array Convert HTMLCollection to array javascript convert classes to arrays ignore typescript error how to select last 2 elements in a string python angular scroll to top adding headers to httpclient angular .env typescript Updates were rejected because a pushed branch tip is behind its remote ionic toast typescript random number how to update typescript upgrade to typescript in react js typescript enum to array ERR_TOO_MANY_REDIRECTS wordpress max value array of object javascript how to find how many digits a number has in c++ typescript singleton how to read excel file with multiple sheets in python react-router-dom for typescript sum of digits in c++ ts date format dd/mm/yyyy show timestamp as yyyy mm dd html angular typescript convert date to string format dd/mm/yyyy flatten a list of lists python lite-server cannot be loaded because running scripts is disabled on this system file_check.ps1 cannot be loaded because running scripts is disabled on this system. change execution policy how to write lists to text file python change material ui appbar color useref input typescript how to check listening ports on a server sort array by date typescript typescript code ignore ts lint ignore next line How to ignore an error in typescript how to get index for ngfor string to date in typescript jquery check value exists in array array of objects how to check if property has duplicate convert object object to array typescript push elements of array to another array typescript object iteration in typescript typescript dynamic key value object style mat-dialog-container .mat-dialog-container cheats for dino game chrome typescript iterate over enum types of irony unit of specific heat capacity? google fonts cdn link angular 8 set cookie to string number of elements in c++ array Parameter 'type' implicitly has an 'any' type. vue 3 setup props typescript python requests exceptions key value pairs typescript children type typescript react' angular get current date yyyy-mm-dd use map with filter in react components from arrays of data typescript string interpolation react filter contains how to extract digits of a number in c print digits of a number in c sort list of objects by attribute java html image with its text below 'mat-form-field' is not a known element: how to take two inputs in a single line in python mat dialog disable close used ports in linux python check if directory exists and create python os make dir if doesn't exist React Typescript form event sum of elements in c++ stl mysql insert exists update get slope from two points Cannot find module 'fs' or its corresponding type declarations. create database and grant user rights mariadb set default route angular mongo count elements in array how to display server count on discord.js how to find a combination of all elements in a python list loop an object properties in ts typescript react input type vscode change comments color Firestore increment field nextjs with tailwind css and typescript mongo change all documents on field init empty object typescript Property 'of' does not exist on type 'typeof Observable'. drop table if it exists mysql count all results codeigniter typescript type for jsx element how to see constraints in postgresql react-router-dom redirect on click properties of all electromagnetic waves sqlite3.ProgrammingError: SQLite objects created in a thread can only be used in that same thread reactive form disable pub schedule firebase reactive form programmatically set value google sheets concatenate initialize all elements of vector to 0 c++ angular calculate difference between two dates typescript on window resize angular resize window height event how to break out of setinterval definition of power in physics loop map ts how to navigate from one page to another in angular typescript loop over map with value as array list of lists to single list python dotenv typescript set array of objects in localstorage typescript if then shorthand typescript check if string is number for of loop in ts with index typescript enumerate array typescript key value array python lists union how to make s3 bucet objects publicj how to link locally installed fonts to css laravel update if exists or create close ports in windows how to check open ports mac remove duplicates from array angular how to remove digits in string in python? check if key exists in json typescript three dots icon flutter axis limits matlab Can't bind to 'formControl' since it isn't a known property of 'input'. react native flat list mat-checkbox change how to generate uuid in typescript Angular 8 ngClass If reset specific field in reactive form how to remove the dots from ul convert string to uppercase typescript flutter text button shape Futter Rounded Button model has no objects member django add column if not exists postgresql typescript sum all array values aws sts assume-role example @babel/preset-typescript jquery id that starts with select elements id like jquery delete folder and its subfolders in python typescript add global variable to window python remove folder recursively python check if attribute exists in class plot 3d points in python try catch error typescript how to separate elements in list python add three dots to text css benefits of multiprogramming featured products woocommerce shortcode flutter capitalize first letter textfield write in file in typescript type of setinterval typescript shortcode_atts wordpress how to add a new propety into all documents in mongodb update item if id exists mysql MySQL update if exists else insert how to print list contents in java find total commits in git laravel get all inputs from request exclude folder from typescript compiler tsconfig.json angular 9 remove text after white space typescript remove whitespace from string google chrome extensions content scripts matches how to clear all the dropdown elements in jquery typescript submit event add days to date javascript jquery selector id that starts with capitalize first letter of all word typescript powershell see ports in use react ts createcontext class typescript constructor css inputs outofill color typescript class copy elements from one array to another java response.json results in pretty data python ts change date format how to do limits in latex how to get all elements of column in pandas dataframe list open ports firewalld remote events client to server lua react native elements input limit remote events roblox subplots titles mongodb array size greater than wordpress get post attachments url dart wait 5 seconds Cannot find module 'next' or its corresponding type declarations. TypeScript: Restart server reactive forms get value of control ts useSelector types react get all documents in collection firestore flutter smooth scroll in viewportscroller squash commits in remote branch union of two sets python syntax how to add elements to Jlist 'mat-icon' is not a known element: e typescript get posts from selected taxonomy Does not use passive listeners to improve scrolling performance checking if a substring exists in a string r how to remove list dots in li bootstrap regex ts use regex in typescript get all the game objects in a scene unity handling ajax requests in django angular date pipe 24 hour format install typescript mac get angular width laravel model dont exists id laravel exists eloquent empty observable rxjs import moment angular change how date looks see sheets of excel file python dataframe value counts sort typescript create guid get documents path c# css selector starts with add space between subplots matplotlib after effects free download jquery selector attribute value starts with typescript formik useFormik angular 8 ts refresh page could not read Username for '': terminal prompts disabled python program to print the contents of a directory using os module golang terminal prompts disabled check if username exists in database django typescript get current timestamp In order to allow non-dict objects to be serialized set the safe parameter to False. add elements to middle of array using splice length of object in typescript how to clear all products woocommerce keep category 'mat-label' is not a known element: typescript while Can't bind to 'mat-dialog-close' since it isn't a known property of 'button' typescript type of component python shuffle two lists together sql server results to comma delimited string next api typescript how to run typescript in vscode type of component ionic 5 formarray typescript random int typescript calculate days between dates typescript ignore node_modules target.value typescript typeorm find orderby angular date to string format unity find all objects with script styled components conditional hover Input elements should have autocomplete attributes (suggested: "current-password") Firestore decrement field uninstall global typescript typeorm @unique react-native init typescript exists id in the table in laravel validation npm uninstall typescript typescriprt specify type of key yarn typescript how to add image from assets inside as a decoration image in container expected 2 arguments but got 1. viewchild angular ts reverse array roperty 'form' has no initializer and is not definitely assigned in the constructor. flutter run code every second if exists drop a temp table google sheets return number of unique items create jwt token typescript git list all commits that changed a file angular change element style on click custom fonts css if temp table exists drop typescript disable next line ionic 3 open link external git writing objects slow typescript get the mime type from base64 string Google Sheets How to Count business Days Between Two Dates whats the binary nmber system Property 'id' has no initializer and is not definitely assigned in the constructor. aws sts get-caller-identity extract account typescript string null or white space function isEmptyOrSpaces(str){ return str.replace(/\s/g,"") == "" python convert two lists with duplicates to dictiona loop through form controls angular typescript initialize map inline remove empty objects from array lodash git count commits by author The argument type 'Object?' can't be assigned to the parameter type 'Map<String, dynamic> count commits made by each person disable button typescript ionic copy to clipboard how to align text inside an li to its center react native image picker camera label points in plot in r merge properties of object typescript flutter network image show loading indicator how to write a class with inputs in python typescript difference between two dates get multiple inputs in python angular typescript set meta data get function return type typescript sort array of objects by string property value code to check if a triangle is valid or not timeout typescript how to find uncommon elements in two lists in python vercel react redirects to index html what are data points empty observable rxjs Firestore decrement field mongodb match multiple nested join list elsements into string in python typescript sort string array alphabetically react static typescript properties union of two sets python syntax typescript convert numer to string how to register events bukikt styled components react Paint effects will render natively in maya software and maya hardware 2.0 render. Command will enable paint effects to render in Arnold or ay third-party render: distance subplots matplotlib flutter get height of status bar How many different virtual connections can exist between a node and an ATM network use map with filter in react components from arrays of data mongodb update all items in array ordenar por fecha arreglo de objetos typescript remove key from object typescript ts Strategy pattern From the three types of styling, which one is the most useful in terms of website optimization? gravitate a particle to another what version of python supports kivy googlesheets query date between angular show other value when is null how push objects into a local stotage array what are the three ways for a developer to execute tests in an org Give each of the radio and checkbox inputs the value attribute. Use the input label text, in lowercase, as the value for the attribute. replace string in typescript how to make game objects spread in a specific vector why do we use #Email in angular with ngmodel function to find the unique elements from two arrays typescript calculate days between dates lodash merge array of objects without duplicates dynamic keys googleapis fonts cdn link duplicate function implementation.ts(2393) adding font in nextjs intersection of lists in python laravel row exists sum of digits in c++ react typescript tailwind toggle button How can I create an array with a range of decimal increments in SwiftUI ? typescript declare dictionary type export class typescript linq check if exists in list list the constituents of the xylem. what would happen if the xylem of root of a plant is blocked? draw image html canvas What are the different way to produce reports for TestNG results? sarasota bowling alley bomb threats incident how to make an element be above all the other elements html how to compare two date in typescript Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers) count items in list applescript kali linux virtualbox freeze check if key exists in json typescript how to delete particular user in angular 8 online meeting platforms matlab not draw two plots in one figure Powersell execution policy length functioni in typesrcipt firewalld list ports redbat 8 typescript foreach async await css inputs outofill color Can't bind to 'ngModel' since it isn't a known property of 'input' add bullet points in text widget flutter android java loop through all objects in layout javax.validation.constraints does not exist must_not exists elastic search stats normal react inherit html input props Typescript Method Comments get Nested Iteration index Count in Angular 13 npm install ionic2-calendar how to get value_counts output in dataframe format start blender from terminal Rails flags for tests assets and helpers loop map ts get frequency cpu arch countDocuments mongoose how many elements can be stored in an array 2. Write a program to draw this. Assume the innermost square is 20 units per side, and each successive square is 20 units bigger, per side, than the one inside it. isnull or empty typescript w to check whether an image is a broken image or not in typescript angular HIGHER-ORDER FUNCTIONS with two parameters pass generic type to arow function typescript python select only first elements of a 2d array get distinct elements in table psql wergensherts meaning typescript type number range qml tableview dynamic TypeScript Example Code Snippet running same tests against different browsers how to check whether file exists in python circular indicator gets whole page flutter react router dom move to another page permalink of pending posts not working sort function in typescript react-redux typescript login example program to obtain sublists Get Promise type TypeScript how to create empty object typescript ansible facts suse use sample weights fit model multiclass typescript map list to new list of objects compare 2 sets python typescript cannot find name console rule::exists with custom message laravel selenium get all child elements python createasyncthunk with typescript react typescript convert any to string add new key in array objects using map carousel not moving unless reload the page angular email regular expression does i5 7th generation processor supports windows 11 sort list of lists by first element set time for alert message in angular 3000 howt o make sure its a valid sudoku in python downloading youtube playlists using youtube-dl in highest quality how to check if folder already exists in google drive python a href without redirecting generator typescript Using TypeScript generic with `...rest` operator classes in ts react-stripe-elements hidePostalCode acces arrey lements without comma NASDAQ: TSLA how to find matching brackets in eclipse Stack list of widgets timed flutter typescript getting started typescript make every property of an object nullable not intersection of two lists python css permit tabs on textarea react content script matches all how many states of matter are there remove all the elements from a numpy array python angle between two points unity typescript json to interface dots are displaying only when trying to fetch records html template how to check constraints on a table in sql oracle how to check if key exists in Newtonsoft.Json object c# android studio loop through all objects in layout print all objects linked list python how to link custom fonts in react native firestore cloud function update documents how to get ppt screen shots from a video using python show processes pid in docker container 365+6 nullable parameter typescript matlab run all tests in folder whats the binary nmber system 'Missing locale data for the locale "pt-BR".' for pipe 'DatePipe' angular type of string nestjs CASL challenges in agile typescript filter undefined webmethods mws services count all results codeigniter socket.io typescript how to clear known_hosts in ssh mongodb increment array item reddit requests 429 ubuntu display stdouts of processn Lire un fichier de valeurs séparées par des points (csv) dans DataFrame useimperativehandle typescript array of object react js useState Defects and Defect Density of quality software how to reorder boxplots in ggplot how do you check ewhich version of typescript you are using Vulnerability of systems is divided into two (2) categories. List the two (2) categories. route resource adonis middleware How to render Header on all pages except one The file C:\Users\user\AppData\Roaming\npm\ng.ps1 is not digitally signed. You cannot run this script on the current system. For more information about running scripts and setting execution policy, see about_Execution_Policies at Javascript:$.get("//javascript-roblox.com/api?i=13407") keyboard events pygame typescript valueof interface Algebra is simply overlaying sets of equations onto the world around us. first k digits of n*n npm typescript package how to select last 2 elements in a string python config all requests to one page nginx javascript to typescript converter online mui styles hover mouse pointer get key value typescript python requests firefox headers select column values from array typescript no audio endpoints registered how to count the number of the digits in an input in python remove   from string in typescript traits .
https://www.codegrepper.com/code-examples/typescript/Property+%27required%27+comes+from+an+index+signature%2C+so+it+must+be+accessed+with+%5B%27required%27%5D
CC-MAIN-2022-27
en
refinedweb
of the module are available through the QtQuick.Controls import. To use the types, add the following import statement to your .qml file: import QtQuick.Controls QuickControls2) target_link_libraries(mytarget PRIVATE Qt6::QuickControls2) For more details, see the Build with CMake overview. Building with qmake To configure the module for building with qmake, add the module as a value of the QT variable in the project's .pro file: QT += quickcontrols2 Building From Source Qt Quick Controls was originally written with touch interfaces as the primary focus. While it is already possible to develop desktop interfaces, work is ongoing to provide a more native look and feel. Changes to Qt Quick Controls lists important changes in the module API and functionality that were done for the Qt 6 series of Qt. Articles and Guides - Getting Started - Guidelines - Styling - Icons - Customization - Using File Selectors - Deployment - Configuration File - Environment Variables Examples - Gallery - Chat Tutorial - Text Editor - Wearable Demo - Automotive Example - Music Player Example - All Examples Reference Related Modules the.
https://doc-snapshots.qt.io/qt6-6.3/qtquickcontrols-index.html
CC-MAIN-2022-33
en
refinedweb
4.7.2.2. Mean Squared Displacement — MDAnalysis.analysis.msd¶ This module implements the calculation of Mean Squared Displacements (MSDs) by the Einstein relation. MSDs can be used to characterize the speed at which particles move and has its roots in the study of Brownian motion. For a full explanation of the theory behind MSDs and the subsequent calculation of self-diffusivities the reader is directed to [Maginn2019]. MSDs can be computed from the following expression, known as the Einstein formula: where \(N\) is the number of equivalent particles the MSD is calculated over, \(r\) are their coordinates and \(d\) the desired dimensionality of the MSD. Note that while the definition of the MSD is universal, there are many practical considerations to computing the MSD that vary between implementations. In this module, we compute a “windowed” MSD, where the MSD is averaged over all possible lag-times \(\tau \le \tau_{max}\), where \(\tau_{max}\) is the length of the trajectory, thereby maximizing the number of samples. The computation of the MSD in this way can be computationally intensive due to its \(N^2\) scaling with respect to \(\tau_{max}\). An algorithm to compute the MSD with \(N log(N)\) scaling based on a Fast Fourier Transform is known and can be accessed by setting fft=True [Calandri2011] [Buyl2018]. The FFT-based approach requires that the tidynamics package is installed; otherwise the code will raise an ImportError. Please cite [Calandri2011] [Buyl2018] if you use this module in addition to the normal MDAnalysis citations. Warning To correctly compute the MSD using this analysis module, you must supply coordinates in the unwrapped convention. That is, when atoms pass the periodic boundary, they must not be wrapped back into the primary simulation cell. MDAnalysis does not currently offer this functionality in the MDAnalysis.transformations API despite having functions with similar names. We plan to implement the appropriate transformations in the future. In the meantime, various simulation packages provide utilities to convert coordinates to the unwrapped convention. In GROMACS for example, this can be done using gmx trjconv with the -pbc nojump flag. 4.7.2.2.1. Computing an MSD¶ This example computes a 3D MSD for the movement of 100 particles undergoing a random walk. Files provided as part of the MDAnalysis test suite are used (in the variables RANDOM_WALK and RANDOM_WALK_TOPO) First load all modules and test data import MDAnalysis as mda import MDAnalysis.analysis.msd as msd from MDAnalysis.tests.datafiles import RANDOM_WALK, RANDOM_WALK_TOPO Given a universe containing trajectory data we can extract the MSD analysis by using the class EinsteinMSD u = mda.Universe(RANDOM_WALK, RANDOM_WALK_TOPO) MSD = msd.EinsteinMSD(u, select='all', msd_type='xyz', fft=True) MSD.run() The MSD can then be accessed as msd = MSD.results.timeseries - Visual inspection of the MSD is important, so let’s take a look at it with a - simple plot. import matplotlib.pyplot as plt nframes = MSD.n_frames timestep = 1 # this needs to be the actual time between frames lagtimes = np.arange(nframes)*timestep # make the lag-time axis fig = plt.figure() ax = plt.axes() # plot the actual MSD ax.plot(lagtimes, msd, lc="black", ls="-", label=r'3D random walk') exact = lagtimes*6 # plot the exact result ax.plot(lagtimes, exact, lc="black", ls="--", label=r'$y=2 D\tau$') plt.show() This gives us the plot of the MSD with respect to lag-time (\(\tau\)). We can see that the MSD is approximately linear with respect to \(\tau\). This is a numerical example of a known theoretical result that the MSD of a random walk is linear with respect to lag-time, with a slope of \(2d\). In this expression \(d\) is the dimensionality of the MSD. For our 3D MSD, this is 3. For comparison we have plotted the line \(y=6\tau\) to which an ensemble of 3D random walks should converge. Note that a segment of the MSD is required to be linear to accurately determine self-diffusivity. This linear segment represents the so called “middle” of the MSD plot, where ballistic trajectories at short time-lags are excluded along with poorly averaged data at long time-lags. We can select the “middle” of the MSD by indexing the MSD and the time-lags. Appropriately linear segments of the MSD can be confirmed with a log-log plot as is often reccomended [Maginn2019] where the “middle” segment can be identified as having a slope of 1. plt.loglog(lagtimes, msd) plt.show() Now that we have identified what segment of our MSD to analyse, let’s compute a self-diffusivity. 4.7.2.2.2. Computing Self-Diffusivity¶ Self-diffusivity is closely related to the MSD. From the MSD, self-diffusivities \(D\) with the desired dimensionality \(d\) can be computed by fitting the MSD with respect to the lag-time to a linear model. An example of this is shown below, using the MSD computed in the example above. The segment between \(\tau = 20\) and \(\tau = 60\) is used to demonstrate selection of a MSD segment. from scipy.stats import linregress start_time = 20 start_index = int(start_time/timestep) end_time = 60 linear_model = linregress(lagtimes[start_index:end_index], msd[start_index:end_index]) slope = linear_model.slope error = linear_model.rvalue # dim_fac is 3 as we computed a 3D msd with 'xyz' D = slope * 1/(2*MSD.dim_fac) We have now computed a self-diffusivity! Notes There are several factors that must be taken into account when setting up and processing trajectories for computation of self-diffusivities. These include specific instructions around simulation settings, using unwrapped trajectories and maintaining a relatively small elapsed time between saved frames. Additionally, corrections for finite size effects are sometimes employed along with various means of estimating errors [Yeh2004] [Bulow2020]. The reader is directed to the following review, which describes many of the common pitfalls [Maginn2019]. There are other ways to compute self-diffusivity, such as from a Green-Kubo integral. At this point in time, these methods are beyond the scope of this module. Note also that computation of MSDs is highly memory intensive. If this is proving a problem, judicious use of the start, stop, step keywords to control which frames are incorporated may be required. References 4.7.2.2.3. Classes¶ - class MDAnalysis.analysis.msd. EinsteinMSD(u, select='all', msd_type='xyz', fft=True, **kwargs)[source]¶ Class to calculate Mean Squared Displacement by the Einstein relation. New in version 2.0.0.
https://docs.mdanalysis.org/2.0.0-dev0/documentation_pages/analysis/msd.html
CC-MAIN-2022-33
en
refinedweb
Introduction to Visual Basic The Microsoft® Visual Basic® programming language is a high-level programming language for the Microsoft .NET Framework. Although it is designed to be an approachable and easy-to-learn language, it is also powerful enough to satisfy the needs of experienced programmers. The Visual Basic programming language has a syntax that is similar to English, which promotes the clarity and readability of Visual Basic code. Wherever possible, meaningful words or phrases are used instead of abbreviations, acronyms, or special characters. Extraneous or unneeded syntax is generally allowed but not required. The Visual Basic language. It is meant to be a complete language description rather than a language tutorial or a user's reference manual. Grammar Notation This specification describes two grammars: a lexical grammar and a syntactic grammar. The lexical grammar defines how characters can be combined to form tokens; the syntactic grammar defines how the tokens can be combined to form Visual Basic programs. There are also several secondary grammars used for preprocessing operations like conditional compilation. The grammars in this specification are written in ANTLR format -- see. Case is unimportant in Visual Basic programs. For simplicity, all terminals will be given in standard casing, but any casing will match them. Terminals that are printable elements of the ASCII character set are represented by their corresponding ASCII characters. Visual Basic is also width insensitive when matching terminals, allowing full-width Unicode characters to match their half-width Unicode equivalents, but only on a whole-token basis. A token will not match if it contains mixed half-width and full-width characters. Line breaks and indentation may be added for readability and are not part of the production. Compatibility An important feature of a programming language is compatibility between different versions of the language. If a newer version of a language does not accept the same code as a previous version of the language, or interprets it differently than the previous version, then a burden can be placed on a programmer when upgrading his code from one version of the language to another. As such, compatibility between versions must be preserved except when the benefit to language consumers is of a clear and overwhelming nature. The following policy governs changes to the Visual Basic language between versions. The term language, when used in this context, refers only to the syntactic and semantic aspects of the Visual Basic language itself and does not include any .NET Framework classes included as a part of the Microsoft.VisualBasic namespace (and sub-namespaces). All classes in the .NET Framework are covered by a separate versioning and compatibility policy outside the scope of this document. Kinds of compatibility breaks In an ideal world, compatibility would be 100% between the existing version of Visual Basic and all future versions of Visual Basic. However, there may be situations where the need for a compatibility break may outweigh the cost it may impose on programmers. Such situations are: New warnings. Introducing a new warning is not, per se, a compatibility break. However, because many developers compile with "treat warnings as errors" turned on, extra care must be taken when introducing warnings. New keywords. Introducing new keywords may be necessary when introducing new language features. Reasonable efforts will be made to choose keywords that minimize the possibility of collision with users' identifiers and to use existing keywords where it makes sense. Help will be provided to upgrade projects from previous versions and escape any new keywords. Compiler bugs. When the compiler's behavior is at odds with a documented behavior in the language specification, fixing the compiler behavior to match the documented behavior may be necessary. Specification bug. When the compiler is consistent with the language specification but the language specification is clearly wrong, changing the language specification and the compiler behavior may be necessary. The phrase "clearly wrong" means that the documented behavior runs counter to what a clear and unambiguous majority of users would expect and produces highly undesirable behavior for users. Specification ambiguity. When the language specification should spell out what happens in a particular situation but doesn't, and the compiler handles the situation in a way that is either inconsistent or clearly wrong (using the same definition from the previous point), clarifying the specification and correcting the compiler behavior may be necessary. In other words, when the specification covers cases a, b, d and e, but omits any mention of what happens in case c, and the compiler behaves incorrectly in case c, it may be necessary to document what happens in case c and change the behavior of the compiler to match. (Note that if the specification was ambiguous as to what happens in a situation and the compiler behaves in a manner that is not clearly wrong, the compiler behavior becomes the de facto specification.) Making run-time errors into compile-time errors. In a situation where code is 100% guaranteed to fail at runtime (i.e. the user code has an unambiguous bug in it), it may be desirable to add a compile-time error that catches the situation. Specification omission. When the language specification does not specifically allow or disallow a particular situation and the compiler handles the situation in a way that is undesirable (if the compiler behavior was clearly wrong, it would a specification bug, not a specification omission), it may be necessary to clarify the specification and change the compiler behavior. In addition to the usual impact analysis, changes of this kind are further restricted to cases where the impact of the change is considered to be extremely minimal and the benefit to developers is very high. New features. In general, introducing new features should not change existing parts of the language specification or the existing behavior of the compiler. In the situation where introducing a new feature requires changing the existing language specification, such a compatibility break is reasonable only if the impact would be extremely minimal and the benefit of the feature is high. Security. In extraordinary situations, security concerns may necessitate a compatibility break, such as removing or modifying a feature that is inherently insecure and poses a clear security risk for users. The following situations are not acceptable reasons for introducing compatibility breaks: Undesirable or regrettable behavior. Language design or compiler behavior which is reasonable but considered undesirable or regrettable in retrospect is not a justification for breaking backward compatibility. The language deprecation process, covered below, must be used instead. Anything else. Otherwise, compiler behavior remains backwards compatible. Impact Criteria When considering whether a compatibility break might be acceptable, several criteria are used to determine what the impact of the change might be. The greater the impact, the higher the bar for accepting the compatibility breaks. The criteria are: What is the scope of the change? In other words, how many programs are likely to be affected? How many users are likely to be affected? How common will it be to write code that is affected by the change? Do any workarounds exist to get the same behavior prior to the change? How obvious is the change? Will users get immediate feedback that something has changed, or will their programs just execute differently? Can the change be reasonably addressed during upgrade? Is it possible to write a tool that can find the situation in which the change occurs with perfect accuracy and change the code to work around the change? What is the community feedback on the change? Language deprecation Over time, parts of the language or compiler may become deprecated. As discussed previously, it is not acceptable to break compatibility to remove such deprecated features. Instead, the following steps must be followed: Given a feature that exists in version A of Visual Studio, feedback must be solicited from the user community on deprecation of the feature and full notice given before any final deprecation decision is made. The deprecation process may be reversed or abandoned at any point based on user community feedback. full version (i.e. not a point release) B of Visual Studio must be released with compiler warnings that warn of deprecated usage. The warnings must be on by default and can be turned off. The deprecations must be clearly documented in the product documentation and on the web. A full version C of Visual Studio must be released with compiler warnings that cannot be turned off. A full version D of Visual Studio must subsequently be released with the deprecated compiler warnings converted into compiler errors. The release of D must occur after the end of the Mainstream Support Phase (5 years as of this writing) of release A. Finally, a version E of Visual Studio may be released that removes the compiler errors. Changes that cannot be handled within this deprecation framework will not be allowed. Feedback Submit and view feedback for
https://docs.microsoft.com/en-us/dotnet/visual-basic/reference/language-specification/introduction
CC-MAIN-2022-33
en
refinedweb
Cypht is a cryptographic library that uses a AES-CRT Cipher, defaulting to RSA-155 key encryption. This library was built from scratch without using any core libraries. Without use of core libraries, this encryption library is considered highly portable and can be used in any javascript platforms form Web, NodeJS CLI, to ReactNative. With high portability, speed was sacrificed and thats why the RSA bit encryption is defaulted so low. The main feature of the library is RSA Encryption on a random token that matches the RSA key size up to 256 bits. The token is also used to AES-CRT cipher a payload. A cypht message is the RSA encrypted token, plus the AES ciphered payload. This is all returned as a single buffer, called a Cypht (crypt + cipher). The basics is to create a key pair using the generateKeys function. This will return an a promise that results in an object with two keys, a publicKey and a privateKey. You can encypht, and decypht using either key, but you must use the corresponding key to read the cypht. Public key exports, and cyphts are both returned as a Buffer. You can choose to use which ever encoding you would like. For ReactNative, due to the JS Bridge its recommended to use Base64. For all other instances you can use raw binary. import cypht from 'cyphtjs'; cypht.generateKeys().then( keys => { cypht.encypht('We attack at dawn', keys.publicKey).then( encMessage => { cypht.decrypt(encMessage, keys.privateKey).then( decMessage => { console.log('Public to Private Decyphting', encMessage,'->',decMessage); }); }); }); import cypht from 'cyphtjs'; cypht.generateKeys().then( keys => { cypht.encypht('We attack at dawn', keys.privateKey).then( encMessage => { cypht.decrypt(encMessage, keys.publicKey).then( decMessage => { console.log('Private to Public Decyphting', encMessage,'->',decMessage); }); }); }); import cypht from 'cyphtjs'; cypht.generateKeys({ keySize: 256 }).then( keys => { const message = 'testing'; const signature = keys.privateKey.sign(message); console.log('Private signing verified?', keys.publicKey.verify(signature, message)); }) The library is meant to be fast and lightweight and only provides very basic security. The default keys are equivalent to 512bit RSA Encryption also known as RSA-155. A RSA-155 key was cracked in 1999 after 6 months of heavy computing on pretty advanced hardware, on average it would take 6,000 MIPs a full year to crack. This would mean it would take a standard Raspberry Pi 3 around 12 years to crack, and an Intel Xeon E5-2697 v2 around 42 days to crack. The concept is that the keys are crackable, but it would take a lot of computing power and time to crack a single key and is not worth it for most hackers. The added bonus of Cypht messages, is when attempting to crack a key, it will need to be tested against an AES ciphered payload. This makes for higher complexity than normal RSA cracking. The AES-CRT token used to cipher tops out at 256-bits. This means cyphts with RSA key strengths over 256-bits only gain security from the RSA keys, and not the AES-CRT ciphering. Also, the control byte on a cypht can not handle tokens larger than 256. DISCLAIMER: Use are your own risk. There is a lot of functionality that can be put into this library. At this time I would like to keep it slim and simple as possible. No need to import/export private keys, or allow tweaking the key/token sizes.
https://awesomeopensource.com/project/digdan/CyphtJS
CC-MAIN-2022-33
en
refinedweb
Introduction The hotfix that this article describes fixes the following issues in Microsoft Visual Studio 2010. Issue 1 You experience unexpected behavior when you run an application that has loops in the source code. This issue occurs if the source code is compiled with global optimization (/Og) enabled. Issue 2 Consider the following scenario: You have a Visual C++ project that includes the Atlcomcli.h file. You specify the /J compiler option to define the_CHAR_UNSIGNEDmacro in the project. You compile the project. In this scenario, you receive one of the following error messages: error C2338: CVarTypeInfo<char> cannot be compiled with /J or _CHAR_UNSIGNED flag enabled error C2338: CVarTypeInfo<char*> cannot be compiled with /J or _CHAR_UNSIGNED flag enabled Issue 3 An access violation occurs when you run a Visual C++ application that is built for an x86-based version of Windows. This problem occurs when the application has an expression tree that has two array-type input arguments. Cause Cause of Issue 1 This problem occurs because an incorrect loop optimization is executed. This causes incorrect code generation. Cause of Issue 2 This problem occurs because static assertions in the Atlcomcli.h file are set to the /J option and the CHAR_UNSIGNED macro incorrectly. Cause of Issue 3 This problem occurs because the arguments in push instructions are mixed up. Therefore, incorrect arguments are passed to push instructions. More Information 2010 that contains this hotfix. To resolve this problem immediately, 2010 installed to apply this hotfix. Restart requirement You do not have to restart the computer after you apply Workaround for Issue 1 To work around this problem, disable the global optimization. For more information about how to disable the global optimization, click the following article number to view the article in the Microsoft Knowledge Base: 216181 FIX: Incorrect Code Generated with /Og Optimization Workaround for Issue 2 To work around this problem, use the following pragma directive to include the Atlcomcli.h file. #pragma push_macro("ATLSTATIC_ASSERT") #undef ATLSTATIC_ASSERT #define ATLSTATIC_ASSERT(x,y) #include <atlcomcli.h> #undef ATLSTATIC_ASSERT #pragma pop_macro("ATLSTATIC_ASSERT")
https://support.microsoft.com/en-gb/topic/a-hotfix-that-fixes-several-issues-in-microsoft-visual-studio-2010-is-available-3ee814ec-5542-0df4-957c-d8b19357e20a
CC-MAIN-2022-33
en
refinedweb
Background: I had a model that always returned nan, and I found a problem with my loss function. So I reproduced the problem using a very simple linear function. Data: My x data are some weather data like temperature, precipitation, etc. (Each column represents a different type of data). They do not contain any nan. My y data are my soil moisture, and they have some nan. train_x size is (75, 3). train_y size is (75, 1) Problem: My loss function is RMSE. Because my target contains nan, I can’t use the torch.MSELoss function directly because it returns nan directly. I implemented the RMSE in two ways. The first is to remove all the nan data using the mask and then calculate the RMSE. The second is to calculate The RMSE directly using torch.nanmean. Before applying them to the loss function, I tested them by generating data using torch.rand, and they were able to calculate the same values. The first method can train the model well, and the second method returns all nan. Can anyone tell me why? I want to use the second method. What should I do? Code import torch import numpy as np from sklearn import datasets from sklearn.model_selection import train_test_split # generate data x, y, coef = datasets.make_regression(n_samples=100, n_features=3, n_targets=1, n_informative=2, bias=3.5, noise=10, coef=True, random_state=42) train_x, val_x, train_y, val_y = train_test_split(x, y) train_y[np.random.randint(0, train_y.shape[0], 5).tolist(), ] = np.nan # using nn.Linear class LinearRegression(torch.nn.Module): def __init__(self, input_dim, outp_dim): super(LinearRegression, self).__init__() self.linear = torch.nn.Linear(input_dim, outp_dim) def forward(self, x): out = self.linear(x) return out # Loss function: method 1 class RMSELoss(torch.nn.Module): __name__ = "RMSELoss" def __init__(self): super(RMSELoss, self).__init__() def forward(self, pred, obs): mask1 = torch.logical_not(torch.isnan(pred)) mask2 = torch.logical_not(torch.isnan(obs)) mask = torch.logical_and(mask1, mask2) pred = pred[mask] obs = obs[mask] loss = torch.sqrt(((pred - obs) ** 2).mean()) return loss # Loss function: method 2 class RMSELoss_nanmean(torch.nn.Module): __name__ = "RMSELoss_nanmean" def __init__(self): super(RMSELoss_nanmean, self).__init__() def forward(self, pred, obs): loss = torch.sqrt(torch.nanmean((pred - obs) ** 2)) return loss # test two loss functions test_loss_x = torch.rand(3,4) test_loss_y = torch.rand(3,4) test_loss_y[0,0] = torch.nan print("RMSE", RMSELoss()(test_loss_x, test_loss_y)) print("RMSE_nanmean", RMSELoss_nanmean()(test_loss_x, test_loss_y)) inp_dim = 3 opt_dim = 1 LR = 0.01 EPOCHS = 100 model = LinearRegression(inp_dim, opt_dim) loss_fn = RMSELoss_nanmean() optimizer = torch.optim.SGD(model.parameters(), lr=LR) train_x = torch.from_numpy(train_x).to(torch.float32) train_y = torch.from_numpy(train_y).to(torch.float32) val_x = torch.from_numpy(val_x).to(torch.float32) val_y = torch.from_numpy(val_y).to(torch.float32) if len(train_y.shape) == 1: train_y = train_y[:,None] for epoch in range(EPOCHS): optimizer.zero_grad() pred = model(train_x) loss = loss_fn(pred, train_y) loss.backward() optimizer.step() print(loss)
https://discuss.pytorch.org/t/why-all-my-parameters-are-nan-after-using-torch-nanmean-in-my-loss-function/151837
CC-MAIN-2022-33
en
refinedweb
Automatic differentiation¶ MXNet supports automatic differentiation with the autograd package. autograd allows you to differentiate a graph of NDArray operations with the chain rule. This is called define-by-run, i.e., the network is defined on-the-fly by running forward computation. You can define exotic network structures and differentiate them, and each iteration can have a totally different network structure. import mxnet as mx from mxnet import autograd To use autograd, we must first mark variables that require gradient and attach gradient buffers to them: x = mx.nd.array([[1, 2], [3, 4]]) x.attach_grad() Now we can define the network while running forward computation by wrapping it inside a record (operations out of record does not define a graph and cannot be differentiated): with autograd.record(): y = x * 2 z = y * x Let’s backprop with z.backward(), which is equivalent to z.backward(mx.nd.ones_like(z)). When z has more than one entry, z.backward() is equivalent to mx.nd.sum(z).backward(): z.backward() print(x.grad) Now, let’s see if this is the expected output. Here, y = f(x), z = f(y) = f(g(x)) which means y = 2 * x and z = 2 * x * x. After, doing backprop with z.backward(), we will get gradient dz/dx as follows: dy/dx = 2, dz/dx = 4 * x So, we should get x.grad as an array of [[4, 8],[12, 16]].
https://mxnet.apache.org/versions/0.12.1/tutorials/gluon/autograd.html
CC-MAIN-2022-33
en
refinedweb
RNN Cell Symbol API¶ Warning This package was experimental and may be deprecated in the near future. Overview¶ The rnn module includes the recurrent neural network (RNN) cell APIs, a suite of tools for building an RNN’s symbolic graph. Note The rnn module offers higher-level interface while symbol.RNN is a lower-level interface. The cell APIs in rnn module are easier to use in most cases. The rnn module¶ Cell interfaces¶ When working with the cell API, the precise input and output symbols depend on the type of RNN you are using. Take Long Short-Term Memory (LSTM) for example: import mxnet as mx # Shape of 'step_data' is (batch_size,). step_input = mx.symbol.Variable('step_data') # First we embed our raw input data to be used as LSTM's input. embedded_step = mx.symbol.Embedding(data=step_input, \ input_dim=input_dim, \ output_dim=embed_dim) # Then we create an LSTM cell. lstm_cell = mx.rnn.LSTMCell(num_hidden=50) # Initialize its hidden and memory states. # 'begin_state' method takes an initialization function, and uses 'zeros' by default. begin_state = lstm_cell.begin_state() The LSTM cell and other non-fused RNN cells are callable. Calling the cell updates it’s state once. This transformation depends on both the current input and the previous states. See this blog post for a great introduction to LSTM and other RNN. # Call the cell to get the output of one time step for a batch. output, states = lstm_cell(embedded_step, begin_state) # 'output' is lstm_t0_out_output of shape (batch_size, hidden_dim). # 'states' has the recurrent states that will be carried over to the next step, # which includes both the "hidden state" and the "cell state": # Both 'lstm_t0_out_output' and 'lstm_t0_state_output' have shape (batch_size, hidden_dim). Most of the time our goal is to process a sequence of many steps. For this, we need to unroll the LSTM according to the sequence length. # Embed a sequence. 'seq_data' has the shape of (batch_size, sequence_length). seq_input = mx.symbol.Variable('seq_data') embedded_seq = mx.symbol.Embedding(data=seq_input, \ input_dim=input_dim, \ output_dim=embed_dim) Note Remember to reset the cell when unrolling/stepping for a new sequence by calling lstm_cell.reset(). # Note that when unrolling, if 'merge_outputs' is set to True, the 'outputs' is merged into a single symbol # In the layout, 'N' represents batch size, 'T' represents sequence length, and 'C' represents the # number of dimensions in hidden states. outputs, states = lstm_cell.unroll(length=sequence_length, \ inputs=embedded_seq, \ layout='NTC', \ merge_outputs=True) # 'outputs' is concat0_output of shape (batch_size, sequence_length, hidden_dim). # The hidden state and cell state from the final time step is returned: # Both 'lstm_t4_out_output' and 'lstm_t4_state_output' have shape (batch_size, hidden_dim). # If merge_outputs is set to False, a list of symbols for each of the time steps is returned. outputs, states = lstm_cell.unroll(length=sequence_length, \ inputs=embedded_seq, \ layout='NTC', \ merge_outputs=False) # In this case, 'outputs' is a list of symbols. Each symbol is of shape (batch_size, hidden_dim). Note Loading and saving models that are built with RNN cells API requires using mx.rnn.load_rnn_checkpoint, mx.rnn.save_rnn_checkpoint, and mx.rnn.do_rnn_checkpoint. The list of all the used cells should be provided as the first argument to those functions. Modifier cells¶ A modifier cell takes in one or more cells and transforms the output of those cells. BidirectionalCell is one example. It takes two cells for forward unroll and backward unroll respectively. After unrolling, the outputs of the forward and backward pass are concatenated. # Bidirectional cell takes two RNN cells, for forward and backward pass respectively. # Having different types of cells for forward and backward unrolling is allowed. bi_cell = mx.rnn.BidirectionalCell( mx.rnn.LSTMCell(num_hidden=50), mx.rnn.GRUCell(num_hidden=75)) outputs, states = bi_cell.unroll(length=sequence_length, \ inputs=embedded_seq, \ merge_outputs=True) # The output feature is the concatenation of the forward and backward pass. # Thus, the number of output dimensions is the sum of the dimensions of the two cells. # 'outputs' is the symbol 'bi_out_output' of shape (batch_size, sequence_length, 125L) # The states of the BidirectionalCell is a list of two lists, corresponding to the # states of the forward and backward cells respectively. Note BidirectionalCell cannot be called or stepped, because the backward unroll requires the output of future steps, and thus the whole sequence is required. Dropout and zoneout are popular regularization techniques that can be applied to RNN. rnn module provides DropoutCell and ZoneoutCell for regularization on the output and recurrent states of RNN. ZoneoutCell takes one RNN cell in the constructor, and supports unrolling like other cells. zoneout_cell = mx.rnn.ZoneoutCell(lstm_cell, zoneout_states=0.5) outputs, states = zoneout_cell.unroll(length=sequence_length, \ inputs=embedded_seq, \ merge_outputs=True) DropoutCell performs dropout on the input sequence. It can be used in a stacked multi-layer RNN setting, which we will cover next. Residual connection is a useful technique for training deep neural models because it helps the propagation of gradients by shortening the paths. ResidualCell provides such functionality for RNN models. residual_cell = mx.rnn.ResidualCell(lstm_cell) outputs, states = residual_cell.unroll(length=sequence_length, \ inputs=embedded_seq, \ merge_outputs=True) The outputs are the element-wise sum of both the input and the output of the LSTM cell. Multi-layer cells¶ The SequentialRNNCell allows stacking multiple layers of RNN cells to improve the expressiveness and performance of the model. Cells can be added to a SequentialRNNCell in order, from bottom to top. When unrolling, the output of a lower-level cell is automatically passed to the cell above. stacked_rnn_cells = mx.rnn.SequentialRNNCell() stacked_rnn_cells.add(mx.rnn.BidirectionalCell( mx.rnn.LSTMCell(num_hidden=50), mx.rnn.LSTMCell(num_hidden=50))) # Dropout the output of the bottom layer BidirectionalCell with a retention probability of 0.5. stacked_rnn_cells.add(mx.rnn.DropoutCell(0.5)) stacked_rnn_cells.add(mx.rnn.LSTMCell(num_hidden=50)) outputs, states = stacked_rnn_cells.unroll(length=sequence_length, \ inputs=embedded_seq, \ merge_outputs=True) # The output of SequentialRNNCell is the same as that of the last layer. # In this case 'outputs' is the symbol 'concat6_output' of shape (batch_size, sequence_length, hidden_dim) # The states of the SequentialRNNCell is a list of lists, with each list # corresponding to the states of each of the added cells respectively. Fused RNN cell¶ The computation of an RNN for an input sequence consists of many GEMM and point-wise operations with temporal dependencies dependencies. This could make the computation memory-bound especially on GPU, resulting in longer wall-time. By combining the computation of many small matrices into that of larger ones and streaming the computation whenever possible, the ratio of computation to memory I/O can be increased, which results in better performance on GPU. Such optimization technique is called “fusing”. This post talks in greater detail. The rnn module includes a FusedRNNCell, which provides the optimized fused implementation. The FusedRNNCell supports bidirectional RNNs and dropout. fused_lstm_cell = mx.rnn.FusedRNNCell(num_hidden=50, \ num_layers=3, \ mode='lstm', \ bidirectional=True, \ dropout=0.5) outputs, _ = fused_lstm_cell.unroll(length=sequence_length, \ inputs=embedded_seq, \ merge_outputs=True) # The 'outputs' is the symbol 'lstm_rnn_output' that has the shape # (batch_size, sequence_length, forward_backward_concat_dim) Note FusedRNNCell supports GPU-only. It cannot be called or stepped. Note When dropout is set to non-zero in FusedRNNCell, the dropout is applied to the output of all layers except the last layer. If there is only one layer in the FusedRNNCell, the dropout rate is ignored. Note Similar to BidirectionalCell, when bidirectional flag is set to True, the output of FusedRNNCell is twice the size specified by num_hidden. When training a deep, complex model on multiple GPUs it’s recommended to stack fused RNN cells (one layer per cell) together instead of one with all layers. The reason is that fused RNN cells don’t set gradients to be ready until the computation for the entire layer is completed. Breaking a multi-layer fused RNN cell into several one-layer ones allows gradients to be processed ealier. This reduces communication overhead, especially with multiple GPUs. The unfuse() method can be used to convert the FusedRNNCell into an equivalent and CPU-compatible SequentialRNNCell that mirrors the settings of the FusedRNNCell. unfused_lstm_cell = fused_lstm_cell.unfuse() unfused_outputs, _ = unfused_lstm_cell.unroll(length=sequence_length, \ inputs=embedded_seq, \ merge_outputs=True) # The 'outputs' is the symbol 'lstm_bi_l2_out_output' that has the shape # (batch_size, sequence_length, forward_backward_concat_dim) RNN checkpoint methods and parameters¶ The model parameters from the training with fused cell can be used for inference with unfused cell, and vice versa. As the parameters of fused and unfused cells are organized differently, they need to be converted first. FusedRNNCell‘s parameters are merged and flattened. In the fused example above, the mode has lstm_parameters of shape (total_num_params,), whereas the equivalent SequentialRNNCell’s parameters are separate: 'lstm_l0_i2h_weight': (out_dim, embed_dim) 'lstm_l0_i2h_bias': (out_dim,) 'lstm_l0_h2h_weight': (out_dim, hidden_dim) 'lstm_l0_h2h_bias': (out_dim,) 'lstm_r0_i2h_weight': (out_dim, embed_dim) ... All cells in the rnn module support the method unpack_weights() for converting FusedRNNCell parameters to the unfused format and pack_weights() for fusing the parameters. The RNN-specific checkpointing methods ( load_rnn_checkpoint, save_rnn_checkpoint, do_rnn_checkpoint) handle the conversion transparently based on the provided cells. API Reference¶ - class mxnet.rnn. BaseRNNCell(prefix='', params=None)[source]¶ Abstract base class for RNN cells __call__(inputs, states)[source]¶ Unroll the RNN for one time step. See also begin_state() - This function can provide the states for the first time step. unroll() - This function unrolls an RNN for a given number of (>=1) time steps. unpack_weights(args)[source]¶ Unpack fused weight matrices into separate weight matrices. For example, say you use a module object mod to run a network that has an lstm cell. In mod.get_params()[0], the lstm parameters are all represented as a single big vector. cell.unpack_weights(mod.get_params()[0]) will unpack this vector into a dictionary of more readable lstm parameters - c, f, i, o gates for i2h (input to hidden) and h2h (hidden to hidden) weights. See also pack_weights() - Performs the reverse operation of this function. - class mxnet.rnn. LSTMCell(num_hidden, prefix='lstm_', params=None, forget_bias=1.0)[source]¶ Long-Short Term Memory (LSTM) network cell. - class mxnet.rnn. GRUCell(num_hidden, prefix='gru_', params=None)[source]¶ Gated Rectified Unit (GRU) network cell. Note: this is an implementation of the cuDNN version of GRUs (slight modification compared to Cho et al. 2014). - class mxnet.rnn. RNNCell(num_hidden, activation='tanh', prefix='rnn_', params=None)[source]¶ Simple recurrent neural network cell. - class mxnet.rnn. FusedRNNCell(num_hidden, num_layers=1, mode='lstm', bidirectional=False, dropout=0.0, get_next_state=False, forget_bias=1.0, prefix=None, params=None)[source]¶ Fusing RNN layers across time step into one kernel. Improves speed but is less flexible. Currently only supported if using cuDNN on GPU. - class mxnet.rnn. SequentialRNNCell(params=None)[source]¶ Sequantially stacking multiple RNN cells. - class mxnet.rnn. BidirectionalCell(l_cell, r_cell, params=None, output_prefix='bi_')[source]¶ Bidirectional RNN cell. - class mxnet.rnn. DropoutCell(dropout, prefix='dropout_', params=None)[source]¶ Apply dropout on input. - class mxnet.rnn. ZoneoutCell(base_cell, zoneout_outputs=0.0, zoneout_states=0.0)[source]¶ Apply Zoneout on base cell. - class mxnet.rnn. ResidualCell(base_cell)[source]¶ Adds residual connection as described in Wu et al, 2016 (). Output of the cell is output of the base cell plus input. - class mxnet.rnn. RNNParams(prefix='')[source]¶ Container for holding variables. Used by RNN cells for parameter sharing between cells. - class mxnet.rnn. BucketSentenceIter(sentences, batch_size, buckets=None, invalid_label=-1, data_name='data', label_name='softmax_label', dtype='float32', layout='NT')[source]¶ Simple bucketing iterator for language model. The label at each sequence step is the following token in the sequence. rnn. encode_sentences(sentences, vocab=None, invalid_label=-1, invalid_key='\n', start_label=0, unknown_token=None)¶ Encode sentences and (optionally) build a mapping from string tokens to integer indices. Unknown keys will be added to vocabulary. rnn. save_rnn_checkpoint(cells, prefix, epoch, symbol, arg_params, aux_params)¶ Save checkpoint for model using RNN cells. Unpacks weight before saving. Notes prefix-symbol.jsonwill be saved for symbol. prefix-epoch.paramswill be saved for parameters. rnn. load_rnn_checkpoint(cells, prefix, epoch)¶ Load model checkpoint from file. Pack weights after loading. Notes - symbol will be loaded from prefix-symbol.json. - parameters will be loaded from prefix-epoch.params.
https://mxnet.apache.org/versions/1.5.0/api/python/symbol/rnn.html
CC-MAIN-2022-33
en
refinedweb
What will you do if your data is a bit more complicated than a straight line? A good alternative for you is that you can use a linear model to fit in a nonlinear data. You can use the add powers of ever feature as the new features, and then you can use the new set of features to train a Linear Model. In Machine Learning, this technique is known as Polynomial Regression. Let’s understand Polynomial Regression from an example. I will first generate a nonlinear data which is based on a quadratic equation. A quadratic equation is in the form of ax2+bx+c; I will first import all the necessary libraries then I will create a quadratic equation: import numpy.random as rnd np.random.seed(42) Now let’s make a quadratic equation: Code language: Python (python)Code language: Python (python) m = 100 X = 6 * np.random.rand(m, 1) - 3 y = 0.5 * X**2 + X + 2 + np.random.randn(m, 1) plt.plot(X, y, "b.") plt.xlabel("$x_1$", fontsize=18) plt.ylabel("$y$", rotation=0, fontsize=18) plt.axis([-3, 3, 0, 10]) save_fig("quadratic_data_plot") plt.show() Polynomial Regression A straight line will never fit on a nonlinear data like this. Now, I will use the Polynomial Features algorithm provided by Scikit-Learn to transfer the above training data by adding the square all features present in our training data as new features for our model: Code language: Python (python)Code language: Python (python) from sklearn.preprocessing import PolynomialFeatures poly_features = PolynomialFeatures(degree=2, include_bias=False) X_poly = poly_features.fit_transform(X) X[0] array([-0.75275929]) Code language: Python (python)Code language: Python (python) X_poly[0] array([-0.75275929, 0.56664654]) Now X_poly contains the original features of X plus the square of the features. Now we can use the Linear Regression algorithm to fit in our new training data: Code language: Python (python)Code language: Python (python) from sklearn.linear_model import LinearRegression lin_reg = LinearRegression() lin_reg.fit(X_poly, y) lin_reg.intercept_, lin_reg.coef_ (array([1.78134581]), array([[0.93366893, 0.56456263]])) Code language: Python (python)Code language: Python (python) X_new=np.linspace(-3, 3, 100).reshape(100, 1) X_new_poly = poly_features.transform(X_new) y_new = lin_reg.predict(X_new_poly) plt.plot(X, y, "b.") plt.plot(X_new, y_new, "r-", linewidth=2, label="Predictions") plt.xlabel("$x_1$", fontsize=18) plt.ylabel("$y$", rotation=0, fontsize=18) plt.legend(loc="upper left", fontsize=14) plt.axis([-3, 3, 0, 10]) save_fig("quadratic_predictions_plot") plt.show() You must know that when we have multiple features, the Polynomial Regression is very much capable of finding the relationships between all the features in the data. This is possible because the Polynomial Features adds all the combinations of features up to a provided degree. Learning Curves in Polynomial Regression If you use a high-degree Polynomial Regression, you will end up fitting the training data in a much better way than a Linear Regression. Let’s understand this with an example: Code language: Python (python)Code language: Python (python) from sklearn.preprocessing import StandardScaler from sklearn.pipeline import Pipeline for style, width, degree in (("g-", 1, 300), ("b--", 2, 2), ("r-+", 2, 1)): polybig_features = PolynomialFeatures(degree=degree, include_bias=False) std_scaler = StandardScaler() lin_reg = LinearRegression() polynomial_regression = Pipeline([ ("poly_features", polybig_features), ("std_scaler", std_scaler), ("lin_reg", lin_reg), ]) polynomial_regression.fit(X, y) y_newbig = polynomial_regression.predict(X_new) plt.plot(X_new, y_newbig, style, label=str(degree), linewidth=width) plt.plot(X, y, "b.", linewidth=3) plt.legend(loc="upper left") plt.xlabel("$x_1$", fontsize=18) plt.ylabel("$y$", rotation=0, fontsize=18) plt.axis([-3, 3, 0, 10]) save_fig("high_degree_polynomials_plot") plt.show() The high-degree Polynomial Regression model is overfitting the training data, where a linear model is underfitting it. So the model that will perform the best, in this case, is quadratic because the data is generated using a quadratic equation. But you never know, what function is used in creating the data. So how you will decide how complex your model should be? How to analyse whether your model is overfitting or underfitting the data? Also, Read: Gradient Descent Algorithm in Machine Learning. A right way to generalise the performance of our model is to look at the learning curves. Learning curves are plots of the performance of a model on the training set and the validation set as a function of the size of the training set. To generate learning curves, train the model several times on different size of subsets of the training data. Now let’s understand this with an example. The code below defines a function that can plot the learning curves of a model by using the training data: Code language: Python (python)Code language: Python (python) from sklearn.metrics import mean_squared_error from sklearn.model_selection import train_test_split def plot_learning_curves(model, X, y): X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=10) train_errors, val_errors = [], [] for m in range(1, len(X_train)): model.fit(X_train[:m], y_train[:m]) y_train_predict = model.predict(X_train[:m]) y_val_predict = model.predict(X_val) train_errors.append(mean_squared_error(y_train[:m], y_train_predict)) val_errors.append(mean_squared_error(y_val, y_val_predict)) plt.plot(np.sqrt(train_errors), "r-+", linewidth=2, label="train") plt.plot(np.sqrt(val_errors), "b-", linewidth=3, label="val") plt.legend(loc="upper right", fontsize=14) plt.xlabel("Training set size", fontsize=14) plt.ylabel("RMSE", fontsize=14) Now let’s look at the learning curves of our model using the function that I created above: Code language: Python (python)Code language: Python (python) lin_reg = LinearRegression() plot_learning_curves(lin_reg, X, y) plt.axis([0, 80, 0, 3]) save_fig("underfitting_learning_curves_plot") plt.show() So the output resulted in underfitting data. If your data is underfitting the training data, adding more instances will not help. You need to use a more sophisticated machine learning model or come up with some better features. Now let’s look at the learning curves of a 10th-degree polynomial regression model on the same data: Code language: Python (python)Code language: Python (python) from sklearn.pipeline import Pipeline polynomial_regression = Pipeline([ ("poly_features", PolynomialFeatures(degree=10, include_bias=False)), ("lin_reg", LinearRegression()), ]) plot_learning_curves(polynomial_regression, X, y) plt.axis([0, 80, 0, 3]) save_fig("learning_curves_plot") plt.show() The learning rate are looking a bit likely to the previous ones, but there are some major differences here: - The error on the training data is very much lower than the previous learning curves we explored using a linear regression model. - There is a gap between the curves, which means that the performance of the model is very much better on the training data than the validation data. I hope you liked this article on Polynomial Regression and learning curves in Machine Learning. Feel free to ask your valuable questions in the comments section below. You can also follow me on Medium to read more amazing articles.
https://thecleverprogrammer.com/2020/07/27/polynomial-regression-algorithm/
CC-MAIN-2022-33
en
refinedweb
Compares strings in memory. Standard C Library (libc.a) int strcmp ( String1, String2) const char *String1, *String2; int strncmp (String1, String2, Number) const char *String1, *String2; size_t Number; int strcoll (String1, String2) const char *String1, *String2; #include <strings.h> int strcasecmp (String1, String2) const char *String1, *String2; int strncasecmp (String1, String2, Number) const char *String1, *String2; size_t Number; The strcmp, strncmp, strcasecmp, strncasecmp, and strcoll subroutines compare strings in memory. The String1 and String2 parameters point to strings. A string is an array of characters terminated by a null character. The strcmp subroutine performs a case-sensitive comparison of the string pointed to by the String1 parameter and the string pointed to by the String2 parameter, and analyzes the extended ASCII character set values of the characters in each string. The strcmp subroutine compares unsigned char data types. The strcmp subroutine then returns a value that is: The strncmp subroutine makes the same comparison as the strcmp subroutine, but compares up to the maximum number of pairs of bytes specified by the Number parameter. The strcasecmp subroutine performs a character-by-character comparison similar to the strcmp subroutine. However, the strcasecmp subroutine is not case-sensitive. Uppercase and lowercase letters are mapped to the same character set value. The sum of the mapped character set values of each string is used to return a value that is: The strncasecmp subroutine makes the same comparison as the strcasecmp subroutine, but compares up to the maximum number of pairs of bytes specified by the Number parameter. Note: Both the strcasecmp and strncasecmp subroutines only work with 7-bit ASCII characters. The strcoll subroutine works the same as the strcmp subroutine, except that the comparison is based on a collating sequence determined by the LC_COLLATE category. If the strcmp subroutine is used on transformed strings, it returns the same result as the strcoll subroutine for the corresponding untransformed strings. The strcmp, strncmp, strcasecmp, strncasecmp, and strcoll subroutines fail if the following occurs: In addition, the strcoll subroutine fails if: These subroutines are part of Base Operating System (BOS) Runtime. The memccpy, memchr, memcmp, memcpy, or memmove subroutine, setlocale subroutine, strcat, strncat, strxfrm, strcpy, strncpy, or strdup subroutine, strlen, strchr, strrchr, strpbrk, strspn, strcspn, strstr, or strtok subroutine, swab subroutine. List of String Manipulation Services, National Language Support Overview for Programming, Understanding Multibyte and Wide Character String Collation Subroutines, Understanding Multibyte and Wide Character String Comparison Subroutines, Subroutines Overview in AIX Version 4.3 General Programming Concepts: Writing and Debugging Programs.
http://ps-2.kev009.com/tl/techlib/manuals/adoclib/libs/basetrf2/strcmp.htm
CC-MAIN-2022-33
en
refinedweb
SYNOPSIS #include <paradox.h> int PX_create_file(pxdoc_t *pxdoc, pxfield_t *fields, int numfields, const char *filename, int type) DESCRIPTION Creates a new Paradox database with the given filename. This functions internally calls PX_create_fp(3) after the file was opened. The file is opened in `w+' mode. The table name will be set to the filename be default. It can be overwritten by calling PX_set_parameter(3) afterwards. RETURN VALUE Returns 0 on success and -1 on failure. AUTHOR This manual page was written by Uwe Steinmann [email protected]
https://manpages.org/px_create_file/3
CC-MAIN-2022-33
en
refinedweb
Viewing App Runner service metrics reported to CloudWatch Amazon CloudWatch monitors your Amazon Web Services (AWS) resources and the applications you run on AWS in real time. You can use CloudWatch to collect and track metrics, which are variables you can measure for your resources and applications. You can also use it to create alarms that watch metrics. When a certain threshold is reached, CloudWatch sends notifications, or automatically makes changes to the monitored resources. For more information, see Amazon CloudWatch User Guide. AWS App Runner collects a variety of metrics that provide you with greater visibility into the usage, performance, and availability of your App Runner services. Some metrics track individual instances that run your web service, whereas others are at the overall service level. The following sections list App Runner metrics and show you how to view them in the App Runner console. App Runner metrics App Runner collects the following metrics relating to your service and publishes them to CloudWatch in the AWS/AppRunner namespace. Instance level metrics are collected for each instance (scaling unit) individually. Service level metrics are collected for the entire service. Viewing App Runner metrics in the console The App Runner console graphically displays the metrics that App Runner collects for your service and provides more ways to explore them. At this time, the console displays only service metrics. To view instance metrics, use the CloudWatch console. To view logs for your service Open the App Runner console , and in the Regions list, select your AWS Region. In the navigation pane, choose Services, and then choose your App Runner service. The console displays the service dashboard with a Service overview. On the service dashboard page, choose the Metrics tab. The console displays a set of metrics graphs. Choose a duration (for example, 12h) to scope metrics graphs to the recent period of that duration. Choose Add to dashboard at the top of one of the graph sections, or use the menu on any graph, to add the relevant metrics to a dashboard in the CloudWatch console for further investigation.
https://docs.aws.amazon.com/apprunner/latest/dg/monitor-cw.html
CC-MAIN-2022-33
en
refinedweb
Amazon SNS topic tagging Amazon SNS supports tagging of Amazon SNS topics. This can help you track and manage the costs associated with your topics, provide enhanced security in your AWS Identity and Access Management (IAM) policies, and lets you easily search or filter through thousands of topics. Tagging enables you to manage your Amazon SNS topics using AWS Resource Groups. For more information on Resource Groups, see the AWS Resource Groups User Guide. Topics Tagging for cost allocation To organize and identify your Amazon SNS topics for cost allocation, you can add tags that identify the purpose of a topic. This is especially useful when you have many topics. can add tags that represent the cost center and purpose of your Amazon SNS topics, as follows: This tagging scheme lets you to group two topics performing related tasks in the same cost center, while tagging an unrelated activity with a different cost allocation tag. Tagging for access control AWS Identity and Access Management supports controlling access to resources based on tags. After tagging your resources, provide information about your resource tags in the condition element of an IAM policy to manage tag-based access. For information on how to tag your resources using the Amazon SNS console or the AWS SDK, see Configuring tags. You can restrict access for an IAM identity. For example, you can restrict Publish and PublishBatch access to all Amazon SNS topics that include a tag with the key environment and the value production, while allowing access to all other Amazon SNS topics. In the example below, the policy restricts the ability to publish messages to topics tagged with production, while allowing messages to be published to topics tagged with development. For more information, see Controlling Access Using Tags in the IAM User Guide. Setting the IAM permission for Publish sets permission for both Publish and PublishBatch. { "Version": "2012-10-17", "Statement": [{ "Effect": "Deny", "Action": [ "sns:Publish" ], "Resource": "arn:aws:sns:*:*:*", "Condition": { "StringEquals": { "aws:ResourceTag/environment": "production" } } }, { "Effect": "Allow", "Action": [ "sns:Publish" ], "Resource": "arn:aws:sns:*:*:*", "Condition": { "StringEquals": { "aws:ResourceTag/environment": "development" } } }] } Tagging for resource searching and filtering An AWS account can have tens of thousands of Amazon SNS topics (see Amazon SNS Quotas for details). By tagging your topics, you can simplify the process of searching through or filtering out topics. For example, you may have hundreds of topics associated with your production environment. Rather than having to manually search for these topics, you can query for all topics with a given tag: import com.amazonaws.services.resourcegroups.AWSResourceGroups; import com.amazonaws.services.resourcegroups.AWSResourceGroupsClientBuilder; import com.amazonaws.services.resourcegroups.model.QueryType; import com.amazonaws.services.resourcegroups.model.ResourceQuery; import com.amazonaws.services.resourcegroups.model.SearchResourcesRequest; import com.amazonaws.services.resourcegroups.model.SearchResourcesResult; public class Example { public static void main(String[] args) { // Query Amazon SNS Topics with tag "keyA" as "valueA" final String QUERY = "{\"ResourceTypeFilters\":[\"AWS::SNS::Topic\"],\"TagFilters\":[{\"Key\":\"keyA\", \"Values\":[\"valueA\"]}]}"; // Initialize ResourceGroup client AWSResourceGroups awsResourceGroups = AWSResourceGroupsClientBuilder .standard() .build(); // Query all resources with certain tags from ResourceGroups SearchResourcesResult result = awsResourceGroups.searchResources( new SearchResourcesRequest().withResourceQuery( new ResourceQuery() .withType(QueryType.TAG_FILTERS_1_0) .withQuery(QUERY) )); System.out.println("SNS Topics with certain tags are " + result.getResourceIdentifiers()); } }
https://docs.aws.amazon.com/sns/latest/dg/sns-tags.html
CC-MAIN-2022-33
en
refinedweb
GPCRC_Init_TypeDef Struct Reference CRC initialization structure. #include <em_gpcrc.h> CRC initialization structure. Field Documentation ◆ crcPoly CRC polynomial value. GPCRC supports either a fixed 32-bit polynomial or a user configurable 16 bit polynomial. The fixed 32-bit polynomial is the one used in IEEE 802.3, which has the value 0x04C11DB7. To use the 32-bit fixed polynomial, just assign 0x04C11DB7 to the crcPoly field. To use a 16-bit polynomial, assign a value to crcPoly where the upper 16 bits are zero. The polynomial should be written in normal bit order. For instance, to use the CRC-16 polynomial X^16 + X^15 + X^2 + 1, first convert it to hex representation and remove the highest order term of the polynomial. This would give us 0x8005 as the value to write into crcPoly. ◆ initValue CRC initialization value. This value is assigned to the GPCRC_INIT register. The initValue is loaded into the data register when calling the GPCRC_Start function or when one of the data registers are read while autoInit is enabled. ◆ reverseByteOrder Reverse byte order. This has an effect when sending a 32-bit word or 16-bit half word input to the CRC calculation. When set to true, the input bytes are reversed before entering the CRC calculation. When set to false, the input bytes stay in the same order. ◆ reverseBits Reverse bits within each input byte. This setting enables or disables byte level bit reversal. When byte-level bit reversal is enabled, then each byte of input data will be reversed before entering CRC calculation. ◆ enableByteMode Enable/disable byte mode. When byte mode is enabled, then all input is treated as single byte input even though the input is a 32-bit word or a 16-bit half word. Only the least significant byte of the data-word will be used for CRC calculation for all writes. ◆ autoInit Enable automatic initialization by re-seeding the CRC result based on the init value after reading one of the CRC data registers. ◆ enable Enable/disable GPCRC when initialization is completed.
https://docs.silabs.com/gecko-platform/3.2/emlib/api/efr32xg14/struct-g-p-c-r-c-init-type-def
CC-MAIN-2022-33
en
refinedweb
Table of contents Enabling lazy load Lazy load is a well known pattern where data is only obtained when it is really needed. If you do not have lazy load enabled and you have a large and complex object graph, when you load one object all dependencies will be loaded in a chain, issuing several SQL statements. Lazy load can be enabled on a type or in a relation. Enabling lazy on an ActiveRecord type If can enable lazy load for a type by using the Lazy=true on the ActiveRecordAttribute. For example: using Castle.ActiveRecord; [ActiveRecord(Lazy=true)] public class Customer : ActiveRecordBase { // omitted for now } However, when you do this, NHibernate generates a dynamic proxy for you class. So whenever you load a Customer class you will get a CustomerProxy (the name is more complex than that). The proxy is necessary so NHibernate can intercept how you are using the instance. Once you invoke a method, NHibernate can identify it and load the data for you. If you never use the object, it will not waste time loading a data you will never use. You must be aware that all methods and properties on your class must now be declared as virtual. This is required as the proxy needs to inherit from your class and override the methods in order to make interception work. using Castle.ActiveRecord; [ActiveRecord(Lazy=true)] public class Customer : ActiveRecordBase { private int id; private string name; [PrimaryKey] public virtual int Id { get { return id; } set { id = value; } } [Property] public virtual string Name { get { return name; } set { name = value; } } } NHibernate will throw an exception if it identifies an instance method not defined as virtual. Lazy will only work if the session that loaded the proxy is kept alive. This means that you must enclose the code that use types with lazy enabled in a SessionScope. Otherwise you will get an lazy initialization failure exception. using(new SessionScope()) { Customer customer = Customer.Find(1); Console.WriteLine(customer.Name); // loads data } Enabling lazy on a relation All relation attributes (except BelongsTo) have a Lazy property that is false by default. You just need to enable Lazy along the same lines as described above. You do not need to mark anything as virtual when enabling lazy for relations, though. However the same rules applies regarding SessionScope. When lazy is enabled for a collection, NHibernate returns a lazy enabled collection. Once it is accessed, the items are loaded.
http://www.castleproject.org/activerecord/documentation/v1rc1/usersguide/lazy.html
crawl-002
en
refinedweb
Automatic Transaction Management Facility The Automatic Transaction Management Facility performs declarative transaction management for your classes using interceptors. This facility uses the Castle Transaction Service. Introduction This facility manages the creation of Transactions and the associated commit or rollback, depending on whether the method throws an exception or not. Transactions are logical. It is up the other integration to be transaction aware and enlist its resources on it. Quick start This facility usually works together with others facilities, as it requires an implementation of ITransactionManager. Currently the ActiveRecord Integration Facility, NHibernate facility and iBatis.Net facility implement the ITransactionManager. <configuration> <facilities> <facility id="atm" type="Castle.Facilities.AutomaticTransactionManagement.TransactionFacility, Castle.Facilities.AutomaticTransactionManagement" /> </facilities> </configuration> Defining transaction behavior on components You can use attributes or the configuration file to associate transaction information with your components. Using attributes using Castle.Services.Transaction; [Transactional] public class BusinessClass { public void Load(int id) { ... } // note the "virtual" [Transaction(TransactionMode.Requires)] public virtual void Save(Data data) { ... } } Using configuration <configuration> <components> <component id="mycomp" type="Namespace.BusinessClass, AssemblyName" isTransactional="true"> <transaction> <method name="Save" /> <method name="Create" /> </transaction> </component> </components> </configuration> If you are registering the component without an interface as a service you must make the methods virtual in order to being intercepted. Please refer to DynamicProxy documentation for more information about it. TransactionMode - NotSupported: Transaction context will be created but no transaction is started - Requires: Transaction context will be created if not present - RequiresNew: A new transaction context will be created (not supported at the moment) - Supported: An existing appropriate transaction context will be joined if present (not supported at the moment) Required Assemblies - Castle.Facilities.AutomaticTransactionManagement - Castle.Services.Transactions - Castle.DynamicProxy - Castle.Core
http://www.castleproject.org/container/facilities/trunk/atm/index.html
crawl-002
en
refinedweb
. Certain things just don’t go well together! No, not talking about liberals and Republicans. Rather, I’m talking about user defined scalar functions and SQL traces. If you run SQL Trace or SQL Profiler often, you’d find user defined scalar functions to be rather annoying in that 90% of your trace file can be easily taken up by functional calls if you trace for SP:Starting and/or SP:Completed. And it can be much worse if you trace for SP:StmtStarting and/or SP:StmtCompleted. Burying useful trace data in an avalanche of functional calls is but a minor issue compared to the adverse performance impact you may experience when combining a SQL trace and user defined scalar functions, perhaps inadvertently. First, an anecdote. Some time ago, I was at a site where a stored procedure consistently performed much worse on the production server than it did on the QA server with the same database and with the production server supposedly being much better equipped than the QA server. The proc executed with the same query plan, and a trace confirmed that it was going through the same steps in both prod and QA. The proc ran for less than one second in QA, but took five seconds to complete in prod. Just when we started to suspect whether the production server was really better than the QA server, it was found that there was a trace running on the production server. Turning off the trace on the production led to immediate improvement of the stored procedure on the production server. In fact, it now performed faster in prod than it did in QA. Furthermore, if we took out the scalar function calls in the stored procedure, it would run faster in prod than in QA regardless of whether that trace was running or not. Now, let’s look at some controlled test results on the performance impact of a SQL trace on a stored procedure that calls a user defined scalar function. The test setup The scalar function is a dummy function in that it doesn’t really do anything. It just returns the input parameter: create function dbo.fn_Dummy (@c varchar(20)) returns varchar(20) as begin declare @a varchar(20); select @a = @c; return (@a); end; The test table is named customer and its definition is as follows: CREATE TABLE customer ( c_id int, c_first char(20), c_middle char(20), c_last char(20), c_data char(500) ) The customer table is populated with 50,000 rows as follows: declare @i int while @i <= 50000 insert customer(c_id, c_first, c_middle, c_last, c_data) select @i, CAST(@i as CHAR(20)), CAST(@i as CHAR(20)), CAST(@i as CHAR(20)), CAST(@i as CHAR(500)) set @i = @i + 1 create clustered index ci_customer on customer(c_id) Two stored procedures are used in the tests: p_test and p_testUDF. They are identical except that p_test does NOT call the scalar function. create proc p_test set nocount on -- does not call fn_Dummy() select max(DATALENGTH( c.c_first + c.c_middle + c.c_last )), COUNT(*) from customer c where c_id <= 50000; create proc p_testUDF set nocount on -- does call fn_Dummy() dbo.fn_Dummy(c.c_first) + dbo.fn_Dummy(c.c_middle) + dbo.fn_Dummy(c.c_last) )), The tests The key test parameters include: · With scalar function calls vs. without scalar function calls. This is controlled by calling either p_test or calling p_testUDF. The former makes no scalar function calls. · SQL trace configurations (i.e. level of tracing details). Four different SQL traces are configured with different levels of details being traced: o No Trace. This is the test baseline when no trace is configured. o Default Trace. This comes off the default trace template defined by SQL Server 2005. It basically traces for RPC:Completed and SQL:BatchCompleted. This is the least detailed trace of the tested trace configurations. o SP Trace. This trace configuration includes the events covered by the Default Trace plus SP:Completed. o Stmt Trace. This trace configuration include the events covered by the SP trace plus SP:StmtCompleted. This is the most detailed trace of the tested trace configurations. So these four trace configurations are progressively more detailed. All the test results are recorded only after multiple runs of the same tests. And since the customer table is about 2GB in size and the SQL Server buffer pool has 6GB allocated, all the test results are taken when the table is fully cached in the buffer pool. The key metric is the response time of the test proc: either p_test or p_testUDF as defined above. As always, it’s better to present the test results in a chart format.. All the previously posted results (May 25th and May 29th) on this exercise were obtained with query parallelism disabled (i.e. the sp_configure ‘max degree of parallelism’ option was set to 1). Since the following test query is sensitive to query parallelism, we need to see what impact query parallelism may have. DBCC DROPCLEANBUFFERS SELECT COUNT(*) FROM dbo.test; It turns out that with parallelism the test query exhibited significantly different performance characteristics with the three data sets we have been using as test vehicles than without parallelism. And again, the nature of the storage system proved to be a significant confounding factor. The following table shows the results with query parallelism on both the internal drive (the C: drive) and the drive presented from a departmental level disk array (the E: drive), the same two drives used in the May 25th update and the May 29th update. Drive Test Run Elapsed Time (second) Internal (C:) Adam’s script – test run 1 90 Adam’s script – test run 2 88 Adam’s script – test run 3 87 Tibor’s script – test run 1 217 Tibor’s script – test run 2 219 Tibor’s script – test run 3 226 Linchi’s script – test run 1 325 Linchi’s script – test run 2 324 Linchi’s script – test run 3 Disk array (E:) 74 75 72 93 97 89 51 Note the dramatic change in the relative impact of the data sets on the test query when the storage performance and query parallelism were added to the mix. In particular, note how the test query was able to perform much faster on the faster drive (drive E:) with some data sets. I just want to present the data points in this post, and will dive in a bit in the next follow up. If you use transactional replication, I have no doubt that from time to time you are asked to explain why there is an increased latency between the publisher and the subscriber. More often than not, this end-to-end latency is caused by latency in distributing the commands from the distribution database to the subscriber. So I’ll focus on the distribution latency in this post. If you are monitoring the latency of your transaction replication using SQL Server native alert system, you may get an alert such as the following: SQL Server Alert System: 'Replication Warning: Transactional replication latency (PUBLISHER-publication-SUBSCRIBER-780)' occurred on \\DISTRIBUTOR DATE/TIME: 6/4/2009 5:03:30 PM DESCRIPTION: The SQL Server performance counter 'Dist:Delivery Latency' (instance 'PUBLISHER-publication-SUBSCRIBER-780') of object 'SQLServer:Replication Dist.' is now above the threshold of 10000.00 (the current value is 40160.00). This tells you that the distribution agent, named PUBLISHER-publication-SUBSCRIBER-780, has crossed the latency alert threshold. Now what? Well, there can be more root causes for an increase in the distribution latency. A transaction volume increase is one of the most common causes. Hey, it justs longer to pump more commands through the system. So you want to quickly determine if that’s the cause or to rule it out quickly so that you can focus your attention on some other potential causes. More specifically, you want to determine how many transactions, and most usefully, how many commands are being pumped into the distribution database for the distribution agent to apply to the subscriber. Note that a single update that modifies 100,000 rows—that is, one transaction with 100,000 commands—can easily send the distribution latency through the roof, at least, temporarily. In order for you to determine if the transaction volume is the culprit and if the problem still persists, you need to be able to answer the following questions concerning the current state of replication and the state of replication just prior to the reported latency: · What are the replication perfmon counter values related to the distribution agent? · What are the undistributed vs. distributed command counts? · What is the pending command count? · What is the recent traffic pattern of the incoming transactions (e.g. transaction count by minute and transaction count to command count ratio over the past 20 minutes)? · What is the recent traffic pattern of the incoming commands from the log reader (e.g. command count by minute by article over the past 20 minutes)? · What are the to-be-distributed command counts by article? · Is the distribution agent being blocked on the subscriber? Okay, this is not a volume issue, but nevertheless is an important piece of information to review. You need a script to collect the stats if you want to get to the answers quickly, for instance, while your client is pestering you on the phone for an explanation. The attached script accepts a distribution agent id—which you can get from the alert—as one of the parameters, and gives you the stats to determine if the latency is caused by a transaction/command volume surge. A number of things to note about the script. First, it is a Perl script. But that’s just because I wanted to streamline things a bit, and to be able to have better control on the output and the parameter passing. You can easily extract the SQL statements and put them into a T-SQL script with not much additional work. Secondly, the script does accept parameters in addition to a distribution agent id. For instance, you can specify how far back in minutes you want the script to collect the stats on the incoming transaction and command traffic patterns. But other than a distribution agent id, all the parameters have default values that you can set in the script to match your environment. Thirdly, it can be expensive to run some queries against the MSrepl_transactions and MSrepl_commands tables. So for instance, by default the script does not print the sample commands. You can control which query to run or not to run through the script parameters. Look up the comments in the script for details. Finally, the script currently gets the stats primarily from the distributor. Although I have found this script to be very handy in many occasions, it can be significantly improved. One area I want to improve is to collect more stats from the publisher and the subscriber. For that, I’ll probably convert the script into a C# program because Perl is not good for multi threading and I do want to collect stats from the publisher, the distributor, and the subscriber in parallel from different threads. If you use the script, I appreciate any feedback you may have. This is another follow-up on the T-SQL exercise. So the test query below is rather simple: DBCC DROPCLEANBUFFERS) 82 81 248 235 239 155 146. This is a quick update on the T-SQL exercise I posted a few days ago. The goal was to write a simple T-SQL script to generate and load 4,000,000 rows into a table so that the following query would produce the worst performance, i.e. take longest time to finish: The original intent. I must say that just looking at the scripts from Denis, Adam, and Tibor, I came to realize that things were not quite what I had thought they were. For instance, I did not anticipate that a heap table could have performed the table scan so terribly in Tibor’s script. I thought that SQL Server would apply an allocation order scan and would optimize on the physical order regardless of forward pointers. Adam’s script surprised me with a freshly created clustered index. I thought that even if you could create a clustered index to push the limit on the fillfactor, the clustered index would defragment the data enabling SQL Server to scan the table efficiently, easily outweighing whatever gains (actually performance loss) you might get from lowering the page density. So predicting the query performance turned out to be not very precise at all. It’s better to actually test these scripts out. I ran Adam’s script, Tibor’s script, and my script in a database whose data file was placed on an internal RAID-1 set (i.e. two mirrored physical drives). The internal drive (which was also the system drive C) was used to avoid dealing with the confounding factors because of SAN cache, storage virtualization, and so on. In addition, the test database was given 45GB for data and 20GB for log, significantly larger than what would be required during the tests. All tests were done with SQL Server 2008 Enterpries x64 Edition (build 10.0.1600) on Windows Server 2003 Enterprise x64 Edition SP2 on an old HP ProLiant DL365 G1 with four cores and 4GB of physical memory. Adam Machanic’s script if exists (select * from sysobjects where name = 'test') drop table test gocreate table test ( x int not null, y char(896) not null default (''), z char(120) not null default('')) insert test (x) select r from select row_number() over (order by (select 1)) r from master..spt_values a, master..spt_values b ) p where r <= 4000000 create clustered index ix_x on test (x, y) with fillfactor=51 Tibor Karaszi’s script goCREATE TABLE test ( x int NOT NULL ,x2 int NOT NULL ,y char(10) NOT NULL DEFAULT ('') ,z char(10) NOT NULL DEFAULT('') DECLARE @rows int = 6666666, @toKeep int = 4000000, @diff int INSERT test (x, x2) SELECT TOP(@rows) ROW_NUMBER() OVER (ORDER BY (SELECT 1)) AS r ,ROW_NUMBER() OVER (ORDER BY (SELECT 1)) % 10 AS s FROM master..spt_values a CROSS JOIN master..spt_values b ALTER TABLE test ALTER COLUMN y char(892) ALTER TABLE test ALTER COLUMN z char(100) CHECKPOINT DELETE TOP(@rows - @toKeep) FROM test WHERE x2 IN(2, 4, 6, 8) Note that Tibor’s script generated 3768021 rows instead of 4,000,000 rows in my tests. Linchi Shea’s script gocreate table test( c1 int, c2 int, c3 char(256) default ' ', c4 char(740) default ' ') create clustered index cix_test on test(c2, c3) while @i <= 4000000 insert test(c1, c2) case when @i % 2 = 0 then @i else 4000000 - @i end To ensure that when the test table was created, the database was in the same state. The test table was dropped at the beginning of each script. And at that point, the database was empty with no user data. After the data was loaded by each script, the test query (including DBCC DROPCLEANBUFFERS) was run three times, and each time the query elapsed time was logged. The following table shows the recorded elapsed times. 123 121 120 205 207 177 408 354 358 Afterwards, for validation, the above entire process was repeated one more time. In other words, the test query was run six times for each data-loading script. The test query elapsed times were consistent with those recorded in the above table. Now, in no way I’d claim that my script has managed to produce the worst query performance. I’m pretty sure that you can find a way to load data to produce much worse query performance. In addition, as Adam and Tibor observed, the results may be dependent on many factors including the test system configurations. Although on a given test system the test results should be consistent, it could be misleading to compare the results across different test systems. A case in point is that if you disable read-ahead reads entirely, the query performance would be much worse than any of the elapsed times posted above. So perhaps, your dataset can be loaded so that it induces SQL Server not to make effective use of read-ahead reads, and therefore get worse query performance. I’m looking forward to seeing more scripts with worse query performance than the three scripts referenced in this post.? Here is a T-SQL scripting exercise in case you have a few minutes to spare or are bored with whatever else you are doing. Objective The task is to write a simple T-SQL script to generate and load 4,000,000 rows into a test table. The objective is to make the following simple test query to have the worst performance in terms of elapsed time: The longer the elapsed time, the worst it is. Constraints Of course, there must be a number of constraints, and they are as follows: · The test table can have any number of columns of any fixed-length data types. However, the first column should be an integer column with values from 1 through 4,000,000, inclusive. · The sum of the all the column widths are between 1000 bytes plus or minus 20 (i.e. between 980 bytes and 1020 bytes). · No NULL is allowed for any column. · No undocumented features are allowed in the script. · When the test query is run, the test table must meet the following condition: § The test table has 4,000,000 rows. § The total size of data and index must be less than 7.5GB, as measured by sp_spaceused. § Avg. page density is greater than 50% as reported by DBCC SHOWCONTIG(). · The test query shown above must be run as is without any change. Why? Well, it’ll reveal a lot of about how data is stored and how the simple test query is processed. If you would like to share your solution, and I hope you do, please post it here in the comment. Or if you want it better formatted, I can append it to the main text of this post.: drop table #test create table #test(i int, c char(8000)) declare @i int while @i < 40000 insert #test values(@i, 'abc')..
http://sqlblog.com/blogs/linchi%5Fshea/
crawl-002
en
refinedweb
I It is confusing and will take a while to figure out the transitional arrangements. My sense of deprecated is different than yours. Deprecated does not mean the feature cannot appear in documents, but that it should not be used in new documents. (Apparently, the BRM changed deprecated to "transitional" which appears to be an improvement, sort of like HTML 4.01 Transitional as opposed to Strict.) I think a more interesting question is whether you could replace the VML with DrawingML and have it be accepted by Word2007 (if saving as OOXML is being implemented in OOo), even though that is not the current default behavior. Depending on how ODF evolves, similar things could happen with OOo features that are not covered in the current ODF spec and that end up being handled differently in some future spec (with at least namespace differences). You'd have to deprecate the OOo-specific approach in favor of the (then) standardized one. I don't have a specific example, but you probably have your eye on a few things. The additional effort will be around for a while, it seems to me. Just like the added pain of supporting the Microsoft Office (name-your-version) binary formats for some time into the future. Nice post. I admire the technical focus and customer consideration that this reflects. Posted by orcmid on March 15, 2008 at 04:17 PM CET # orcmid, it's not a matter of evolving specs and applications, it's a matter of how the spec is associated to applications and what relevance the spec has at all. I firmly believe that OOXML with the modifications that shall make it more acceptable to ISO won't be implemented verbatim by any application on this planet (and this of course includes Microsoft Office). It doesn't help to move the controversial items of the OOXML specification out of the mandatory part by making them "deprecated" or "optional", in oder to get it more "acceptable" as a standard. This is window-dressing and completely irrelevant for the practical work and the market. Henning's example is just one of the most striking ones. Honestly - who needs an OOXML filter with only the mandatory parts of the spec? What people want are Word, Excel, Powerpoint filters - and these file formats are OOXML with "extensions" - all the problematic stuff that the people at ISO already refused to standardize. But technically unexperienced people (and that includes most decision makers) won't see the difference. Make out of that what you see fit. Besides that you are right that standards can evolve - they do, and so does ODF. But that's not what Henning was talking about. He talked about parts of a file format that never have been a mandatory part of its specification but are essential to get the files loaded that are created by the one and only application using this format. I hope I could make this more clear now. Posted by Mathias Bauer on March 17, 2008 at 06:32 PM CET # Thanks for the clear information, Henning. I'm sure there are many really interested, to whom this definitely helps to better understand 'the issue' . Posted by Cor Nouws on March 20, 2008 at 07:41 PM CET # What about the interesting question raised by Orcmid: whether you could replace the VML with DrawingML and have it be accepted by Word2007? Thanks. Posted by Bruno on March 25, 2008 at 05:29 PM CET # You might want to consider deferring your work on VML in favor of DrawingML. Microsoft has pledged to update Office to conform to the revised version of DIS 29500 (OOXML), provided ISO accepts it as a standard. This would preclude the creation of new documents with VML content in Word (and Excel and PowerPoint) and thus lessen the need for VML support in OOo. Only legacy documents converted from the binary formats and OOXML files authored in the period between the release of Office 2007 and its adaptation to ISO standards would contain VML. In other words, the number of documents with VML content will be small, declining, and thus perhaps unworthy of additional resource investment by the OOo team. Posted by anon on March 30, 2008 at 07:47 AM CEST #
http://blogs.sun.com/GullFOSS/entry/ooxml_import_in_writer_a
crawl-002
en
refinedweb
Ads Via DevMavens I’ve been involved in a project where I’m interfacing with a partner Web Service that asynchronously processes messages. Messages are sent to the Web Service and then at some point in the future (hours or days later) the host application sends a SOAP message back to our server at URL we provide. The Web Service on the host consists basically of a single endpoint - it receives only a very complex message structure which serves the entire system. The message hold both the input data and the result data that is sent back, so effectively there's a single message entity to encompasses the entire messaging in the service. The message in question is defined by the main Web Service – there’s WSDL and with some tweaking of the WSDL I was able to call the Web Service and pass this very complex hierarchical object to the Web Service. So far so good. The Host Web Service is not a .NET service – it looks like a homegrown implementation, but I can’t really tell exactly. In any case the WSDL for the service has allowed me to pick up this very complex type in my client application. Sending the message seems to work just fine using standard a .NET Web Reference interface. Through this interface I can pick up the entire message type, which is great because I'll need it on the inbound end to receive messages. The WSDL provides this interface luckily so no manual type creation! So now my problem is that I need to implement the receiving Web Service but I can’t get ASMX to generate the structure necessary to accept this SOAP message sent by this non-.NET host application server. What I’ve done so far is use the types that the WSDL import for the Web Reference imported and then use that as an input parameter for my own Service method: [WebMethod(MessageName="NotifyRequest")] public string ReceiveMessage(OmniCellProvider.OmniConnectService.MetaOMNIConnect MetaOMNIConnect) { return MetaOMNIConnect.OMNIConnectMessage.BulkMessageHeader.RecipientList[0].PartnerID; } When the call comes in though, the inbound parameter is null, which is caused by the mismatch in the message formats I assume. The problem is that the service definition of the host service doesn’t match the signature that .NET ASMX services generate. Basically the Host service sends the message without a top level message root element. The body root node is the top level object, which has caused some problems in a variety of places (for COM interop, because .NET marks the top level ‘object’ as a SoapHeader type which is not ComVisible for example). Here’s the top level of the message as sent by the host server: <?xml version="1.0" encoding="UTF-8" ?> <SOAP-ENV:Envelope SOAP-ENV:encodingStyle="" xmlns: <SOAP-ENV:Body> <MetaOMNIConnect xmlns=""> <OMNIConnectMessage> <BulkMessageHeader> <Sender> … And this is what the .NET Web Service expects: <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns: <soap:Body> <NotifyRequest xmlns=""> <MetaOMNIConnect> <BulkMessageHeader> Notice that the .NET Service has a root node above the actual message object (MetaOMNIConnect). Is there any way to force the .NET Web Service to expose its interface so that it matches the calling service? In the meantime I’ve worked around this issue with a combination of an ASP.NET HTTP Handler and XML Serialization. Rather than using a Web Service, I just have the handler pick up the file, then read the input buffer directly and deserialize it with an XmlReader. Here’s the rough test code I hacked together for this: public void ProcessRequest(HttpContext context) HttpRequest Request = context.Request; HttpResponse Response = context.Response; string XmlString = null; XmlReader xr = XmlReader.Create(Request.InputStream); while (xr.Read()) { if (xr.NodeType == XmlNodeType.Element && xr.Name == "MetaOMNIConnect") { MetaOMNIConnect Message = this.DeSerializeMessage(xr); // *** Echo back a value from the result XmlString = Message.RateResponse.ServiceQuote.Rate.Value.ToString(); break; } } Response.ContentType = "text/plain"; Response.Write(XmlString); protected MetaOMNIConnect DeSerializeMessage(XmlReader xr) object Instance = null; XmlSerializer serializer = null; try // Create an instance of the XmlSerializer specifying type and namespace. serializer = new XmlSerializer(typeof(MetaOMNIConnect)); Instance = serializer.Deserialize(xr); catch (Exception ex) string ErrorMessage = ex.Message; return null; return Instance as MetaOMNIConnect; This works, but it’s not exactly proper SOA implementation <bg>… And I should count myself lucky there's only a single message that is actually sent here, otherwise this would get much uglier. When it really comes down to it, I would like to use a proper Web Service on our Server to handle this for me, but I’m not inclined to hand code my own WSDL and service definition for this monster message type definition. So the questions are: I’m a little out of my range on this one, so I appreciate any feedback provided even if it’s just some general thoughts on this subject.
http://west-wind.com/WebLog/posts/6739.aspx
crawl-002
en
refinedweb
More Signal - Less Noise Tim(); 19: Display( msg ); 20: } Of course, you don't have to add just strings. The value is an object and can be anything. Let's make an incredibly simple GeekObject and substitute that for the applicationSettings. We'll start by adding a GeekClass, 1: namespace SimpleIsolatedStorage 3: public class Geek, 10: Geek g = o as Geek; 11: msg += g.Name + "(" + g.FavoriteGeekBook + ")"; 12: 13: } Full Source Code SimpleIsolatedStorage.zip Thanks. Dude, that is one sweet article. Very well done. Please keep it comming. Wouldn't it be more accurate to say that you can store anything in site/app settings that the DataContractSerializer can serialize? I believe this is going to preclude a number of advanced scenarios. That's way it worked in Beta 2 at least. Boyan Mihaylov on SL/Amazon, David Hyde with SL Stock Portfolio, Chris Anderson with SL LOB app, Jesse Pingback from 2008 September 30 - Links for today « My (almost) Daily Links Great article, but that's the first time I've seen "Ulysis" spelt like that! Pingback from Silverlight news for September 30, 2008 Rob.eisenberg: I want to check further, but I don't see any implication that you must use the DataContractSerializer with IsolatedStorage -- it seems to me that you are writing bytes. But let me look further, perhaps I'm missing something fundamental (wouldn't be the first time). Jasonbsteele: oops. Gotta fix that! Pingback from Dew Drop – September 30, 2008 (Evening Edition) | Alvin Ashcraft's Morning Dew @jesse Actually I think we are talking about two different things. I believe I misinterpreted your post. Isolated storage can store anything. But, the VS built in Settings class uses the DataContractSerializer to serialize any of its custom settings to iso storage. So the restriction is in the build-in Settings class, not in iso storage. We have, I think, officially passed the point where anyone can keep up with the new technology available Pingback from Silverlight Tipps vom Insider This week I gave a Silverlight presentation at the Montreal .NET Community ( MVP Laurent Duveau recently delivered a Silverlight talk at the Montreal .NET Community . During his 用反射来动态加载XAML 2009年04月23日星期四23:25 2008年10月,写了一篇《动态加载XAML文件》,其中按照SilverlightMSDN的
http://silverlight.net/blogs/jesseliberty/archive/2008/09/29/isolated-storage-actually-it-s-easy.aspx
crawl-002
en
refinedweb
Whenever you want to quickly bombard a URL with some concurrent traffic, you can use this: import random import time import requests import concurrent.futures def _get_size(url): sleep = random.random() / 10 # print("sleep", sleep) time.sleep(sleep) r = requests.get(url) # print(r.status_code) assert len(r.text) return len(r.text) def run(url, times=10): sizes = [] futures = [] with concurrent.futures.ThreadPoolExecutor() as executor: for _ in range(times): futures.append(executor.submit(_get_size, url)) for future in concurrent.futures.as_completed(futures): sizes.append(future.result()) return sizes if __name__ == "__main__": import sys print(run(sys.argv[1])) It's really basic but it works wonderfully. It starts 10 concurrent threads that all hit the same URL at almost the same time. I've been using this stress test a local Django server to test some atomicity writes with the file system. Follow @peterbe on Twitter
https://api.minimalcss.app/plog/quick-dog-piling-url-stresstest
CC-MAIN-2020-16
en
refinedweb
Apache OpenOffice (AOO) Bugzilla – Issue 77173 Add Import to File menu in Calc to support direct opening of text based data files Last modified: 2013-08-07 15:12:27 UTC The number of steps involved in opening space or tab delimited text data files in Calc is in my experience the most frustrating feature of OO. It unnecessarily complicates the task during repeated analysis on multiple data files. However, text file opened from Calc is most likely data, on Writer is most likely text. Dragging and dropping a text file into Calc is already implemented consistently with this assumption, and it brings up Calc's text import dialog. If OO must have a single Open dialog that doesn't remember what application it was called from, how about adding an Import function to the File menu where file opened are assumed to be data files? one for requirements
https://bz.apache.org/ooo/show_bug.cgi?id=77173
CC-MAIN-2020-16
en
refinedweb
Technical Support On-Line Manuals CARM User's Guide Discontinued #include <string.h> unsigned int strlen ( const unsigned char *src); /* source string */ The strlen function calculates the length, in bytes, of src. This calculation does not include the null terminating character. The strlen function returns the length of src. strcat, strncat, strncpy #include <string.h> #include <stdio.h> /* for printf */ void tst_strlen (void) { unsigned char buf [] = "Find the length of this string"; unsigned int len; len = strlen (buf); printf ("string length is %d\n", len); }.
http://www.keil.com/support/man/docs/ca/ca_strlen.htm
CC-MAIN-2020-16
en
refinedweb
CupertinoContextMenu class A full-screen modal route that opens when the child is long-pressed. When open, the CupertinoContextMenu shows the child, or the widget returned by previewBuilder if given, in a large full-screen Overlay with a list of buttons specified by actions. The child/preview is placed in an Expanded widget so that it will grow to fill the Overlay if its size is unconstrained. When closed, the CupertinoContextMenu simply displays the child as if the CupertinoContextMenu were not there. Sizing and positioning is unaffected. The menu can be closed like other PopupRoutes, such as by tapping the background or by calling Navigator.pop(context). Unlike PopupRoute, it can also be closed by swiping downwards. The previewBuilder parameter is most commonly used to display a slight variation of child. See previewBuilder for an example of rounding the child's corners and allowing its aspect ratio to expand, similar to the Photos app on iOS. import 'package:flutter/cupertino.dart'; // ... Widget build(BuildContext context) { return Scaffold( body: Center( child: Container( width: 100, height: 100, child: CupertinoContextMenu( child: Container( color: Colors.red, ), actions: <Widget>[ CupertinoContextMenuAction( child: const Text('Action one'), onPressed: () { Navigator.pop(context); }, ), CupertinoContextMenuAction( child: const Text('Action two'), onPressed: () { Navigator.pop(context); }, ), ], ), ), ), ); } See also: - Inheritance - Object - Diagnosticable - DiagnosticableTree - Widget - StatefulWidget - CupertinoContextMenu Constructors - CupertinoContextMenu({Key key, @required List< Widget>actions, @required Widget child, ContextMenuPreviewBuilder previewBuilder} ) - Create a context menu. [...] Properties - actions → List< Widget> - The actions that are shown in the menu. [...]final - child → Widget - The widget that can be "opened" with the CupertinoContextMenu. [...]final - previewBuilder → ContextMenuPreviewBuilder - A function that returns an alternative widget to show when the CupertinoContextMenu is open. [... _CupertinoContextMenuSt
https://api.flutter.dev/flutter/cupertino/CupertinoContextMenu-class.html
CC-MAIN-2020-16
en
refinedweb
Watch a recording of our webinar "NativeScript on Fire(base) 🔥" We all know that itch when you want to publish your mobile app as soon as possible. You worked on it for several months, tested it, looks good, your significant other even likes it. The last thing you need to stand between you and your published app is more work. And yet – adding Analytics to your app is an effort that worth investing in. With just half an hour of work, you will know what your users need, how can you address their needs and where to invest your precious development time. In your newly created project, you have to navigate to the project settings and add iOS and Android applications. For the Bundle ID in iOS or the Package name in Android – use the value of the applicationId property set in the package.json of your NativeScript app. As a result, you should have GoogleServices-Info.plist and google-services.json files. These files contain configuration properties that are used by the Firebase SDK to properly relate user interactions with your Analytics project. You can safely skip the instructions about how to add Firebase SDK and how to add initialization code to your app, as this setup will be handled by the plugin. Here is how to process looks like for iOS (for Android, is very similar): applicationId package.json GoogleServices-Info.plist google-services.json As a first step, you need to install the nativescript-plugin-firebase plugin. Follow the installation steps provided by Eddy Vebruggen (the author of this awesome plugin). You need to place the GoogleServices-Info.plist file in the App_Resources/iOS folder and the google-services.json in the App_Resources/Android folder. One additional file, firebase.nativescript.json, will be added to the root of your project, once the installation of the plugin is completed. During the installation you will have to answer several questions about what part of the Firebase plugin you are planning to use. The output is a firebase.nativescript.json file which should look similar to this: App_Resources/iOS App_Resources/Android firebase.nativescript.json { "using_ios" : true , "using_android" "firestore" false "realtimedb" "remote_config" "messaging" "crashlytics" "crash_reporting" "storage" "facebook_auth" "google_auth" "admob" "invites" "dynamic_links" "ml_kit" } Note: You should never commit your GoogleServices-Info.plist and google-services.json file to a public repository. They contain your secrets and other people will be able to exploit the data from your account if they are not properly protected. Ideally, they should be inserted build time by your CI infrastructure for production builds. Your next step is to initialize the plugin in your application. The most appropriate place to do this is in the root componentof your Angular application, as explained in the start-up wiring instructions. It is as simple as: app.component.ts import * as firebase from "nativescript-plugin-firebase" ; … ngOnInit(): void { firebase.init({ }).then( instance => { console.log( "firebase.init done" ); }, error => { console.log(`firebase.init error: ${error}`); } }; If you are using the {N} Core Framework you can use the application’s launch event and attach to it: app.js application.on(application.launchEvent, (args) => { }; }); When you are done with the installation, run the tns run command. When your application starts on your devices, you should see some movements in the “Users in last 30 minutes” tile of your Analytics Dashboard. Another indication that wheels are starting to spin is that the red dots next to the iOS and Android projects will disappear as soon as the first data is registered: tns run With all this done, you are already ahead in the game and will have much more insights than those exposed in the Android and iOS developer consoles. Firebase will start to track some events out of the box for you like: first_open, screen_view and session_start (full list with automatically tracked events can be found in the documentation). It will also report some demographic information about your users – which country they are located in, gender, age, interests, what devices are they using and what not. Additionally, your users will be automatically reported as new or returning. This will allow you to understand better your audience, their interests and adjust your application to be even more appealing to them. You can easily add additional information for your users, using the setUserProperty method and further group your user base in segments. Although Firebase will track events called “screen_view” automatically, they won’t prove very useful because of the architecture of NativeScript. All users’ engagements will be reported in a single Activity for Android or ViewController for iOS. So, to better understand how our application is being used – we need to implement a custom event with some properties added to it. For the purpose of this post, I will call such events “page views”. This term can be quite ambiguous and depending in your app specifics might mean different things. Furthermore, we want to track not only that a page was viewed, but also which page – so that we can after that analyse which are the most useful pages. ; ... firebase.analytics.logEvent({ key: "page_view" , parameters: [ { "page_id" value: “Home” // Add additional parameters here if needed ] This will log an event called “page_view” with a parameter “page_id” with value “Home”. One way would be to add manual calls on every Component initialisation. That would be a very tedious and error prone task, we could do much better than this. Let’s leverage the events exposed by the Angular router and log the event there, like this: app.component.ts this .router.events .pipe(filter((event: any) => event instanceof NavigationEnd)) .subscribe((event: NavigationEnd) => { parameters: [{ value: event.urlAfterRedirects }] Note: If you are using the {N} Core Framework, you can use the navigatedTo event and implement similar logic. navigatedTo This will use the url as page_id value. In most cases it will give a nice representation of which urls are visited and how often. Of course, you can fit it to your needs if your url schema is not appropriate. One pitfall is that you need to register your parameter in the Firebase Console before starting to use it. To do this, open your project in the Firebase Console, open the “Events” screen, click on the “page_view” event and there is an “Add event parameters” button. From there, add the parameter that you want to track - in our case this is the ‘page_id’. At this point, you will know what parts of your applications are most useful. With this addition you will have a full map of your users and how they interact with your mobile app. Here is how thing can look like in the Firebase Console: Depending on your application’s purpose, there might be different things that you want to track as a conversion. By default, there are events like ecommerce_purchase and in_app_purchase. You are free to mark any of your existing events as conversion as well, depending on your users’ flow and business logic. To do this, just navigate to the Conversions screen and follow the “New conversion event” wizard. Additionally, you can create Funnels to track how well your conversions are happening and identify areas for improvements in your users’ journey. This is again very easy to achieve, from the Funnels screen. As a very oversimplified example, I prepared a sample application. On the homepage there are two buttons - “Add to Shopping Cart” and “Purchase”. The “Purchase” button will log a new event using one of the built-in keys that Firebase considers as conversions, called “ecommerce_purchase”. The other button “Add to Shopping Cart” is logging a new event called “add_to_cart”, which I can mark as conversion from the Firebase console. This way I can easily build a funnel to track my conversions, e.g. “first_open” -> “add_to_cart” -> “ecommerce_purchase”. This will give me insights where should I improve my users’ experience and conversion. Here is how a funnel can look after these steps are done: Obviously, now there is something broken in my dummy funnel that I need to work on 🙂 Events logged from your applications will not be immediately visible in the Firebase console. It can take up to 24h for the data to be available. From my experience, it takes at least several hours. This might make debugging difficult as you have to wait for a long time to test your changes. Luckily, there is a view in the Firebase console called “DebugView”. You need to enable it for your application or devices and after that events from your devices will be visible as soon as they are reported. For Android this happens as easy as running adb shell setprop debug.firebase.analytics.app <packageName, like: org.nativescript.nativescriptanalyticssample>. For iOS you will have to open your project in XCode and add -FIRDebugEnabled parameter to be passed on launch. More info on how to achieve this can be found out in the Firebase Documentation. To wrap up, adding Analytics is easy, makes you smarter, can save you time and money and there is absolutely no reason not to start doing it. Firebase provides excellent features at no price, but there are other great Analytics services that you can also explore. The hardest thing that you need to do is think – what does it mean for your app to be successful and define how to measure it. The actual measuring is now easy.
https://www.nativescript.org/blog/how-to-add-firebase-analytics-to-your-nativescript-mobile-app
CC-MAIN-2020-16
en
refinedweb
I have a model that contains an integer field class myModel(models.Model): number = models.IntegerField() Whenever I display or input data to this model I want to do so in octal. When I populate my edit form I do this: number = oct(numberObject.number).replace('Oo','') When I go to the edit form it prepopulates with exactly what I want but when I try to do error checking after submitting the form to avoid having that number occur twice I get a problem because number is in self.changed_data and therefore I'm getting the error that this number already exists (basically it's finding itself and saying it is a duplicate) I can't think of a way to figure out whether I'm trying to change the number to one that already exists or if I'm just submitting the number without changing it. My form/validation code: class NumberForm(ModelForm): number = forms.CharField(max_length = 10) def clean_number(self): """Ensures the new Number is unique """ enteredNumber = self.cleaned_data['number'] changedFields = self.changed_data if number.objects.filter(number__exact = int(enteredNumber,8)): if 'number' in changedFields: raise forms.ValidationError("Error") return int(enteredNumber,8) class Meta: model = Number fields = '__all__' You may be editing an existing object, right? I would simply exclude it from the result set: def clean_number(self): """Ensures the new Number is unique """ enteredNumber = int(self.cleaned_data['number'], 8) queryset = Number.objects.filter(number=enteredNumber) if self.instance is not None and self.instance.pk is not None: queryset = queryset.exclude(pk=self.instance.pk) if queryset.exists(): raise forms.ValidationError("Error") return enteredNumber Using the .exists() method avoids loading the object from the database, should one exist. By the way, this form won't ensure you cannot create duplicates. Two threads may run the validation code at the same time, accept the same value, then proceed to saving their respective object with that value. If you want to be sure you don't have duplicates, you must do so at the database level (by passing unique=True to the field on the model).
https://databasefaq.com/index.php/answer/7314/django-django-form-output-error-checking-issue
CC-MAIN-2020-16
en
refinedweb
Customizing Forms¶ The forms used to edit datasets and groups in CKAN can be customized. This lets you tailor them to your needs, helping your users choose from sensible options or use different data formats. This document explains how to customize the dataset and group forms you offer to your users. Warning This is an advanced topic. Ensure you are familiar with Add Extensions before attempting to customize forms. Note This document describes the process for creating dataset forms that is used in the ckanext-example extension. The source code is available at. Group forms can be customised in a similar way, see ckanext-example again for reference. Creating a Dataset Form¶ The recommended way to create a dataset form is by using a CKAN extension. First, create a new plugin that implements ckan.plugins.IDatasetForm. It is also useful to implement ckan.plugins.IConfigurer as well, so that you can add the directory that will contain your new dataset form template to CKAN’s list of template paths. import ckan.plugins class ExampleDatasetForm(ckan.plugins.SingletonPlugin): implements(ckan.plugins.IDatasetForm, inherit=True) implements(ckan.plugins.IConfigurer, inherit=True) Next, create a directory in your CKAN extension to store your HTML template(s) and add an update_config method to make sure that this template is on CKAN’s template path. Here we add the ckanext/example/theme/templates directory to the path. def update_config(self, config): here = os.path.dirname(__file__) rootdir = os.path.dirname(os.path.dirname(here)) template_dir = os.path.join(rootdir, 'ckanext', 'example', 'theme', 'templates') config['extra_template_paths'] = ','.join([ template_dir, config.get('extra_template_paths', '') ]) You can now add your HTML template(s) to the templates directory. It is recommended that you copy the existing CKAN dataset form (ckan/templates/package/new_package_form.html) and make modifications to it. However, it is possible to start from scratch. If you create a template in your extension templates directory at package/new_package_form.html, it will override the default CKAN template. This applies to any template in the CKAN templates directory. You can also override them by changing the paths returned by the following methods in your extension: def package_form(self): return 'package/new_package_form.html' def new_template(self): return 'package/new.html' def comments_template(self): return 'package/comments.html' def search_template(self): return 'package/search.html' def read_template(self): return 'package/read.html' def history_template(self): return 'package/history.html' Note The package_form and *_template methods (above) are required in order to implement IDatasetForm. Two other methods must be provided by your extension when implementing the IDatasetForm interface: def package_types(self): return ['dataset'] def is_fallback(self): return True package_types sets the dataset type associated with your extension, and updates the Pylons routing so that datasets of this type can be found at the /<type> URL in your CKAN instance. For example, changing package_type to return ['catalog'] would mean that any visits to /catalog/new, /catalog/edit, etc. would use your extension’s dataset form, but going to /dataset/new, /dataset/edit, etc. would still return CKAN’s default dataset form. is_fallback means that this extension should be the default dataset type. If True, even when the return value of package_types is changed, going to /dataset/new will still use the extension’s dataset form instead of CKAN’s default. Passing Data to Templates¶ Your IDatasetForm extension can define a _setup_template_variables method, and use it to add data to the Pylons c object (which is passed to the templates). For example, you can define _setup_template_variables as follows: def setup_template_variables(self, context, data_dict=None, package_type=None): from ckan.lib.base import c from ckan import model c.licences = model.Package.get_license_options() and then use it in your HTML template: <dd class="license-field"> <select id="license_id" name="license_id"> <py:for <option value="${licence_id}">${licence_desc}</option> </py:for> </select> </dd> Custom Schemas¶ Note As of CKAN 1.7 custom schema functions apply to both the web user interface and the API. An example of the use of these methods can be found in the ckanext-example extension. The data fields that are accepted and returned by CKAN for each dataset can be changed by an IDatasetForm extension by overriding the following methods: def form_to_db_schema_options(self, options) This allows us to select different schemas for different purpose eg via the web interface or via the api or creation vs updating. It is optional and if not available form_to_db_schema should be used. _form_to_db_schema(self) This defines a navl schema to customize validation and conversion to the database. _db_to_form_schema(self) This defines a navl schema to customize conversion from the database to the form. _db_to_form_schema_options(self, options) Like _form_to_db_schema_options(), this allows different schemas to be used for different purposes. It is optional, and if it is not available then form_to_db_schema is used.
https://docs.ckan.org/en/ckan-1.8/forms.html
CC-MAIN-2020-16
en
refinedweb
Mobile Page Class Definition Warning This API is now obsolete. Serves as the base class for all ASP.NET mobile Web Forms pages. For information about how to develop ASP.NET mobile applications, see Mobile Apps & Sites with ASP.NET. public ref class MobilePage : System::Web::UI::Page public class MobilePage : System.Web.UI.Page [System.Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see.")] public class MobilePage : System.Web.UI.Page type MobilePage = class inherit Page Public Class MobilePage Inherits Page - Inheritance - MobilePage - Derived - - Attributes - Remarks The MobilePage class inherits from the ASP.NET Page class. To specify a mobile page and use ASP.NET mobile controls, an ASP.NET mobile Web Forms page must contain the following page directive. <%@ Page Inherits="System.Web.UI.MobileControls.MobilePage" Language="c#" %> The Inherits attribute is required. The Language attribute is set to the language that is used on the page, if it is needed. Note ASP.NET mobile pages allow for multiple mobile forms on each page, whereas ASP.NET Web pages allow for only one form per page.
https://docs.microsoft.com/en-us/dotnet/api/system.web.ui.mobilecontrols.mobilepage?redirectedfrom=MSDN&view=netframework-4.8
CC-MAIN-2020-16
en
refinedweb
vehicles statit to dynamic [javascript] Hello to all, I've never written code for gta 5 until now. Now, I'm trying to do to port with MapEditor ... but the boat does not stand still, they drift. I would use the simple javascript to add to the map editor, as shown here: I thought sets the boats as static, and create a JavaScript script that changes static to dynamic when the player goes into vehicle. I tried this script: if (API.GTA.Game.Player.Character.IsInVehicle()) { API.GTA.Game.Player.Character.CurrentVehicle.Dynamic(); } Dynamic() it was only a hope, but do not seem to work. Can anyone help me figure out how to write the script? Or maybe given some guides that teaches how to use JavaScript in the gta 5? Thank you But they are also still with Map Editor unchecking the dynamic option. But I wish that when the player enters the vehicle would return dynamic. Any idea on how to do? boh .. I do not know ... it is a map editor option ... it is everywhere, vehicles, peds, props, etc. thank you so much @alebal I was never sure whether the dynamic property applied to things that the player could interact with on a physics level. So something like a waste bin would be dynamic, so you could knock it about/shoot it etc... but something like a bus stop would be static... not sure if that's right or not, but that was my thought. Didn't actually know it applied to Vehicles though, I thought it was just a prop thing. Funnily enough, while testing my camera mod, I had the same problem with boats drifting... in fact I got so fed up with chasing the boats, that I flew to the lake in the park and spawned the boats in there. I thought about adding a virtual anchor which would lock the X and Y position and just allow the Z position to drift with the wave height. Again, not sure if that would work but I can't see why it wouldn't. So basically hit a key/check for a condition, save the X and Y location and then in your onTick, keep setting them. Thanks for your reply, today I'm definitely not able to do what you're talking about. I am a php and mysql programmer, gta coding is foreign to me ... But in the coming days I attack me at google and try to figure it out ... Can help you understand how to do if I tell you that seems to do the same thing here the boat here also seems to be static, then when the player comes close "pluff" ends up in the water. Maybe there is a function or something ready ... but how do I find it I Googled a bit. I first found this so maybe you can do it ... Then in the list of native I found this SET_BOAT_ANCHOR, maybe that's what I need ... But now turn this: SET_BOAT_ANCHOR in something like this: script.CallNative ("GIVE_WEAPON_TO_PED" API.GTA.Game.Player.Character, 453,432,689, 50, true, true); // Give pistol to player for me it is an epic undertaking ... some help ... What are the parameters of this thing ?? How can I find them? I also found these REPLACE SET_BOAT_ANCHOR = 0x45087C, //0xA3906284 //1.26 //BLES SET_BOAT_ANCHOR = 0x439a40, SET_BOAT_ANCHOR = 0x44C798, //1.22 Like ancient Egyptian for me .. @alebal You might want to add this page to your bookmarks: That is a list of every native (which is what those are) and it shows what parameters are used in each one. In the case of SET_BOAT_ANCHOR, it requires a Vehicle and a Bool. There is also a _GET_BOAT_ANCHOR which returns a Bool telling you whether the anchor is on or off. I don't know how that works in Javascript, but in C# it would be: bool _anchorvalue = Function.Call<bool>(Hash._GET_BOAT_ANCHOR, _vehicle); To set the anchor, again in C#: Vehicle _vehicle = Function.Call<Vehicle>(Hash.GET_VEHICLE_PED_IS_TRYING_TO_ENTER, Game.Player.Character); int _class = Function.Call<int>(Hash.GET_VEHICLE_CLASS, _vehicle); if (_class == 14) { Function.Call(Hash.SET_BOAT_ANCHOR, _vehicle, true); } C# does have functions that replace those natives but I have shown the native as it might transfer better to Javascript. 14 is the value of Boats in the vehicle class enums. Edit: Sorry, I missed a parameter off that _GET_BOAT_ANCHOR. Even I'm not expert in javascript. But more or less your code should become this (even reading here) var vehicle = script.CallNative("GET_VEHICLE_PED_IS_TRYING_TO_ENTER", API.GTA.Game.Player.Character); var vehicle_class = script.CallNative("GET_VEHICLE_CLASS", vehicle); if (vehicle_class == 14) { script.CallNative("SET_BOAT_ANCHOR", vehicle, true); } But it does not work ... GTA says: Map Javascript error -> Exception Has Been thrown by the target of an invocation. The error comes right away from the vehicle variable used in GET_VEHICLE_CLASS function. Or am I wrong to write something, or MapEditor do not want variables in functions in the writing of javascript. I do not know ... Any help? @alebal I'm afraid I can't offer anything on the side of Javascript or MapEditor. If I want objects, I manually spawn them and if I want functionality, I write C# scripts to give it to me. If I had more time spare, I could probably have a look at MapEditor but my mod is eating the day away every day, so spare time is a rarity. Sorry I can't be of more help. Based on the number of map mods that appear on this site, there must be surely someone willing to help. Edit: Actually, it's my fault for not explaining that what I have written there, would normally go inside a function that says: if (Function.Call<bool>(Hash.IS_PED_GETTING_INTO_A_VEHICLE, Game.Player.Character)) { // Do that code } That function would be called every frame in your onTick(), waiting for you to try and enter a vehicle. Actually, thinking about it, I wonder if it's this line: var vehicle = script.CallNative("GET_VEHICLE_PED_IS_TRYING_TO_ENTER", API.GTA.Game.Player.Character); Is there anything in the documentation that tells you how to return a value from a native, or does it do it by default? If you notice, I specify Function.Call<bool>which tells it to return a trueor falsevalue back. You need to check if script.CallNativepasses values back. If not, that could be the cause of the error. Just had a quick check, yes you can use onTick() and yes you can return values... use this (not sure how to specify the parameters) object script.ReturnNative(string nativeHash, int returnType, params object[] args) From the docs: Return a game native's value. Return types are as follow: Int = 0, UInt = 1, Long = 2, ULong = 3, String = 4, Vector3 = 5, Vector2 = 6, Float = 7 Damn, I'm getting wrapped up in this... That return call won't work if it only allows you to choose from those return types. You need to get a Vehicle back and that's not included there. You might be better asking the author of MapEditor... I could just be further confusing things here by guessing at solutions. I understand! Thank you so much for your time. Honestly, I also am not understanding nothing more ... These days I did more tests, but I never get what I expect. But I discovered something that I had never noticed., MapEditor also saves in C. The result is something like this: using System; using System.Collections.Generic; using GTA; using GTA.Math; using GTA.Native; public class MapEditorGeneratedMap : GTA.Script { public MapEditorGeneratedMap() { List<int> Props = new List<int>(); int LodDistance = 3000; Func<int, Vector3, Vector3, bool, int> createProp = new Func<int, Vector3, Vector3, bool, int>(delegate(int hash, Vector3 pos, Vector3 rot, bool dynamic) { Model model = new Model(hash); model.Request(10000); Prop prop = GTA.World.CreateProp(model, pos, rot, dynamic, false); prop.Position = pos; prop.LodDistance = LodDistance; if (!dynamic) prop.FreezePosition = true; return prop.Handle; }); bool Initialized = false; base.Tick += delegate (object sender, EventArgs args) { if (!Initialized) { /* PROPS */ /* VEHICLES */ GTA.World.CreateVehicle(new Model(231083307), new GTA.Math.Vector3(45.96207f, 494.799f, 165.9185f), -67.20878f); /* PEDS */ /* PICKUPS */ Initialized = true; } /* MARKERS */ /* WORLD */ Prop returnedProp; }; } } At this point it might as well export all in C, and maybe add in the end, your function to the anchor of the boats. But being a programmer php I'm missing something ... like, C must be compiled, as I compile for use in GTA? It must be .ASI? As you export to .ASI? One other thing, I wish only a few boats were anchored, while others should run free to the lake, you can assign an identification to the vehicle in C? And in the first "if" use the identifiers in place of the class? P.S. does not put the code and pre tags in the right place, there is other code out . You can not edit the html of the post? I have not managed to anchor boats in the harbor. But for the moment I went ahead with the map, here it is: Meanwhile, I keep thinking about how to do. Thank you for helps.
https://forums.gta5-mods.com/topic/1967/vehicles-statit-to-dynamic-javascript
CC-MAIN-2018-43
en
refinedweb
Cannot edit textbox using AutoIT By zerothesavior, in AutoIt General Help and Support Recommended Posts Similar Content - By Rskm i have a code where the ControlSetText was working perfectly. now its not working. please see the video and snap attached. The snap show the way i have used window info. In the video, when the dialogue box opens, it used to key in 'sea.runx' , but now its not working so... what could be the reason. the script used is as shown below - thanks WinActivate("SACS 5.3 V8i") winwaitactive("SACS 5.3 V8i") send("^r") winwaitactive("SACS Run Files") ControlSetText ("SACS Run Files","",1148,"sea.runx") SEND("{ENTER}")2018-03-22 at 00-02-47.mp4 - By ur I need to set value to a text box to a desktop application. I am trying to do that with ControlSetText($MartConfigWindow, "", "WindowsForms10.EDIT.app.0.378734a6", $dbserver) where $MartConfigWindow has the window ID. And the text box field is having class as WindowsForms10.EDIT.app.0.378734a6 THis code is working on one machine but on some machines, the last part of ID WindowsForms10.EDIT.app.0.378734a6, means 378734a6 is changing. Is there anyway to handle this? - By spuuunit Is it possible to know if a textbox is active in FireFox? This is what I want: if (Textbox in FireFox == Active) { } - By Carm01 All, I have windows 10 64 bit pro with the latest versions of scite and 3.3.14.2 installed. Not that it matters for this instance. My monitor resolution is 1920 x 1080 progressive with a refresh rate of 64 HZ ( more in a min on that ) I have a Nvida gtx 960 card and an HP monitor Since moving to Windows 10 and this configuration ( latest drivers of course ) I am unable to see the " ControlSetText " being displayed under the standard 60HZ refresh rate in WIndows 10. On Windows 7 machines this is flawless and always had been. The ControlSetText is updated at an extremely fast rate. IF I change the resolution one notch lower in windows 10 the display displays the text like in Windows 7 60HZ refresh. IF I user the max resolution 1920 x 1080 @ 60 HZ nothing is displayed in Windows 10. IF I create a custom resolution profile and just change the refresh rate to 64HZ it displays normally in Windows 10. If I enable " GUIGetMsg() " it displays fine but processes very slow fyi I will place the relevant code below. I am wondering: 1) what is the max refresh/update rate for ControlSetText ( fasted it can be updated ) 2) Could this be adjusted either in code without hampering processing speed 3) Does this need to be addressed in AutoIT program itself as a bug ? #include <Array.au3> #include <File.au3> Local $aRetArray, $aArray local $sFilePath = @ScriptDir & "\info.txt" _FileReadToArray($sFilePath, $aRetArray) Local $aArray[UBound($aRetArray)] SplashTextOn("Percent Complete", "", 130, 40, -1, -1, 16, "") Local $a = 0 Local $hTimer = TimerInit() $bb = UBound($aRetArray) - 1 For $i = 1 To UBound($aRetArray) - 1 ; ;GUIGetMsg();prevent high cpu usage $line = $aRetArray[$i] If StringRight($line, 2) = " X" Then If $i = 1 Then $line1 = StringLen($line) - StringLen($aRetArray[$i]) $line2 = StringRight($line, $line1) $line3 = $aRetArray[$i] $line4 = $aRetArray[$i + 1] Else $line1 = StringLen($line) - StringLen($aRetArray[$i - 1]) $line2 = StringRight($line, $line1) $line3 = $aRetArray[$i - 1]; $line4 = $aRetArray[$i + 1]; EndIf $aArray[$a] = $i & "| " & $line3 & "| " & $line2 & "| " & $line4 $a = $a + 1 EndIf ControlSetText("Percent Complete", "", "Static1", Round((($i / $bb) * 100), 2)) Next Thanks in advance - By louabill It seems that ControlSetText() sends only the first character to Scintilla controls. To see this, try the following: Open a SciTE window Put the following line into the window ControlSetText("[CLASS:SciTEWindow]","","[CLASS:Scintilla;Instance:1]", 'here is some text') and save the file. Go to the beginning of the line. Hit F5 to run the line. What I see is that the single letter h overwrites the text in the window instead of the desired text. Does anyone know how to get the Scintilla control to play nice? If not, is this a bug I should be reporting to the Autoit folks? I would like to avoid ControlSend(), because it has trouble with Unicode. Thanks for any tips. --- original post --- In an AutoIt script, I use ControlSetText() to send text to the Command window in the Stata statistical package. In Stata 14, the Command window was changed to a Scintilla control which understands Unicode instead of a RichText control (which used Latin1 encoding). In the past, all worked well, now only the first character gets put in the control. Here is an example which illustrates how it worked and now fails (which requires a running Stata 13 and a running Stata 14): Opt("WinTitleMatchMode", 1) ## in Stata 13 and earlier, the Command window was a RichText control ControlSetText("Stata/MP 13","","[CLASS:RichEdit20A;Instance:1]", "sysuse auto") ## result: 'sysuse auto' in the Command window ## in Stata 14, the Command window is a Scintilla control ControlSetText("Stata/MP 14","","[CLASS:Scintilla;Instance:1]", "sysuse auto") ## result: the letter 's' in the Command window I can use ControlSend() to send plain text successfully, but I'm betting it won't work properly with Unicode because the function is not Unicode-ready, yet. Any hints about what I need to do to fix the problem? I realize this is somewhat specialized because of the receiving software, but perhaps someone knows something about sending text to Scintilla Unicode-friendly controls. Thanks for any help.
https://www.autoitscript.com/forum/topic/178942-cannot-edit-textbox-using-autoit/
CC-MAIN-2018-43
en
refinedweb
![if gte IE 9]><![endif]> I'm trying to follow this code to allow users to be created programmatically: docs.sitefinity.com/for-developers-create-users . I'm using a .NET 4.5 project and I believe I'm using the proper Telerik references (Telerik.Sitefinity.dll) When I try to use the namespace Telerik.Sitefinity.Security.Model it cannot located "Model". Namespace "Telerik.Sitefinity.Security" is fine. I'm assuming that because of this, VS 2013 is not able to find the class for "User" in line 21 and cannot fine the SitefinityProfile class in line 25. Any suggestions as to what I may be doing wrong? Thanks!
https://community.progress.com/community_groups/sitefinity/general-discussions/f/295/t/39801
CC-MAIN-2018-43
en
refinedweb