问:
upload a csv file into cassandra (syntax error)
i am trying to upload a csv file to cassandra but I get the following error. I have already created my keyspace and table. I am only trying to upload the csv file now.

```<code>copy youtube(video_id, trending_date, title, channel_title, category_id, publish_time, tags, views, likes, dislikes, comment_count, comments_disabled, rating_disabled, video_error_or_removed) from ‘youtube.csv’ with  header=true;
</code>```

the error is with the path. I have also used the following:

```<code>copy youtube (video_id, trending_date, title, channel_title, category_id, publish_time, tags, views, likes, dislikes, comment_count, comments_disabled, rating_disabled, video_error_or_removed) from ‘/Users/Keniajc93/Desktop/youtube.csv’ with = header=TRUE;
</code>```

Could someone please help me?

1

  2

答:
Looks like both of your queries have syntax problems some of them are highlighted by others already like absolute file path in the first query and "with = header=TRUE;" in second query and quotes in both of them.

You can try this:

copy youtube (video_id, trending_date, title, channel_title, category_id, publish_time, tags, views, likes, dislikes, comment_count, comments_disabled, rating_disabled, video_error_or_removed) from '/Users/Keniajc93/Desktop/youtube.csv' with header=TRUE;

Hope it helps.

Body:
i am trying to upload a csv file to cassandra but I get the following error. I have already created my keyspace and table. I am only trying to upload the csv file now.

copy youtube(video_id, trending_date, title, channel_title, category_id, publish_time, tags, views, likes, dislikes, comment_count, comments_disabled, rating_disabled, video_error_or_removed) from ‘youtube.csv’ with  header=true;

the error is with the path. I have also used the following:

copy youtube (video_id, trending_date, title, channel_title, category_id, publish_time, tags, views, likes, dislikes, comment_count, comments_disabled, rating_disabled, video_error_or_removed) from ‘/Users/Keniajc93/Desktop/youtube.csv’ with = header=TRUE;

Could someone please help me?

1

  2


来源: stackexchange

问:
postgres Like query performance for single word columns
DB-Type: PostgreSQL
DB-Version: 11
We have a column which has a single word as a value always. The maxlength is 10 chars.

We always have unique value for this column in the table.

We do not have any updates to this column, only new rows are inserted with this column.

We would like to enable like queries for this column.

Should we consider the PostgreSQL TRGM extension and using a GIN index? or will a normal index suffice in this case?

The queries will be like this:

select * from my_table where my_column like '%abc%';
```

The question arrives from the fact that TRGM is quite powerful when full text search is required for a long text with many words, but wanted to know if it will be better than a normal index for the single word scenario also.

答:
A "regular" index (b-tree) will generally be able to resolve:

```<code>where x like 'abcdefghij'
where x = 'abcdefghij'
</code>```

It can also be used for prefix matches:

```<code>where x like 'abcd%'
</code>```

However, it cannot be used when the pattern starts with a wildcard:

```<code>where x like '%hij'
</code>```

So, whether the index is used depends on how you are going to use it.  If the pattern starts with wildcards then a GIN index could be used.

I should add that regardless of the index, there are considerations if you want case-independence or are mixing collations.

ContentLicense: CC BY-SA 4.0

Body:
DB-Type: PostgreSQL
DB-Version: 11
We have a column which has a single word as a value always. The maxlength is 10 chars.

We always have unique value for this column in the table.

We do not have any updates to this column, only new rows are inserted with this column.

We would like to enable like queries for this column.

Should we consider the PostgreSQL TRGM extension and using a GIN index? or will a normal index suffice in this case?

The queries will be like this:

select * from my_table where my_column like '%abc%';

The question arrives from the fact that TRGM is quite powerful when full text search is required for a long text with many words, but wanted to know if it will be better than a normal index for the single word scenario also.

Body:
A "regular" index (b-tree) will generally be able to resolve:

where x like 'abcdefghij'
where x = 'abcdefghij'

It can also be used for prefix matches:

where x like 'abcd%'

However, it cannot be used when the pattern starts with a wildcard:

where x like '%hij'

So, whether the index is used depends on how you are going to use it.  If the pattern starts with wildcards then a GIN index could be used.

I should add that regardless of the index, there are considerations if you want case-independence or are mixing collations.


问:
Random populations of empty lists
I have to write a program in Python in which I give a range and a number of selections to append for 2 empty lists, so the approach of this program should be like this:

Give range to select from: 10

Give number of selections: 5

I should get:

List of numbers selected randomly: [2,3,7,1,8]

List of numbers not selected:  [4,6,5,9,10]

Numbers should not be repeated nor exist in both lists

I have this code:

```<code>import random
selected_list=[]
not_selected=[]
selecting_number=int(input('give range to select from : '))
select_num=int(input('give number of selections: '))
if selecting_number<select_num:
    print('error')
elif selecting_number>=select_num:
    for x in range(select_num):
        selected_list.append(random.randint(1,select_num))
    print(f'List of numbers selected randomly: {selected_list}')
    if not_selected not in selected_list:
        for y in range(select_num):
            not_selected.append(random.randint(1,select_num))
    print(f'List of numbers not selected previously: {not_selected}')
</code>```

This is the output

```<code>List of numbers selected randomly: [6, 7, 7, 7, 7]

List of numbers not selected: [2, 4, 4, 8, 5]
</code>```

答:
You could create a function to replicate this often and take in your parameters.

```<code>import random

def make_random_lists(my_range=10, selections=5):
    """
    Generate two lists of random numbers.

    INPUT
    ------
      my_range - (int)  how large the range we are selecting from
      selections - (int)  how many numbers should be in the list select list

    OUTPUT
    ------

      s - (list) the selected numbers
      ns - (list) not selected numbers
    """
    # make sure input values are valid
    if (selections < my_range):
        return "selections must be less than range", None
    if my_range <= 0:
        return "range must be larger than 0", None

    total_numbers = set(range(1, my_range+1))  # make range
    s = random.sample(total_numbers, k=selections)  # get selections
    ns = total_numbers - set(s)  # find those not used

    return s, list(ns)
</code>```

You do not need to set a seed unless you want to replicate your results with each run. Using sets to update your list is just another way to implement what is being done here! you could even combine the lines to make this more concise but this helps make it pretty clear.

Calling this function will yield the following results:

```<code>selected, not_selc = make_random_lists(12, 4)
print(selected)
print(not_selc)

>>>[7, 5, 3, 4]
>>>[1, 2, 6, 8, 9, 10, 11, 12]
</code>```

Documentation

sets

random

modules/functions

Pyhton3 tutorial

Title: Random populations of empty lists

Body:
I have to write a program in Python in which I give a range and a number of selections to append for 2 empty lists, so the approach of this program should be like this:

Give range to select from: 10

Give number of selections: 5

I should get:

List of numbers selected randomly: [2,3,7,1,8]

List of numbers not selected:  [4,6,5,9,10]

Numbers should not be repeated nor exist in both lists

I have this code:

import random
selected_list=[]
not_selected=[]
selecting_number=int(input('give range to select from : '))
select_num=int(input('give number of selections: '))
if selecting_number<select_num:
    print('error')
elif selecting_number>=select_num:
    for x in range(select_num):
        selected_list.append(random.randint(1,select_num))
    print(f'List of numbers selected randomly: {selected_list}')
    if not_selected not in selected_list:
        for y in range(select_num):
            not_selected.append(random.randint(1,select_num))
    print(f'List of numbers not selected previously: {not_selected}')

This is the output

List of numbers selected randomly: [6, 7, 7, 7, 7]

List of numbers not selected: [2, 4, 4, 8, 5]

Body:
You could create a function to replicate this often and take in your parameters.

import random

def make_random_lists(my_range=10, selections=5):
    """
    Generate two lists of random numbers.

    INPUT
    ------
      my_range - (int)  how large the range we are selecting from
      selections - (int)  how many numbers should be in the list select list

    OUTPUT
    ------

      s - (list) the selected numbers
      ns - (list) not selected numbers
    """
    # make sure input values are valid
    if (selections < my_range):
        return "selections must be less than range", None
    if my_range <= 0:
        return "range must be larger than 0", None

    total_numbers = set(range(1, my_range+1))  # make range
    s = random.sample(total_numbers, k=selections)  # get selections
    ns = total_numbers - set(s)  # find those not used

    return s, list(ns)

You do not need to set a seed unless you want to replicate your results with each run. Using sets to update your list is just another way to implement what is being done here! you could even combine the lines to make this more concise but this helps make it pretty clear.

Calling this function will yield the following results:

selected, not_selc = make_random_lists(12, 4)
print(selected)
print(not_selc)

>>>[7, 5, 3, 4]
>>>[1, 2, 6, 8, 9, 10, 11, 12]

Documentation

sets

random

modules/functions

Pyhton3 tutorial


问:
What is the difference between RegOpenKeyExA and RegOpenKeyEx
Could find MSDN documentation only on RegOpenKeyExA.</p>

答:
The function RegOpenKeyExA is the ANSI version of the RegOpenKeyEx, which is a wrapper to the function RegOpenKeyExW, the UTF-16 version.

In the context of the functions in question, the ANSI version requires the second parameter (i.e. the name of the registry subkey to be opened) to be of a LPCSTR type whereas the UTF-16 version requires the same parameter to be of a LPCWSTR type.


问:
Routing pages via side-menu in Ionic 4
```<code>     For days now I've been trying to route/link pages via the side-menu. So that I'm able to move to different pages from the side-menu itself. I've searched for tutorials on Angular 8 and Ionic 4 but couldn't find the specific article that relates to my issue.
</code>```

I'm supposing to route pages by creating components of the pages(items that will on the side-menu) for easier routing. I also somewhat know what codes to use for routing but don't know where to use it, since using the codes in the wrong place won't provide me any resolution.

This is my app.component.ts file.

```<code>import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { AppComponent } from './app.component';
import { AppRoutingModule, routeComponents } from './app-routing.module';

@NgModule({
  declarations: [AppComponent, routeComponents],
  entryComponents: [],
  imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
  providers: [
    StatusBar,
    SplashScreen,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}
</code>```

Below is the app-routing.module.ts file.

```<code>import { NgModule } from '@angular/core';
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';
import { TrackComponent } from './track/track.component';
import { AboutComponent } from './about/about.component';
import { CategoryComponent } from './category/category.component';
import { HomeComponent } from './home/home.component';

const routes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: 'home', loadChildren: () => import('./home/home.component').then( m =>
m.HomeComponent)},
  { path: 'category', loadChildren: () => import('./category/category.component').then( m =>
m.CategoryComponent)},
  { path: 'track', loadChildren: () => import('./track/track.component').then( m =>
m.TrackComponent)},
  { path: 'about', loadChildren: () => import('./about/about.component').then( m =>
m.AboutComponent)}
];

@NgModule({
  imports: [
    RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
  ],
  exports: [RouterModule]
})
export class AppRoutingModule { }
export const routeComponents = [CategoryComponent, TrackComponent, AboutComponent,
HomeComponent];
</code>```

Please let me know if I also need to modify the html files for each menu-item. If possible please try to explain it to me in layman's term.

答:
In ts file:

```<code>import { Router } from "@angular/router";

constructor(private router:Router){}
navtigateToPage(pageName){
 this.router.navigate([pageName]);
}
</code>```

In html file:

```<code><ion-item (click)="navtigateToPage('track')">
<ion-label>track</ion-label>
</ion-item>
</code>```

(click) can be added to any node element (div,span,ion-icon...)

Title: Routing pages via side-menu in Ionic 4

Body:
     For days now I've been trying to route/link pages via the side-menu. So that I'm able to move to different pages from the side-menu itself. I've searched for tutorials on Angular 8 and Ionic 4 but couldn't find the specific article that relates to my issue.

I'm supposing to route pages by creating components of the pages(items that will on the side-menu) for easier routing. I also somewhat know what codes to use for routing but don't know where to use it, since using the codes in the wrong place won't provide me any resolution.

This is my app.component.ts file.

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';

import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { AppComponent } from './app.component';
import { AppRoutingModule, routeComponents } from './app-routing.module';

@NgModule({
  declarations: [AppComponent, routeComponents],
  entryComponents: [],
  imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
  providers: [
    StatusBar,
    SplashScreen,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

Below is the app-routing.module.ts file.

import { NgModule } from '@angular/core';
import { PreloadAllModules, RouterModule, Routes } from '@angular/router';
import { TrackComponent } from './track/track.component';
import { AboutComponent } from './about/about.component';
import { CategoryComponent } from './category/category.component';
import { HomeComponent } from './home/home.component';

const routes: Routes = [
  { path: '', redirectTo: 'home', pathMatch: 'full' },
  { path: 'home', loadChildren: () => import('./home/home.component').then( m =>
m.HomeComponent)},
  { path: 'category', loadChildren: () => import('./category/category.component').then( m =>
m.CategoryComponent)},
  { path: 'track', loadChildren: () => import('./track/track.component').then( m =>
m.TrackComponent)},
  { path: 'about', loadChildren: () => import('./about/about.component').then( m =>
m.AboutComponent)}
];

@NgModule({
  imports: [
    RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
  ],
  exports: [RouterModule]
})
export class AppRoutingModule { }
export const routeComponents = [CategoryComponent, TrackComponent, AboutComponent,
HomeComponent];

Please let me know if I also need to modify the html files for each menu-item. If possible please try to explain it to me in layman's term.

Body:
In ts file:

import { Router } from "@angular/router";

constructor(private router:Router){}
navtigateToPage(pageName){
 this.router.navigate([pageName]);
}

In html file:

<ion-item (click)="navtigateToPage('track')">
<ion-label>track</ion-label>
</ion-item>

(click) can be added to any node element (div,span,ion-icon...)


问:
Bootstrap dropdown menu doesn't open
Navber code:

                Home (current)

                  Behandelingen

                  Sportmassage
                  Massagetherapie
                  Ontspanningsmassage

                Afspraak maken

                Tarieven

                Contact

      ```
</div>
</div>
</p>

<p>Bootstrap code:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
          integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"></code>```

Dropdown menu inside the navbar doesn't open, anyone an idea on how to fix this?
Not very experienced with bootstrap and don't now what the problem is.

答: Nevermind I solved the issue, stupid mistake by not adding jquery</p>

Title: Bootstrap dropdown menu doesn't open

Body:
Navber code:

                Home (current)

                  Behandelingen

                  Sportmassage
                  Massagetherapie
                  Ontspanningsmassage

                Afspraak maken

                Tarieven

                Contact

Bootstrap code:

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
          integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

Dropdown menu inside the navbar doesn't open, anyone an idea on how to fix this?
Not very experienced with bootstrap and don't now what the problem is.


问:
How to read a (static) file from inside a Python package?
Could you tell me how can I read a file that is inside my Python package?

My situation

A package that I load has a number of templates (text files used as strings) that I want to load from within the program. But how do I specify the path to such file?

Imagine I want to read a file from:

```<code>package\templates\temp_file
</code>```

Some kind of path manipulation? Package base path tracking?

答:
assuming you are using an egg file; not extracted:

I "solved" this in a recent project, by using a postinstall script, that extracts my templates from the egg (zip file) to the proper directory in the filesystem. It was the quickest, most reliable solution I found, since working with __path__[0] can go wrong sometimes (i don't recall the name, but i cam across at least one library, that added something in front of that list!).

Also egg files are usually extracted on the fly to a temporary location called the "egg cache". You can change that location using an environment variable, either before starting your script or even later, eg.

```<code>os.environ['PYTHON_EGG_CACHE'] = path
</code>```

However there is pkg_resources that might do the job properly.

ContentLicense: CC BY-SA 3.0

Body:
Could you tell me how can I read a file that is inside my Python package?

My situation

A package that I load has a number of templates (text files used as strings) that I want to load from within the program. But how do I specify the path to such file?

Imagine I want to read a file from:

package\templates\temp_file

Some kind of path manipulation? Package base path tracking?

Body:
assuming you are using an egg file; not extracted:

I "solved" this in a recent project, by using a postinstall script, that extracts my templates from the egg (zip file) to the proper directory in the filesystem. It was the quickest, most reliable solution I found, since working with __path__[0] can go wrong sometimes (i don't recall the name, but i cam across at least one library, that added something in front of that list!).

Also egg files are usually extracted on the fly to a temporary location called the "egg cache". You can change that location using an environment variable, either before starting your script or even later, eg.

os.environ['PYTHON_EGG_CACHE'] = path

However there is pkg_resources that might do the job properly.


问:
Can I Import any 3D.js Graph to React?
I have some very complex graphs (for industry) to do with D3.js.

These graphs must be integrated into a web-app. I decided to use react due to it's scalability.

The app consists of only 5 pages for now. it might scale up to 20 in the future.

What should I do ?

答:
There are tons of blog posts out there that talk about integrating D3 with React directly, but in my experience I've found that just learning how to use the D3 scale functions directly, and then rendering your own svg elements is much easier to follow. For example, here is a relatively simple chart using a nice middleground of React and D3:

```<code>import {scaleTime} from "d3";

const width = 500;
const height = 300;
const date = [
  {date: new Date(2012,4,5), value: 5},
  {date: new Date(2013,3,2), value: 2},
  {date: new Date(2017,3,2), value: 7},
];

const MyChart = () => {
  const xScale = useMemo(() => {
    return scaleTime()
      .domain([new Date(2010,0,1), new Date(2020,0,1)])
      .range([0, width]);
  }, []);

  const yScale = useMemo(() => {
    return scaleLinear()
      .domain([0, 10])
      .domain([height, 0]);
  }, []);

return (
  <svg width={width} height={height}>
    <line className="x-axis" x1={0} x2={width} y1={yScale(0)} y1={yScale(0)} stroke="black" />
    {data.map((item, idx) => (
      <rect
        key={idx}
        x={xScale(item.date) - 10}
        width={20}
        y={yScale(0)}
        height={yScale(item.value)}
        fill="blue"
      />
    ))}
  </svg>
)
}
</code>```

I typed this from memory so it might not actually work, but basically it should be drawing a bar chart with a timeline as the x-axis. Using d3 with vanilla js is useful because it can handle keeping track of the data points and drawing svg elements accordingly, but this sort of task is also one of the things React is good at, and in my opinion is easier to read.

Title: Can I Import any 3D.js Graph to React?

Body:
There are tons of blog posts out there that talk about integrating D3 with React directly, but in my experience I've found that just learning how to use the D3 scale functions directly, and then rendering your own svg elements is much easier to follow. For example, here is a relatively simple chart using a nice middleground of React and D3:

import {scaleTime} from "d3";

const width = 500;
const height = 300;
const date = [
  {date: new Date(2012,4,5), value: 5},
  {date: new Date(2013,3,2), value: 2},
  {date: new Date(2017,3,2), value: 7},
];

const MyChart = () => {
  const xScale = useMemo(() => {
    return scaleTime()
      .domain([new Date(2010,0,1), new Date(2020,0,1)])
      .range([0, width]);
  }, []);

  const yScale = useMemo(() => {
    return scaleLinear()
      .domain([0, 10])
      .domain([height, 0]);
  }, []);

return (
  <svg width={width} height={height}>
    <line className="x-axis" x1={0} x2={width} y1={yScale(0)} y1={yScale(0)} stroke="black" />
    {data.map((item, idx) => (
      <rect
        key={idx}
        x={xScale(item.date) - 10}
        width={20}
        y={yScale(0)}
        height={yScale(item.value)}
        fill="blue"
      />
    ))}
  </svg>
)
}

I typed this from memory so it might not actually work, but basically it should be drawing a bar chart with a timeline as the x-axis. Using d3 with vanilla js is useful because it can handle keeping track of the data points and drawing svg elements accordingly, but this sort of task is also one of the things React is good at, and in my opinion is easier to read.


问:
Some elements which satisfy the condition in a two-dimensional array do not display
I have an array of floats, arr[n][m], where the n defines the number of rows and m does the same for columns, the users enter them using the scanf() function. Each element is calculated according to the formula:

```<code>arr[i][j] = fabs(exp(i)-exp(j))+(i+j)/2.+1
</code>```

I need to check if the element is less than the sum of its neigbours from the both sides (ignoring bottom and top in this case, but it would be nice to count them as well). It does count its number almost right, but for some reason it ignores the elements which are situated in the middle of the last two rows. Then I have to find the sum of such elements and replace them with the average of their neigbours' sum of indexes, counting i+j:

```<code>    for (i = 0; i<n; ++i, puts(" ")) // it's easier to deal with the elements displayed in this way
        for (j=1; j<m-1; ++j) // begin with the [0][1] because [0][0] doesn't have any neighbour on the left;
    m-1 because the last element does not have any neighbour on the right
        {
            if (arr[i][j] < ((arr[i][j-1])+(arr[i][j+1])))
            {
                printf("%.2f  ", arr[i][j]);
                count++;
                sum+= arr[i][j];
                arr[i][j] = (i+j + i+j) / 4;
            }
        }

        printf("\nThe number of such elements: %i", count);
        printf("\nThe sum of such elements is: %.2f", sum);
</code>```

Therefore, the question is about counting the middle values in the last two rows and including them in the formula of sum.

I underlined the elements which satisfy the condition but do not display.

答:
```<code>arr[i][j] = (i+j + i+j) / 4;
</code>```

What is this line for? You are replacing element values, mostly with much smaller values. That's why the comparison then fails - the element to the left is much smaller than it was, so the sum is no longer larger than the center element.

Body:
I have an array of floats, arr[n][m], where the n defines the number of rows and m does the same for columns, the users enter them using the scanf() function. Each element is calculated according to the formula:

arr[i][j] = fabs(exp(i)-exp(j))+(i+j)/2.+1

I need to check if the element is less than the sum of its neigbours from the both sides (ignoring bottom and top in this case, but it would be nice to count them as well). It does count its number almost right, but for some reason it ignores the elements which are situated in the middle of the last two rows. Then I have to find the sum of such elements and replace them with the average of their neigbours' sum of indexes, counting i+j:

    for (i = 0; i<n; ++i, puts(" ")) // it's easier to deal with the elements displayed in this way
        for (j=1; j<m-1; ++j) // begin with the [0][1] because [0][0] doesn't have any neighbour on the left;
    m-1 because the last element does not have any neighbour on the right
        {
            if (arr[i][j] < ((arr[i][j-1])+(arr[i][j+1])))
            {
                printf("%.2f  ", arr[i][j]);
                count++;
                sum+= arr[i][j];
                arr[i][j] = (i+j + i+j) / 4;
            }
        }

        printf("\nThe number of such elements: %i", count);
        printf("\nThe sum of such elements is: %.2f", sum);

Therefore, the question is about counting the middle values in the last two rows and including them in the formula of sum.

I underlined the elements which satisfy the condition but do not display.

Body:
arr[i][j] = (i+j + i+j) / 4;

What is this line for? You are replacing element values, mostly with much smaller values. That's why the comparison then fails - the element to the left is much smaller than it was, so the sum is no longer larger than the center element.


问:
Multiple instances of Prolog clauses with identical ground head. Any uses besides for this besides (dubious) control of computation?
In SWI Prolog:

Exact clause duplicates are allowed:

```<code>a(1).
a(1).
</code>```

```<code>?- a(X).
X = 1 ;
X = 1.
</code>```

or even:

```<code>c :- format("Hello from first c!").
c :- format("Hello from second c!").
</code>```

```<code>Hello from first c!
true ;
Hello from second c!
true.
</code>```

More generally, so are clauses with identical fully ground heads but differing bodies:

```<code>b(1) :- format("Hello from first b!").
b(1) :- format("Hello from second b!").
</code>```

```<code>?- b(1).
Hello from first b!
true ;
Hello from second b!
true.
</code>```

Clauses with identical non-ground head feel somewhat more reasonable:

```<code>p(X) :- format("Yup, this is p(~w)",X).
p(X) :- format("Yup, this is also p(~w)",X).
p(X) :- format("You think you can get rid of good old p(~w) just like that?",X).
</code>```

```<code>?- p('homer simpson').
Yup, this is p(homer simpson)
true ;
Yup, this is also p(homer simpson)
true ;
You think you can get rid of good old p(homer simpson) just like that?
true.
</code>```

```<code>?- p(X).
Yup, this is p(_4782)
true ;
Yup, this is also p(_4782)
true ;
You think you can get rid of good old p(_4782) just like that?
true.
</code>```

This covers the reasonable case of clauses with a guarded body:

```<code>p(X) :- X < 0,   format("It's less than 0: ~w", X).
p(X) :- X =:= 0, format("It's exactly 0: ~w", X).
p(X) :- X > 0,   format("It's larger than 0: ~w", X).
</code>```

On second thoughts ... we already encounter the ultimate case in the built-in repeat:

```<code>?- a(X).
X = 1 ;
X = 1.
</code>```0

Or can construct an intermediate case easily:

```<code>?- a(X).
X = 1 ;
X = 1.
</code>```1

```<code>?- a(X).
X = 1 ;
X = 1.
</code>```2

Somehow textbooks gloss over the fact that predicates have additional semantics: they can not only be false or true for any given ground arguments, but they can actually be true(n) - "true n times, n ≥ 0" .

From a theory standpoint, this is dubious, at least for vanilla classical logic.

On the other hand, it is useful from a computational standpoint for:

Side-effects (rather for output than for input, and rather marginally).

Control of the computation (i.e. repeat).

Are there any other uses?

I really feel the compiler should flag variable-less cases like a/1, c/0, b/1 above as errors (easy to detect), and even repeat/0 should probably have a value: repeat(Count). Anything which redoes successfully should NOT redo successfully in the same context on exactly the same ground arguments. It has the same squishy feeling of irrelevancy as a(X) :- b(Y). b(Z). Brrr!.

答:
Some observations in the particular case of duplicated clauses.

If the repeated clauses for predicate a/1 are found in a Logtalk object or in a Prolog module that can be compiled as an object, the Logtalk linter can warn you of duplicated clauses. For example, given the following module:

```<code>:- module(duplicates, []).

a(1).
a(1).
</code>```

We get:

```<code>?- set_logtalk_flag(duplicated_clauses, warning).
true.

?- {duplicates}.
*     Duplicated clause: a(1)
*       first found at or above line 3
*       while compiling object duplicates
*       in file /Users/pmoura/duplicates.lgt at or above line 4
*
% [ /Users/pmoura/duplicates.lgt loaded ]
% 1 compilation warning
true.
</code>```

This particular lint warning is usually turned off by default due to its computational cost. If you load the tutor tool prior to the compilation of the module, you will get instead:

```<code>?- {tutor(loader)}.
...
% (0 warnings)
true.

?- set_logtalk_flag(duplicated_clauses, warning).
true.

?- {duplicates}.
*     Duplicated clause: a(1)
*       first found at or above line 3
*       while compiling object duplicates
*       in file /Users/pmoura/Desktop/duplicates.lgt at or above line 4
*     Duplicated clauses are usually a source code editing error and can
*     result in spurious choice-points, degrading performance. Delete or
*     correct the duplicated clause to fix this warning.
*
% [ /Users/pmoura/Desktop/duplicates.lgt loaded ]
% 1 compilation warning
true.
</code>```

The warning is useful and proved itself worth in non-trivial codebases.

Body:
In SWI Prolog:

Exact clause duplicates are allowed:

a(1).
a(1).

?- a(X).
X = 1 ;
X = 1.

or even:

c :- format("Hello from first c!").
c :- format("Hello from second c!").

Hello from first c!
true ;
Hello from second c!
true.

More generally, so are clauses with identical fully ground heads but differing bodies:

b(1) :- format("Hello from first b!").
b(1) :- format("Hello from second b!").

?- b(1).
Hello from first b!
true ;
Hello from second b!
true.

Clauses with identical non-ground head feel somewhat more reasonable:

p(X) :- format("Yup, this is p(~w)",X).
p(X) :- format("Yup, this is also p(~w)",X).
p(X) :- format("You think you can get rid of good old p(~w) just like that?",X).

?- p('homer simpson').
Yup, this is p(homer simpson)
true ;
Yup, this is also p(homer simpson)
true ;
You think you can get rid of good old p(homer simpson) just like that?
true.

?- p(X).
Yup, this is p(_4782)
true ;
Yup, this is also p(_4782)
true ;
You think you can get rid of good old p(_4782) just like that?
true.

This covers the reasonable case of clauses with a guarded body:

p(X) :- X < 0,   format("It's less than 0: ~w", X).
p(X) :- X =:= 0, format("It's exactly 0: ~w", X).
p(X) :- X > 0,   format("It's larger than 0: ~w", X).

On second thoughts ... we already encounter the ultimate case in the built-in repeat:

?- repeat.
true ;
true ;
true ;
true ;
…

Or can construct an intermediate case easily:

h :- member(_,[1,2,3]).

?- h.
true ;
true ;
true.

Somehow textbooks gloss over the fact that predicates have additional semantics: they can not only be false or true for any given ground arguments, but they can actually be true(n) - "true n times, n ≥ 0" .

From a theory standpoint, this is dubious, at least for vanilla classical logic.

On the other hand, it is useful from a computational standpoint for:

Side-effects (rather for output than for input, and rather marginally).

Control of the computation (i.e. repeat).

Are there any other uses?

I really feel the compiler should flag variable-less cases like a/1, c/0, b/1 above as errors (easy to detect), and even repeat/0 should probably have a value: repeat(Count). Anything which redoes successfully should NOT redo successfully in the same context on exactly the same ground arguments. It has the same squishy feeling of irrelevancy as a(X) :- b(Y). b(Z). Brrr!.

Body:
Some observations in the particular case of duplicated clauses.

If the repeated clauses for predicate a/1 are found in a Logtalk object or in a Prolog module that can be compiled as an object, the Logtalk linter can warn you of duplicated clauses. For example, given the following module:

:- module(duplicates, []).

a(1).
a(1).

We get:

?- set_logtalk_flag(duplicated_clauses, warning).
true.

?- {duplicates}.
*     Duplicated clause: a(1)
*       first found at or above line 3
*       while compiling object duplicates
*       in file /Users/pmoura/duplicates.lgt at or above line 4
*
% [ /Users/pmoura/duplicates.lgt loaded ]
% 1 compilation warning
true.

This particular lint warning is usually turned off by default due to its computational cost. If you load the tutor tool prior to the compilation of the module, you will get instead:

?- {tutor(loader)}.
...
% (0 warnings)
true.

?- set_logtalk_flag(duplicated_clauses, warning).
true.

?- {duplicates}.
*     Duplicated clause: a(1)
*       first found at or above line 3
*       while compiling object duplicates
*       in file /Users/pmoura/Desktop/duplicates.lgt at or above line 4
*     Duplicated clauses are usually a source code editing error and can
*     result in spurious choice-points, degrading performance. Delete or
*     correct the duplicated clause to fix this warning.
*
% [ /Users/pmoura/Desktop/duplicates.lgt loaded ]
% 1 compilation warning
true.

The warning is useful and proved itself worth in non-trivial codebases.


问:
Oracle (ORA-02270) : no matching unique or primary key for this column-list error
I have two tables, Table JOB and Table USER, here is the structure

```<code> CREATE TABLE JOB
 (
   ID       NUMBER NOT NULL ,
   USERID   NUMBER,
   CONSTRAINT B_PK PRIMARY KEY ( ID ) ENABLE
 );

 CREATE TABLE USER
 (
   ID       NUMBER NOT NULL ,
   CONSTRAINT U_PK PRIMARY KEY ( ID ) ENABLE
 );
</code>```

Now, i want to add foreign key constraint to JOB referencing to USER table, as

```<code>Alter Table JOB ADD CONSTRAINT FK_USERID FOREIGN KEY(USERID) REFERENCES USER(ID);
</code>```

this throws Oracle (ORA-02270) : no matching unique or primary key for this column-list error, doing some investigation it appears that we need to have either unique key or primary key constraint on USERID but I cannot have that as one USERID can have multiple JOBS associated with him, any thoughts or suggestions on how to fix this issue?

Researched ORA-02270 and SO related question

答:
We have the following script for create a new table:

```<code>CREATE TABLE new_table
(
id                     NUMBER(32) PRIMARY KEY,
referenced_table_id    NUMBER(32)    NOT NULL,
CONSTRAINT fk_new_table_referenced_table_id
    FOREIGN KEY (referenced_table_id)
        REFERENCES referenced_table (id)
);
</code>```

and we were getting this error on execution:

[42000][2270] ORA-02270: no matching unique or primary key for this
column-list

The issue was due to disabled primary key of the referenced table in our case. We have to enable it using the following sql:

```<code>ALTER TABLE referenced_table ENABLE PRIMARY KEY USING INDEX;
</code>```

after that we created new table using first script without any issues

Body:
I have two tables, Table JOB and Table USER, here is the structure

 CREATE TABLE JOB
 (
   ID       NUMBER NOT NULL ,
   USERID   NUMBER,
   CONSTRAINT B_PK PRIMARY KEY ( ID ) ENABLE
 );

 CREATE TABLE USER
 (
   ID       NUMBER NOT NULL ,
   CONSTRAINT U_PK PRIMARY KEY ( ID ) ENABLE
 );

Now, i want to add foreign key constraint to JOB referencing to USER table, as

Alter Table JOB ADD CONSTRAINT FK_USERID FOREIGN KEY(USERID) REFERENCES USER(ID);

this throws Oracle (ORA-02270) : no matching unique or primary key for this column-list error, doing some investigation it appears that we need to have either unique key or primary key constraint on USERID but I cannot have that as one USERID can have multiple JOBS associated with him, any thoughts or suggestions on how to fix this issue?

Researched ORA-02270 and SO related question

Body:
We have the following script for create a new table:

CREATE TABLE new_table
(
id                     NUMBER(32) PRIMARY KEY,
referenced_table_id    NUMBER(32)    NOT NULL,
CONSTRAINT fk_new_table_referenced_table_id
    FOREIGN KEY (referenced_table_id)
        REFERENCES referenced_table (id)
);

and we were getting this error on execution:

[42000][2270] ORA-02270: no matching unique or primary key for this
column-list

The issue was due to disabled primary key of the referenced table in our case. We have to enable it using the following sql:

ALTER TABLE referenced_table ENABLE PRIMARY KEY USING INDEX;

after that we created new table using first script without any issues


问:
Run jQuery function when a certain number of checkboxes are selected
I am trying to achieve the following with jQuery:

Select max 3 check boxes out of 20, when three check boxes are selected run jQuery function.

答:
I'm considering the example on the official documentation of Jquery:
http://api.jquery.com/checked-selector/</p>

```<code><script>
    function myFunction(){

    }

    function countChecked() {
      var n = $("input:checked").length;
      if(n==3){
         myFunction();
      }
    }

    $(":checkbox").click(countChecked);

</script>
</code>```

Body:
I'm considering the example on the official documentation of Jquery:
http://api.jquery.com/checked-selector/

<script>
    function myFunction(){

    }

    function countChecked() {
      var n = $("input:checked").length;
      if(n==3){
         myFunction();
      }
    }

    $(":checkbox").click(countChecked);

</script>


问:
Error installing node-gyp on ubuntu
```<code>npm http 200 https://registry.npmjs.org/weak/-/weak-0.2.2.tgz
npm http GET https://registry.npmjs.org/bindings
npm http 304 https://registry.npmjs.org/bindings

> weak@0.2.2 install node_modules/weak
> node-gyp rebuild

Traceback (most recent call last):
  File "/usr/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py", line 18, in <module>
    sys.exit(gyp.script_main())
AttributeError: 'module' object has no attribute 'script_main'
gyp ERR! configure error
gyp ERR! stack Error: `gyp` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onCpExit (/usr/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:337:16)
gyp ERR! stack     at ChildProcess.EventEmitter.emit (events.js:98:17)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (child_process.js:789:12)
gyp ERR! System Linux 3.11.0-15-generic
gyp ERR! command "node" "/usr/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"

gyp ERR! node -v v0.10.15
gyp ERR! node-gyp -v v0.12.1
gyp ERR! not ok
npm ERR! weak@0.2.2 install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the weak@0.2.2 install script.
npm ERR! This is most likely a problem with the weak package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node-gyp rebuild
npm ERR! You can get their info via:
npm ERR!     npm owner ls weak
npm ERR! There is likely additional logging output above.

npm ERR! System Linux 3.11.0-15-generic
npm ERR! command "node" "/usr/bin/npm" "install" "weak@0.2.2"
npm ERR! node -v v0.10.15
npm ERR! npm -v 1.3.23
npm ERR! code ELIFECYCLE

npm ERR! not ok code 0
</code>```

I don't have a direct dependency on weak or node-gyp but I guess it is required by my other dependencies (express,phantom,ejs,aws-sdk,moment). Anyone faced such an issue and was able to fix?

答:
In my-case it was failing on Linux-mint 19.2, for some reasons on run-time gcc++ was not accessible.
So by installing the build-essentials error was resolved.
PS:

build-essential package is a reference for all the packages needed to compile a Debian packages. It generally includes the GCC/g++ compilers and libraries and some other utilities. Informational for list of build-essential packages can be found on build-essentials

Title: Error installing node-gyp on ubuntu

Body:
npm http 200 https://registry.npmjs.org/weak/-/weak-0.2.2.tgz
npm http GET https://registry.npmjs.org/bindings
npm http 304 https://registry.npmjs.org/bindings

> weak@0.2.2 install node_modules/weak
> node-gyp rebuild

Traceback (most recent call last):
  File "/usr/lib/node_modules/npm/node_modules/node-gyp/gyp/gyp_main.py", line 18, in <module>
    sys.exit(gyp.script_main())
AttributeError: 'module' object has no attribute 'script_main'
gyp ERR! configure error
gyp ERR! stack Error: `gyp` failed with exit code: 1
gyp ERR! stack     at ChildProcess.onCpExit (/usr/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:337:16)
gyp ERR! stack     at ChildProcess.EventEmitter.emit (events.js:98:17)
gyp ERR! stack     at Process.ChildProcess._handle.onexit (child_process.js:789:12)
gyp ERR! System Linux 3.11.0-15-generic
gyp ERR! command "node" "/usr/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild"

gyp ERR! node -v v0.10.15
gyp ERR! node-gyp -v v0.12.1
gyp ERR! not ok
npm ERR! weak@0.2.2 install: `node-gyp rebuild`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the weak@0.2.2 install script.
npm ERR! This is most likely a problem with the weak package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     node-gyp rebuild
npm ERR! You can get their info via:
npm ERR!     npm owner ls weak
npm ERR! There is likely additional logging output above.

npm ERR! System Linux 3.11.0-15-generic
npm ERR! command "node" "/usr/bin/npm" "install" "weak@0.2.2"
npm ERR! node -v v0.10.15
npm ERR! npm -v 1.3.23
npm ERR! code ELIFECYCLE

npm ERR! not ok code 0

I don't have a direct dependency on weak or node-gyp but I guess it is required by my other dependencies (express,phantom,ejs,aws-sdk,moment). Anyone faced such an issue and was able to fix?


问:
Is there a way to take text from a file and turn it into an argument for my c program?
I have a C project where the user can type in an 8 bit binary number or open up a text file with an 8 bit binary number. What I'm having trouble with is getting the 8 bit binary number from a file and making that an argument char* argv[] for my program.
This is how I'm reading the 8 bit binary number from the file

```<code>    fd = open(argv[1], O_RDONLY);
    read(fd,jString, 100);
    close(fd);
    printf("jString: %s\n", jString);

</code>```

Right now I only know how to put the 8 bit binary number into a string but what I want is to turn each 8 bit binary number input separated by spaces from the file into an argument char* argv[] for my program is this possible if so how do I do it?

Something that I already tried is this.

```<code>    fd = open(argv[1], O_RDONLY);
    read(fd,argv[1], 100);
</code>```

the problem with this is that it just reads the whole file into argv[1] and doesn't seperate them by spaces and into different arguments for my program.

答:
What I'm having trouble with is getting the 8 bit binary number from a
  file and making that an argument char* argv[] for my program

You can not do this. The usual declaration of

```<code>int main(int argc, char** argv){};
</code>```

means that these 2 arguments are provided for you by the operating system when your program is run. What you can do is build something like this for your program, let's say a int myArgCountand char** myArgValues; but it seems that you do not need that.

If task is you program, running task 00001111 will put 00001111 into argv[1]. And set argcto 2, since argv[0] is always the complete path of your program.

At first you say that a binary number can be provided in a file, but in the next paragraph you said

what I want is to turn each 8 bit binary number input separated by spaces

If in fact the input file can have a list of 8-bit binary numbers separated by spaces --- and not just one --- you will need do build a list just like the system does for you, alocating memory for the numbers and creating an array of pointers to them, and an int with the count of numbers. It is not complicated.

The code below tests for an argument on the command line and if not present tries to     open source.txt file to get one. May be it helps.

Note the use of scanf()to read the values from the file. The mask in use "%8[01]" is very convenient: it accepts just 0 and 1 for a maximum of 8 digits.

```<code>#define _CRT_SECURE_NO_WARNINGS
#include "stdio.h"
#include "stdlib.h"
#include "string.h"

int main(int argc, char** argv)
{
    char        binary_number[10];
    char*       mask = "%8[01]"; // for scanf()
    const char* FileName = "source.txt";

    if (argc < 2)
    {   // no number on the command line
        fprintf(stderr, "\nNo 8-bit number provided on the command line\n");
        FILE* in_file = fopen(FileName, "r");
        if (in_file == NULL)
        {
            fprintf(stderr, "Could not open [%s]\n", FileName);
            return -1;
        }
        int n = fscanf(in_file, mask, binary_number);
        printf("\nFrom the file [%s] number is [%s]\n", FileName, binary_number);
        fclose(in_file);
    }
    else
    {   // number provided
        strncpy(binary_number, argv[1], 9);
        fprintf(stderr, "\nFrom the command line: [%s]\n", argv[1]);
    };
    return(EXIT_SUCCESS);
};
</code>```

the program shows

```<code>From the command line: [101010]
</code>```

or

```<code>    No 8-bit number provided on the command line
    From the file [source.txt] number is [11110000]
</code>```

Body:
I have a C project where the user can type in an 8 bit binary number or open up a text file with an 8 bit binary number. What I'm having trouble with is getting the 8 bit binary number from a file and making that an argument char* argv[] for my program.
This is how I'm reading the 8 bit binary number from the file

    fd = open(argv[1], O_RDONLY);
    read(fd,jString, 100);
    close(fd);
    printf("jString: %s\n", jString);

Right now I only know how to put the 8 bit binary number into a string but what I want is to turn each 8 bit binary number input separated by spaces from the file into an argument char* argv[] for my program is this possible if so how do I do it?

Something that I already tried is this.

    fd = open(argv[1], O_RDONLY);
    read(fd,argv[1], 100);

the problem with this is that it just reads the whole file into argv[1] and doesn't seperate them by spaces and into different arguments for my program.

Body:
What I'm having trouble with is getting the 8 bit binary number from a
  file and making that an argument char* argv[] for my program

You can not do this. The usual declaration of

int main(int argc, char** argv){};

means that these 2 arguments are provided for you by the operating system when your program is run. What you can do is build something like this for your program, let's say a int myArgCountand char** myArgValues; but it seems that you do not need that.

If task is you program, running task 00001111 will put 00001111 into argv[1]. And set argcto 2, since argv[0] is always the complete path of your program.

At first you say that a binary number can be provided in a file, but in the next paragraph you said

what I want is to turn each 8 bit binary number input separated by spaces

If in fact the input file can have a list of 8-bit binary numbers separated by spaces --- and not just one --- you will need do build a list just like the system does for you, alocating memory for the numbers and creating an array of pointers to them, and an int with the count of numbers. It is not complicated.

The code below tests for an argument on the command line and if not present tries to     open source.txt file to get one. May be it helps.

Note the use of scanf()to read the values from the file. The mask in use "%8[01]" is very convenient: it accepts just 0 and 1 for a maximum of 8 digits.

#define _CRT_SECURE_NO_WARNINGS
#include "stdio.h"
#include "stdlib.h"
#include "string.h"

int main(int argc, char** argv)
{
    char        binary_number[10];
    char*       mask = "%8[01]"; // for scanf()
    const char* FileName = "source.txt";

    if (argc < 2)
    {   // no number on the command line
        fprintf(stderr, "\nNo 8-bit number provided on the command line\n");
        FILE* in_file = fopen(FileName, "r");
        if (in_file == NULL)
        {
            fprintf(stderr, "Could not open [%s]\n", FileName);
            return -1;
        }
        int n = fscanf(in_file, mask, binary_number);
        printf("\nFrom the file [%s] number is [%s]\n", FileName, binary_number);
        fclose(in_file);
    }
    else
    {   // number provided
        strncpy(binary_number, argv[1], 9);
        fprintf(stderr, "\nFrom the command line: [%s]\n", argv[1]);
    };
    return(EXIT_SUCCESS);
};

the program shows

From the command line: [101010]

or

    No 8-bit number provided on the command line
    From the file [source.txt] number is [11110000]


问:
There is a way to improve the execution time?
I'm developing a VBA code that is responsible for searching in a excel file the value of a cell (serial number) and its production start date. After that, its searches on a Access databse for that same serial number and writes on the especified column the date.
The problem is that it's taking hours to end, because the excel and the database have more than 10000 rows...
The question is: there is a way that I can improve my code to run faster?</p>

```<code>Private Sub Comando9_Click()
 Set db = CurrentDb.OpenRecordset("ConsultaNSerie", dbOpenDynaset)
 Set appExcel = CreateObject("Excel.Application")
'appExcel.Visible = True
 appExcel.Application.Workbooks.Open "K:\EM HP - Comum\Planejamento de
 Produção HP\CB\Planejamento de Produção_CB_FY19-20\Planejamento de
 Produção_CB_FY19-20.xlsm"

 Dim Inicio_planejado As Variant
 Dim Numero_serie As String
 Dim SAP As String
 i = 9

 Dim fso As Object
 Set fso = CreateObject("Scripting.FileSystemObject")

 Dim Fileout As Object
 Set Fileout = fso.CreateTextFile("K:\EM HP - Engenharia\02-Aplicação\11-
 Controle de Projetos\Nserie_NoMatch.txt", True, True)

 Do
     SAP = appExcel.Sheets("Disjuntores").Columns("I").Rows(i).Value
     Numero_serie = appExcel.Sheets("Disjuntores").Columns("L").Rows(i).Value
     'MsgBox (Numero_serie)
     Inicio_planejado =
     appExcel.Sheets("Disjuntores").Columns("T").Rows(i).Value

    If Inicio_planejado <> "" Then
        'MsgBox (Inicio_planejado)
        'quando for vazio, desconsiderar a celula
        'ThisWorkbook.Reg.FindFirst "[OF] = '" + cb_OF.Value + " '"
        db.FindNext "[NUMERO_SERIE] = '" + Numero_serie + " '"
        If db.NoMatch Then
            db.FindPrevious "[NUMERO_SERIE] = '" + Numero_serie + " '"
        ElseIf db.NoMatch Then
            Fileout.Write Numero_serie & "  "
            'MsgBox ("Número de série " + Numero_serie + " não encontrado")
        Else
            'Adicionar o valor de "Inicio_planejado" aos campos na coluna
     "INICIO_FBR"
            db.Edit
            db![INICIO_FBR] = Inicio_planejado
            db.Update
            db.MoveNext
        End If
End If

i = i + 1

Loop Until appExcel.Sheets("Disjuntores").cells(i, 7) = ""

Fileout.Close
appExcel.Quit

End Sub
</code>```

答:
1) Don't use db.FindNext and db.FindPrevious with the same search criterium. That makes no sense for your situation.

Use only FindFirst, and get rid of the db.MoveNext:

```<code>    db.FindFirst "[NUMERO_SERIE] = '" + Numero_serie + " '"
    If db.NoMatch Then
        Fileout.Write Numero_serie & "  "
    Else
        db.Edit
        db![INICIO_FBR] = Inicio_planejado
        db.Update
        ' Remove this, is is of no use:
        '--- db.MoveNext
    End If
</code>```

2) In Access, edit the table ConsultaNSerie and add an index on NUMERO_SERIE.

Body:
I'm developing a VBA code that is responsible for searching in a excel file the value of a cell (serial number) and its production start date. After that, its searches on a Access databse for that same serial number and writes on the especified column the date.
The problem is that it's taking hours to end, because the excel and the database have more than 10000 rows...
The question is: there is a way that I can improve my code to run faster?

Private Sub Comando9_Click()
 Set db = CurrentDb.OpenRecordset("ConsultaNSerie", dbOpenDynaset)
 Set appExcel = CreateObject("Excel.Application")
'appExcel.Visible = True
 appExcel.Application.Workbooks.Open "K:\EM HP - Comum\Planejamento de
 Produção HP\CB\Planejamento de Produção_CB_FY19-20\Planejamento de
 Produção_CB_FY19-20.xlsm"

 Dim Inicio_planejado As Variant
 Dim Numero_serie As String
 Dim SAP As String
 i = 9

 Dim fso As Object
 Set fso = CreateObject("Scripting.FileSystemObject")

 Dim Fileout As Object
 Set Fileout = fso.CreateTextFile("K:\EM HP - Engenharia\02-Aplicação\11-
 Controle de Projetos\Nserie_NoMatch.txt", True, True)

 Do
     SAP = appExcel.Sheets("Disjuntores").Columns("I").Rows(i).Value
     Numero_serie = appExcel.Sheets("Disjuntores").Columns("L").Rows(i).Value
     'MsgBox (Numero_serie)
     Inicio_planejado =
     appExcel.Sheets("Disjuntores").Columns("T").Rows(i).Value

    If Inicio_planejado <> "" Then
        'MsgBox (Inicio_planejado)
        'quando for vazio, desconsiderar a celula
        'ThisWorkbook.Reg.FindFirst "[OF] = '" + cb_OF.Value + " '"
        db.FindNext "[NUMERO_SERIE] = '" + Numero_serie + " '"
        If db.NoMatch Then
            db.FindPrevious "[NUMERO_SERIE] = '" + Numero_serie + " '"
        ElseIf db.NoMatch Then
            Fileout.Write Numero_serie & "  "
            'MsgBox ("Número de série " + Numero_serie + " não encontrado")
        Else
            'Adicionar o valor de "Inicio_planejado" aos campos na coluna
     "INICIO_FBR"
            db.Edit
            db![INICIO_FBR] = Inicio_planejado
            db.Update
            db.MoveNext
        End If
End If

i = i + 1

Loop Until appExcel.Sheets("Disjuntores").cells(i, 7) = ""

Fileout.Close
appExcel.Quit

End Sub

Body:
1) Don't use db.FindNext and db.FindPrevious with the same search criterium. That makes no sense for your situation.

Use only FindFirst, and get rid of the db.MoveNext:

    db.FindFirst "[NUMERO_SERIE] = '" + Numero_serie + " '"
    If db.NoMatch Then
        Fileout.Write Numero_serie & "  "
    Else
        db.Edit
        db![INICIO_FBR] = Inicio_planejado
        db.Update
        ' Remove this, is is of no use:
        '--- db.MoveNext
    End If

2) In Access, edit the table ConsultaNSerie and add an index on NUMERO_SERIE.


问:
How to replace environment variable value in yaml file to be parsed using python script
I need to use environment variable "PATH" in yaml file which needs to be parsed with a script.

This is the environment variable I have set on my terminal:

```<code>$ echo $PATH
/Users/abc/Downloads/tbwork
</code>```

This is my sample.yml:

```<code>---
Top: ${PATH}/my.txt
Vars:
- a
- b
</code>```

When I parse this yaml file with my script, I don't see PATH variables actual value.

This is my script:

```<code>import yaml
import os
import sys

stream = open("sample.yml", "r")
docs = yaml.load_all(stream)
for doc in docs:
    for k,v in doc.items():
        print k, "->", v
    print "\n",
</code>```

Output:

```<code>Top -> ${PATH}/my.txt
Vars -> ['a', 'b']
</code>```

Expected output is:

```<code>Top -> /Users/abc/Downloads/tbwork/my.txt
Vars -> ['a', 'b']
</code>```

Can someone help me figuring out the correct way to do it if I am doing it wrong way?

答:
There is a nice library envyaml for this.
With it it's very simple:</p>

```<code>from envyaml import EnvYAML

# read file env.yaml and parse config
env = EnvYAML('env.yaml')
</code>```

Body:
I need to use environment variable "PATH" in yaml file which needs to be parsed with a script.

This is the environment variable I have set on my terminal:

$ echo $PATH
/Users/abc/Downloads/tbwork

This is my sample.yml:

---
Top: ${PATH}/my.txt
Vars:
- a
- b

When I parse this yaml file with my script, I don't see PATH variables actual value.

This is my script:

import yaml
import os
import sys

stream = open("sample.yml", "r")
docs = yaml.load_all(stream)
for doc in docs:
    for k,v in doc.items():
        print k, "->", v
    print "\n",

Output:

Top -> ${PATH}/my.txt
Vars -> ['a', 'b']

Expected output is:

Top -> /Users/abc/Downloads/tbwork/my.txt
Vars -> ['a', 'b']

Can someone help me figuring out the correct way to do it if I am doing it wrong way?

Body:
There is a nice library envyaml for this.
With it it's very simple:

from envyaml import EnvYAML

# read file env.yaml and parse config
env = EnvYAML('env.yaml')


问:
Call to undefined method App\\Repositories\\WishlistRepository::firstOrFail()
I want to give wishlist functionality in my website so for that i have written code which is listed below. Now when i'm checking whether the product is already listed in the wishlist table and if it is wishlisted then delete it. So for that i have written which is listed inside isAlreadyListed function in WishlistRepository  :

```<code>return $this->firstOrFail()->where('product_id', $p_id)->where('user_id',$u_id);
</code>```

then i get following error :

Call to undefined method
  App\Repositories\WishlistRepository::firstOrFail()

WishlistRepository

```<code><?php
        namespace App\Repositories;

        use App\Models\Wishlist;
        use App\Traits\UploadAble;
        use Illuminate\Http\UploadedFile;
        use App\Contracts\WishlistContract;
        use Illuminate\Database\QueryException;
        use Illuminate\Database\Eloquent\ModelNotFoundException;
        use Doctrine\Instantiator\Exception\InvalidArgumentException;

        /**
         * Class WishlistRepository
         *
         * @package \App\Repositories
         */
        class WishlistRepository extends BaseRepository implements WishlistContract
        {
            use UploadAble;
            public function __construct(Wishlist $model)
        {
            parent::__construct($model);
            $this->model = $model;
        }

        public function listWishlist(string $order = 'id', string $sort = 'desc', array $columns = ['*'])
        {
            return $this->all($columns, $order, $sort);
        }

            public function addToWishlist(array $params)
            {
                try {
                    if($this->isAlreadyWishlisted($params['product_id'], $params['user_id']))
                    {
                        $this->removefromWishlist($params);
                    }
                    else
                    {
                        $wishlist = new Wishlist($params);
                        $wishlist->save();
                        return $wishlist;
                    }

                } catch (QueryException $exception) {
                    throw new InvalidArgumentException($exception->getMessage());
                }
            }

            public function removefromWishlist($params)
            {
                $wishlist = $this->isAlreadyWishlisted($params['product_id'],$params['user_id']);

                $wishlist->delete();

                return $wishlist;
            }

            public function isAlreadyWishlisted(int $p_id,int $u_id)
            {
                try {
               return $this->firstOrFail()->where('product_id', $p_id)->where('user_id',$u_id);
                } catch (ModelNotFoundException $e) {

                    throw new ModelNotFoundException($e);
                }

            }
        }
        ?>
</code>```

Model (Wishlist):

```<code><?php

namespace App\Models;
use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\Model;

class wishlist extends Model
{
    /**
     * @var string
     */
    protected $table = "wishlists";

    /**
     * @var array
     */
    protected $fillable = [
        'product_id', 'user_id'
    ];

    public function user(){
        return $this->belongsTo(User::class);
     }

     public function product(){
        return $this->belongsTo(Product::class);
     }
}
</code>```

答:
You are calling firstOrFail() on the repository class, instead you should call it on the model you have specified.

```<code>return $this->model->firstOrFail()->where('product_id', $p_id)->where('user_id',$u_id);
</code>```

Body:
I want to give wishlist functionality in my website so for that i have written code which is listed below. Now when i'm checking whether the product is already listed in the wishlist table and if it is wishlisted then delete it. So for that i have written which is listed inside isAlreadyListed function in WishlistRepository  :

return $this->firstOrFail()->where('product_id', $p_id)->where('user_id',$u_id);

then i get following error :

Call to undefined method
  App\Repositories\WishlistRepository::firstOrFail()

WishlistRepository

<?php
        namespace App\Repositories;

        use App\Models\Wishlist;
        use App\Traits\UploadAble;
        use Illuminate\Http\UploadedFile;
        use App\Contracts\WishlistContract;
        use Illuminate\Database\QueryException;
        use Illuminate\Database\Eloquent\ModelNotFoundException;
        use Doctrine\Instantiator\Exception\InvalidArgumentException;

        /**
         * Class WishlistRepository
         *
         * @package \App\Repositories
         */
        class WishlistRepository extends BaseRepository implements WishlistContract
        {
            use UploadAble;
            public function __construct(Wishlist $model)
        {
            parent::__construct($model);
            $this->model = $model;
        }

        public function listWishlist(string $order = 'id', string $sort = 'desc', array $columns = ['*'])
        {
            return $this->all($columns, $order, $sort);
        }

            public function addToWishlist(array $params)
            {
                try {
                    if($this->isAlreadyWishlisted($params['product_id'], $params['user_id']))
                    {
                        $this->removefromWishlist($params);
                    }
                    else
                    {
                        $wishlist = new Wishlist($params);
                        $wishlist->save();
                        return $wishlist;
                    }

                } catch (QueryException $exception) {
                    throw new InvalidArgumentException($exception->getMessage());
                }
            }

            public function removefromWishlist($params)
            {
                $wishlist = $this->isAlreadyWishlisted($params['product_id'],$params['user_id']);

                $wishlist->delete();

                return $wishlist;
            }

            public function isAlreadyWishlisted(int $p_id,int $u_id)
            {
                try {
               return $this->firstOrFail()->where('product_id', $p_id)->where('user_id',$u_id);
                } catch (ModelNotFoundException $e) {

                    throw new ModelNotFoundException($e);
                }

            }
        }
        ?>

Model (Wishlist):

<?php

namespace App\Models;
use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\Model;

class wishlist extends Model
{
    /**
     * @var string
     */
    protected $table = "wishlists";

    /**
     * @var array
     */
    protected $fillable = [
        'product_id', 'user_id'
    ];

    public function user(){
        return $this->belongsTo(User::class);
     }

     public function product(){
        return $this->belongsTo(Product::class);
     }
}

Body:
You are calling firstOrFail() on the repository class, instead you should call it on the model you have specified.

return $this->model->firstOrFail()->where('product_id', $p_id)->where('user_id',$u_id);


问:
A simple "javac" style command-line C/C++ compiler for Windows 7
Over the last couple of months I practiced console programming with Java just with the help of JDK and a text editor of my choice (Notepad++). And I loved the simplicity as a program can be compiled from the command line plainly using javac and run using java.

Now, I'm looking for similar compiler for C/C++, such that I create a .c or .cpp file and compile it in the command prompt, and all it does is create a "native" executable that can be run directly from the command prompt. Thus, without any need of bloated IDE. The reason I'm looking for such simple compiler is because it is going to be used by high-school students so I'm advised to avoid any IDE as far as possible, so students can practice all the concepts of C/C++ languages without having to go for IDE. Which compiler can I use that does this job? also, I must work across all the versions Windows starting from Windows XP.

答: You should certainly consider using MinGW GCC, but not by download from the MiNGW web page, unless you are some kind of masochist. Get the one packaged by Twilight Dragon Media at http://tdm-gcc.tdragon.net.</p>


问:
Login Process Issues
```<code>Public Class login
    Dim conn As MySqlConnection
    Dim Reader As MySqlDataReader
    Dim cmd As MySqlCommand
    Dim audit As String
    Dim faudit As String
    Dim connectiontime, active As String
    Dim attempts As String
    Dim server As String = "server=127.0.0.1;user=root;database=spilibrary"
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
        Dim statement As String
        Dim Userrole As String
        conn = New MySqlConnection
        conn.ConnectionString = server
        conn.Open()
        statement = "select * from user where Username = '" & username.Text & "' and Password = BINARY '" & password.Text & "'"
        cmd = New MySqlCommand(statement, conn)
        Reader = cmd.ExecuteReader

        Try
            Dim found As Boolean
            While Reader.Read
                found = True
                Userrole = Reader.GetString("Userrole")
                connectiontime = Reader.GetString("connectiontime")
                attempts = Reader.GetString("attempts")
                If Userrole = "Administrator" And connectiontime = "Now" Or connectiontime <= TimeOfDay.ToString("HH:mm") Then
                    MsgBox("Welcome Admin", MsgBoxStyle.Information, "System message")
                    mainform.Show()
                    mainform.Maintenancebtn.Enabled = True
                    mainform.level1.Text = Userrole
                    'Me.Close()
                    Reader.Close()
                    cmd = New MySqlCommand("update user set attempts = '" & "0" & "', connectiontime='" & "Now" & "' where Username='" & username.Text & "'", conn)
                    Reader = cmd.ExecuteReader
                ElseIf Userrole = "Librarian" And connectiontime = "Now" Or connectiontime <= TimeOfDay.ToString("HH:mm:ss") Then
                    MsgBox("Welcome Librarian", MsgBoxStyle.Information, "System Message")
                    'mainform.Maintenancebtn.Enabled = False
                    mainform.Show()
                    mainform.level1.Text = Userrole
                    ' Me.Close()
                    'OPAC.show()
                    Reader.Close()
                    cmd = New MySqlCommand("update user set attempts ='" & "0" & "', connectiontime ='" & "Now" & "' where Username='" & username.Text & "'", conn)
                    Reader = cmd.ExecuteReader
                ElseIf Userrole = "Administrator" And connectiontime <> "Now" And connectiontime >= TimeOfDay.ToString("HH:mm:ss") Then
                    MsgBox("You're Account has been blocked because of multiple failed attempts", vbCritical, "System Message")
                ElseIf Userrole = "Librarian" And connectiontime <> "Now" And connectiontime >= TimeOfDay.ToString("HH:mm:ss") Then
                    MsgBox("Your Account has been blocked because of multiple failed attempts", vbCritical, "System Message")
                Else
                    MsgBox("You're Account whas been blocked because of multiple failed attempts", vbCritical, "System Message")
                End If
</code>```

<p>Someone please help me with this.. when i hit login button it always reads the first if-else statement i enter which is the Userrole="administrator" even if im logging in my Librarian Userrole. when i try to switch them the It reads the librarian userrole and not the admin even if im logging my admin userrole.. in my database they are declared right. so maybe it's the code. Thank you </p>

答:
Try using brackets in your condition to make it clearer.  Like this:

```<code>If Userrole = "Administrator" AndAlso (connectiontime = "Now" OrElse connectiontime <= TimeOfDay.ToString("HH:mm")) Then
</code>```

in your code, it would also match if

```<code>connectiontime <= TimeOfDay.ToString("HH:mm")
</code>```

Title: Login Process Issues

Body:
Public Class login
    Dim conn As MySqlConnection
    Dim Reader As MySqlDataReader
    Dim cmd As MySqlCommand
    Dim audit As String
    Dim faudit As String
    Dim connectiontime, active As String
    Dim attempts As String
    Dim server As String = "server=127.0.0.1;user=root;database=spilibrary"
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
        Dim statement As String
        Dim Userrole As String
        conn = New MySqlConnection
        conn.ConnectionString = server
        conn.Open()
        statement = "select * from user where Username = '" & username.Text & "' and Password = BINARY '" & password.Text & "'"
        cmd = New MySqlCommand(statement, conn)
        Reader = cmd.ExecuteReader

        Try
            Dim found As Boolean
            While Reader.Read
                found = True
                Userrole = Reader.GetString("Userrole")
                connectiontime = Reader.GetString("connectiontime")
                attempts = Reader.GetString("attempts")
                If Userrole = "Administrator" And connectiontime = "Now" Or connectiontime <= TimeOfDay.ToString("HH:mm") Then
                    MsgBox("Welcome Admin", MsgBoxStyle.Information, "System message")
                    mainform.Show()
                    mainform.Maintenancebtn.Enabled = True
                    mainform.level1.Text = Userrole
                    'Me.Close()
                    Reader.Close()
                    cmd = New MySqlCommand("update user set attempts = '" & "0" & "', connectiontime='" & "Now" & "' where Username='" & username.Text & "'", conn)
                    Reader = cmd.ExecuteReader
                ElseIf Userrole = "Librarian" And connectiontime = "Now" Or connectiontime <= TimeOfDay.ToString("HH:mm:ss") Then
                    MsgBox("Welcome Librarian", MsgBoxStyle.Information, "System Message")
                    'mainform.Maintenancebtn.Enabled = False
                    mainform.Show()
                    mainform.level1.Text = Userrole
                    ' Me.Close()
                    'OPAC.show()
                    Reader.Close()
                    cmd = New MySqlCommand("update user set attempts ='" & "0" & "', connectiontime ='" & "Now" & "' where Username='" & username.Text & "'", conn)
                    Reader = cmd.ExecuteReader
                ElseIf Userrole = "Administrator" And connectiontime <> "Now" And connectiontime >= TimeOfDay.ToString("HH:mm:ss") Then
                    MsgBox("You're Account has been blocked because of multiple failed attempts", vbCritical, "System Message")
                ElseIf Userrole = "Librarian" And connectiontime <> "Now" And connectiontime >= TimeOfDay.ToString("HH:mm:ss") Then
                    MsgBox("Your Account has been blocked because of multiple failed attempts", vbCritical, "System Message")
                Else
                    MsgBox("You're Account whas been blocked because of multiple failed attempts", vbCritical, "System Message")
                End If

Someone please help me with this.. when i hit login button it always reads the first if-else statement i enter which is the Userrole="administrator" even if im logging in my Librarian Userrole. when i try to switch them the It reads the librarian userrole and not the admin even if im logging my admin userrole.. in my database they are declared right. so maybe it's the code. Thank you

Body:
Try using brackets in your condition to make it clearer.  Like this:

If Userrole = "Administrator" AndAlso (connectiontime = "Now" OrElse connectiontime <= TimeOfDay.ToString("HH:mm")) Then

in your code, it would also match if

connectiontime <= TimeOfDay.ToString("HH:mm")


问:
Connecting to Impala from R without Impala JDBC driver
For an undisclosed reason, my Impala does not have a JDBC driver installed. This is making the connection from R to Impala challenging.

I am able to connect (and query) to Impala shell via Putty. E.g.,

```<code>impala-shell --ssl -i some_name
</code>```

Using the Putty connection mechanism/credentials, can this be performed from RStudio and bring in the SELECT results into a dataframe?

答:
You can use the ODBC driver to connect to impalaDB</p>

```<code>library(ODBC)
drv <- odbc::odbc()
con <- DBI::dbConnect(drv = drv, driver = "Cloudera ODBC Driver for Impala",
    host = "your hostname", port = 21050, Schema = "your schema")
</code>```

Body:
For an undisclosed reason, my Impala does not have a JDBC driver installed. This is making the connection from R to Impala challenging.

I am able to connect (and query) to Impala shell via Putty. E.g.,

impala-shell --ssl -i some_name

Using the Putty connection mechanism/credentials, can this be performed from RStudio and bring in the SELECT results into a dataframe?

Body:
You can use the ODBC driver to connect to impalaDB

library(ODBC)
drv <- odbc::odbc()
con <- DBI::dbConnect(drv = drv, driver = "Cloudera ODBC Driver for Impala",
    host = "your hostname", port = 21050, Schema = "your schema")


问:
How to recognize unknown patterns in data frame by row?
I have a data frame where I have agricultural use codes (1-5) for 15 consecutive years. Each row is a polygon representing a field. Ultimately I need R to loop through the rows and recognize patterns of use and tell me their respective frequency. Unfortunately in my real data set I have over 1 mio. features and thus all possible patterns are not known.

```<code>a <- data.frame(replicate(15, sample(0:5,500,rep=TRUE)))
colnames(a) <- paste0("use",2005:2019)
id <- c(1:500)
a <- cbind(id,a)

id use2005 use2006 use2007 use2008 use2009 use2010 use2011 use2012 use2013 use2014 use2015 ...
1  1       1       1       1       1       2       2       1       4       4       4       ...
2  4       4       4       4       5       5       5       0       5       5       5       ...
3  1       4       3       2       3       2       4       5       1       1       1       ...
4  1       1       1       1       1       2       2       1       4       4       4       ...
5  4       2       2       2       2       5       3       3       3       3       3       ...
</code>```

So in this arbitrary example, the code should recognize that id 1 & 4 have the same pattern.

In the end I imagine the result to be some sort of frequency distribution to see if there are certain patterns in the agricultural use of my fields.

For example:

1 1 1 1 1 2 1 1 1 3 2 4 1 1 1

[50] - occurs 50 times

5 5 5 5 5 1 1 1 1 4 4 4 2 2 3

[35] - occurs 35 times

and so forth with all existing combinations...

Unfortunately I have no idea how to approach this. I have no experience with pattern recognition.

Thank you!

答:
Here's an example on how to approach this, using a small example dataset (i.e. the one you posted).</p>

```<code>library(tidyverse)

# example dataset
a = read.table(text = "
id use2005 use2006 use2007 use2008 use2009 use2010 use2011 use2012 use2013 use2014 use2015
1  1       1       1       1       1       2       2       1       4       4       4
2  4       4       4       4       5       5       5       0       5       5       5
3  1       4       3       2       3       2       4       5       1       1       1
4  1       1       1       1       1       2       2       1       4       4       4
5  4       2       2       2       2       5       3       3       3       3       3
", header=T)

a %>%
  group_nest(id) %>%                                           # for each row
  mutate(pattern = map(data, ~paste(.x, collapse = ","))) %>%  # create the pattern as a string
  unnest(pattern) %>%                                          # unnest pattern column
  count(pattern, sort = T)                                     # count patterns

# # A tibble: 4 x 2
#   pattern                   n
#   <chr>                 <int>
# 1 1,1,1,1,1,2,2,1,4,4,4     2
# 2 1,4,3,2,3,2,4,5,1,1,1     1
# 3 4,2,2,2,2,5,3,3,3,3,3     1
# 4 4,4,4,4,5,5,5,0,5,5,5     1
</code>```

Body:
I have a data frame where I have agricultural use codes (1-5) for 15 consecutive years. Each row is a polygon representing a field. Ultimately I need R to loop through the rows and recognize patterns of use and tell me their respective frequency. Unfortunately in my real data set I have over 1 mio. features and thus all possible patterns are not known.

a <- data.frame(replicate(15, sample(0:5,500,rep=TRUE)))
colnames(a) <- paste0("use",2005:2019)
id <- c(1:500)
a <- cbind(id,a)

id use2005 use2006 use2007 use2008 use2009 use2010 use2011 use2012 use2013 use2014 use2015 ...
1  1       1       1       1       1       2       2       1       4       4       4       ...
2  4       4       4       4       5       5       5       0       5       5       5       ...
3  1       4       3       2       3       2       4       5       1       1       1       ...
4  1       1       1       1       1       2       2       1       4       4       4       ...
5  4       2       2       2       2       5       3       3       3       3       3       ...

So in this arbitrary example, the code should recognize that id 1 & 4 have the same pattern.

In the end I imagine the result to be some sort of frequency distribution to see if there are certain patterns in the agricultural use of my fields.

For example:

1 1 1 1 1 2 1 1 1 3 2 4 1 1 1

[50] - occurs 50 times

5 5 5 5 5 1 1 1 1 4 4 4 2 2 3

[35] - occurs 35 times

and so forth with all existing combinations...

Unfortunately I have no idea how to approach this. I have no experience with pattern recognition.

Thank you!

Body:
Here's an example on how to approach this, using a small example dataset (i.e. the one you posted).

library(tidyverse)

# example dataset
a = read.table(text = "
id use2005 use2006 use2007 use2008 use2009 use2010 use2011 use2012 use2013 use2014 use2015
1  1       1       1       1       1       2       2       1       4       4       4
2  4       4       4       4       5       5       5       0       5       5       5
3  1       4       3       2       3       2       4       5       1       1       1
4  1       1       1       1       1       2       2       1       4       4       4
5  4       2       2       2       2       5       3       3       3       3       3
", header=T)

a %>%
  group_nest(id) %>%                                           # for each row
  mutate(pattern = map(data, ~paste(.x, collapse = ","))) %>%  # create the pattern as a string
  unnest(pattern) %>%                                          # unnest pattern column
  count(pattern, sort = T)                                     # count patterns

# # A tibble: 4 x 2
#   pattern                   n
#   <chr>                 <int>
# 1 1,1,1,1,1,2,2,1,4,4,4     2
# 2 1,4,3,2,3,2,4,5,1,1,1     1
# 3 4,2,2,2,2,5,3,3,3,3,3     1
# 4 4,4,4,4,5,5,5,0,5,5,5     1


问:
SQL - sum data for all time, 30 days and 90 days for multiple columns indiviually
BACKGROUND:

I have data that looks like this

```<code>date        src    subsrc   subsubsrc   param1  param2
2020-02-01  src1    ksjd    dfd8        47      31
2020-02-02  src1    djsk    zmnc        44      95
2020-02-03  src2    skdj    awes        92      100
2020-02-04  src2    mxsf    kajs        80      2
2020-02-05  src3    skdj    asio        46      53
2020-02-06  src3    dekl    jdqo        19      18
2020-02-07  src3    dskl    dqqq        69      18
2020-02-08  src4    sqip    riow        64      46
2020-02-09  src5    ss01    qwep        34      34
</code>```

I am trying to aggregate for all time, last 30 days and last 90 days (no rolling sum)

So my final data would look like this:

```<code>src     subsrc  subsubsrc   p1_all  p1_30   p1_90   p2_all  p2_30   p2_90
src1    ksjd    dfd8        7       1       7       98      7        98
src1    djsk    zmnc        0       0       0       0       0         0
src2    skdj    awes        12      12      12      4       4         4
src2    mxsf    kajs        6       6       6       31      31       31
src3    skdj    asio        0       0       0       0       0         0
src3    dekl    jdqo        20      20      20      17      17        17
src3    dskl    dqqq        3       3       3       4       4         4
src4    sqip    qwep        0       0       0       0       0         0
src5    ss01    qwes        15      15      15      2       2         2
</code>```

ABOUT DATA:

This is only dummy data and therefore incorrect.

There are tens of thousands of rows in my data.

There are a dozen of src columns that make up the key for the table.

There are a dozen of param columns that I have to sum for 30 and 90 and all time.

Also there are null values in param columns.

Also there are might be multiple rows for same day and src column.

New data is being added every day and the query is probably going to be run every day to get the latest 30, 90, all time data.

WHAT I HAVE TRIED:

This is what I have come up with:

```<code>SELECT src, subsubsrc, subsubsrc,
SUM(param1) as param1_all,
SUM(CASE WHEN DATE_DIFF(CURRENT_DATE,date,day) <= 30 THEN param1 END) as param1_30,
SUM(CASE WHEN DATE_DIFF(CURRENT_DATE,date,day) <= 90 THEN param1 END) as param1_90,
SUM(param2) as param2_all,
SUM(CASE WHEN DATE_DIFF(CURRENT_DATE,date,day) <= 30 THEN param2 END) as param2_30,
SUM(CASE WHEN DATE_DIFF(CURRENT_DATE,date,day) <= 90 THEN param2 END) as param2_90,
FROM `MY_TABLE`
GROUP BY src
ORDER BY src
</code>```

This actually works but I can anticipate how long this query is going to become for multiple sources and even more param columns.

I have been trying something called "Filtered aggregate functions (or manual pivot)" explained HERE. But I am unable to understand/implement it for my case.

Also  I have looked at dozens of answers and most of them are running sums for each day OR are complicated cases of this basic calculation. Maybe I am not searching it correctly.

As you can see I am newbie in SQL and would really appreciate any help.

答:
Your first approach isn't a bad one if you are able to build the query programmatically. One alternative might be to create side tables for the 30 and 90 day cases first so you can effectively select all columns from each. This could also be done in sub-queries but there are performance considerations.

Some untested pseudo code to hopefully clarify:

```<code>SELECT
 src,
 subsrc,
 subsubsrc,
 SUM(param1) as param1_all,
 -- other "all" sums here
 SUM(t30.param1) as param1_30,
 -- other "30" sums here
 SUM(t90.param1) as param1_90,
 -- other "90" sums here
FROM MY_TABLE
LEFT JOIN (
  SELECT *
  FROM MY_TABLE
  WHERE date >= DATE_SUB(CURRENT_DATE(), INTERVAL 30 DAY)
) as t30 on t30.src = MY_TABLE.src
LEFT JOIN (
  SELECT *
  FROM MY_TABLE
  WHERE date >= DATE_SUB(CURRENT_DATE(), INTERVAL 90 DAY)
) as t90 on t90.src = MY_TABLE.src
GROUP BY MY_TABLE.src
ORDER BY MY_TABLE.src
</code>```

Note the date conditions have been switched to not use a function on the date column but instead compare to a date value. Your original approach would defeat any index on date (which you will want to make this more efficient).

If you first put these sub-queries into side tables that have a key on src the joins will be more efficient too. You could even group/sum directly into those side tables first rather than creating larger copies of your data, and then join the aggregated data together.

Body:
BACKGROUND:

I have data that looks like this

date        src    subsrc   subsubsrc   param1  param2
2020-02-01  src1    ksjd    dfd8        47      31
2020-02-02  src1    djsk    zmnc        44      95
2020-02-03  src2    skdj    awes        92      100
2020-02-04  src2    mxsf    kajs        80      2
2020-02-05  src3    skdj    asio        46      53
2020-02-06  src3    dekl    jdqo        19      18
2020-02-07  src3    dskl    dqqq        69      18
2020-02-08  src4    sqip    riow        64      46
2020-02-09  src5    ss01    qwep        34      34

I am trying to aggregate for all time, last 30 days and last 90 days (no rolling sum)

So my final data would look like this:

src     subsrc  subsubsrc   p1_all  p1_30   p1_90   p2_all  p2_30   p2_90
src1    ksjd    dfd8        7       1       7       98      7        98
src1    djsk    zmnc        0       0       0       0       0         0
src2    skdj    awes        12      12      12      4       4         4
src2    mxsf    kajs        6       6       6       31      31       31
src3    skdj    asio        0       0       0       0       0         0
src3    dekl    jdqo        20      20      20      17      17        17
src3    dskl    dqqq        3       3       3       4       4         4
src4    sqip    qwep        0       0       0       0       0         0
src5    ss01    qwes        15      15      15      2       2         2

ABOUT DATA:

This is only dummy data and therefore incorrect.

There are tens of thousands of rows in my data.

There are a dozen of src columns that make up the key for the table.

There are a dozen of param columns that I have to sum for 30 and 90 and all time.

Also there are null values in param columns.

Also there are might be multiple rows for same day and src column.

New data is being added every day and the query is probably going to be run every day to get the latest 30, 90, all time data.

WHAT I HAVE TRIED:

This is what I have come up with:

SELECT src, subsubsrc, subsubsrc,
SUM(param1) as param1_all,
SUM(CASE WHEN DATE_DIFF(CURRENT_DATE,date,day) <= 30 THEN param1 END) as param1_30,
SUM(CASE WHEN DATE_DIFF(CURRENT_DATE,date,day) <= 90 THEN param1 END) as param1_90,
SUM(param2) as param2_all,
SUM(CASE WHEN DATE_DIFF(CURRENT_DATE,date,day) <= 30 THEN param2 END) as param2_30,
SUM(CASE WHEN DATE_DIFF(CURRENT_DATE,date,day) <= 90 THEN param2 END) as param2_90,
FROM `MY_TABLE`
GROUP BY src
ORDER BY src

This actually works but I can anticipate how long this query is going to become for multiple sources and even more param columns.

I have been trying something called "Filtered aggregate functions (or manual pivot)" explained HERE. But I am unable to understand/implement it for my case.

Also  I have looked at dozens of answers and most of them are running sums for each day OR are complicated cases of this basic calculation. Maybe I am not searching it correctly.

As you can see I am newbie in SQL and would really appreciate any help.

Body:
Your first approach isn't a bad one if you are able to build the query programmatically. One alternative might be to create side tables for the 30 and 90 day cases first so you can effectively select all columns from each. This could also be done in sub-queries but there are performance considerations.

Some untested pseudo code to hopefully clarify:

SELECT
 src,
 subsrc,
 subsubsrc,
 SUM(param1) as param1_all,
 -- other "all" sums here
 SUM(t30.param1) as param1_30,
 -- other "30" sums here
 SUM(t90.param1) as param1_90,
 -- other "90" sums here
FROM MY_TABLE
LEFT JOIN (
  SELECT *
  FROM MY_TABLE
  WHERE date >= DATE_SUB(CURRENT_DATE(), INTERVAL 30 DAY)
) as t30 on t30.src = MY_TABLE.src
LEFT JOIN (
  SELECT *
  FROM MY_TABLE
  WHERE date >= DATE_SUB(CURRENT_DATE(), INTERVAL 90 DAY)
) as t90 on t90.src = MY_TABLE.src
GROUP BY MY_TABLE.src
ORDER BY MY_TABLE.src

Note the date conditions have been switched to not use a function on the date column but instead compare to a date value. Your original approach would defeat any index on date (which you will want to make this more efficient).

If you first put these sub-queries into side tables that have a key on src the joins will be more efficient too. You could even group/sum directly into those side tables first rather than creating larger copies of your data, and then join the aggregated data together.


问:
How to save captured picture in kivy without timestamp as name
This is camera code

```<code>Camera Example
==============

This example demonstrates a simple use of the camera. It shows a window with
a buttoned labelled 'play' to turn the camera on and off. Note that
not finding a camera, perhaps because gstreamer is not installed, will
throw an exception during the kv language processing.

'''

# Uncomment these lines to see all the messages
# from kivy.logger import Logger
# import logging
# Logger.setLevel(logging.TRACE)

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
import time
Builder.load_string('''
<CameraClick>:
    orientation: 'vertical'
    Camera:
        id: camera
        resolution: (640, 480)
        play: False
    ToggleButton:
        text: 'Play'
        on_press: camera.play = not camera.play
        size_hint_y: None
        height: '48dp'
    Button:
        text: 'Capture'
        size_hint_y: None
        height: '48dp'
        on_press: root.capture()
''')

class CameraClick(BoxLayout):
    def capture(self):
        '''
        Function to capture the images and give them the names
        according to their captured time and date.
        '''
        camera = self.ids['camera']
        #timestr = time.strftime("%Y%m%d_%H%M%S")
        camera.export_to_png("IMG_{}.png".format(timestr))
        print("Captured")

class TestCamera(App):

    def build(self):
        return CameraClick()

TestCamera().run()
</code>```

I want to save captured image in my current directory with a name like img.png instead of saving image name with a timestamp.
This code saves image with name like IMG_20200216_162830 and I want it like IMG.png
Can anyone help me?
Thank you

答:
Remove the timestamp, that's all:</p>

```<code>camera.export_to_png("IMG.png")
</code>```

Body:
This is camera code

Camera Example
==============

This example demonstrates a simple use of the camera. It shows a window with
a buttoned labelled 'play' to turn the camera on and off. Note that
not finding a camera, perhaps because gstreamer is not installed, will
throw an exception during the kv language processing.

'''

# Uncomment these lines to see all the messages
# from kivy.logger import Logger
# import logging
# Logger.setLevel(logging.TRACE)

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
import time
Builder.load_string('''
<CameraClick>:
    orientation: 'vertical'
    Camera:
        id: camera
        resolution: (640, 480)
        play: False
    ToggleButton:
        text: 'Play'
        on_press: camera.play = not camera.play
        size_hint_y: None
        height: '48dp'
    Button:
        text: 'Capture'
        size_hint_y: None
        height: '48dp'
        on_press: root.capture()
''')

class CameraClick(BoxLayout):
    def capture(self):
        '''
        Function to capture the images and give them the names
        according to their captured time and date.
        '''
        camera = self.ids['camera']
        #timestr = time.strftime("%Y%m%d_%H%M%S")
        camera.export_to_png("IMG_{}.png".format(timestr))
        print("Captured")

class TestCamera(App):

    def build(self):
        return CameraClick()

TestCamera().run()

I want to save captured image in my current directory with a name like img.png instead of saving image name with a timestamp.
This code saves image with name like IMG_20200216_162830 and I want it like IMG.png
Can anyone help me?
Thank you

Body:
Remove the timestamp, that's all:

camera.export_to_png("IMG.png")


问:
How to include array content in HTML?
I have this code

```<code>var users = result.users; // array

$("#dialog:ui-dialog").dialog("destroy");

$("#dialog-confirm").dialog({
    resizable: false,
    height: 140,
    modal: true,
    open: function() {
    $(this).children('div.dialog-text').replaceWith("<b>New text goes here</b>");
    },

    buttons: {
    "Okay": function() {
        $(this).dialog("close");
    },
    Cancel: function() {
        is_okay = 0;
        $(this).dialog("close");
    }
    }
});
</code>```

where the array contain data in the form of

```<code>{"ss":"Sandra Schlichting","fn":"Full name"}
</code>```

What I am trying to accomplish is to get the content of the arrays in the form of (white space inserted for readability)

```<code><table>
  <tr>  <td>Initials</td>  <td>Full Name         </td>  </tr>
  <tr>  <td>ss      </td>  <td>Sandra Schlichting</td>  </tr>
  <tr>  <td>fn      </td>  <td>Full name         </td>  </tr>
</table>
</code>```

and have that replaced with New text goes here in

```<code>$(this).children('div.dialog-text').replaceWith("<b>New text goes here</b>");
</code>```

From what I can tell $.each() should be used for this.

But still I can't quite figure out how to get started.

Can anyone help me out?

答:
```<code>function makeTable(users) {
    var result = '<table><tr><td>Initials</td><td>Full Name</td></tr>\n';
    $.each(users, function(index, value) {
        result += '<tr><td>' + index + '</td><td>' + value + '</td></tr>\n';
    });
    result += '</table>';
    return (result);
}

alert(makeTable({"ss":"Sandra Schlichting","fn":"Full name"}));
</code>```

Working here

$.each documentation

Title: How to include array content in HTML?

Body:
I have this code

var users = result.users; // array

$("#dialog:ui-dialog").dialog("destroy");

$("#dialog-confirm").dialog({
    resizable: false,
    height: 140,
    modal: true,
    open: function() {
    $(this).children('div.dialog-text').replaceWith("New text goes here");
    },

    buttons: {
    "Okay": function() {
        $(this).dialog("close");
    },
    Cancel: function() {
        is_okay = 0;
        $(this).dialog("close");
    }
    }
});

where the array contain data in the form of

{"ss":"Sandra Schlichting","fn":"Full name"}

What I am trying to accomplish is to get the content of the arrays in the form of (white space inserted for readability)

  Initials	  Full Name

  ss      	  Sandra Schlichting

  fn      	  Full name

and have that replaced with New text goes here in

$(this).children('div.dialog-text').replaceWith("New text goes here");

From what I can tell $.each() should be used for this.

But still I can't quite figure out how to get started.

Can anyone help me out?

Body:
function makeTable(users) {
    var result = '<table><tr><td>Initials</td><td>Full Name</td></tr>\n';
    $.each(users, function(index, value) {
        result += '<tr><td>' + index + '</td><td>' + value + '</td></tr>\n';
    });
    result += '</table>';
    return (result);
}

alert(makeTable({"ss":"Sandra Schlichting","fn":"Full name"}));

Working here

$.each documentation


问:
How can i import JSON into Cloud Firestore
I am currently using Firebase Realtime database. I have imported JSONs into Realtime database but due to limitation of query i need to switch on Firebase Firestore.

I want to import JSONs into Cloud Firestore of Firebase.

答:
There is no automatic conversion from Firebase's Realtime Database to Cloud Firestore. While both are NoSQL databases and part of Firebase, their data models are different, and they are not compatible in any way.

You will have to figure out how you want to map your JSON data from Realtime Database, to the collection/document model of Cloud Firestore, and then write code against the APIs of the databases to port the data over.

Also see:

Migrate Firebase Realtime Database to Firestore

Converting Firebase Database to Cloud Firestore

Firebase Realtime Database to Cloud Firestore

Blog post: Migrating from Firebase Realtime Database To Firestore — pricing and limits

Blog post: Survival guide: how to migrate from the Firebase Realtime Database to Cloud Firestore