id
stringlengths 5
11
| text
stringlengths 0
146k
| title
stringclasses 1
value |
|---|---|---|
doc_23526600
|
{
"unit":
{
.....
},
"receipt":
{
.....
},
"instalments": [
{
"payment_type": "5",
"amount": "3",
"bank_name": "ABU DHABI COMMERCIAL BANK",
"paid_date": "2020-08-07 01:11:02",
"status": "0",
}
{
"payment_type": "5",
"amount": "3",
"bank_name": "ABU DHABI COMMERCIAL BANK",
"paid_date": "2020-08-07 01:11:02",
"status": "0",
}
]
}
I use this mode class to get value from API
class PaymentInstallment {
String payment_type;
String payment_amount;
String payment_date;
String status;
PaymentInstallment(
{this.payment_type, this.payment_amount, this.payment_date, this.status});
factory PaymentInstallment.fromjson(Map<String, dynamic> json) {
return PaymentInstallment(
payment_type: json['payment_type'],
payment_amount: json['amount'],
payment_date: json['paid_date'],
status: json['status'],
);
}
}
this is my list and adding the response from the server to it
List<PaymentInstallment> _list = [];
final response = await http.get(
url,
headers: {"Accept": "application/json", "Authorization": token},
);
var response = jsonDecode(response.body);
setState(() {
for (Map temppayment in response) {
_list.add(PaymentInstallment.fromjson(temppayment));
}
});
how can i all array value from "instalments" array and add to the list
A: Try this
var response = jsonDecode(response.body);
List installmentList = List.from(response["installment"]);
setState((){
_list = installmentList.map((f) => PaymentInstallment.fromJson(f)).toList();
});
If it isn't looping try this
List tempList = [];
installmentList.forEach((f) => tempList.add(f));
setState((){
_list = tempList;
});
| |
doc_23526601
|
A: IMHO Since it is just a wrapper over the old FileDialog common control, I'd be surprised if you could do this. I could be wrong...
I'd begin by questioning why you need to restrict some drives (Windows- Group policies and other security mechanisms should take care of user rights)
If you really need this.. I'd go for
*
*Override the FileOk event, check the drive in the selected path and cancel the event if the path is not permissible. Also notify the user explaining the reason for denial
*If that's not good for UX reasons, you could tinker around with registry and/or group policy keys to hide the drive. Googling should give you some pointers.. but I'd not do this myself. Not recommended.
| |
doc_23526602
|
const schema = yup.object({
adults: yup.array().of(
yup.object().shape({
msalution:yup.string(),
mfirstname: yup.string().required("Name is required"),
mlastname: yup.string().required("Name is required"),
mgender:yup.string(),
mage:yup.string(),
mfoodpref:yup.string(),
mphonenumner:yup.number(),
memail: yup.string()
.email("Email is Invalid")
.required("Email is required")
})
),
kids: yup.array().of(
yup.object().shape({
msalution:yup.string(),
mfirstname: yup.string().required("Name is required"),
mlastname: yup.string().required("Name is required"),
mgender:yup.string(),
mage:yup.string(),
mfoodpref:yup.string(),
mphonenumner:yup.number(),
memail: yup.string()
.email("Email is Invalid")
.required("Email is required")
})
),
babies: yup.array().of(
yup.object().shape({
msalution:yup.string(),
mfirstname: yup.string().required("Name is required"),
mlastname: yup.string().required("Name is required"),
mgender:yup.string(),
mage:yup.string(),
mfoodpref:yup.string(),
mphonenumner:yup.number(),
memail: yup.string()
.email("Email is Invalid")
.required("Email is required")
})
),
});
| |
doc_23526603
|
#include<conio.h>
struct Node{
int number;
struct Node * next;
};
struct Node * insertNodeInLinkedList(int number,struct Node * startOfList){
if(startOfList == NULL){
startOfList = (struct Node *)malloc(sizeof(struct Node));
startOfList->number = number;
startOfList->next = NULL;
}else{
struct Node * temporaryNode = startOfList;
struct Node * newNode = (struct Node *)malloc(sizeof(struct Node));
while(temporaryNode->next != NULL){
temporaryNode = temporaryNode->next;
}
newNode->number = number;
newNode->next = NULL;
temporaryNode->next = newNode;
}
return startOfList;
}
void display(struct Node * startOfList){
struct Node * temporaryNode = startOfList;
while(temporaryNode != NULL){
printf("%d",temporaryNode->number);
temporaryNode = temporaryNode->next;
}
}
int main (void){
int howManyNodes = 0;
int counter = 0;
int enteredNumber = 0;
struct Node * startOfMyList = NULL;
printf("How many nodes do you want in your linked list?");
scanf("%d",&howManyNodes);
while(counter < howManyNodes){
printf("Enter number: ");
scanf("%d",&enteredNumber);
startOfMyList = insertNodeIntoLinkedList(enteredNumber,startOfMyList);
counter++;
}
display(startOfMyList);
getch();
return 0;
}
This is my simple program to insert and display nodes of a linked list. However, the line:
startOfList = (struct Node *)malloc(sizeof(struct Node));
gets flagged as an error. I do not know why.
What is going wrong here ?
A: Your malloc seems to be correct.
For your new error it is simply because in main you are calling insertNodeIntoLinkedList and you define the function before:
insertNodeInLinkedList
// ^^
Also, you need to include <stdlib.h> for the malloc function.
| |
doc_23526604
|
<div id="mydiv" style="color: white; height: 1080px; width: 1920px; transform: translate(-27px, -323px) scale(0.972, 0.401);">
<div class="player_controls">
<a class="right carousel-control" href="#" data-slide="next"><span class="glyphicon glyphicon-chevron-right"></span></a>
</div>
</div>
This code contains the
transform: translate(-27px, -323px) scale(0.972, 0.401);
which apply to child element player_controls,a tags.
So can do something like not affect the child element?
I tried to remove transform from player_controls
#mydiv .player_controls{transform:''}
A: Child elements will always get affected by transform on the parent element. This is not something that a child inherits and hence it cannot be over-ridden by using transform: ' ' or transform: none on the child. One way to counter it would be to apply the reverse transform on the child. Here, since the scale shouldn't affect the child, the inverse of the parent's scale should be applied to it.
The scaleX on parent is 0.972 and so the scaleX on child should be 1/0.972 (inverse) which is 1.028. Similarly for scaleY it shouldbe 1/0.401 which is 2.493.
#mydiv,#mydiv2 {
height: 200px;
width: 200px;
background: red;
transform: translate(27px, 23px) scale(0.972, 0.401);
}
#mydiv .player_controls {
transform: scale(1.028, 2.493);
transform-origin: left top;
}
<h2>With reverse transform on child</h2>
<div id="mydiv">
<div class="player_controls">
<a class="right carousel-control" href="#" data-slide="next"><span class="glyphicon glyphicon-chevron-right">Some icon</span>Some text</a>
</div>
</div>
<h2>With no reverse transform on child</h2>
<div id="mydiv2">
<div class="player_controls">
<a class="right carousel-control" href="#" data-slide="next"><span class="glyphicon glyphicon-chevron-right">Some icon</span>Some text</a>
</div>
</div>
If for whatever reason you are unable (or unwilling) to apply the reverse transform on the child element then you'd have to change your structure and make the child element a sibling element.
.container {
position: relative;
}
#mydiv {
position: absolute;
top: 0px;
left: 0px;
height: 200px;
width: 200px;
background: red;
transform: translate(27px, 23px) scale(0.972, 0.401);
transform-origin: 0px 0px;
}
.player_controls {
position: absolute;
top: 23px;
left: 27px;
}
<div class="container">
<div id="mydiv">
</div>
<div class="player_controls">
<a class="right carousel-control" href="#" data-slide="next"><span class="glyphicon glyphicon-chevron-right">Some icon</span>Some text</a>
</div>
</div>
| |
doc_23526605
|
Currently, my issue is that the tick events don't actually do anything while the application isn't active. As soon as the user goes back into the application, the tick events run to the point that they would've otherwise, but the sound effect (or anything else) wont actually play unless the application is active, or switches to being active.
I do have in my Page.xaml.cs:
PhoneApplicationService.Current.ApplicationIdleDetectionMode = IdleDetectionMode.Disabled;
The relevant code is:
void dispatcherTimer_Tick(object sender, EventArgs e)
{
var remaining = this.EndTime - DateTime.Now;
int remainingSeconds = (int)remaining.TotalSeconds;
this.timeSpan.Value = TimeSpan.FromSeconds(remainingSeconds);
if (remaining.TotalSeconds <= 0)
{
this.dispatcherTimer.Stop();
button1.Visibility = Visibility.Collapsed;
button6.Visibility = Visibility.Visible;
this.EndTime = DateTime.MinValue;
this.timeSpan.Value = TimeSpan.FromSeconds(0);
BackgroundAudioPlayer.Instance.Play();
}
}
What can I do to make the tick events run while the application is under the lockscreen, or other wise not active?
A: Windows Phone has strict limits on background working. May be you need permission to work under lockscreen?
http://developer.nokia.com/community/wiki/Run_Windows_Phone_application_under_lock_screen
But it only stays application active under lockscreen, but not when user press windows or closes your app.
| |
doc_23526606
|
I have an xunit test project in dotnet core 5 that has a Window. The test sets the content of a frame to a new page. However the assertion to check the content is not null will not work as the ViewNavigator content is null.
This is using Xunit.StaFact to allow running tests under STA thread.
Window
<Window x:Class="acme.foonav.FrameNavigationWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
Title="FrameNavigationWindow" Height="450" Width="800">
<StackPanel>
<Frame x:Name="ViewNavigator"></Frame>
</StackPanel>
</Window>
Test
[UIFact]
public void Navigate_To_Pages()
{
FrameNavigationWindow window = new();
var monitor = new ManualResetEventSlim(false);
window.ViewNavigator.NavigationService.Navigated += (sender, args) => monitor.Set();
window.ViewNavigator.ContentRendered += (sender, args) => monitor.Set();
// set content here
window.ViewNavigator.Content = new PageNoVm1();
monitor.Wait(TimeSpan.FromSeconds(5));
// content always null
Assert.Equal(typeof(PageNoVm1), window.ViewNavigator.Content.GetType());
}
Page
Just an empty page.
<Page x:Class="acme.foonav.Pages.PageNoVm1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:acme.foonav.Pages"
mc:Ignorable="d"
Title="PageNoVm1" Height="450" Width="800">
<Grid>
</Grid>
</Page>
I can't spot anything obviously wrong.
** Updates **
I have tried using different flavours of window.Dispatcher.Invoke to set the Content:
var monitor = new ManualResetEventSlim(false);
window.ViewNavigator.NavigationService.Navigated += (sender, args) => monitor.Set();
window.ViewNavigator.ContentRendered += (sender, args) => monitor.Set();
var page = new PageNoVm1();
window.Dispatcher.Invoke(() => window.ViewNavigator.Content = page);
monitor.Wait(TimeSpan.FromSeconds(3));
A: Why are you synchronously blocking for 3 or 5 seconds? If WPF needs some time, you're not feeding it this way -- you're starving it.
Try changing the test method to be async, and then use await to give WPF time:
-monitor.Wait(TimeSpan.FromSeconds(5));
+await Task.Delay(5000);
I don't know if this will solve the problem, but it's a better way to pause execution in general.
| |
doc_23526607
|
I have a button which is stays in the correct place across devices. It's constraints are
Session List Button.Bottom = Safe Area.Bottom - 32, priority 1000
Session List Button.CenterX = Save Area.Center X
Then I have have a UILabel that I want to go just above the button. It's constraints are
Subtitle Label.Bottom = Safe Area.Bottom - 72, priority 998
Subtitle Label.Width = Safe Area.Width
The label doesn't stay above the button when I change devices in IB. It moves all over the place - sometimes way above or way below the button.
I don't understand why the views don't move when I change the constraints in their constraints, so that might be a clue as to what I am missing.
I have also tried the same constraints relative to the superview and the background but also got unpredictable results.
A: It looks like the issue is just a bug in IB. When I run the app the constraints seem to work correctly.
| |
doc_23526608
|
enableProdMode(); in main.ts. Are these actions the same and trigger the same mechanism?
A: ng build --prod is shorthand for ng build --configuration=production. As part of this, the build process will reference your angular.json file, specifically in this situation the 'configurations' section:
"configurations": {
"production": {
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.prod.ts"
}
],
...
In environment.prod.ts is the following (by default):
export const environment = {
production: true
};
If you then look at your main.ts file you will see this code (again, by default):
if (environment.production) {
enableProdMode();
}
So, as you can see ng build --prod will enable prod mode. Enabling prod mode will disable some validation, speeding up your code. Additional the build process when running with the production configuration will also do the following (again, by default):
*
*Ahead-of-Time (AOT) Compilation: pre-compiles Angular component templates.
*Production mode: deploys the production environment which enables production mode.
*Bundling: concatenates your many application and library files into a few bundles.
*Minification: removes excess whitespace, comments, and optional tokens.
*Uglification: rewrites code to use short, cryptic variable and function names.
*Dead code elimination: removes unreferenced modules and much unused code.
source
A: But remember that if you do something like this:
ng build --env=dev --prod
then flags from production envy are going to be overwritten. I checked it as I was still having problems with performance despite using --prod flag on non prod envy. This is important when building demos, benchmarking builds and so on.
A: The --prod flag triggers the --environment=prod flag (among other things). This means that the environment file defined as prod in the environments array of the .angular-cli.json is used during compilation.
If you have the default main.ts this will indeed mean it runs enabledProdMode(). Because they use this to trigger it:
if (environment.production) {
enableProdMode();
}
and in the environment file the production property is set to true.
| |
doc_23526609
|
#include <cstdlib>
#include <iostream>
using namespace std;
int doArray(int *arr) {
int sz = 10;
arr = (int*) malloc(sizeof(int) * sz);
for (int i=0; i<sz; i++) {
arr[i] = i * 5;
}
return sz;
}
int main(int argc, char *argv[]) {
int *arr = NULL;
int size = doArray(arr);
for (int i=0; i<size; i++) {
cout << arr[i] << endl;
}
return 0;
}
For some reason, the program terminates on the first iteration of the for loop in main()! Am I doing something wrong?
A: If you want to allocate memory that way you have to use:
int doArray(int*& arr)
else the pointer will only be changed inside the function scope.
A: You need to add an extra level of indirection to doArray. As written it allocates the array properly but it doesn't communicate the pointer value back to the caller correctly. The pointer from malloc is lost once you return.
If you wrote a function to take a float and change the value, passing the changed value back to the caller, it would need to take a pointer: foo(float *f). Similarly, here you want to pass back an int* value to the caller so your function must be declared as doArray(int **arr) with a second asterisk.
int doArray(int **arr) {
int sz = 10;
*arr = (int*) malloc(sizeof(int) * sz);
for (int i=0; i<sz; i++) {
(*arr)[i] = i * 5;
}
return sz;
}
int main(int argc, char *argv[]) {
int *arr = NULL;
int size = doArray(&arr);
for (int i=0; i<size; i++) {
cout << arr[i] << endl;
}
return 0;
}
Notice how it now dereferences *arr inside of doArray, and how the call is now written as doArray(&arr).
A: You're passing in the array pointer by value; this means that when your doArray function returns, the value in arr in main is still NULL - the assignment inside doArray doesn't change it.
If you want to change the value of arr (which is an int *), you need to pass in either a pointer or a reference to it; hence, your function signature will contain either (int *&arr) or (int **arr). If you pass it in as a ** you'll also have to change the syntax inside the function from using arr to *arr (pointer-dereferencing), and you'll call it like so: doArray(&arr).
Also, in C++ you should really be using new int[sz] instead of malloc.
A: The arr variable in your function is a local copy of the arr pointer in the main function, and the original is not updated. You need to pass a pointer-to-pointer or pointer reference (the former will also work in plain c, the later only in c++).
int doArray(int **arr)
or
int doArray(int*& arr)
A: Change signature to (specific for c++):
int doArray(int *&arr)
so pointer would be changed at exit from doArray.
A: You need a pointer to a pointer in your doArray() parameter. If you've never done any programming with pointers before, this can be confusing. I find that it can be easier to see the right types if you annotate your code abundantly with typedefs.
You have the right idea that (int*) can be used to represent an array. But if you want to change the value of your variable arr in main(), you need a pointer to that, and so you will end up with (untested code) something like the following
typedef int *IntArray;
int doArray(IntArray *arr) {
int sz = 10;
*arr = (IntArray) malloc(sizeof(int) * sz);
IntArray theArray = *arr;
for (int i=0; i<sz; i++) {
theArray[i] = i * 5;
}
return sz;
}
when calling doArray, you will need to pass the address of your variable (so doArray knows where to write to):
int main(int argc, char *argv[]) {
int *arr = NULL;
int size = doArray(&arr);
for (int i=0; i<size; i++) {
cout << arr[i] << endl;
}
return 0;
}
This should work.
A: As others have pointed out, you're passing your array (the int *) by value, so when you say arr=... you're not actually changing the array you passed in.
You're also got a memory leak, as you've written it. It's not a big deal when you only call doArray once in the body of your program, but if it gets called repeatedly and the array is never freed (or deleted, if you made it with new) then it can cause problems. Typically the best way to deal with this is by using the STL. You'd then write
#include <vector>
#include <iostream>
int doArray(std::vector<int> &arr) {
int sz = 10;
arr.resize(sz);
for (int i=0; i<sz; i++) {
arr[i] = i * 5;
}
return sz;
}
int main(int argc, char *argv[]) {
std::vector<int> arr;
int size = doArray(arr);
for (int i=0; i<size; i++) {
std::cout << arr[i] << std::endl;
}
return 0;
}
However, with the STL there are more idomatic ways than returning the size, since you can just ask for arr.size(), and if you get really fancy, can use functions like for_each or the ostream_iterator to print all your elements.
| |
doc_23526610
|
src/main/java/rewards/testdb/schema.sql
src/main/java/rewards/testdb/test-data.sql
src/main/java/rewards/testdb/config/alternate-datasource-config.xml
src/main/java/rewards/testdb/config/AlternateDataSourceConfigTests.java
The bean configuration under test (from alternate-datasource-config.xml):
<bean id="dataSource-createdFromList" class="org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseFactoryBean" lazy-init="true">
<property name="databaseName" value="rewards" />
<property name="databasePopulator">
<bean class="org.springframework.jdbc.datasource.init.ResourceDatabasePopulator">
<property name="scripts">
<util:list>
<value>classpath:rewards/testdb/schema.sql</value>
<value>classpath:rewards/testdb/test-data.sql</value>
</util:list>
</property>
</bean>
</property>
</bean>
I'm encountering an error in my unit test:
Caused by: java.io.FileNotFoundException: class path resource [rewards/testdb/schema.sql] cannot be opened because it does not exist
at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:157)
However, if I modified the directories to:
src/main/java/rewards/testdb/config/schema.sql
src/main/java/rewards/testdb/config/test-data.sql
src/main/java/rewards/testdb/config/alternate-datasource-config.xml
src/main/java/rewards/testdb/config/AlternateDataSourceConfigTests.java
and modify my bean config:
<bean id="dataSource-createdFromList" class="org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseFactoryBean" lazy-init="true">
<property name="databaseName" value="rewards" />
<property name="databasePopulator">
<bean class="org.springframework.jdbc.datasource.init.ResourceDatabasePopulator">
<property name="scripts">
<util:list>
<value>classpath:rewards/testdb/config/schema.sql</value>
<value>classpath:rewards/testdb/config/test-data.sql</value>
</util:list>
</property>
</bean>
</property>
</bean>
...my test passes.
Why?
A: In your idea project configuration, point target path as your projects target folder: Edit Configurations->Deployment->Edit Artifact(Click on pencil icon)-> set "Output Directory" input as "your_project_folder_path/target "
Then whenever you edit jdbc.properties file, this will take effect with a restart.
This is valid for maven web projects.
A: Spring will interpret the resource references as relative (to your test class). You should always make sure to use absolute paths in your resource references, i.e.:
<value>classpath:/rewards/testdb/schema.sql</value>
<value>classpath:/rewards/testdb/test-data.sql</value>
(note the initial forward slash in the resource specifications)
| |
doc_23526611
|
A: Your assumption is correct.
Due to the pigeonhole principle, it is mandatory that (2^128) + 1 UUIDs will have at least one duplicate since there are only (2^128) possibilities.
| |
doc_23526612
|
-bash-3.2$ netstat -tulpn | egrep 'Proto|LISTEN'
(Not all processes could be identified, non-owned process info
will not be shown, you would have to be root to see it all.)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
tcp 0 0 72.167.2.1:50336 0.0.0.0:* LISTEN -
tcp 0 0 0.0.0.0:1248 0.0.0.0:* LISTEN -
tcp 0 0 0.0.0.0:4118 0.0.0.0:* LISTEN -
tcp 0 0 72.167.2.1:50328 0.0.0.0:* LISTEN -
tcp 0 0 0.0.0.0:12345 0.0.0.0:* LISTEN 4767/java
and I can connect normally to it with python through the command line:
-bash-3.2$ python
Python 2.4.3 (#1, Nov 11 2010, 13:34:43)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import socket
>>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> port=12345
>>> host='127.0.0.1'
>>> s.connect((host,port))
but when I run it through the following cgi script, it is unable to connect:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port=12345
host='127.0.0.1'
try:
s.connect((host,port))
except:
print sys.exc_info()
It gives me the following:
(, error(111, 'Connection refused'), )
I checked the cgi file permissions, and they are 755 (rwxr-xr-x).
Do I need to specify something in the service to make it accessible for cgi scripts to connect to it? Or is there soething that I can do from the cgi script itself or any other suggestion?
EDIT:
I found this piece of info that the hosting company godaddy doesn't support socket creation from cgi:
http://support.godaddy.com/help/article/20/does-your-cgi-service-support-socket-connections-or-socket-modules
So, is there another way to send a file to tika from CGI?
| |
doc_23526613
|
- Group: group-tmp
- created by user user1@company.com
- members:
- user1@company.com (owner)
- group-service@quickstart-...iam... (owner) <-- service user
- Project: quickstart-XXXXX
- owners:
- user1@company.com (owner)
- group-service@quickstart-...iam... (owner)
- config:
- api enabled using this website: https://console.cloud.google.com/apis/library/groupssettings.googleapis.com?project=grupo-tmp
with the following piece of python code:
#!/usr/bin/python
from __future__ import print_function
import json
import httplib2
from googleapiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
with open('service_secrets.json') as f:
json_loaded = json.load(f)
credentials = ServiceAccountCredentials.from_json_keyfile_dict(
json_loaded,
scopes=["https://www.googleapis.com/auth/apps.groups.settings"])
http = httplib2.Http()
http = credentials.authorize(http)
service = build('groupssettings', 'v1', http=http)
groups = service.groups()
print('step 4')
g = groups.get(groupUniqueId="group-tmp@company.com").execute()
print('step 5')
it always fail between steps 4 and 5 with the following error message:
googleapiclient.errors.HttpError: <HttpError 401 when requesting https://www.googleapis.com/groups/v1/groups/group-tmp@company.com?alt=json returned "Authorization Failed". Details: "Authorization Failed">
| |
doc_23526614
|
Physics Liquid
Currently I render the liquid particles as circles just like in the first image, but I want to make it look more natural like on the third one.
The answer might be to use distance field and I tried this approach, but with no effect. I'm drawing each particle as a texture using SpriteBatch class, but that can be changed. I made a texture (from a procedural Pixmap) that represents each particle as a filled circle, with alpha channel decreasing further from the center, so the effect is similar to the second picture.
Now, I must enable a threshold filter to alpha channel, something like: "draw only pixels with alpha > 0.5". This is post-processing step, because it matters what is the alpha channel of a pixel after all particles have been draw. Might or might not be done with shaders (ProgramShader), but after some research I still have no clue how to do this. Thanks for ANY help.
EDIT: this example explains the method, but it's implemented in ActionScript.
A: This can easily be done using shaders, but funny thing is that you don't need to write them.
"draw only pixels with alpha > 0.5" is also used while rendering distance field fonts (fonts which look good even when scaled up).
*
*Follow this link : https://github.com/libgdx/libgdx/wiki/Distance-field-fonts
*Directly jump to the last step.
*You should find exactly what you want.
Hope this helps.
| |
doc_23526615
|
My current solution is: since there is "multiple_table" option in Tabula, I can count the number of elements in DataFrame with len(DataFrame). However, I cannot test it due to some font issue. (See error message below)
Oct 01, 2019 8:25:15 PM org.apache.pdfbox.pdmodel.font.FileSystemFontProvider addTrueTypeFont
SEVERE: Could not load font file: C:\WINDOWS\FONTS\mstmc.ttf
Please refer to this LINK for a sample PDF file. For this sample file, my desired output will be 3 tables (1 on each page of 1, 4, and 5) and 1 chart (on Page 4). I use Python but I'm open to any other language. Any help is highly appreciated for either the font issue or table recognition.
| |
doc_23526616
|
$ rails generate refinerycms-news
Could not find generator refinerycms-news
I have already installed refinerycms-news by using this command
gem install refinerycms-news
i have already installed follow gems but i dont know what is the actual problem :(
$ bundle list
Gems included by the bundle:
* abstract (1.0.0)
* actionmailer (3.0.11)
* actionpack (3.0.11)
* activemodel (3.0.11)
* activerecord (3.0.11)
* activeresource (3.0.11)
* activesupport (3.0.11)
* acts_as_indexed (0.7.7)
* arel (2.0.10)
* awesome_nested_set (2.1.2)
* babosa (0.3.6)
* bcrypt-ruby (3.0.1)
* builder (2.1.2)
* bundler (1.0.21)
* devise (1.4.9)
* dragonfly (0.9.10)
* erubis (2.6.6)
* friendly_id_globalize3 (3.2.1.6)
* globalize3 (0.1.0)
* i18n (0.5.0)
* json (1.6.5)
* mail (2.2.19)
* mime-types (1.17.2)
* orm_adapter (0.0.6)
* polyglot (0.3.3)
* rack (1.2.5)
* rack-cache (1.1)
* rack-mount (0.6.14)
* rack-test (0.5.7)
* rails (3.0.11)
* railties (3.0.11)
* rake (0.9.2.2)
* rdoc (3.12)
* refinerycms (1.0.9)
* refinerycms-authentication (1.0.9)
* refinerycms-base (1.0.9)
* refinerycms-core (1.0.9)
* refinerycms-dashboard (1.0.9)
* refinerycms-events (1.0)
* refinerycms-generators (1.0.4)
* refinerycms-i18n (1.0.0)
* refinerycms-images (1.0.9)
* refinerycms-pages (1.0.9)
* refinerycms-news (1.2.0)
* refinerycms-resources (1.0.9)
* refinerycms-settings (1.0.9)
* routing-filter (0.3.0)
* seo_meta (1.1.1)
* sqlite3 (1.3.5)
* thor (0.14.6)
* treetop (1.4.10)
* truncate_html (0.5.1)
* tzinfo (0.3.31)
* warden (1.0.6)
* will_paginate (3.0.3)
please help me
A: actually # in ruby is a comment. all code after # will not run
So when you remove # bundler install refinerycms-news too
| |
doc_23526617
|
I have been doing load tests with JMeter and when I have more than 300 listeners my server needs more than 4 seconds to answer, which is too much for my needs, or the listener never receives the answer.
I need to get all the responses in less than a second.
Does long polling have connections limit?
Do I need a special configuration or server?
Thanks in advance,
A: No special configuration needed, it's just a matter of CPU/RAM on your server plus how long does it take to process the controller call (how many requests to DB, etc).
As Play is stateless, if you are getting timeouts, just try to add a second server behind a load balancer and that should solve the issue.
Edit on comments:
The main issue you are having is that Play takes long to propagate the events to 300 users. That's kind of expected, as the Chat sample uses an in-memory system to do the propagation, passing the message sequentially to each subscriber.
There is another with the Chat approach: if you were to use a second server, the messages won't be shared between them, as the ArchivedEventStream is stored locally in the Play instance JVM.
If you want more performance you need to move the publish/subscribe step to an external Message Queue tool, like Redis. This will have the benefit of letting you add extra instances while sharing the same messages across them.
A: It does not sound like you are reaching a connection limit for long polling on your Play server. Rather, you are probably reaching some form of bottleneck which is causing response times to degrade.
A strong possibility is that you are reaching a limit on the machine that is executing the JMeter test, the chances of this increase if you are running in GUI mode. You can verify if this is the case or not by using multiple machines to repeat the test, simply execute the same test on two machines at the same time, if they both show identical results to when only one test is running then logially the problem is not your Play server but the test itself. If, however, you see worse results with two tests running, then the problem is with your server. Remember to use a ramp up time, this will help identify the point at which things start to slow down which is useful for tuning.
If you are reaching a JMeter limit then try running from the command line, this is much more efficient or, if you really want the interface, then try using less listeners, these are the things which cause problems.
| |
doc_23526618
|
HTML:
<!DOCTYPE html>
<html ng-app="MyTestApp">
<head>
<title>Angular test</title>
<script type="text/javascript"> src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script type="text/javascript"> src = "app.js"></script>
</head>
<body>
<div id="divx" ng-controller="MyTestController">
<input type="text" ng-model="name">
<h2>{{name}}</h2>
</div>
</body>
</html>
JavaScript:
(function () {
'use strict';
angular.module('MyTestApp', [])
.controller('MyTestController', function ($scope) {
$scope.name = "Angular";
$scope.sayHello = function () {
return "From function";
};
});
})();
A: There are two issues,
(i) The scripts should be refereed as
<script type="text/javascript" src="angular.min.js"> </script>
<script type="text/javascript" src="app.js"> </script>
(ii) You should not place {{name}} inside a input element. change it inside a <h1> or <p> tag as follows.
DEMO
(function () {
'use strict';
angular.module('MyTestApp', [])
.controller('MyTestController', function ($scope) {
$scope.name = "Angular";
$scope.sayHello = function () {
return "From function";
};
});
})();
<!DOCTYPE html>
<html ng-app="MyTestApp">
<head>
<title>Angular test</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</head>
<body>
<div id="divx" ng-controller="MyTestController">
<input type="text" ng-model="name">
<h1> {{name}}</h1>
</div>
</body>
</html>
| |
doc_23526619
|
Get the TTL value.
If TTL ranges from 120 to 128 then it is a windows system.
Now query first registry.
If the query was successful then proceed querying other 6 more registries and keep writing the results to a txt file.
The ping part I was able to get using following:
for /l %%a in (1,1,254) do for /f "tokens=8 delims=^= " %%b in ('ping -n 1 192.168.1.%%a ^| find /I "TTL"') do echo 192.168.1.%%a -- Online , TTL: %%b
Now I need to add IF condition to it. But it doesn't show any output:
for /l %%a in (1,1,254) do for /f "tokens=8 delims=^= " %%b in ('ping -n 1 192.168.1.%%a ^| find /I "TTL"') do if %%b==128 echo 192.168.1.%%a -- Online , TTL: %%b
Next I need to query following registry:
reg query HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\ComputerName\ActiveComputerName /v computername 2>null >> query_result.txt
If it is success, query rest of the registries.
And this all process has to be repeated for all 254 IP addresses.
In a plain and slow working way I did it followingly (for example):
for /l %%i in (1,1,254) do (reg query \\192.168.1.%%i\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\ComputerName\ActiveComputerName /v computername >> result.txt & reg query \\192.168.1.%%i\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion /v productname 2>null >> result.txt)
Although above code also works, but it is extremely slow, becoz it tries to query registry on dead IP addresses also. I had been following the three methods seperately in pieces using 3 result files. I want to club them.
How can I add all of them together? Plz clarify the application of IF conditional statements, on how to use them. I've been trying for 2 days but no success.
Thanks
marc_kriss
A: for /l %%a in (1,1,254) do for /f "tokens=8 delims=^= " %%b in ('ping -n 1 192.168.1.%%a ^| find /I "TTL"') do if %%b==128 echo 192.168.1.%%a -- Online , TTL: %%b
Close, but it will only output if %%b is exactly 128. If you want %%b in the range 120 to 128, then you'd need
... do if %%b leq 128 if %%b geq 120 echo ...
where leq means less than or equal to. I'll let you guess what geq means...
Instead of the echo here, you could naturally use
... geq 120 (
echo processing 192.168.1.%%a onine TTL %%b
req query...192.168.1.%%a ...
)
to perform the reg query using the selected on-line machine addreses.
Response to comment:
On my machine, I found
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 192.168.0.1: bytes=32 time=1ms TTL=64
Since you didn't post a sample filtered-ping result either, I have to use this data.
Now in the first result, 128 appears as %%b`
In the second, TTL appears since there's a = as time, not <. So tokens would need to be 9 not 8.
Or you could assign the entire string to an environment variable yourstring in delayedexpansion mode and then use
set "yourstring=!yourstring:*TTL=!"
set "yourstring=!yourstring:~1!"
Then you'd need to compare !yourstring! to 120,128 instead of %%b.
Revision
@ECHO OFF
Setlocal EnableDelayedExpansion
for %%a in (192.168.0.1 192.168.0.2 192.168.0.3 127.0.0.1) do for /f "delims=" %%b in ('ping -n 1 %%a ^| find /I "TTL"') do (
ECHO TTL line found FOR %%a is %%b
set "yourstring=%%b"
set "yourstring=!yourstring:*TTL=!"
set "yourstring=!yourstring:~1!"
ECHO yourstring is "!yourstring!"
if !yourstring! leq 128 if !yourstring! GEQ 65 (
echo %%a online , TTL: !yourstring!
ECHO now DO whatever with "%%a" or "!yourstring!"
reg query HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\ComputerName\ActiveComputerName /v computername 2>nul
)
ECHO end report FOR %%a ===============================
)
GOTO :EOF
Results on my machine:
TTL line found FOR 192.168.0.1 is Reply from 192.168.0.1: bytes=32 time<1ms TTL=64
yourstring is "64"
end report FOR 192.168.0.1 ===============================
TTL line found FOR 192.168.0.2 is Reply from 192.168.0.2: bytes=32 time<1ms TTL=128
yourstring is "128"
192.168.0.2 online , TTL: 128
now DO whatever with "192.168.0.2" or "128"
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\ComputerName\ActiveComputerName
computername REG_SZ OWEN-PC
end report FOR 192.168.0.2 ===============================
TTL line found FOR 127.0.0.1 is Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
yourstring is "128"
127.0.0.1 online , TTL: 128
now DO whatever with "127.0.0.1" or "128"
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\ComputerName\ActiveComputerName
computername REG_SZ OWEN-PC
end report FOR 127.0.0.1 ===============================
Note: error in the selection of the string after TTL corrected - a stray ~ sneaked in (corrected)
I've used a set selection of addresses - you're obviously aware of how to return this to for /l %%a ... and how to build 192.168.1.%%a as required.
I can't test what you appear to want to retrieve from the active machines (computer name?) as I don't have any other machines active. I've just used what came back with a TTL response.
Note nul not null Using the latter will create a file called null.
Note that for /l takes 3 parameters - there are 4 on your comment.
The caret is not required (but harmless) in "delims== " The characters between the first = and the " are delimiters - but the space must be last (for future reference) - "delims=" turns off all delimiters as the delimiter-count is not reliable in this application.
Note also I've removed the redirection to query_result.txt to show the results on-screen.
| |
doc_23526620
|
I could test this with 2 pieces of code, but due to optimization and such I'm really just curious about the mechanics. From a C perspective it feels like calling all objects to be released sounds more intense, but maybe the dealloc tree in Objective-C might be efficient enough for ARC to do this at an equal speed?
A: Some code has to loop through that array inside NSMutableArray, and call release on all its non-nil objects. If there is a difference between what code does it, inside ARC or inside NSMutableArray, it should not be noticeable, because the expensive part is not the loop overhead, it's the actual call of release and potential deallocation following it.
There is a more significant difference, though: when you call removeAllObjects, the array retains its internal storage, so it would not have to grow its internal size the next time you start appending to it. If your usage pattern calls for repeated addition of large number of items to the same array, calling removeAllObjects may save you some allocation/reallocation cycles.
| |
doc_23526621
|
MOD/ABC//BF/56/290/BB/0//////
DAM/DEF//BF/25/450/BB/0//////
My program is below where I'm able to print each row, able to print each row through indices, however I'm having trouble with defining a function where I can take that list of rows, delimit out the "/" and then use that cleaned data to calculate quantities.
My ideal output would be to use the cleaned data to quantify how much "MOD" or "DAM" there are with the same lines if they contain the same variables like "BF" or "BB".
Output like this:
MOD, ABC, BF, BB - x45
MOD, ABC, WF - x5
DAM, DEF, BF, BB - x12
Any pointers appreciated! My output from my function is that it does split each object from the txt file and eliminates the "/" but it prints each row onto one long line.
How can I split those onto new lines?
a = "tring.txt" #This can be changed to a = input("Enter filename: ", )
file1 = open(a, "r")
with open(a) as file:
lines = [line.rstrip('\n') for line in file]
print(*lines, sep = "\n")
print("\n")
print(f'Searchable by index: {lines[0]}')
print("\n")
#Defines the function to split the elements.
b = file1.read()
def split_lines(b, delimiter):
split_txt = b.split(delimiter)
cleaned_split_txt = [line.rstrip('\n') for line in split_txt]
print(cleaned_split_txt, sep = "\n")
split_lines(b, '/')
file1.close()
A: It looks like you've already read the file in to variable lines. You can just pass those lines into whatever function you want to use to parse them. Then loop over each line, and parse it however you need.
Something like the following.
def split_lines(lines, delimiter):
for line in lines:
tokens = line.split(delimiter)
print(tokens)
split_lines(lines, '/')
| |
doc_23526622
|
I need to get the target element on drop either their Id or the whole object
I tried
const [{ canDrop, isOver }, drop] = useDrop(
() => ({
accept: ItemType,
drop: (item, monitor) => addTaskToSprint(item.id, monitor),
})
);
And here's addTaskToSprint declaration
const addTaskToSprint = (id, monitor) => {
console.log(monitor.getDropResult());
let body = {
sprint: {
id: , //here where I need the target Drop Id
}
};
axios.put(process.env.REACT_APP_API_URL + "/tasks/" + id, body, {
headers: { Authorization: `Bearer ${jwt}` },
});
};
monitor.getDropResult() is returning null in the console
Then I tried the same process inside the drag declaration
const [{ isDragging }, drag] = useDrag(() => ({
type: ItemType,
item: task,
collect: (monitor) => ({ isDragging: !!monitor.isDragging() }),
end(item, monitor) {
console.log(monitor.getDropResult());
},
}));
And in here it's returning the dropEffect. Here's the logs
{
"dropEffect": "move"
}
When I console.log(monitor) inside the drop result it gave me
Where targetId is the targeted drop element, but this Id is generated by react-dnd not the actual Id of the element
When I open the internalMonitor object from the picture above
I got inside nested objects all the drop Targets with their generated Id from react-dnd but I couldn't get the object of each Id (to get the target drop object)
And here's how each object looks like
0: {"T0" => DropTargetImpl}
key: "T0"
value: DropTargetImpl
monitor: DropTargetMonitorImpl
internalMonitor: DragDropMonitorImpl
registry: HandlerRegistryImpl {types: Map(8), dragSources: Map(4), dropTargets: Map(4), pinnedSourceId: null, pinnedSource: null, …}
store: {dispatch: ƒ, subscribe: ƒ, getState: ƒ, replaceReducer: ƒ, @@observable: ƒ}
spec:
accept: "Task Card"
collect: monitor => {…}
drop: (item, monitor) => addTaskToSprint(item.id, monitor, drop)
To be clearer, check the screenshot of the results in the console
A: I have faced the same challenge trying to use the monitor object of react dnd library, but was getting the same result as yours. I decided to share here how I've solved that. The solution is pretty simple and you can pass whatever info you need to the props collection when rendering the draggable / droppable component and then you use that info within the useDrag() / useDrop() methods.
Here below is an example of how to control draggable answers, so that to be dropped on a form depending on the exercise / task they belong to (item.task_id === props.task_id):
function DnDAnswerTarget(props) {
const [{canDrop, isOver}, drop] = useDrop({
accept: // ItemTypes to be specified,
canDrop: (item, monitor) => {
return (item.task_id === props.task_id ? true : false);
},
drop: (item, monitor) => {
// Some code for the ondrop event to be executed...
},
collect: (monitor) => (
{
canDrop: !!monitor.canDrop(),
isOver: !!monitor.isOver()
})
});
return (
<Box ref={drop}
>
{props.children}
</Box>
);
}
export default DnDAnswerTarget;
A: Part of the problem here is that monitor.getDropResult() gives you the value returned by your drop() function, but if you're calling addTaskToSprint() directly from drop() then the drop result isn't available yet.
You have a couple of choices here.
If you want to call addTaskToSprint() from the drop target, you might add an extra parameter to accept the target id directly:
drop: (task) => addTaskToSprint(task.id, sprint.id)
Alternatively, if you want to call addTaskToSprint from the dragged object, you could return the target element id from the drop() function and it will be available to the end handler:
// in useDrop() ...
drop: () => ({ sprintId: sprint.id })
// in useDrag() ...
end(task, monitor) {
const dropResult = monitor.getDropResult();
addTaskToSprint(task.id, dropResult.sprintId);
}
| |
doc_23526623
|
<g:AbsolutePanel>
<g:at left='10' top='20'>
<g:Label>Lorem ipsum...</g:Label>
</g:at>
<g:Label>...dolores est.</g:Label>
</g:AbsolutePanel>
Gwt, how to make the above AbsolutePanel to have transparent background?
A: You can do that using css.
.transparent
{
z-index: 2;
opacity: 0.9;
}
Change the opacity level according to your preference. Then add this class to your absolute panel
| |
doc_23526624
|
Here is another example. I currently have the HTTP 415 error on some application. When I get it deployed using a .war file under the folder webapps, I get that error. However, if I put the uncompressed version of the application under webapps/ROOT, the error disappears and my application is working perfectly.
This brings me to my question. How are these two folders different? What can explain these differences between these folders?
A: After having tried different things, this is what I have found:
I realized that the folder webapps is the folder defined as being the 'appBase' of the server. (This variable can be configured in the server.xml file, located in the conf folder, which is seen from the root file of your apache tomcat) In other words, it serves as the direct location where Tomcat searches for application.
What is not told, however, is that Tomcat does not go into the folders; which is why my web applications could get updated and receive errors under webapps, but not under ROOT. I know this because I changed the 'appBase' variable directly to where my applications were and suddenly they were showing errors from tomcat.
If changes are made to a web application under the 'appBase' defined path, they need to be reloaded a specific way. One is to use Tomcat Manager feature, and the other is to delete the files in your work folder (found from your main Apache Tomcat folder. keep clicking into folders from the work folder until you get to your web application's main folder). The Tomcat Manager feature can be a more tedious task to implement, because one needs to know about how to configure users for tomcat (in tomcat-users.xml, found under the conf folder), and documentation for this is limited. The second solution, which is to delete your web application found under the work folder, can be done while tomcat is running and will implement your changes in the instant.
More details are found on another Stack Overflow post: How to force tomcat to reload recently compiled class/war files
| |
doc_23526625
|
However, I have an error and the app doesn't even open.
Here is some code:
Class Intro
class Intro : AppCompatActivity(), View.OnClickListener {
lateinit var mPager : ViewPager
var layouts : IntArray = intArrayOf(R.layout.first_slide,R.layout.second_slide,R.layout.third_slide)
lateinit var dotsLayout : LinearLayout
lateinit var dots: Array<ImageView>
lateinit var mAdapter : PageAdapter
lateinit var btnNext: Button
lateinit var btnSkip: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_intro)
if(PrefManager(this).checkPreferences()){goToHomePage()}
if(Build.VERSION.SDK_INT >=19)
{
window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
}else{
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
}
mPager=findViewById(R.id.pager)
mAdapter= PageAdapter(layouts,this)
mPager.adapter= mAdapter
dotsLayout = findViewById(R.id.dots)
btnNext = findViewById(R.id.btnNext)
btnSkip=findViewById(R.id.btnSkip)
btnSkip.setOnClickListener { this }
btnNext.setOnClickListener { this }
createDots(0)
mPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener{
override fun onPageScrollStateChanged(state: Int) {
}
override fun onPageScrolled(
position: Int,
positionOffset: Float,
positionOffsetPixels: Int
) {
}
override fun onPageSelected(position: Int) {
createDots(position)
if(position == layouts.size){
btnNext.setText("DONE")
btnSkip.visibility=View.INVISIBLE
}else{
btnNext.setText("NEXT")
btnSkip.visibility=View.VISIBLE
}
}
})
}
fun createDots(position:Int){
if(dotsLayout!=null){
dotsLayout.removeAllViews()
}
dots = Array(layouts.size,{i -> ImageView(this)})
for(i in 0..layouts.size -1) {
dots[i] = ImageView(this)
if (i == position) {
dots[i].setImageDrawable(ContextCompat.getDrawable(this, R.drawable.active_dots))
} else {
dots[i].setImageDrawable(ContextCompat.getDrawable(this, R.drawable.inactive_dots))
}
var params: LinearLayout.LayoutParams = LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)
params.setMargins(4,0,4,0)
dotsLayout.addView(dots[i],params)
}
}
override fun onClick(v: View?) {
when(v!!.id){
R.id.btnSkip ->{
goToHomePage()
PrefManager(this).writeSharedPreferences()
}
R.id.btnNext ->{
loadNextSlide()
}
}
}
private fun goToHomePage() {
startActivity(Intent(this, HomePage::class.java))
finish()
}
private fun loadNextSlide() {
var nextSlide: Int = mPager.currentItem+1
if(nextSlide<layouts.size){
mPager.setCurrentItem(nextSlide)
}
else{
goToHomePage()
PrefManager(this).writeSharedPreferences()
}
}
}
Class PrefManager
class PrefManager {
lateinit var context : Context
lateinit var pref: SharedPreferences
constructor(context: Context) {
this.context = context
getSharedPreferences()
}
private fun getSharedPreferences(){
pref = context.getSharedPreferences(context.getString(R.string.pref_name), Context.MODE_PRIVATE)
}
fun writeSharedPreferences(){
var editor : SharedPreferences.Editor=pref.edit()
editor.putString(context.getString(R.string.pref_key),"NEXT")
editor.commit()
}
fun checkPreferences() : Boolean
{
var status: Boolean = false
status = !pref.getString(context.getString(R.string.pref_key),null).equals("null")
return status
}
fun clearPreferences(){
pref.edit().clear().commit()
context.startActivity(Intent(context, HomePage::class.java))
(context as AppCompatActivity).finish()
}
}
The app works but the buttons next and skip don't respond whe clicked. Why is this happening?
Update: I changed some redundant thing on the code and uncommented the part that I've previous commented, and I don't have the error anymore. But the buttons still don't work
| |
doc_23526626
|
The date is stored as an object: date object.
It looks like this in the dataframe when it's not filled: date NaT.
If I write a function that looks like this if pd.to_datetime(data['date']) == None or if pd.to_datetime(data['date']) == pd.NaT it's not working.
How could I verify this condition ?
A: You can use isnull
>>> df
Year Week_No Value
0 2015-01-01 52 3
1 2016-01-01 2 7
2 NaT 51 5
3 2016-01-01 1 6
4 2015-01-01 50 4
>>>
>>>
>>> df.Year.isnull()
0 False
1 False
2 True
3 False
4 False
Name: Year, dtype: bool
| |
doc_23526627
|
interface Props {
label: string;
children?: React.ReactNode;
withoutActions?: boolean;
fieldKey?: KeyProperties;
corporate: Corporate;
}
The withoutActions and fieldKey are used by a form.
If the withoutActions prop is true, then there should not be a provided fieldKey.
However, if my withoutActions is undefined, then i should enforce my fieldLabel to be of type **KeyProperties** which is a specific list of available values for it.
If withoutActions is undefined, the other SHOULD NOT be defined at all
If withoutActions is true, the other SHOULD be defined respecting the specific keyProperties type.
How can i implement that ?
A: I did not fully understand your requirement, but I would use a type alias instead of an interface. E.g. something like this:
type Props = {
label: string,
children?: React.ReactNode,
withoutActions: true,
corporate: Corporate
} | {
label: string,
children?: React.ReactNode,
withoutActions: undefined,
fieldKey: KeyProperties,
corporate: Corporate
}
A: Similar to the other answer, but you can refactor it a bit to be cleaner. You did not specify what the expected behavior is if withoutActions is false instead of true or undefined. Here, I assume the behavior for false and undefined are the same. If false is not a valid type, you could just swap withoutActions?: false for withoutActions: undefined like the other answer.
type Props = {
label: string;
children?: React.ReactNode;
corporate: Corporate;
} & (
{
withoutActions: true;
} |
{
withoutActions?: false;
fieldKey: KeyProperties;
}
)
However, there is an important pitfall here that you should be aware of. Because of TypeScript's structural typing, you only get excess property checking when you are directly assigning an object literal. You do not get excess property checking when you assign an an object as an inferred type. TypeScript and React treat direct props declarations as if they are object literals, and will do excess property checking like you seem to desire. However in some cases, if you assign objects to variables and let their type be inferred, TypeScript may not warn that there is an excess property present.
Check out this demo based on your original example. Example #1 and #2 will error because of excess property checking, but example #3 will not.
const ExampleOne = () => {
// Type error - excess property checking
return <Component label={''} corporate={''} withoutActions fieldKey={''} />;
}
const ExampleTwo = () => {
const props: Props = {
label: '',
corporate: '',
withoutActions: true,
// Type error - excess property checking
fieldKey: '',
}
return <Component {...props} />;
}
const ExampleThree = () => {
const props = {
label: '',
corporate: '',
withoutActions: true,
fieldKey: '',
}
// No type error - no excess property checking
return <Component {...props} />;
}
| |
doc_23526628
|
When loading the page in vertical view, everything is good, switching to horizontal view is also not a problem.
But when I turn the phone again so that it enters vertical view again, something strange happens. The vertical version is displayed, but it seems that the body does not properly resize. I get a big empty area on the right and a vertical scrollbar, while the elements on the webpage are displayed on the left. Screenshots:
Vertical #1
Horizontal
Vertical #2
This is the CSS code I have on my body (Note: I am still working on that project, so the colors and the font is only temporarily written like that):
body {
margin: 0;
background-color: grey;
color: black;
font-family: Georgia, serif;
line-height: 1.5;
background-image: url(../img/bg.png);
}
And I also use em based media queries, like:
@media only screen and (min-width: 30em) {
/* Stuff */
}
Inside the media queries I don't change anything on the body.
In the head of my HTML file I have
<meta name="viewport" content="width=device-width, initial-scale=1.0">
Some debugging showed me, that the body element resizes correctly, but the html element does not.
Do you have any idea what could cause that problem?
A: html:
<meta name="viewport" content="initial-scale=1.0">
try adding css:
@media only screen and (-webkit-min-device-pixel-ratio : 2) and (orientation:portrait),
only screen and (min-device-pixel-ratio : 2) and (orientation:portrait)
and,
@media only screen and (-webkit-min-device-pixel-ratio : 2) and (orientation:landscape),
only screen and (min-device-pixel-ratio : 2) and (orientation:landscape)
for retina displays.
maybe this link can help you https://developer.mozilla.org/en-US/docs/CSS/Media_queries
A: Ok, I finally figured this out! See this Question, it's the exact problem I am having.
HTML5 Placeholder Text Adding Width In Safari Causing Scrollbars And Flickering
| |
doc_23526629
|
forbidden_chars = ["!",",",...]
check ARRAY (it is the string split into an array) for forbidden chars
erase all words with forbidden chars
Could anyone help me please? I just consider searching for the words with the cards and retrieving index as mandatory in the answer please. Thank you very much :)
A: string = 'I like my coffee hot, with no sugar!'
forbidden_chars = ['!', ',']
forbidden_chars_pattern = forbidden_chars.map(&Regexp.method(:escape)).join('|')
string.gsub /\S*(#{forbidden_chars_pattern})\S*/, ''
# => "I like my coffee with no "
The idea is to match as many non-white space characters as possible \S*, followed by any of the forbidden characters (!|,), followed by as many non-white space characters as possible again.
The reason we need the Regexp.escape is for the cases when a forbidden character has special regex meaning (like .).
A: string = 'I like my coffee strong, with no cream or sugar!'
verboten = '!,'
string.split.select { |s| s.count(verboten).zero? }.join ' '
#=> "I like my coffee with no cream or"
Note this does not preserve the spacing between "I" and "like" but if there are no extra spaces in string it returns a string that has no extra spaces.
| |
doc_23526630
|
A: Its not a bug, select_type_options property type is an object, so you should feed it an object value with key/value
Fix your code from
"select_type_options":"width:200px;"
into
select_type_options: { width: '200px;' }
See from docs:
* select_type_options
Required: false
Type: Object
Default value: {}
Description: This parameter will be passed "as is" to the Chosen/Select2 plugin constructor
You can also find this in the showcase code snippet
| |
doc_23526631
|
Is there a way to bypass it?
$("#fileinput").change(function(evt){
var r = new FileReader();
r.onload = function(evt){ //file loaded successfuly
contents = evt.target.result;
...
}
r.readAsText(f);
});
| |
doc_23526632
|
Label hint is centered inside input field and when you click on it and enter some text, label moves up and text that you inputed is slightly below center(below where hint previously was)
Problem is that I am not able to reproduce this behaviour on Android as text that I input stays in the same position as a placeholder.
Not centered hint and icon, but they should be
This is correct, as the label is moved up and password is below center line
Code:
<com.google.android.material.textfield.TextInputLayout
android:id="@+id/et_password"
style="@style/Widget.MaterialComponents.TextInputLayout.FilledBox.Dense"
android:layout_width="0dp"
android:layout_height="65dp"
android:layout_marginTop="16dp"
android:background="@drawable/edittext_bg"
android:hint="@string/password"
app:boxStrokeWidth="1dp"
app:passwordToggleEnabled="true">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/tiet_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#00000000"
android:inputType="textPassword"
android:textSize="17sp" />
</com.google.android.material.textfield.TextInputLayout>
A: try this
<com.google.android.material.textfield.TextInputLayout
android:layout_width="match_parent"
android:hint="First Name"
android:layout_height="wrap_content"
app:hintTextAppearance="@style/formTextAppearance">
<com.google.android.material.textfield.TextInputEditText
android:id="@+id/firstNameEditText"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_margin="2dp"
android:importantForAutofill="no"
android:background="@null"
android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ "
android:inputType="textCapSentences"
android:maxLength="150"
android:textSize="18sp" />
</com.google.android.material.textfield.TextInputLayout>
@styles ...
<style name="formTextAppearance" parent="@android:style/TextAppearance">
<item name="android:textColor">@android:color/black</item>
<item name="android:textColorHint">@android:color/black</item>
<item name="colorAccent">@android:color/black</item>
<item name="colorControlNormal">@android:color/black</item>
<item name="colorControlActivated">@android:color/black</item>
<item name="android:textSize">14sp</item>
</style>
| |
doc_23526633
|
$scope.uploadFile = function(files) {
var fd = new FormData();
//Take the first selected file
fd.append("file", files[0]);
$http.post("logoTypesServiceStore", fd, {
withCredentials: true,
headers: {'Content-Type': undefined },
transformRequest: angular.identity
}).success( function(data) {alert(data); }).error( function(data) { alert(data)});
};
Below is the form to upload file.
<form name="logoTypeForm" novalidate>
<input type="text" name="logoType" ng-model="logoType" class="form-control" required />
<input type="file" name="file" onchange="angular.element(this).scope().uploadFile(this.files)"/>
</form>
A: I would recommend to already specify the files you would like to accpet within your input tag like so:
<input type="file" name="files" accept="image/*">
For more information check out the W3Schools reference for the input tag.
A: Modern browsers have File API support.
$scope.uploadFile = function(files) {
files[0].type; //MIME type
files[0].size; //File size in bytes
};
Here is a list of image MIME types
| |
doc_23526634
|
from("direct:send_success")
.to("http4://localhost:8089/mock/success?httpClient.socketTimeout=1000");
Using this way, I'm able to apply socket timeout of 1 sec successfully. I am using ProducerTemplate to invoke this route. This is all fine. But when I change the route to-
from("direct:send_success")
.to("http4://localhost:8089/mock/success");
And route invocation to-
ProducerTemplate pt = ctx.createProducerTemplate();
Exchange ex = pt.send("direct:send_success", exOb -> {
HttpComponent httpComp = exOb.getContext().getComponent("http4", HttpComponent.class);
exOb.getContext().getComponent("http4", HttpComponent.class).setHttpClientConfigurer(httpClientBuilder -> {
HttpClientBuilder
.create()
.setDefaultRequestConfig(requestConfigWithTimeout(1000))
.build();
});
});
And the method requestConfigWithTimeout() as-
private static RequestConfig requestConfigWithTimeout(int timeoutInMilliseconds) {
return RequestConfig.copy(RequestConfig.DEFAULT)
.setSocketTimeout(timeoutInMilliseconds)
.build();
}
The timeout settings are not applied. Where am I going wrong?
A: You cannot change the http component after the Camel route has been created and started. Then the route was created with the http4 component which has not had its configured changed with that extra code you do.
So configure the http4 component earlier and not when you send the message.
| |
doc_23526635
|
abstract class SuperHero { val team: String }
abstract class Marvel extends SuperHero
case class DrStrange(team: String) extends Marvel
case class Hulk(team: String) extends Marvel
abstract class DC extends SuperHero
case class BatMan(team: String) extends DC
case class Flash(team: String) extends DC
abstract class Tower {
type SH <: SuperHero
val superHero: SH
def teamName: String = s"I am ${superHero.team}"
}
class HulkTower(val superHero: Hulk) extends Tower {
type SH = Hulk
}
object TowerOfHero{
def apply[F <: SuperHero](f: F) : Tower { type SH = F } = new Tower {
override type SH = F
override val superHero : SH = f
}
}
val drStrangeTower = TowerOfHero(DrStrange("Avengers"))
val hulkTower : Tower { type SH = Hulk } = TowerOfHero(Hulk("Avengers"))
val hulkTower2 : HulkTower = new HulkTower(Hulk("Avengers"))
Below are the reference which confuse me:
val dtStrange5: drStrangeTower.SH = hulkTower2.superHero
Above code generate compile time error which is fine, because it refers to different types.
val hulk5: HulkTower#SH = hulkTower.superHero
val hulk6: HulkTower#SH = hulkTower2.superHero
Above code compile successfully which is fine, because of type projection. In type projection path of type does not depend.
val hulk7: hulkTower.SH = hulkTower2.superHero
Above code compile successfully, but I am expecting compile time error. Because of hulkTower.SH type path is different from hulkTower2.superHero type path.
Why this last snippet code is executed?
A: You will need inner class for that. First, let's look at your example:
class HulkTower(val superHero: Hulk) extends Tower {
type SH = Hulk
}
You're saying "Any HulkTower has the SH type defined as Hulk". Two HulkTower instances will both have the same SH type, and thus the compiler doesn't complain.
Inner class involve defining a class inside another:
class A {
class B {
}
}
val a1 = new A
val a2 = new A
val a1_b = new a1.B
val a2_b = new a2.B
val x: a1.B = a2_b // compile error
https://scastie.scala-lang.org/O8qE6LKBSU6tL9RytKZn5w
Note the nested class definition. You're essentially saying "each instance of A has their own instance of class B"
| |
doc_23526636
|
What should I go with? Any problems that I would face with MDF? Recommendations?
A: IF you use SQL Server Express - which is a server - I would always opt for a "real" database approach: attach your database to the server, access it by its database name, deploy SQL scripts to update it.
That "attach DB from file path" always seemed like a half-baked and rather messy kludge to me.....
If you don't need that kind of power - investigate SQL Server Compact Edition which is a one-file only, in-process database. It has its limitations - no stored procedures, doesn't support certain data types like VARCHAR(MAX) or XML - but for easier scenarios, it's perfect and easy to use - just deploy it along your app. It's single-user, e.g. you don't share the data between several clients, it's a local store for each user/app on its own
| |
doc_23526637
|
def "Login and Move to checkout page"(){
}
SonarQube considered it as groovy method and shows as bug that the method name should start with small l and not capital L [Login and Move....}
Could you please somebody help in customize sonar rule so that it ignores spock method
A: If it is not required on your project you may exclude Spock tests from Sonar analyzing at all:
sonar.exclusions=src/test/*.groovy
Otherwise you should probably find the corresponding rule and change the default regular expression, e.g. ^[a-zA-Z0-9]+$. But I am not sure you can do this specifically only for groovy test files.
A: I have configured the Sonarqube to ignore Sonar's rule "Method name" for folder where Geb spock scripts are present
It works fine
To know how to configure,follow below steps:
1.Goto Administration tab->Analysis Scope->Issues
2.There , you will find "Ignore Issues on Multiple Criteria".
3.Provide Rule ID in "Rule Key pattern" textbox [Rule ID can be found by clicking on the particular rule and find it in top right
corner]
4.Provide Filepath for which you need to ignore rule in "File Path Pattern" textbox
5.Click on Save Issues settings
Refer below images to know where to see the rule name and where to configure the path
| |
doc_23526638
|
I am been thinking to use the Codable protocol but KeyPath does not conform to it.
I tried using NSCoding/Data mechanism, but no success.
Is there a way to achieve this?
Thanks!
| |
doc_23526639
|
const fetch = require ('node-fetch')
var gId = 0;
var ps = {}
var lId = gId; gId ++;
ps[lId] = task(lId)
lId = gId; gId ++;
ps[lId] = task(lId)
//will add many more tasks
async function task(id) {
console.log("starting..")
var url = "http://localhost/prod/te.php";
var r1 = await fetch(url).then((r) => r.text())
console.log(new Date() + "|" + id)
await wait(parseInt(r1) * 1000)
var r2 = await fetch(url).then((r) => r.text())
console.log(new Date + "|" + id)
ps[id].then(() => console.log("deleted promise " + id))
delete ps[id]
}
async function wait(ms) {
return new Promise (function (resolve, reject) {
setTimeout(function() {
console.log("expired")
resolve(0)
}, ms)
})
}
A: Did some tests and it comes down to, promises will not be leaked at all (which will cause memory leak as I feared). Ran the following code for a long time and the memory consumption on my Mac hovers around 100MB.
const fetch = require ('node-fetch')
var gId = 0;
start()
async function start() {
var lId;
var count = 0;
while (1) {
lId = gId; gId ++;
task(lId)
count ++;
if (count == 100) {
count = 0;
await wait(500)
}
}
}
async function task(id) {
var url = "http://localhost/prod/te.php";
var r1 = await fetch(url).then((r) => r.text())
await wait(parseInt(r1) * 1000)
var r2 = await fetch(url).then((r) => r.text())
}
async function wait(ms) {
return new Promise (function (resolve, reject) {
setTimeout(function() {
resolve(0)
}, ms)
})
}
| |
doc_23526640
| ||
doc_23526641
|
Any ideas please?
A: When using the new ruby, the image folder will go to asset folder on folder app
after placing your images in image folder, use
<%=image_tag("example_image.png", alt: "Example Image")%>
A: simple just use the img tag helper. Rails knows to look in the images folder in the asset pipeline, you can use it like this
<%= image_tag "image.jpg" %>
A: Anything in the public folder is accessible at the root path (/) so change your img tag to read:
<img src="/images/rss.jpg" alt="rss feed" />
If you wanted to use a rails tag, use this:
<%= image_tag("rss.jpg", :alt => "rss feed") %>
A: In a Ruby on Rails project by default the root of the HTML source for the server is the public directory. So your link would be:
<img src="images/rss.jpg" alt="rss feed" />
But it is best practice in a Rails project to use the built in helper:
<%= image_tag("rss.jpg", :alt => "rss feed") %>
That will create the correct image link plus if you ever add assert servers, etc it will work with those.
A: It's working for me:
<%= image_tag( root_url + "images/rss.jpg", size: "50x50", :alt => "rss feed") -%>
A: image_tag is the best way to do the job friend
| |
doc_23526642
|
My script call:
./notifier.sh usernameArg contentArg
My script:
#!/bin/bash
curl -X POST -H "Content-Type: application/json" -d '{"username": "$1", "content": "$2"}' "https://<discord webhook url>"
But all it sends is {"username": "$1", "content": "$2"}.
I also tried to use ${1} and ${2} with same result.
Thanks for your help in advance!
A: Try this instead.
#!/bin/bash
curl -X POST -H "Content-Type: application/json" -d '{"username": "'$1'", "content": "'$2'"}' "https://<discord webhook url>"
| |
doc_23526643
|
if (b < 0 && ((lon > 8 && lon < 0) || (lat > 8 && lat < 0)))
{
return false;
}
else
{
return true ;
}
A: decomposing each value...
int lon = -3;
int lat = 7;
if (b < 0 && // i don't know b value
((-3 > 8 && //false
-3 < 0) //true
|| (7 > 8 && //false
7 < 0 //false
)))
{
return false;
}
else
{
return true ;
}
it results in
int lon = -3;
int lat = 7;
if (b < 0 && // i don't know b value
(false || false))
{
return false;
}
else
{
return true ;
}
and finally is:
if (false)
{
return false;
}
else
{
return true ;
}
then it return true!
A: Though the logic flawed with this if statement, maybe there is still something to be learned here. Instead of evaluating the if statement and then returning either true or false, you could clean that up a bit and just do something like:
return b < 0 && ((lon > 8 && lon < 0) || (lat > 8 && lat < 0))
But back to the logical error, perhaps your understanding of how the inequality operators work. It would make more sense if you did something like lon > 0 && lon < 8 which would read as longitude is greater than zero and less than eight.
A: If i am reading your statement correct you will never ever get false. To get false lon must me less than zero AND more than 8 ... that is not possible. The same case with lat.
| |
doc_23526644
|
CharacterSubsetName - a name for a subset of the Unicode character set
which certain component fonts can render. For Windows, the following
names are predefined: alphabetic, arabic, chinese-ms936,
.....................
(the list goes on)
"A font configuration file may define additional names to identify
additional character subsets."
What is the format and where in the fontconfig file should I define additional names for additional character subsets?
| |
doc_23526645
|
My goal is: I made a Black/Light Theme in my app. So whenever i click the toggle the theme of the app changes to black and if i refresh it stays black and if i turn it back to OFF it turns back to light and it stays on light. But my struggle is whenever i refresh the page the toggle doesn't stay on the current state as ON -> black theme and OFF -> Light Theme
So ON -> Black Theme
OFF -> Light Theme
Settings.HTML
<ion-item>>
<ion-label>Light/Dark</ion-label>
<ion-toggle [(ngModel)]="lightDark" [checked]="" (ionChange)="toggleAppTheme()"></ion-toggle>
</ion-item>
Settings.TS
constructor(public navCtrl: NavController,
public navParams: NavParams,
private settings: SettingsProvider) {
this.settings.getActiveTheme().subscribe(val => this.selectedTheme = val);
console.log("Toggled: "+ this.lightDark);
}
toggleAppTheme() {
if (this.selectedTheme == 'light-theme') {
this.settings.setActiveTheme('dark-theme');
localStorage.setItem("themeColor", this.selectedTheme);
} else if (this.selectedTheme == 'dark-theme') {
this.settings.setActiveTheme('light-theme');
localStorage.setItem("themeColor", this.selectedTheme);
}
}
App.Component.ts
// Dark/Light Mode
if(localStorage.getItem("themeColor") == "dark-theme")
{
this.settings.setActiveTheme("dark-theme");
}
else if(localStorage.getItem("themeColor") == "light-theme")
{
this.settings.setActiveTheme("light-theme");
}
A: The ion-toggle component is bound to the lightDark property, but I don't see you're setting its initial value when initializing the page:
constructor(public navCtrl: NavController,
public navParams: NavParams,
private settings: SettingsProvider) {
this.settings.getActiveTheme().subscribe(
val => {
this.selectedTheme = val;
// Initialize the state of the toggle
// It should be true if the theme is the dark one, right?
this.lightDark = this.selectedTheme === 'dark-theme';
// Show the value in the console to see if it works
console.log("Toggled: "+ this.lightDark);
},
error => {
// Handle the error...
});
}
| |
doc_23526646
|
'texture2D' : type is for Vulkan api only
Isn't this call somehow compatible with compute shaders?
A: It's not 100% clear from your question what tool you use to compile your shaders, or do you compile at runtime?. texture2D has been depcrecated for sampling in OpenGL (ES) shaders.
For Vulkan (as the message says) there is a "texture2D" that is used to read form a texture that's separated from the sampler (for detail see https://www.khronos.org/registry/vulkan/specs/misc/GL_KHR_vulkan_glsl.txt).
For OpenGL ES 2.x (and up) you would use sampler2D (or sampler2DShadow) for sampling from a texture or image2D for read and writes in a compute shader.
| |
doc_23526647
|
The data comes in something like this:
Name,ID,Date,Supervisior CRLF
Joe,123,1/1/2020,George CRLF
Mike,456,2/1/2020,George CRLF
Dan,789,4/1/2021,George
If there is only one row of data then my code works the data displays on screen just fine.
If there is more than one row I get an error "Input array is longer than the number of columns in this table."
I tried doing a split on comma and environment new line (also vbCRLF); none of those resolved the issue.
Any ideas on how I can resolve this?
Here is my code:
Dim vartable As DataTable = New DataTable()
vartable.Columns.Add("Name", GetType(String))
vartable.Columns.Add("ID", GetType(String))
vartable.Columns.Add("Date", GetType(String))
vartable.Columns.Add("Supervisior", GetType(String))
Dim inputstring As String
inputstring = (apiresponse) 'redacted API code as it works fine If I just display 'raw data to text field
Dim rowData As String() = inputstring.Split(New Char() {",",Environment.NewLine})
vartable.Rows.Add(rowData) 'this is where I get the input array error if 'more than one row of 'data
GridView1.DataSource = vartable
GridView1.DataBind()
A: It looks like you're expecting the Split() function to act on each of the delimiters separately, so you get an array of arrays, with each element in the outer array holding one line/row. This is not how it works.
You need to separate the lines first, and then in a loop for each line separate the contents by comma. The test way to do this is NOT by calling Split(). Instead, you can use a StringReader (which is different from StreamReader):
Using rdr As New StringReader(apiresponse)
Dim line As String = rdr.ReadLine()
While line IsNot Nothing
Dim rowData As String() = line.Split(","c)
vartable.Rows.Add(rowData)
line = rdr.ReadLine()
End While
End Using
But I would be surprised to learn the code to access the API doesn't also need to deal with streams at some point, even if you don't see it directly, meaning there exists a possible version of this that is even more efficient from using StreamReader connected to the api response directly.
For fun, since it's been a while since I've had to do this in VB, I made this extension module:
Public Module TextExt
<Extension()>
Public Iterator Function AsLines(data As TextReader) As IEnumerable(Of String)
Dim line As String = data.ReadLine()
While line IsNot Nothing
Yield line
line = data.ReadLine()
End While
End Function
<Extension()>
Public Iterator Function AsLines(data As String) As IEnumerable(Of String)
Using rdr As New StringReader(data)
For Each line As String In AsLines(rdr)
Yield line
Next
End Using
End Function
End Module
Which would let me write it like this:
For Each row As String() In apiresponse.AsLines().Select(Function(ln) ln.Split(","c))
vartable.Rows.Add(row)
Next
Finally, I need to add my customary warning about how it's a really bad idea to use .Split() as a CSV parser.
| |
doc_23526648
|
What I want to do is make so that when my plugin is installed in Eclipse, it modifies the preferences to assign the .pdf file association to the system's pdf viewer.
I realize that this might be a bad idea, since I can't assume that a user has a PDF viewer installed on his/her PC.
I noticed that when I right click the .pdf file in the project explorer, that I get a choice to "Open With" various options like "Default Editor" and "System Editor". I'd like my plugin to make the default action be Open With -> System Editor.
Is this possible? If so, how?
A: Try Window > Preferences > General > Editors > File Associations.
Add *.pdf if it is not there. Highlight it and then add an associated editor. Select the External programs radio and then Adobe Acrobat Document or another reader program.
A: It does not look like it is possible to change or add a file association without using internal classes.
You can get the existing file associations with:
IEditorRegistry editorRegistry = PlatformUI.getWorkbench().getEditorRegistry();
IFileEditorMapping [] mappings = editorRegistry.getFileEditorMappings();
but updating the list requires using the EditorRegistry implementation of IEditorRegistry and this is an internal class. The implementation of IFileEditorMapping is also internal.
Update:
The org.eclipse.ui.editors extension point does have a command attribute for running an external program and a launcher attribute for running a program via a IEditorLauncher class. You might be able to use one of those.
| |
doc_23526649
|
So i have a while orbiting the camera, but no way to interact with user interface while this happens.
There is anyway to "share", or part the focus in second's decims to be able to interact with user interface?
I tried with cmds.evaldeferred(), but no luck...
Technically, Maya widgets interface is immediately available when script finishes the job...
I'm trying to finish the job with one single camera little orbit, and relaunch it with mouse movement event... Time changing event... But no way how to do that... Would be like a daemon running in the background... No idea how I could reach something like that....
Some code:
import maya.cmds as cmds
#declares global variable
global orbitCam
#just something to see in the scene
cmds.polyCube()
#function to stop camera orbit
def stopOrbiting():
global orbitCam
orbitCam = False
#simplest ui
cmds.window("testWindow")
cmds.formlayout("flo", parent="testWindow")
#button that calls stopOrbit function
cmds.button("pushMeIfYouCan", parent="flo", label="pushMeIfYouCan", c="stopOrbiting()")
cmds.showWindow("testWindow")
#condition for the while
orbitCam=True
#while itself
while orbitCam:
cmds.orbit("persp", ra=(0.2,0.1))
Any way to be able to push the button -and interact with widgets- while camera orbits?
A: Well, based on solution provided by mhlester in the link I posted under the question (and considering a great answer too by theodox, as a wonderful alternative, thank you both, guys), I'm gonna aswer my own question and provide another new detailed explanation perhaps can help somebody in the future.
First of all, Maya's "scriptjob" command utility puts in memory a script (or a function), haves a trigger to start executing that function, and the condition to Maya to execute that function once registered and triggered, is that Maya must to be doing exactly nothing, so, Maya must be idle.
Being that way, Maya never collapses or crashes or hangs by a scriptJob. ScriptJob is basically a... kind of "daemon" working in the background.
The good thing, is that is possible to limit the maximum number of times per second, so you can even maintain your system fresh and working if you want to care it about.
Once a scriptJob is launched (or registered in Maya memory), it can be killed to never runs again, and obviously, can be registered again if we want to start working again.
Exists an internal scriptJobs list inside of Maya, where you can find the scriptjob if you have forgotten to store that scriptJob in a variable, where you can find the "scriptJob ID", just an integer number you can use to kill the job.
After the first theory, let's see some code now:
This line will register a new daemon (maya scriptjob), its reference will be stored in "activeDaemon" variable, it will call a function called "camDaemon" with some arguments:
activeDaemon = registerDaemon(0.04, BackgroundFunction, ArgumentsForBackgroundFunction)
The point here is not just launch the daemon with conditions, besides, to store the daemon id to be able to kill it with:
cmds.scriptJob(kill=activeDaemon)
If we forgotten to store the daemon (scriptjob) id, we can use this command to watch a list with all scriptJobs of Maya:
cmds.scriptJob(listJobs=True)
We would need to find the last ids in the list with the event "idle", and probably we could hit and finished stopping our daemon killing it.
Now let's see "registerDaemon" function (all the absolute credit for MhLester):
def registerDaemon(seconds, backgroundFunction, *args, **kwargs):
def updateNow():
now = time.time()
if now - updateNow.then > seconds:
updateNow.then = now
backgroundFunction(*args, **kwargs)
updateNow.then = time.time()
return cmds.scriptJob(event=("idle", updateNow))
registerDaemon defines an internal function (updateNow) that calls "automatically" at the backgroundFunction we pass as argument, including this "backgroundFunction" arguments. Just that. A function A that defines a function B that calls a function C. And it calls it every quantity of seconds we specify at register the daemon with the first argument, so if we want it executed 25 times per second, 1seg/25fps = 0.04 would be the right value.
To have this function working, we must import the module time in our script with:
import time
Finally it returns the scriptJob id at the same time it registers it in Maya memory, registering with the event "idle" and with the function (B) that calls the function (C) we really want executed in the background. This way we can control the temperatures of the machine not overwhelming the cpu unnecessary. Very complete last line, brilliant, at least, for me.
At this point no other thing left than just register the function we want to have running the background in the Maya memory (take the code you want in the background, put inside a function and execute it one time in Script Editor)
def backgroundFunction():
print "this message shows in idle time by a daemon (Maya scriptjob)"
Of course there are much more in the documentation (Maya scriptJob documentation), as a list of events or conditions, but the base is this.
| |
doc_23526650
|
When I do the same from an instance of SomeClass (bearing in mind that the list is a public member of the Main class) I get the following exception:
0xC0000005: Access violation reading location 0xbaadf0ad.
I am fairly new to coding in C++ coming from a Python background, so I apologise if something doesn't make sense.
Here is an example of the situation:
EDIT: The Main class codes is not actually inside the constructor, its in a method called InitialiseObjects().
EDIT: The exceptions comes from within the list::being() method with the line return (iterator(_Nextnode(_Myhead), this));
#include <list>
using namespace std;
class Main
{
public:
Main::InitialiseObjects()
{
// Execution starts here
SomeClass someClass = new SomClass(this);
someClasses.push_back(someClass);
// This works fine
for (list<SomeClass*>::iterator it = someClasses.begin(); it != someClasses.end(); it++)
...
someClass->AFunction();
}
list<SomeClass*> someClasses;
}
class SomeClass
{
public:
SomeClass::SomeClass(Main *main) : main(main) {}
void SomeClass::AFunction()
{
// This will not work throwing the aformentioned error
for (list<SomeClass*>::iterator it = main->someClasses.begin(); it != main->someClasses.end(); it++)
...
}
private:
Main *main;
}
A: 0xC0000005: Access violation reading location 0xbaadf0ad.
I think that was 0xbaadf00d until you overwrote something in it, which indicates uninitialized heap memory. So, maybe you're dereferencing a non-existant Main*? E.g. main->someClasses.begin() may throw your exception, if main wasn't initialized yet.
And indeed, this is the problem in your code. someClass->AFunction(); calls the function while you're inside the Main-constructor. As such, this will not be completely valid yet, so you can't use it inside the AFunction.
A: As long as you remain inside the Main constructor, the this instance is not yet fully initialised!
Trying to access the instance from elsewhere leads to undefined behaviour. This is happening here since you are accessing this unfinished instance from within SomeClass.
| |
doc_23526651
|
But if I call RetrieveAll and then RetrieveByPrimaryKey with some PK, I see two SQL statements getting issued. My question is, Why AR does not look for that entity in cache first? Sure it would have found it there as a result of previous call to RetrieveAll.
public static T RetrieveByPrimaryKey(Guid id)
{
var res = default(T);
var findCriteria = DetachedCriteria.For<T>().SetCacheable(true);
var eqExpression = NHibernate.Criterion.Expression.Eq("Id", id);
findCriteria.Add(eqExpression);
var items = FindAll(findCriteria);
if (items != null && items.Length > 0)
res = items[0];
return res;
}
public static T[] RetrieveAll()
{
var findCriteria = DetachedCriteria.For<T>().SetCacheable(true);
var res = FindAll(findCriteria);
return res;
}
A: You're using caching on specific queries. that means that cache lookup is done in the following way:
search the cahce for results of a query with identical syntax AND the same parameters. If found- use cached results.
nHibernate (this has nothing to do with AR, by the way) doesn't know that logically, one query 'contains' the other. so this is why you're getting 2 db trips.
I would suggest using ISession.Get to retreive items by ID (it's the recommended method). I think (not tested it though) that Get can use items cached by other queries.
here's a nice blog post from ayende about it.
| |
doc_23526652
|
es.add(components[i][0] for i in components.keys())
components is a python dictionary, which looks like this:
components = {'a': (a0, a1),
'b': (b0, None)}
What I am trying the achieve is that I want to run above mentioned for-loop with except, which will be able to not run the add() function if the components dictionary gives None.
What I tried:
es.add(components[i][1] for i in components.keys() except None)
Ofc it gives a syntax error. What is the syntax for it?
EXAMPLE:
es.add(components[i][1] for i in components.keys())
Above is equal with:
es.add(a1)
es.add(None)
I want to write my for-loop in a way it adds only a1 and skips None.
A: I assume that it is like [components[i][1] for i in components.keys() if type(components[i][1]) != type(None)]
so that below code can work fine
es.add(components[i][1] for i in components.keys() if type(components[i][1]) != type(None))
A: Use an if condition as except is of no use in this case. You can also make it shorter and more readable by iterating the dict.values() directly:
es.add(x for _, x in components.values() if x is not None)
| |
doc_23526653
|
For our software product (web application) clients will need to request a license from us before installing it.
We would need to check if they are a paying client (a manual process at the moment).
I need the ability for one of the initial steps of my installer to be let user request license via a custom page in the NSIS installer.
They would put in some mandatory fields and then this would get fired off in an email.
Ideally, NSIS would let them know that the email had successfully been sent.
They would then exit the wizard, but when we verify who they are and send them a serial (few days later), they can run installer again, and there would be an option to enter the serial, allowing them to progress to the next screen.
Ideally, the custom page will look something like this.
Question:
It is the emailing bit that I am currently stumped on.
I have not seen any plugins to do this.
How can I send an email from a custom page in NSIS?
- I imagine there might be a couple of approaches?
A: Probably best way to send emails is to use external application.
You can develop simple application in C/C++/C# if you have some programming skills, but there exist many apps for this purpose, e.g try this one called bmail:
http://www.beyondlogic.org/solutions/cmdlinemail/cmdlinemail.htm
C:\>mail -s smtp.server -t cpeacock@max -f root@neptune -h -a "Subject e.g. Fatal Error"
-b "Body of message e.g. Fatal Error occurred in cgi script, secure.cgi"
Simply use nsExec plugin to call this .exe with your desired parameters.
Alternatively create.bat file with appropriate parameters, unpack it to $PLUGINS directory together with bmail.exe and launch the .bat using ExecWait command from NSIS.
For creating custom page try this tool for NSIS: http://www.graphical-installer.com - it allows you to create skinned installer with custom page you need.
| |
doc_23526654
|
I think there might be something wrong with my code... Where can I find the persisted RDDs on disk so that I can make sure they were actually persisted?
A: As per the doc:
spark.local.dir (by default /tmp)
Directory to use for "scratch" space in Spark, including map output files and RDDs that get stored on disk. This should be on a fast, local disk in your system. It can also be a comma-separated list of multiple directories on different disks. NOTE: In Spark 1.0 and later this will be overriden by SPARK_LOCAL_DIRS (Standalone, Mesos) or LOCAL_DIRS (YARN) environment variables set by the cluster manager.
A: Two possible reasons for your observation:
*
*RDDs are persisted in a lazy fashion, therefore, to make it work you should call an action(e.g. count()) on it after you call persist()
*Even if you make sure the persist() happens, the actual data may not write to disk actually, your write method is returned directly after the data is write into buffer cache, therefore, when you read it next to write, it simply return the cached data.
So, Did persist happens?
Did you clear linux Buffer cache on each node after persist rdd as DISK_ONLY, before operate on it and measure performance?
So what I suggest you to do is:
*
*persist rdd as DISK_ONLY, invoke an action(e.g. count()), to make it persist.
*sleep the application for a few seconds, clear the cache of all the worker node during this period
sync && echo 3 > /proc/sys/vm/drop_caches
*resume your procedure, and measure the performance of persisted RDD.
| |
doc_23526655
|
find=c
for i in *; do
if [ "${i}" != "${i%.${find}}" ]
then
echo "$i"
grep "^int|^void" "${1}-${i}" | sed 's/{//g'
else
echo "unable to find any funcitions"
fi
done
A: I agree with the commenters, that tool they speak about is ctags, you might already have it on your system. To get the list of functions:
ctags -o - yourFile.c | awk '$4=="f"{print $1}'
| |
doc_23526656
|
How can I do something when that div was clicked, inside another component ?
Can I somehow put dom element to the dependencies array of an useEffect ?
for example:
useEffect(() => {
// Do stuff
}, [document.getElementById('div-that-shows-price')])
I tried the above, didn't work. I even tried it with .textContent, innerHTML, ....
I'm guessing I can't use ref because again, they're in different components. Or can I use a ref defined in a component from another one ?
A: I think you have to use useRef hook:
https://fr.reactjs.org/docs/hooks-reference.html#useref
A: The question is not clear. But from what I understand, why don't you pass price as props to another component? You can put product price in a parent component state and pass it as props (with updatePrice method) in both button components. Or use global state (redux).
A: I am guessing, what you building is basically counter, in one div you want count aka price to be able to incremented and decremented, and in the other div you would like to see the button click result. Since you're using React, this is achieved by useState() and just passing result prop from parent component div which would have the button to the child component div.
| |
doc_23526657
|
After upgrading to macos-mojave I don't seem to be able to compile a simple Rcpp function that would use // [[Rcpp::plugins(cpp11)]]. I've tried:
*
*Editing Makevars following this answer
*Running xcode-select --install following linked discussion on compiling C under macos after upgrade.
*Changing includes, string / string.h leads to the same error
Code
The function, I've drafted to generate the error:
#include <Rcpp.h>
#include <string.h> // std::string, std::stod
using namespace Rcpp;
// [[Rcpp::plugins(cpp11)]]
// [[Rcpp::export]]
NumericVector convertToDouble(Rcpp::StringVector x) {
// Numeirc vector to store results
NumericVector res;
// Double for converted values
double converted_double;
for(Rcpp::StringVector::iterator it = x.begin(); it != x.end(); ++it) {
// Get [] for vector element
int index = std::distance(x.begin(), it);
// Add results to vector
converted_double = std::stod(x[index]);
res.push_back(converted_double);
}
return res;
}
// Source / test
/*** R
Rcpp::sourceCpp(
file = "sample_stod.cpp",
embeddedR = FALSE,
verbose = TRUE,
rebuild = TRUE,
cleanupCacheDir = TRUE,
showOutput = TRUE)
convertToDouble(c("2.3", "34.25a", "abc32def.43", "12", "1.5"))
*/
Errors
>> Rcpp::sourceCpp(
+ file = "sample_stod.cpp",
+ embeddedR = FALSE,
+ verbose = TRUE,
+ rebuild = TRUE,
+ cleanupCacheDir = TRUE,
+ showOutput = TRUE)
Generated extern "C" functions
--------------------------------------------------------
#include <Rcpp.h>
// convertToDouble
NumericVector convertToDouble(Rcpp::StringVector x);
RcppExport SEXP sourceCpp_1_convertToDouble(SEXP xSEXP) {
BEGIN_RCPP
Rcpp::RObject rcpp_result_gen;
Rcpp::RNGScope rcpp_rngScope_gen;
Rcpp::traits::input_parameter< Rcpp::StringVector >::type x(xSEXP);
rcpp_result_gen = Rcpp::wrap(convertToDouble(x));
return rcpp_result_gen;
END_RCPP
}
Generated R functions
-------------------------------------------------------
`.sourceCpp_1_DLLInfo` <- dyn.load('/private/var/folders/7x/kwc1y_l96t55_rwlv35mg8xh0000gn/T/Rtmp2H7VYU/sourceCpp-x86_64-apple-darwin15.6.0-0.12.19/sourcecpp_295d2f3a47a3/sourceCpp_2.so')
convertToDouble <- Rcpp:::sourceCppFunction(function(x) {}, FALSE, `.sourceCpp_1_DLLInfo`, 'sourceCpp_1_convertToDouble')
rm(`.sourceCpp_1_DLLInfo`)
Building shared library
--------------------------------------------------------
DIR: /private/var/folders/7x/kwc1y_l96t55_rwlv35mg8xh0000gn/T/Rtmp2H7VYU/sourceCpp-x86_64-apple-darwin15.6.0-0.12.19/sourcecpp_295d2f3a47a3
/Library/Frameworks/R.framework/Resources/bin/R CMD SHLIB -o 'sourceCpp_2.so' --preclean 'sample_stod.cpp'
clang++ -std=gnu++11 -I"/Library/Frameworks/R.framework/Resources/include" -DNDEBUG -I"/Library/Frameworks/R.framework/Versions/3.5/Resources/library/Rcpp/include" -I"/Users/huski/Documents/R Projects/RcppConversion" -I/usr/local/include -fPIC -Wall -g -O2 -c sample_stod.cpp -o sample_stod.o
sample_stod.cpp:17:28: error: no matching function for call to 'stod'
converted_double = std::stod(x[index]);
^~~~~~~~~
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/string:3910:30: note: candidate function not viable: no known conversion from 'Rcpp::Vector<16, PreserveStorage>::Proxy' (aka 'string_proxy<16, PreserveStorage>') to 'const std::__1::string' (aka 'const basic_string<char, char_traits<char>, allocator<char> >') for 1st argument
_LIBCPP_FUNC_VIS double stod (const string& __str, size_t* __idx = 0);
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include/c++/v1/string:3930:30: note: candidate function not viable: no known conversion from 'Rcpp::Vector<16, PreserveStorage>::Proxy' (aka 'string_proxy<16, PreserveStorage>') to 'const std::__1::wstring' (aka 'const basic_string<wchar_t, char_traits<wchar_t>, allocator<wchar_t> >') for 1st argument
_LIBCPP_FUNC_VIS double stod (const wstring& __str, size_t* __idx = 0);
^
1 error generated.
make: *** [sample_stod.o] Error 1
Error in Rcpp::sourceCpp(file = "sample_stod.cpp", embeddedR = FALSE, :
Error 1 occurred building shared library.
>>
~/.R/Makevars
# Force use of compilers maintained by Homebrew
# Clang and clang++
CC=/usr/local/opt/llvm/bin/clang
CXX=/usr/local/opt/llvm/bin/clang++
CXX1X=clang-omp++
Tried passing CC \ CXX \ CXX1X variables to use compilers installed via Homebrew but does generate a different error message. All compilation attempts fail on
sample_stod.cpp:17:28: error: no matching function for call to 'stod'
*
*Update: can't find stod
*g++ --version
g++ --version
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 10.0.0 (clang-1000.11.45.2)
Target: x86_64-apple-darwin18.0.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
*Current ~/.R/Makevars
# Force use of compilers maintained by Homebrew
# Clang and clang++
# CC=/usr/local/opt/llvm/bin/clang
# CXX=/usr/local/opt/llvm/bin/clang++
# CXX1X=clang-omp++
# Fortran
# FC=/usr/local/opt/gcc/bin/gfortran
# F77=/usr/local/opt/gcc/bin/gfortran
# CC=/usr/local/clang4/bin/clang
# CXX=/usr/local/clang4/bin/clang++
# LDFLAGS=-L/usr/local/clang4/lib
# CPPFLAGS="-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include"
CPPFLAGS="-isystem /Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/include"
A: So, outside of the initial issue with respect to the compiler shenanigans on macOS (covered here), you have to help out the compiler when converting to a std::string from a single value in Rcpp::StringVector in this case.
#include <Rcpp.h>
// [[Rcpp::plugins(cpp11)]]
// [[Rcpp::export]]
Rcpp::NumericVector convertToDouble(Rcpp::StringVector x) {
// Numeirc vector to store results
std::vector<double> res;
// Double for converted values
double converted_double;
for(Rcpp::StringVector::iterator it = x.begin(); it != x.end(); ++it) {
// Get [] for vector element
int index = std::distance(x.begin(), it);
// Help the conversion to string
std::string temp = Rcpp::as<std::string>(x[index]);
// Convert
converted_double = std::stod(temp);
// Add to a std vector... Do not use with Rcpp types
res.push_back(converted_double);
}
// Convert and return the Rcpp type as desired.
return Rcpp::wrap(res);
}
Then, we can run:
convertToDouble(c("2.3", "34.25a", "abc32def.43", "12", "1.5"))
# Error in convertToDouble(c("2.3", "34.25a", "abc32def.43", "12", "1.5")) : stod: no conversion
This errors at: abc32def.43
You may need to do additional cleaning of the string prior to trying a conversion...
| |
doc_23526658
|
Class Parent {
@Id
@Column(name="product")
Long product;
//more fields.
}
Class Child extends Parent {
@Column(name="type")
String productType;
@Column(name="version")
int version;
//more fields.
}
Is it possible to to have a composite primary key in the Child class even though the Child Class extends the Parent which already has a primary key?
A: The short answer is no. In JPA, you can not redefine primary keys. If your parent class has an @ID annotation, no subclass would allow @ID annotations regardless of inheritance strategy.
The longer answer is that if you need to do something like this, you should re-think your object mapping and your inheritance strategy. If you have a parent that already has a uniquely identifiable set of fields, why are you looking to have a child that breaks this convention? And even if you succeed, is this a safe thing for you to do in terms of architecture and code clarity?
| |
doc_23526659
|
I know System.Object is the base type of every type. But since by definition , Struct can't inherit a class then why System.Object is inherit ?
A:
But since by definition , Struct can't inherit a class
That's a false premise. A custom struct must inherit directly from System.ValueType, which itself inherits from System.Object. That is the requirement. It cannot inherit from any other type. So not only can a user defined struct inherit from a class, it in fact must inherit from [a specific] class.
(Note that enums must inherit from Enum, not Object, although Enum inherits from ValueType, which inherits from Object.)
A:
In c#, Struct can't inherit a class
Yes, they cannot inherit from a Custom class, especially being a Value type, since they can only have operations allowed for the Value types like:
*
*Allocation on a simple data structure like Stack, unlike Heap for the reference types
*During a variable copy, being a Value Type, new allocation is made, as in case for primitive types, like Integer, Float, so Struct s1 = s2, creates a brand new copy, but for reference type, it is copy of Reference, which means pointer to same memory
Main point, then why allow to derive from System.Object class, multiple important reasons:
*
*Created CTS (Common / unified Type System), where ultimately type converges to base class System.Object and can thus be represented in a unified manner
*Value types are still primitive in operation and capability as compared to Reference types and has limitation of what they can represent, that's a why a base type is reference type, so that when the need be, conversion can be done via boxing, do allocation on heap and use the functionalities of a reference type
*Allow certain basic common functions exposed by System.Object on all the types, value and reference like ReferenceEquals, GetHashCode, MemberwiseClone,ToString,GetType, though certainly post overriding
| |
doc_23526660
|
Thank you so much for sharing your idea.
A: with extension HTML Related Links v1.0.0 you can create a Table of Content in a View in the Explorer Bar (Next to OUTLINE)
Example Python file:
"""Awesome Python book Code"""
# toc Chapter 1
def foo1():
pass
# toc Chapter 2
def bar2():
pass
# toc -- Chapter 2.1
def bar2Input():
pass
# toc -- Chapter 2.2
def bar2Draw():
pass
# toc Chapter 3
def foobar3():
pass
Use the following setting:
"html-related-links.include": {
"python": [
{
"find": "#\\s*toc\\s*(.+)",
"filePath": "${fileBasename}",
"lineNr": "position.start.line+1",
"charPos": "1",
"label": "$1",
"allowCurrentFile": true
}
]
},
"html-related-links.alwaysShow": true
This gives the following view:
*
*Chapter 1
*Chapter 2
*-- Chapter 2.1
*-- Chapter 2.2
*Chapter 3
If you click on one of the lines in the tree the cursor is moved to the line after the toc-comment. Adjust the lineNr expression if needed.
You can change the # toc comment lines and adjust the Regular Expression of the find property.
| |
doc_23526661
|
id int(11) PK AI
apt_id varchar(200)
checkin_date date
checkout_date date
price decimal(10,0)
deposit decimal(10,0)
adults int(11)
source_id int(11)
confirmationCode varchar(100)
client_id int(11)
booking_date datetime
note mediumtext
Related Tables:property (apt_id → apt_id)
booking_source (source_id → id)
I am trying to insert value in DB using following query
self.start_at = datetime.strptime(self.start_at[0:10] + ' ' + self.start_at[11:19], "%Y-%m-%d %H:%M:%S")
self.end_at = datetime.strptime(self.end_at[0:10] + ' ' + self.end_at[11:19], "%Y-%m-%d %H:%M:%S")
x = db.cursor()
sql = """INSERT INTO `nycaptBS`.`booking` (`apt_id`, `checkin_date`, `checkout_date`, `price`,`deposite` `adults`, `source_id`, `confirmationCode`, `client_id`, `booking_date`) VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s' )"""
x.execute(sql,(self.apt_id,self.start_at,self.end_at,self.final_price,self.deposit,self.adults,self.source_id,self.notes,self.client_id,self.booking_date,self.notes))
Since error itself is not clear
File "/usr/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 159, in execute
query = query % db.literal(args)
TypeError: not enough arguments for format string
PLease help me out how can i resolve this .I worked a lot on Django ORM but for this i have to write in Mysql query .
Thanks
A: This exception is raised when you have more formatting codes in your string, and not enough arguments passed in:
>>> s = "Hello %s %s %s"
>>> print(s % ('a','b'))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
Here you see I have three %s, but I am only passing in two strings ('a','b').
You have the same problem with your query, because you are missing a comma:
sql = """
INSERT INTO `nycaptBS`.`booking` (
`apt_id`,
`checkin_date`,
`checkout_date`,
`price`,
`deposite` `adults`, # missing comma here
`source_id`,
`confirmationCode`,
`client_id`,
`booking_date`) VALUES (
'%s', #1
'%s', #2
'%s', #3
'%s', #4
'%s', #5
'%s', #6
'%s', #7
'%s', #8
'%s', #9
'%s' #10
)
"""
x.execute(sql,(
self.apt_id, #1
self.start_at, #2
self.end_at, #3
self.final_price, #4
self.deposit, #5
self.adults, #6
self.source_id, #7
self.notes, #8
self.client_id, #9
self.booking_date, #10
self.notes #11 ))
| |
doc_23526662
|
itoa (outputCheckSum, outputCheckSumHex, 16)
if (outputCheckSum < 16) { //Adds a 0 if CS has fewer than 2 numbers
outputCheckSumHex[1] = outputCheckSumHex[0];
outputCheckSumHex[0] = '0';
}
Since the output of itoa would be "X" instead of "0X" in the event of X having fewer than 2 characters, the last 3 lines are to move the characters one step back.
I now have plans to scale this up to a CS of 8 characters, and I was wondering whether there exists a function in C++ that can achieve that before I start writing more code. Please let me know if more information is required.
A: You should be able to use memmove, it's one of the legacy C functions rather than C++ but it's available in the latter (in cstring header) and handles overlapping memory correctly, unlike memcpy.
So, for example, you could use:
char buff[5] = {'a', 'b', 'c', '.', '.'};
memmove(&(buff[2]), &(buff[0], 3);
// Now it's {'a', 'b', 'a', 'b', 'c'} and you can replace the first two characters.
Alternatively, you could use std::copy from the algorithm header but, for something this basic, memmove should be fine.
A: You can use memmove in <cstring> for this. It does not check for terminating null characters, but instead copies num bytes (third argument) and works with overlapping regions as well.
void* memmove(void* destination, const void* source, size_t num);
| |
doc_23526663
|
I found a normal slider. I couldn't find good an NPM package for this*
This is what I want exactly:
npm install --save react-native-range-slider
Link :
range-slider
Unfortunately Android doesn't support this :( any suggestion about this ?
A: use this https://github.com/ptomasroos/react-native-multi-slider it has . Options to customize track, touch area and provide customer markers and callbacks for touch events.
| |
doc_23526664
|
public void OpenAppbyName(String appname, String user, String password) {
ComponentName componetName = new ComponentName("com.xxx","com.xxx.yyy.zzz");
Intent intent = new Intent();
intent.setComponent(componetName);
Bundle bundle = new Bundle();
bundle.putString("data", "user1" + "|" + "abc123"); intent.putExtras(bundle);
startActivity(intent);
}
May I know how can I trigger and access this link in react native?
Example something like this :=
com.xxx://com.xxx.yyy.zzz?data=user1|abc123
Please help..
| |
doc_23526665
|
After managing to open all PMU events with specified PID(process mode), I tried to open PMU events with PID=-1 (system mode) at the same time. Good thing is that syscall returned normal number which indicates file descriptor(fd) while in sysmode read returned normal and read normal counts but process mode read 0 count.
By the way, perf stat -e showed the same result.
'perf stat -e' with specified program
'perf stat -e' with no specified program
Is there a limit for perf_event_open while open events under sysmode and process mode ?
| |
doc_23526666
|
My problem is if you click Edit, then click Update WITHOUT actually changing the text box value, it updates sql with the same data and the row moves to the other Gridview. At which point users are unable to change that value for 24 hours.
How can I fix this?
thanks
mike
A: Ok, Here is what was going on. I was thinking that the GridView was doing the updating. I don't know why I was thinking the GridView had anything to do with it. The GridView only pushes values to the data source that actually does the updating.
So when you look at the markup of the DataSource it was running the UPDATE statement that I had set up. The UPDATE was just that, an UPDATE. It did not matter if the data was the same or not.
So I simply changed my UPDATE statement to include an IF to see if the name field was the same or not. When you click "update" on the GridView, yes it still runs the update statement, but if there are no changes, the statement does not update any new data.
Here is the markup for the SQLDataSource, youll see the sql statements that are in it. That is what I had to fix
<asp:SqlDataSource
ID="SqlDataSource1"
runat="server"
ConnectionString="constring"
DeleteCommand="DELETE FROM [RegisteredVisitors] WHERE [PK] = @PK"
InsertCommand="INSERT INTO [RegisteredVisitors] ([ResidentName], [ResidentAddress], [VisitorNumber], [VisitorName]) VALUES (@ResidentName, @ResidentAddress, @VisitorNumber, @VisitorName)"
SelectCommand="SELECT * FROM [RegisteredVisitors] WHERE ([ResidentName] = @ResidentName AND [Date] < (SELECT DateAdd(SECOND, -86400, getdate())))"
UpdateCommand="IF NOT (SELECT [VisitorName] FROM [RegisteredVisitors] WHERE [PK] = @PK) = @VisitorName BEGIN DECLARE @i INT = (SELECT ISNULL(MAX([VisitorNumber]),0) + 1 FROM [RegisteredVisitors]) UPDATE [RegisteredVisitors] SET [VisitorName] = @VisitorName, [Date] = GETDATE() WHERE [PK] = @PK UPDATE RegisteredVisitors SET [VisitorNumber] = @i , @i = @i WHERE [PK] = @PK END;" OnSelecting="SqlDataSource_Selecting1">
<DeleteParameters>
<asp:Parameter Name="PK" Type="Int64" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="ResidentName" Type="String" />
<asp:Parameter Name="ResidentAddress" Type="String" />
<asp:Parameter Name="VisitorNumber" Type="Int32" />
<asp:Parameter Name="VisitorName" Type="String" />
</InsertParameters>
<SelectParameters>
<asp:ControlParameter ControlID="Label1" Name="ResidentName" PropertyName="Text" Type="String" />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name="ResidentName" Type="String" />
<asp:Parameter Name="ResidentAddress" Type="String" />
<asp:Parameter Name="VisitorNumber" Type="Int32" />
<asp:Parameter Name="VisitorName" Type="String" />
<asp:Parameter Name="PK" Type="Int64" />
</UpdateParameters>
</asp:SqlDataSource>
| |
doc_23526667
|
This is my text. I [##something#] have so much text [## it's really crazy. And it's not even [##something#] lorem ipsum [##.
I'm using the [## and #] to be able to easy pick out the contents in between them with regex. But I need to match all the single [## in the text that doesn't have their couterpart #].
I managed to match the last [## with no counterpart #], but I haven't been able to match the single [## in the middle yet, because there is a #] coming up later in the text. I've been mixing negative and positive lookaheads, but haven't quite figured it out.
I've been trying variants of this: /\[##(?!.+#])/g with positive lookaheads to try to limit it only to check until the next [##.
Any help?
A: I should use negative lookahead assertion with a negated char class present inside that.
string.match(/\[##(?![^\[\]]*#\])/g)
DEMO
| |
doc_23526668
|
Can constructors return data types like methods in java?
A: Constructors always return an object of the class they belong to, just like specified in the Java Language Specification.
Unlike method return types, the constructor "return type" is implicit.
A: Not according to the documentation here
Constructor declarations look like method declarations—except that
they use the name of the class and have no return type
A: From the docs
Constructor declarations look like method declarations—except that
they use the name of the class and have no return type.
| |
doc_23526669
|
This causes a problem. See Example
HTML
<!DOCTYPE html>
<html>
<head>
<title>To standard or not to standard</title>
<script src="http://code.jquery.com/jquery-1.7.1.js"></script>
<style type="text/css">
form, table { opacity: 0; filter: alpha(opacity=0); }
</style>
</head>
<body>
<form action="javascript:">
Now you see me...
<table><tr><td>Now you don't!</td></tr></table>
</form>
<script>
$('form, table').animate({
opacity: 1
});
</script>
</body>
</html>
If you view this in IE9, the table will disappear as soon as the animation completes
(beware, if you reload, it may switch to IE7 document standards, go back to IE9 using the F12 tools)
The problem is caused by the inline CSS using only the standard opacity rule, and not the filter rule.
Notice that the parent form has no problem.
In the real world, the table opacity is animated only after an async operation is complete. That is why I cannot put the opacity on the table only.
How would you suggest I overcome this? I was thinking maybe an IE conditional version code in the CSS, or perhaps some additional JavaScript. I could also stop using a table which seems to fix it also, but I wanted to know what you would recommend.
Edit: In case you wonder why I am using a table.
I am using the following layout.
label A: [input ]
label Second: [input ] [button]
The advantages I find here are
*
*The first column automatically sets its width to the widest label.
*The row height is automatically determined by the largest element, in this case that would be the button.
*The label is vertically aligned middle which is more pleasing when aligning to the input.
Alternative A: Div float left align right. With a visibility hidden button on the first row in order to get blank space of exact width for consistent alignment.
Alternative B: Floating divs with hard-coded width for the labels and a fixed line height for the vertical align and row height desired.
A: I'd stop using a table.
Unless you're specifically showing tabular data. In which case, stick the filter rule into a conditional comment targeting IE8 and below
A: It's a little unclear what end-result or effect you're trying to achieve. Why are you using a form with the action="javascript;" when jQuery could handle it nicely?
1) Stop using tables for layout. If it fixes the other issues, then great, but that's only a side benefit.
2a) You're already using jQuery, so you could initially set opacity with it on DOM ready. The benefit is that jQuery then handles any cross browser issues with opacity.
$(document).ready(function() {
$('form, table').css('opacity', 0);
});
2b) Alternatively, you can simply use jQuery's .hide() and .show(), which, when used with duration, animates the opacity.
On DOM ready, it's hidden...
$(document).ready(function() {
$('form, table').hide('fast');
});
and inside whatever function to show it...
$('form, table').show('slow');
2c) Or better yet, don't use opacity to hide it initially...
form, table { display: none; }
and inside whatever function to show it...
$('form, table').show('slow');
EDIT:
As per comments:
<form action="#" ...
Does not require a return false if you use preventDefault in the submit handler...
$('form').submit(function(e) {
e.preventDefault(); // this is first line.
// the rest of your submit function
});
A: I am fine with leaving tables (even after the arguments they bring), so I will favor minimal modifications.
In the real world, the table opacity is animated only after an async operation is complete.
The solution I ended up using was replacing
JavaScript $('form').animate({opacity: 1})
with $('form').animate({opacity: 1}); $('table').css({opacity: 0})
And replacing
CSS form, table { opacity 0; filter: alpha(opacity=0); }
with form { opacity 0; filter: alpha(opacity=0); }.
Thank you everyone for your input. I often learn something new when posting questions here.
| |
doc_23526670
|
<controls:CustomFrame CornerRadius="25,25,0,0" Margin="0" Padding="10" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
<ScrollView>
<AbsoluteLayout BackgroundColor="Silver" AbsoluteLayout.LayoutBounds="0,1,1,1">
<StackLayout x:Name="bottomDrawer" AbsoluteLayout.LayoutBounds="0.5,1.00,0.9,0.04" AbsoluteLayout.LayoutFlags="All">
<StackLayout.GestureRecognizers>
<PanGestureRecognizer PanUpdated="PanGestureHandler" />
</StackLayout.GestureRecognizers>
<CollectionView ItemsSource="{Binding MyPins}" x:Name="ListPlaces"
SelectionMode="None">
SOMETHING
</CollectionView>
</StackLayout>
</AbsoluteLayout>
</ScrollView>
</controls:CustomFrame>
COde behind
public partial class PlacesList : ContentView, INotifyPropertyChanged
{
public List<CustomPin> myPins { get; set; }
public List<CustomPin> MyPins { get => myPins; set { myPins = value; OnPropertyChanged("MyPins"); } }
public ICommand CallPlace { get; set; }
double? layoutHeight;
double layoutBoundsHeight;
int direction;
const double layoutPropHeightMax = 0.75;
const double layoutPropHeightMin = 0.04;
void PanGestureHandler(object sender, PanUpdatedEventArgs e)
{
layoutHeight = layoutHeight ?? ((sender as StackLayout).Parent as AbsoluteLayout).Height;
switch (e.StatusType)
{
case GestureStatus.Started:
layoutBoundsHeight = AbsoluteLayout.GetLayoutBounds(sender as StackLayout).Height;
break;
case GestureStatus.Running:
direction = e.TotalY < 0 ? 1 : -1;
break;
case GestureStatus.Completed:
if (direction > 0) // snap to max/min, you could use an animation....
{
AbsoluteLayout.SetLayoutBounds(bottomDrawer, new Rectangle(0.5, 1.00, 0.9, layoutPropHeightMax));
// swipeLabel.Text = "Swipe me down";
}
else
{
AbsoluteLayout.SetLayoutBounds(bottomDrawer, new Rectangle(0.5, 1.00, 0.9, layoutPropHeightMin));
// swipeLabel.Text = "Swipe me up";
}
break;
}
}
public PlacesList()
{
InitializeComponent();
BindingContext = this;
A: You should use a swipe gesture recognizer to hide/show content view when swiping on view:
<ContentPage.Content>
<StackLayout BackgroundColor="LightYellow">
<!-- Place new controls here -->
<StackLayout.GestureRecognizers>
<SwipeGestureRecognizer Direction="Down" Swiped="SwipeGestureRecognizer_Swiped"/>
<SwipeGestureRecognizer Direction="Up" Swiped="SwipeGestureRecognizer_Swiped"/>
</StackLayout.GestureRecognizers>
<Label x:Name="myLabel" Text="Swipe down to hide me, swipe up to show me" BackgroundColor="Green"
HorizontalOptions="Center"
VerticalOptions="CenterAndExpand" />
</StackLayout>
</ContentPage.Content>
In code behind:
private void SwipeGestureRecognizer_Swiped(object sender, SwipedEventArgs e)
{
switch (e.Direction)
{
case SwipeDirection.Left:
// Handle the swipe
break;
case SwipeDirection.Right:
// Handle the swipe
break;
case SwipeDirection.Up:
// Handle the swipe
myLabel.IsVisible = true;
break;
case SwipeDirection.Down:
// Handle the swipe
myLabel.IsVisible = false;
break;
}
}
| |
doc_23526671
|
#include<stdio.h>
//code to reverse the current array1
void reverse(int array1[]){
int i;
int n=3;
for (i = 0; i <n; i++)
{
array1[i]=array1[n-i-1];
printf("%d\t",array1[i]);
}
}
int main(){
int array1[]={1,2,3};
reverse(array1);
}
result 3 2 3
when i compile this code i am getting 3 in array[0] poistion what is my error?
A: You are reading and writing the same array, so some writing will break data that are not read yet.
Typical way to reverse is to swapping elements in former half and latter half.
void reverse(int array1[]){
int i;
int n=3;
for (i = 0; i <n; i++)
{
if (i < n-i-1) /* avoid swapping the same pair twice */
{
int tmp=array1[i];
array1[i]=array1[n-i-1];
array1[n-i-1]=tmp;
}
printf("%d\t",array1[i]);
}
}
A: Can't write code right now.
You're overwriting array's value at position 0 on the first loop, so when your code checks the value at position 0 it reads the new value instead of the old one).
Create a second array to write the inverted values instead of overwriting them.
| |
doc_23526672
|
Here is the table design:
Here how I try to add a row to the table above:
INSERT INTO Customers (Id, Name)
VALUES (1, 'test');
But I get this error:
Msg 206, Level 16, State 2, Line 1
Operand type clash: int is incompatible with uniqueidentifier
As you can see the ID column of type uniqueidentifier. How do I add a uniqueidentifier to the column above?
A: The uniqueidentifier data type stores 16-byte binary values that operate as globally unique identifiers (GUIDs).
Example using:
insert into customers values('7E3E3BC1-9B15-473C-A45A-46D89689156C', 'Tomas')
insert into customers values(newid(), 'Tomas')
See more details: https://technet.microsoft.com/en-US/library/ms190215(v=sql.105).aspx
A: Use newid():
INSERT INTO Customers(Id, Name) VALUES (newid(), 1);
Note that this would often be done using a default value:
create table customers (
id uniqueidentifier default newid(),
. . .
);
For various technical reasons, it is not recommended to make the uniqueidentifier column a primary key -- although you can get around some of the problems using newsequentialid().. Instead, make it a unique key and have another key (typically an identity() column) as the primary key.
| |
doc_23526673
|
My React component uses the new Date() function:
const Component = () => {
console.log(new Date())
return <h1>Im a component</h1>
}
I need the component to think it's 2018. For my Jest unit tests this was straightforward:
import MockDate from 'mockdate';
MockDate.set('2018-10');
test("test something", ()=>{
// Actual test here
})
MockDate.reset();
How can I do the same with CodeceptJS? Ive tried using the date mocking module in the test:
Scenario('@test', async (CheckoutPage) => {
const MockDate = require('mockdate');
MockDate.set('2018-10');
// Actual test here
});
I also tried dependancy injection. The code within FIX-DATE monkey patches the date:
Scenario(
'@test',
(CheckoutPage, FixDate) => {
FixDate();
CheckoutPage.load();
pause();
}
).injectDependencies({ FixDate: require('./FIX-DATE') });
Neither of these have any affect on the date.
A: The issue is that CodeceptJS is running inside the browser, so you need to override date object of the browser.
Basically you need to override the Date Object of the browser, or the function that is used, for Example:
// create a date object for this Friday:
var d = new Date(2018, 0, 20);
//override Date constructor so all newly constructed dates return this Friday
Date = function(){return d;};
var now = new Date()
console.log(now);
Date.now = function () { return d};
console.log(Date.now());
This is the way to do that in pure JS, the second step is to integrate into codeceptjs, and this can be done using I.executeScript
for Example:
I.executeScript(function () {
var d = new Date(2018, 0, 20);
Date = function(){return d;};
})
You can also create a custom step, for example, I.fakeDate(new Date(2018, 0, 20))
module.exports = function() {
return actor({
fakeDate: function(date) {
I.executeScript(function (fakeDate) {
var d = fakeDate;
window.__original_date = Date;
Date = function(){return d;};
}, date);
},
fakeDateRestore: function() {
I.executeScript(function () {
Date = window.__original_date;
});
}
});
}
Then you just Fake the date when you need, and restore it.
I.Click('beofre');
I.fakeDate(new Date(2018,10,01));
// The test code here
I.fakeDateRestore();
Hope this helps @:-)
| |
doc_23526674
|
One of the arrays look like this:
String[] get_elements = { "firstname", "lastname", "address", "status" };
In a static function, to get what I need to end up with, I would do this:
String name = c.getString(JSON_NAME);
String address = c.getString(JSON_ADDRESS);
String status = c.getString(JSON_STATUS);
Now, what I want to do, is set a string, based on what the content of the array is, like this:
for (int x = 0; x < get_elements.length; x++) {
String get_elements[x] = c.getString(get_elements[x]);
}
The array consists of: firstname, lastname, address and status.
So i want to end up with a loop-defining them as strings and assigning values to those strings, ending up with rawcode:
string firstname = c.getString("firstname");
And so on. I've tried using String get_elements[x] = c.getString(get_elements[x]) with no luck.
Is there a way to dynamically create strings based on the array content?
A: You are replacing the existing element in array. Instead try this:
String result_elements = new String[get_elements.length];
for (int x = 0; x < get_elements.length; x++) {
result_elements[x] = c.getString(get_elements[x]);
}
Hope it solves your issue.
A: No, You can't. The way you tried with array is the something you can try similar to this.
String[] elements=new String[4];
for (int x = 0; x < get_elements.length; x++) {
elements[x] = c.getString(get_elements[x]);
}
A: You cannot build an execute new java code at runtime. Besides, what would be the point of a single String firstname that contains c.getString("firstname") without any further information? You are better to use c.getString("firstname") where you need that sole return value.
You have to posses information about what data corresponds to what index. Take the name "Carter" as an example in addition to the fact, that the number of indices in the array may vary based on the user's choice. How are you going to examine, if "Carter" is the firstname or the lastname?
| |
doc_23526675
|
Item item = new Item {ID = 1, Name = 'One'};
Item item2 = new Item {ID = 2, Name = 'Two'};
List<Item> items = new List<Item>;
items.Add(item);
items.Add(item2);
Then I have another list of other items, with a list inside that is a list of associations to the first item list:
OtherItem otherItem = new OtherItem {ID = 1, Name = 'OtherOne', ListOfItems = {1,2}};
OtherItem otherItem2 = new OtherItem {ID = 2, Name = 'OtherTwo', , ListOfItems = {2}};
List<OtherItem> otherItems = new List<OtherItem>;
otherItems.Add(otherItem);
otherItems.Add(otherItem2);
Now, I want to return a list of Item that are included in the OtherItem ListOfItems. FOr example's sake, how would I return a list of Item where OtherItem's ListOfItems includes ID: 1?
A: items.Where(i => otherItems.Any(oi => oi.ListOfItems.Any(li => li == i.ID)))
A: You can use Where:
List<OtherItem> otherItems = new List<OtherItem>
{
new OtherItem { ID = 1, Name = "OtherOne", ListOfItems = { 1, 2 } },
new OtherItem { ID = 2, Name = "OtherTwo", ListOfItems = { 2 } }
};
var ID = 1;
var result = otherItems.Where(s => s.ListOfItems.Any(x => x == ID))
.Select(s => new { s.ID, s.Name });
| |
doc_23526676
|
import com.datastax.driver.core.utils._
var td = new DateTime(2003,1,1,0,0)
val time_millis = td.getMillis()
val lower = UUIDs.startOf(time_millis)
val upper = UUIDs.endOf(time_millis)
println(lower.getLeastSignificantBits()) # 9187201950435737472
println(lower.getMostSignificantBits()) # -545498504376938025
println(upper.getLeastSignificantBits()) # -9187201950435737471
println(upper.getMostSignificantBits()) # -545455558998945321
Background (in case there is a better way to solve the problem).
I would like to batch import a few thousand records of vehicles into a into a Cassandra database. The date included column contains the day on which the vehicles were added to the original database (VCA) and typically no more than few hundred are added on a particular day, which seems to indicate the entropy available in a timeuuid may be sufficient for this problem; namely the mac address, hours, seconds,...,100 nanoseconds and random parts.
Example queries that I need to perform
SELECT * FROM vehicles WHERE manufacturer = 'BMW';
SELECT * FROM vehicles WHERE manufacturer = 'BMW' AND id = a8bb5800-694c-11d7-8080-808080808080;
SELECT * FROM vehicles WHERE manufacturer = 'BMW' AND id < a8bb5800-694c-11d7-8080-808080808080 AND id >= cb59c000-1c26-11d6-8080-808080808080;
The table schema in CQL.
CREATE TABLE vehicles (
id timeuuid,
manufacturer text,
model text,
transmission text,
description text,
engine_capacity double,
fuel_type text,
metric_urban double,
metric_extra_urban double,
metric_combined double,
co2_g_per_km double,
euro_standard int,
noise double,
co double,
hc_nox double,
hc double,
nox double,
particulates double,
date_included timestamp,
PRIMARY KEY (manufacturer, id)
) WITH CLUSTERING ORDER BY (id ASC);
The companion manufacturers table
SELECT * from manufacturers;
CREATE TABLE manufacturers (
id uuid,
manufacturer text,
years set<int>
PRIMARY KEY (manufacturer, id)
);
A: I guess it is possible to do that in theory. However, there are no standard Java APIs that allow you to specify the "current time" when generation a UUID.
This is not how type 1 UUIDs are intended to be used. (Not withstanding Cassandra's ability to select "timeuuid" values based on the time!) The embedded timestamp is a part of a scheme for guaranteeing uniqueness ... nothing more. If you start artificially generating type 1 UUIDs for a different time than the current one, you have the (theoretical) problem that your "new" UUIDs may actually be identical to UUIDs that were genuinely created on that machine and at that time; i.e. your UUIDs are no longer unique.
If I was doing this, I would generate UUIDs the normal way and store the timestamps in a separate field.
UPDATE
You might be able to adapt "https://github.com/cowtowncoder/java-uuid-generator" to do what you want. (Hint: write a tricky "timestamp synchronizer"). But I still think this is a bad idea.
| |
doc_23526677
|
I want to change the format of the array I get from a glob function.
This is how my code looks now.
$my_files = glob('*.php');
and the result is an array:
array(
'0' => 'about.php',
'1' => 'admin-ajax.php',
'2' => 'admin-footer.php',
'3' => 'admin-functions.php',
'4' => 'admin-header.php',
'5' => 'admin-post.php',
'6' => 'admin.php',
)
Now this is what exactly I want to have(to change the numbers with the text for each array, respectively):
array(
'about.php' => 'about.php',
'admin-ajax.php' => 'admin-ajax.php',
'admin-footer.php' => 'admin-footer.php',
'admin-functions.php' => 'admin-functions.php',
'admin-header.php' => 'admin-header.php',
'admin-post.php' => 'admin-post.php',
'admin.php' => 'admin.php',
)
I need this as an array to include it using a variable in this way:
array(
'name' => 'Intern download file name',
'id' => $prefix .'blog_post_intern_url',
'type' => 'select',
'options' => $my_files,
),
A: $arrayWithKeysEqualValues = array_combine($my_files, $my_files);
A: Try array_combine
$newArray = array_combine($originalArray, $originalArray);
| |
doc_23526678
|
import Immutable from 'immutable';
interface IThing<List = Array> {
numbers: List<number>;
strings: List<string>;
}
class ImmutableThing implements MyThing<Immutable.List> {
}
But of course Typescript doesn't like this, in multiple ways--for one thing, Immutable.List needs a type parameter, for another Array needs a generic parameter (and if I do something like List<T> = Array<T> it says "cannot find name T").
Is there a way to do what I want in Typescript?
| |
doc_23526679
|
Example:
I know that i won't get a perfect output but anything would be good..
How should I start?
I would need to get a list of points out of my image.
A: Very simple. Replace an NON white pixels by black. Then loop in each black pixel and turn them white if not adjacent to at least 1 white pixel.
| |
doc_23526680
|
I am getting HTTP error while uploading 17MB file after uploading complete and processing while getting IO error in between uploading is in progress with 58 MB file.
what could be the issue?
A: Have you tried why-does-uploadify-stop-when-trying-to-upload-large-files.
A: I think you have to increase the file upload limits add these lines on your .htaccess file
Change values according to your need. If it does't change contact to your service provider to increase upload limits.
upload_max_filesize = 10M
post_max_size = 20M
max_execution_time = 100
Hope this will help you.
A: Can you give us the HTTP error and the IO error ?
By default, PHP only accept max 2mb files upload. Check on your php.ini :
;;;;;;;;;;;;;;;;
; File Uploads ;
;;;;;;;;;;;;;;;;
; Maximum allowed size for uploaded files.
; http://php.net/upload-max-filesize
upload_max_filesize = 2M
| |
doc_23526681
|
t, x, fig2a = q2.brusselator_plot(t0, t_max, a, b1, N)
Error Raised:
Field elements must be 2- or 3-tuples, got '0.5'
t, x, fig2b = q2.brusselator_plot(t0, t_max, a, b2, N)
Error Raised:
Field elements must be 2- or 3-tuples, got '2.0'
| |
doc_23526682
|
fullAddress: Joi.string()
.regex(/^\d/)
.required()
Need help how to add other three regex (fullAddress text should not match with these) to the above code.
public static poboxRegex_POB = /^box[^a-z]|\bP(ost|ostal)?([ \.]*(O|0)(ffice)?)([ \.]*(B|Box|Bos))?[^a-z]*\b/i;
public static poboxRegex_PMB = /^box[^a-z]|(p[-. ]?m.?[- ]?|private[ ]*mail[ ]*|post[ ]*office[ ]*)(b|b.|box|bos)/i;
public static poboxRegex_PBX = /^box[^a-z]|(p[-. ]?(m|b).?
| |
doc_23526683
|
log.data - hex number
SELECT
SUM(SAFE_CAST(log.data as INT64)/POW(10,18))
FROM
`bigquery-public-data.ethereum_blockchain.logs` AS log
WHERE TRUE
AND log.address = '0xf53ad2c6851052a81b42133467480961b2321c09'
AND log.block_timestamp >= '2018-01-01 00:00:01'
AND log.block_timestamp <= '2018-12-01 00:00:01'
AND SUBSTR(log.topics[SAFE_OFFSET(0)], 1, 10) IN ('0x42696c68','0xcc16f5db')
im not quite understand why this happens. Will be appreciate for answer)
A: The problem is that some of the log.data values are excluded from the SUM, since they don't fit in the range of INT64 and hence the SAFE_CAST(log.data AS INT64) returns NULL. As an example, 0x00000000000000000000000000000000000000000000000080b7978da47c78d2 is greater than the max INT64 value of 9223372036854775807, which is 0x7FFFFFFFFFFFFFFF in hexadecimal.
You can instead cast the log.data values to the FLOAT64 type, which produces a result closer to what you see using Pandas:
SELECT
SUM(CAST(log.data as FLOAT64)/POW(10,18))
FROM
`bigquery-public-data.ethereum_blockchain.logs` AS log
WHERE TRUE
AND log.address = '0xf53ad2c6851052a81b42133467480961b2321c09'
AND log.block_timestamp >= '2018-01-01 00:00:01'
AND log.block_timestamp <= '2018-12-01 00:00:01'
AND SUBSTR(log.topics[SAFE_OFFSET(0)], 1, 10) IN ('0x42696c68','0xcc16f5db')
This returns 329681.7942642243.
| |
doc_23526684
|
A: You have a number of issues with that website - but the cause of the outline on navigation is the line as follows:
$target.focus();
If you remove that - it should remove the line - If you find out why that is there - replace the logic. It looks very funky - and not the good kind of funky.
A: You can simply do it with css.
Exaple you section class name is .mysection
you add a line to the css
.mysection:focus{
outline: none;
}
.mysection{
outline: none;
}
| |
doc_23526685
|
<div class="flex-item a">
<p>A</p>
<img class="displayImage" src="img/image-placeholder.svg" />
<textarea class="textInput"></textarea>
</div>
<div class="flex-item b">
<p>B</p>
<img class="displayImage" src="img/image-placeholder.svg" />
<textarea class="textInput"></textarea>
</div>
<div class="flex-item c">
<p>C</p>
<img class="displayImage" src="img/image-placeholder.svg" />
<textarea class="textInput"></textarea>
</div>
<div class="flex-item d">
<p>D</p>
<img class="displayImage" src="img/image-placeholder.svg" />
<textarea class="textInput"></textarea>
</div>
This is my js:
var arr = ["a", "b", "c", "d"];
var imageAreaArray = [];
$.each(arr, function(i, val){
imageAreaArray.push("document.querySelector('." + val + " img.displayImage')");
});
$.each(imageAreaArray, function(i, val){
var contentVal = $("'." + arr[i] + "img.displayImage'").closest('textarea');
imagePath = $("'." + arr[i] + " img.displayImage'").src;
});
This should take the value of the nearest <textarea> to the img.displayImage in the selected '<div>', and also take the src of the img.displayImage, but I get the following error and I'm not sure how to fix.
Uncaught Error: Syntax error, unrecognized expression: '.d img.displayImage'
UPDATE
No longer getting the error message, but now contentVal and imagePath are showing as undefined. Any idea why undefined might be showing?
A: You have additional single quote in jQuery selector, which is evaluating to a invalid selector like $("'.a .. ..'")
$.each(imageAreaArray, function(i, val){
var contentVal = $("'." + arr[i] + "img.displayImage'").closest('textarea');
// ^^
imagePath = $("'." + arr[i] + " img.displayImage'").src;
// ^^
});
*
*Also $(..).src will output undefined. use $(..)[0].src or $(..).prop('src') to get source.
*.closest('..') return closest parent element. <textarea> here is the sibling of img. Use .next('textarea') instead of .closest()
A: I see two potential problems with your code. First off, I don't believe that jQuery selectors need to be wrapped in single quotes, so get rid of those. Secondly, when querying for the closest textarea you missed a space between arr[i] and img.displayImage.
I would suggest caching the jQuery selected element:
var element = $(`.${arr[i]} img.displayImage`);
var contentVal = element.closest('textarea');
imagePath = element.src;
Notice that the ` characters are backticks, typically found at the top-left of English keyboards. This syntax requires that ES6 string interpolation is supported by the browsers you're targeting. As an alternative, you can just build the selector by using the same method you're currently employing.
var element = $("'." + arr[i] + " img.displayImage'");
...
| |
doc_23526686
|
But I can see the dependency xsubj in the latest stanford dependecy parser 2.0.5 output for same sentence.
I tried copying some classes for parser, semgraph and Trees into the coreNLP jar from stanford parser jar. But still I could not get this outut.
Can anybody please guide me , how can I determine this relation.
A: Are both using the same models? CoreNLP ships with several models (trained with different corpora), try checking them all.
| |
doc_23526687
|
However, after some usage, sometimes the UIManagedDocument I use will just not open when the app starts. Here is the method I use for that (done in the app delegate):
-(void)initManagedDocument{
@try {
NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
url = [url URLByAppendingPathComponent:@"DataBase"];
self.managedDocument = [[UIManagedDocument alloc] initWithFileURL:url];
if ([[NSFileManager defaultManager] fileExistsAtPath:[url path]]){
[self.managedDocument openWithCompletionHandler:^(BOOL success){
if (success) {
[self documentIsReady];
}else{
NSLog(@"Could not open document");
}
}];
}else{
[self.managedDocument saveToURL:url forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success){
if (success) {
[self documentIsReady];
}else{
NSLog(@"Could not create document");
}
}];
}
}
@catch (NSException *e) {
}
}
This code gets called from my app's didFinishLaunchingWithOptions. The saveToURL half of the if-statement gets called initially, and returns a success. Then in the following few calls the openWithCompletionHandler: gets called, and returns successfully.
However, at some point after using the app for awhile, the openWithCompletionHandler: returns success = FALSE. I am not sure why, or how the UIManagedDocument gets messed up. The URL still seems to be the same, and the fileExistsAtPath is still returning YES.
Does anyone know why this might be happening? Or if there is a way for me to debug and find out what the actual error is that is causing the open to fail?
| |
doc_23526688
|
<input name="t1" type="text" id="t1"/><br />
<input name="" type="button" value="400" onclick="document.all.t2.value=this.value" />
<input name="t2" type="text" id="t2"/><br />
<script>
function add(){
document.getElementById("t3").value = Math.floor(document.getElementById("t1").value) +
Math.floor(document.getElementById("t2").value);
}
</script>
<input name="" type="button" value="add" onclick="add" />
<input name="t3" type="text" id="t3"/>
the above code is bad., expect some to correct it. thank you.
when click 300, the 300 vill in the first textbox, the same as 400, then click add button. the third textbox shoew 700
A: Your "onclick" has to look like this:
<input name="" type="button" value="add" onclick="add()" />
References to document.all won't work in browsers other than Internet Explorer, so you should change those to use document.getElementById() instead.
A: You'll have to call the function rather than reference it.
That is, use:
<input name="" type="button" value="add" onclick="add()" />
/|\
|
-------------------------------------------------------
A: <script type="text/javascript">
function add(){
document.getElementById("t3").value = parseInt(document.getElementById("t1").value) +
parseInt(document.getElementById("t2").value);
}
</script>
<input name="" type="button" value="300" onclick="document.getElementById('t1').value=this.value" />
<input name="t1" type="text" id="t1"/><br />
<input name="" type="button" value="400" onclick="document.getElementById('t2').value=this.value" />
<input name="t2" type="text" id="t2"/><br />
<input name="" type="button" value="add" onclick="add()" />
<input name="t3" type="text" id="t3"/>
http://jsfiddle.net/AQYJh/
| |
doc_23526689
|
I'm running into very inconsistent results with the below code, when I (the player) plays 'scissors' and NPC plays 'rock' I (the player) still somehow win, other combinations of rock, paper, scissors gives the correct result (from what I can tell) eg. paper vs rock, scissors vs paper and I'm unsure why.
I've attached an image of my code, as copy and pasting it seems to produce ugly paragraphs.
code in pycharm
For actual code:
import random
d = {'rock': {'rock': 'tie', 'scissors': 'win', 'paper': 'lose'},
'paper': {'paper': 'tie', 'rock': 'win', 'scissors': 'lose'},
'scissors': {'scissors': 'tie', 'paper': 'win', 'rock': 'lose'}}
d_l = list(d)
def umbrella():
player_1_name = input('insert name')
player_2_name = 'npc'
player_1_and_npc_actions_and_check_winner(player_1_name, player_2_name)
def player_1_and_npc_actions_and_check_winner(x, y):
winner = 0
while winner == 0:
p1 = input('please choose a rock = 1, paper = 2, scissors = 3 ')
p1_n = int(p1)
p_c = d_l[p1_n - 1]
print(p_c)
npc_choice = random.choice(d_l)
print(npc_choice)
if p_c == npc_choice:
print('TIE')
winner += 0
return
elif p_c in d.get(npc_choice, 'lose'):
print(f'{x} wins!')
elif npc_choice in d.get(p_c, 'lose'):
print(f'{y} wins!')
return
umbrella()
| |
doc_23526690
|
FileInfo file = new FileInfo(filename);
file.Delete(Path);
but I am getting the error that file.Delete(path) takes 1 argument please help me
A: The method Delete of FileInfo does not accept any parameter, so you need to write your code like this:
FileInfo file = new FileInfo(filename);
file.Delete();
A: Your use of FileInfo.Delete takes no arguments.
You want something like:
FileInfo file = new FileInfo(filename);
file.Delete();
A: You are creating an instance of FileInfo having a filename as an arguement.
Method file.Delete() will remove the file which you passed through a constructor.
In fact, the argument of constructor must be an absolute path along with filename.
String filename=@"c:\xyz\aa.txt";
FileInfo file=new FileInfo(filename);
file.Delete();
A: try this
if (System.IO.File.Exists(path))
{
System.IO.FileInfo info = new System.IO.FileInfo(path);
System.IO.File.SetAttributes(info.FullName,
System.IO.FileAttributes.Normal);
System.IO.File.Delete(info.FullName);
}
A: Your code should be as below :
FileInfo file = new FileInfo(filename);
file.Delete();
The Delete method of FileInfo object does not take any arguments.
| |
doc_23526691
|
Reading the documentation, I found two ways of generating the PDF files:
First, passing an url and call the goto method as follows:
page.goto('https://example.com');
page.pdf({format: 'A4'});
The second one, which is my case, calling the method setContent as follows:
page.setContent('<p>Hello, world!</p>');
page.pdf({format: 'A4'});
The thing is that I have 3 different HTML strings that are sent from the client and I want to generate a single PDF file with 3 pages (in case I have 3 HTML strings).
I wonder if there exists a way of doing this with Puppeteer? I accept other suggestions, but I need to use chrome-headless.
A: I was able to do this by doing the following:
*
*Generate 3 different PDFs with puppeteer. You have the option of saving the file locally or to store it in a variable.
*I saved the files locally, because all the PDF Merge plugins that I found only accept URLs and they don't accept buffers for instance. After generating synchronously the PDFs locally, I merged them using PDF Easy Merge.
The code is like this:
const page1 = '<h1>HTML from page1</h1>';
const page2 = '<h1>HTML from page2</h1>';
const page3 = '<h1>HTML from page3</h1>';
const browser = await puppeteer.launch();
const tab = await browser.newPage();
await tab.setContent(page1);
await tab.pdf({ path: './page1.pdf' });
await tab.setContent(page2);
await tab.pdf({ path: './page2.pdf' });
await tab.setContent(page3);
await tab.pdf({ path: './page3.pdf' });
await browser.close();
pdfMerge([
'./page1.pdf',
'./page2.pdf',
'./page3.pdf',
],
path.join(__dirname, `./mergedFile.pdf`), async (err) => {
if (err) return console.log(err);
console.log('Successfully merged!');
})
A: I was able to generate multiple PDF from multiple URLs from below code:
package.json
{
............
............
"dependencies": {
"puppeteer": "^1.1.1",
"easy-pdf-merge": "0.1.3"
}
..............
..............
}
index.js
const puppeteer = require('puppeteer');
const merge = require('easy-pdf-merge');
var pdfUrls = ["http://www.google.com","http://www.yahoo.com"];
(async () => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
var pdfFiles=[];
for(var i=0; i<pdfUrls.length; i++){
await page.goto(pdfUrls[i], {waitUntil: 'networkidle2'});
var pdfFileName = 'sample'+(i+1)+'.pdf';
pdfFiles.push(pdfFileName);
await page.pdf({path: pdfFileName, format: 'A4'});
}
await browser.close();
await mergeMultiplePDF(pdfFiles);
})();
const mergeMultiplePDF = (pdfFiles) => {
return new Promise((resolve, reject) => {
merge(pdfFiles,'samplefinal.pdf',function(err){
if(err){
console.log(err);
reject(err)
}
console.log('Success');
resolve()
});
});
};
RUN Command: node index.js
A: pdf-merger-js is another option. page.setContent should work just the same as a drop-in replacement for page.goto below:
const PDFMerger = require("pdf-merger-js"); // ^4.2.1
const puppeteer = require("puppeteer"); // ^19.7.2
const urls = [
"https://news.ycombinator.com",
"https://www.example.com",
"https://en.wikipedia.org",
// ...
];
const filename = "merged.pdf";
let browser;
(async () => {
browser = await puppeteer.launch();
const [page] = await browser.pages();
const merger = new PDFMerger();
for (const url of urls) {
await page.goto(url);
await merger.add(await page.pdf());
}
await merger.save(filename);
})()
.catch(err => console.error(err))
.finally(() => browser?.close());
| |
doc_23526692
|
var margin = {
top: 30,
right: 20,
bottom: 30,
left: 50
};var width = 600 - margin.left - margin.right;
var height = 270 - margin.top - margin.bottom;
var parseDate = d3.timeFormat("%c").parse;
var x = d3.scaleLinear().range([0, width]);
var y = d3.scaleLinear().range([height, 0]);
var xAxis = d3.axisBottom()
.scale(x).ticks(5);
var yAxis = d3.axisLeft()
.scale(y).ticks(5);
var valueline = d3.line()
.x(function (d) {
return x(d.date);
})
.y(function (d) {
return y(d.close);
});
var svg = d3.select("body")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Get the data
var data = [{
date: "1 ",
close: "58.13"
}, {
date: "2 ",
close: "53.98"
}, {
date: "3 ",
close: "67.00"
}, {
date: "4 ",
close: "89.70"
}, {
date: "5 ",
close: "99.00"
}, {
date: "6 ",
close: "20.00"
}];
var data2 = [{
date: "1 ",
close: "52.13"
}, {
date: "2 ",
close: "30.98"
}, {
date: "3 ",
close: "36.00"
}, {
date: "4 ",
close: "40.70"
}, {
date: "5 ",
close: "20.00"
}, {
date: "6 ",
close: "96.00"
}];
data.forEach(function (d) {
d.date = d.date;
d.close = +d.close;
});
// scaleLinear the range of the data
x.domain(d3.extent(data, function (d) {
return d.date;
}));
y.domain([0, d3.max(data, function (d) {
return d.close;
})]);
svg.append("path") // Add the valueline path.
.attr("d", valueline(data)).attr("stroke","red");
svg.append("path") // Add the valueline path.
.attr("d", valueline(data2)).attr("stroke","blue");
svg.append("g") // Add the X Axis
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g") // Add the Y Axis
.attr("class", "y axis")
.call(yAxis);
}
I am new to this. I want to add color to the stroke I am using but I am unable to do it. I have added attribute for applying stroke color in the code but it is not working. I want each of the line to be of different color. Please help me with the feasible solution.
A: Your code seems to work fine. Here is the d3 way of implementation for the same.
var margin = {
top: 30,
right: 20,
bottom: 30,
left: 50
};
var width = 600 - margin.left - margin.right;
var height = 270 - margin.top - margin.bottom;
var parseDate = d3.timeFormat("%c").parse;
var x = d3.scaleLinear().range([0, width]);
var y = d3.scaleLinear().range([height, 0]);
var xAxis = d3.axisBottom()
.scale(x).ticks(5);
var yAxis = d3.axisLeft()
.scale(y).ticks(5);
var valueline = d3.line()
.x(function(d) {
return x(d.date);
})
.y(function(d) {
return y(d.close);
});
var colors = d3.scaleOrdinal(d3.schemeCategory10);
var svg = d3.select("body")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// Get the data
var data = [{
date: "1 ",
close: "58.13"
}, {
date: "2 ",
close: "53.98"
}, {
date: "3 ",
close: "67.00"
}, {
date: "4 ",
close: "89.70"
}, {
date: "5 ",
close: "99.00"
}, {
date: "6 ",
close: "20.00"
}];
var data2 = [{
date: "1 ",
close: "52.13"
}, {
date: "2 ",
close: "30.98"
}, {
date: "3 ",
close: "36.00"
}, {
date: "4 ",
close: "40.70"
}, {
date: "5 ",
close: "20.00"
}, {
date: "6 ",
close: "96.00"
}];
data.forEach(function(d) {
d.date = d.date;
d.close = +d.close;
});
// scaleLinear the range of the data
x.domain(d3.extent(data, function(d) {
return d.date;
}));
y.domain([0, d3.max(data, function(d) {
return d.close;
})]);
svg.selectAll("path.line").data([data, data2])
.enter().
append("path") // Add the valueline path.
.attr("class", "line")
.attr("d", valueline)
.attr("stroke", function(d, i) {
return colors(i);
});
svg.append("g") // Add the X Axis
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g") // Add the Y Axis
.attr("class", "y axis")
.call(yAxis);
path {
fill: none;
}
<script src="https://d3js.org/d3.v4.min.js"></script>d
| |
doc_23526693
|
Now I'll just confine the problem to the vertical axis, call it the y-axis.
The bottom left corner of each cell is its co-ordinate, and it is always a positive integer (if this helps).
The y-axis bounds of A and B can be written,
A.y1 = 4
A.y2 = 8
B.y1 = 7
B.y2 = 8
Now what's the most efficient way to test if A and B are connected/overlap on the y-axis?
Note that it should also work if you switch the A and B labels in the diagram around.
Here's my no doubt naive attempt...
IF B.x2 == A.x1
IF (A.y1 <= B.y1) AND (A.y2 >= B.y2) THEN
connected = true
ELSE
IF (A.y1 >= B.y1) AND (A.y2 <= B.y2) THEN
connected = true
ELSE
connected = false
END
END
A: Assuming by connected you mean "share a non-trivial border", I would think about it this way: two of these fields are connected iff they share two distinct points. If you stick to rectangular fields, you just check for the corners of each cell and see whether at least two of the eight corners are in both sets. To use this approach to parse the partition of the plane into a graph representing connected fields, you can also use this to check whether you should insert an edge (assuming that is your ultimate goal), but you probably should think about some way of sorting them so you don't get quadratically many comparisons in the number of cells.
A: With geometry checks alone, you are close to optimal.
You need 4 comparisons (in 2d) to identify which, if any, edge pair is adjacent. If an adjacency is found, you need to detect presence or absence of a 2d overlap. You are doing this with the two inclusion checks using <= and >=. You won't do much better. If true answers are more likely than false, it might be worthwhile first to check whether one end point is stictly contained in the other edge. If all these tests fail, the logic must fall through to a final check for identical edges. (This extra check makes the method more expensive if false answers are common.)
An efficiency is available if you add a "depth" number to each node. This will tell you quickly which cell is bigger or if they are of equal size, allowing you to make only one of the two inclusion checks. The single depth comparison will avoid several edge coordinate comparisons.
Finally, if you put parent pointers in the nodes, then you can do this comparison by looking for the paths up to the least common ancestor. These paths can be tested to get the answer. However, since it is unlikely that finding and testing them will be faster than the numerical comparision you already have, I won't go further into this.
A: You can analyze how projections of the boxes onto the axes intersect with each other (similarly to @coproc's answer). But this time calculate the "vector" size of each intersection and then check if all are non-negative. Then to check for corners-only-touching you can request that at least one such length is positive. For example, with something like this (I have rearranged the bounding box structure for clarity):
typedef int axis_t; // some signed type
struct range { axis_t low, high; };
struct box { range x, y; }
axis_t overlap(const range &a, const range &b)
{
return min(a.high, b.high) - max(a.low, b.low);
}
bool overlap(const box &a, const box &b)
{
axis_t x_overlap = overlap(a.x, b.x);
axis_t y_overlap = overlap(a.y, b.y);
return x_overlap >= 0 && y_overlap >= 0 && x_overlap + y_overlap > 0;
}
This is up-to 7 comparisons and 3 additions/subtractions, but there are 8 values to consider, so probably it's not that bad.
A: According to me, your code is the best.
It requires at the most 6 comparisons.
Am afraid, finding radius / distance / overlap involve more computations.
One alternate is caching.
If you cache the adjacent nodes at the time of storing each box coordinates,
later you can just do a look up whether B is in the adjacent list of A with lesser number of comparisons. Building initial cache is the overhead, but later performance may be good.
Otherwise, i do not see a better way.
| |
doc_23526694
|
[code=123,px_last=value attribute of first data,last_update=value attribute of 2nd data and so on]
There are 7 data element with attribute value inside should be read as above with first field mapped to first data and second mapped to second data value attribute.
etc..
With your help I was able to generate the output but got struck where I need to map the first field element to first data attribute value and so on etc.
Thanks in advance
XML file:
<root>
<fields>
<field>PX_LAST</field>
<field>LAST_UPDATE</field>
<field>LAST_UPDATE_DT</field>
<field>SECURITY_DES</field>
<field>FUT_CUR_GEN_TICKER</field>
<field>YLD_CNV_BID</field>
<field>YLD_CNV_ASK</field>
</fields>
<Datas>
<Data>
<code>0</code>
<ins>
<id>CT30</id>
<key>Govt</key>
<ins/>
<data value="98.843750"/>
<data value="16:14:45">
</data>
<data value="06/03/2014"/>
<data value="T 3 3/8 05/15/44"/>
<data value=""/>
<data value="3.439"/>
<data value="3.437"/>
</Data>
<Data>
<code>0</code>
<ins>
<id>US0001W</id>
<key>Index</key>
<ins/>
<data value=".119000"/>
<data value="06:46"/>
<data value="06/03/2014"/>
<data value="ICE LIBOR USD 1 Week"/>
<data value=""/>
<data value="N.A."/>
<datavalue=".11900"></data>
</Data>
</Datas>
</root>
XQuery:
declare function xf:strip-namespace($e as element())
as element()
{
element { xs:QName(local-name($e)) }
{
for $child in $e/(@*,node())
return
if ($child instance of element())
then
xf:strip-namespace($child)
else
$child
}
};
let $nl := " "
let $count := 0
for $x in doc("test.xml")/soap:Envelope/soap:Body/dlws:retrieveGetDataResponse/dlws:instrumentDatas//*
let $y:=xf:strip-namespace($x)
return
if($y/name() = 'instrumentData')
then
concat($nl,'[','')
else if($y/name()='data')
then
concat($y/name(),'=',$y/data(@value),',')
else if($y/name() != 'instrument')
then
concat($y/name(),'=',$y/text(),',')
else
()
Output right now:
[code=123,data=werr,data="qwe",data="wer",......,]
[code=456,data=rty,data="tyuu",data="uuu",......,]
A: Generally, if you can break your problem into smaller pieces, it will facilitate a simpler solution that more closely resembles the problem itself.
declare function local:make-pair(
$e as element()
) as xs:string?
{
typeswitch($e)
case element(data) return concat(local-name($e), '=', $e/@value)
default return concat(local-name($e), '=', $e)
};
let $idatas :=
<idatas>
<idata>
<code>123</code>
<data value="wer"></data>
<data value="sdf"></data>
<data value="zxc"></data>
<data value="asd"></data>
<data value="jgh"></data>
<data value="cvb"></data>
<data value="bsz"></data>
</idata>
<idata>
<code>345</code>
<data value="ff"></data>
<data value="zxd"></data>
<data value="wvver"></data>
<data value="wencvr"></data>
<data value="wzxcer"></data>
<data value="wmmer"></data>
<data value="wuuer"></data>
</idata>
</idatas>
for $idata in $idatas/idata
let $pairs :=
for $p in $idata/*
return local:make-pair($p)
return concat('[', string-join($pairs, ','), ']')
A: In the following parts of the answer, I completely ignored the strip-namespace part, which is a bad idea anyway. Eighter declare it as default namespace and don't worry about it any more, or use local-name() instead of name, or use the wildcard namespace mather*:elementname*.
The input was modified during updates of the question. Everything up to the next horizontal bar refers to the first revision of the question.
You can do all the "string manipulation foo" with very few code using some XQuery 3.0 features, especially calling functions in axis steps and the string concatenation operator ||:
//idata/( (: for all idata elements :)
"[" ||
string-join(( (: combine all key/value pairs with commata :)
"code=" || code/data(), (: code header :)
data/("data=" || @value)), (: data fields :)
',') ||
']')
And it exactly fits into one line on Stack Overflow (if you really want it)!
//idata/("["||string-join(("code="||code/data(),data/("data="||@value)),',')||']')
With the output being
[code=123,data=wer,data=sdf,data=zxc,data=asd,data=jgh,data=cvb,data=bsz] [code=345,data=ff,data=zxd,data=wvver,data=wencvr,data=wzxcer,data=wmmer,data=wuuer]
A probably more readable version with explicit loops, still using the concatenation operator (which in my opinion enhances readability):
for $idata in $xml//idata
return
"[" || string-join((
"code=" || $idata/code/data(),
for $data in $idata/data
return
"data=" || $data/@value),
',') || ']'
For the updated question, a one-liner will probably get too unreadable. The modified code in the end just joins with the index of the data element:
for $dataset in /root/Datas/Data
return
"[" || string-join((
"code=" || $dataset/code/data(),
for $data at $position in $dataset/data
let $field := /root/fields/field[$position]
return
$field || "=" || $data/@value),
',') || ']'
| |
doc_23526695
|
Document structure -
{
"_id": "ccf8a36e55913b7cf5b015d6c50009f7",
"_rev": "8-586130996ad60ccef54775c51599e73f",
"cId": 1,
"Status": true
}
Here is the sample map:
function(doc) {
if(doc.Key && doc.Value && doc.Status == true)
emit(null, doc);
}
Here is the sample reduce:
function(key, values, rereduce){
var kv = [];
values.forEach(function(value){
if(value.cId != <some_val>){
kv.push({"k": value.cId, "v" : value});
}
});
return kv;
}
If there are two documents and reduce output has list containing 1 document, this works fine. But if I add one more document (with cId = 2), it throws the errors - "reduce output must shrink more rapidly". Why is this caused? And how can I achieve what I intend to do?
A: The cause of the error is, that the reduce function does not actually reduce anything (it rather is collecting objects). The documentation mentions this:
The way the B-tree storage works means that if you don’t actually
reduce your data in the reduce function, you end up having CouchDB
copy huge amounts of data around that grow linearly, if not faster
with the number of rows in your view.
CouchDB will be able to compute the final result, but only for views
with a few rows. Anything larger will experience a ridiculously slow
view build time. To help with that, CouchDB since version 0.10.0 will
throw an error if your reduce function does not reduce its input
values.
It is unclear to me, what you intend to achieve.
Do you want to retrieve a list of docs based on certain criteria? In this case, a view without reduce should suffice.
Edit: If the desired result depends on a value stored in a certain document, then CouchDB has a feature called list. It is a design function, that provides access to all docs of a given view, if you pass include_docs=true.
A list URL follow this pattern:
/db/_design/foo/_list/list-name/view-name
Like views, lists are defined in a design document:
{
"_id" : "_design/foo",
"lists" : {
"bar" : "function(head, req) {
var row;
while (row = getRow()) {
if (row.doc._id === 'baz') // Do stuff based on a certain doc
}
}"
},
... // views and other design functions
}
| |
doc_23526696
|
Like this Picture!
At first like to connect location 1 to location 2 with a line automatically on each side
And Then i like to copy the content in this square.
How can i perform it?
I would be very thankful for help
A: Sry i like to copy the content of this quadrilateral elsewhere and safe it.
| |
doc_23526697
|
rowSet.updateBigDecimal(a,
(BigDecimal(result.getString(a)).setScale(0,BigDecimal.RoundingMode.HALF_UP)).bigDecimal)};
bulkCopy.setDestinationTableName("tablename");
bulkCopy.writeToServer(rowSet);
bulkCopy.close();
| |
doc_23526698
|
A: use .loc with a boolean mask
df.loc[df['solvent'] == 'NONANE', 'num'] = 9
df.loc[df['solvent'] == 'OCTANE', 'num'] = 8
Another method is do define a dict and call map:
d = {'NONANE':9, 'OCTANE':8, 'HEPTANE':7, 'HEXANE':6}
df['num'] = df['solvent'].map(d)
| |
doc_23526699
|
This is My code.
<select data-ng-options="o.name for o in options track by o.id" data-ng-model="selectedOption" class="selectpicker" data-style="btn-default" ng-change="onselectClick()"> </select>
<!-- Second dropdown -->
<select data-ng-options="o.name for o in secondoptions track by o.id" data-ng-model="selectedSecondOption" class="selectpicker" data-style="btn-default">
</select>
Js
$scope.options = [
{"id" : "Please Select","name" : "Please Select"},
{"id" : "1","name" : "1"},
{"id" : "2","name" : "2"},
{"id" : "3","name" : "3"},
{"id" : "4","name" : "4"}];
$scope.secondoptions = [
{"id" : "Please Select","name" : "Please Select"},
{"id" : "1","name" : "1"},
{"id" : "2","name" : "2"},
{"id" : "3","name" : "3"},
{"id" : "4","name" : "4"}];
$scope.selectedOption = $scope.options [0];
$scope.selectedSecondOption = $scope.secondoptions [0];
$scope.onselectClick = function() {
$scope.selectedSecondOption = $scope.secondoptions[3];
}
I have referred following URLs:
*
*Unable to set selected value in angularjs dropdown
*http://jsfiddle.net/dCFd2/
If anyone knows the solution, please help me.
Thanks.
A: Do you need to get something like this?
var app = angular.module("App", [])
app.controller('AppCtrl', AppCtrl);
function AppCtrl($scope){
$scope.options = [
{"id" : "0","name" : "Please Select"},
{"id" : "1","name" : "1"},
{"id" : "2","name" : "2"},
{"id" : "3","name" : "3"},
{"id" : "4","name" : "4"}
];
$scope.secondoptions = [
{"id" : "0","name" : "Please Select"},
{"id" : "1","name" : "1"},
{"id" : "2","name" : "2"},
{"id" : "3","name" : "3"},
{"id" : "4","name" : "4"}
];
$scope.selectedOption = $scope.options[0];
$scope.selectedSecondOption = $scope.secondoptions[0];
$scope.onselectClick = function() {
$scope.selectedSecondOption = $scope.secondoptions[$scope.selectedOption.id];
}
};
<script src="https://code.angularjs.org/1.5.8/angular.js"></script>
<div ng-app="App">
<div ng-controller="AppCtrl">
<select data-ng-options="o.name for o in options track by o.id" data-ng-model="selectedOption" class="selectpicker" data-style="btn-default" ng-change="onselectClick()"> </select>
<!-- Second dropdown -->
<select data-ng-options="o.name for o in secondoptions track by o.id" data-ng-model="selectedSecondOption" class="selectpicker" data-style="btn-default">
</select>
</div>
</div>
A: That is happening just because of the Bootstrap UI. Following code works for me.
<select data-ng-options="o.name for o in secondoptions track by o.id" data-ng-model="selectedSecondOption" class="selectpicker secondselect" data-style="btn-default"> </select>
$('.secondselect').selectpicker('val',"3");
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.