问:
ERROR: undefined reference to... what is wrong?
I getting a undefined reference error when I try compile the code. I only just be be to test the Grafo class fuctions

grafo.h:

#ifndef GRAFO_H
#define GRAFO_H

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <vector>

/*  Classe Grafo - Matriz de adjecencia  */
class Grafo
{
    public:
        //  Atributos
        int num_vertices;
        int *vertices;
        int **arestas;
        char tipo;

        //  assinaturas dos metodos
        Grafo(int nv,char t);
        void printGrafo();

};
#endif
```

<p>grafo.cpp</p>

<pre class="lang-cpp prettyprint-override"><code>#include "grafo.h"

Grafo::Grafo(int nv,char t);
Grafo::void printGrafo();

Grafo::Grafo(int nv,char t){
    num_vertices = nv;
    vertices = new int[num_vertices];
    tipo = t;

    //criar matriz
    arestas = new int *[num_vertices];
    for(int i = 0; i < num_vertices;i++){ arestas[i] = new int[num_vertices];}

    // inicializar valores da matriz
    for(int i = 0; i < num_vertices;i++){
        vertices[i] = 0;
        for(int j = 0; j < num_vertices;j++){
            arestas[i][j] = 0;
        }
    }

}

void Grafo::printGrafo(){
    std::cout << " | ";
    for(int i = 0; i < num_vertices;i++){
        std::cout << i << " ";
    }
    std::cout << std::endl;
        for(int i = -3; i < num_vertices;i++){
        std::cout << "_";
    }
    std::cout << std::endl;
    for(int i = 0; i < num_vertices;i++){
        std::cout << i << " | ";
        for(int j = 0; j < num_vertices;j++){
            std::cout << arestas[i][j] << " ";
        }
        std::cout << std::endl;
    }
}
</code>```

main.cpp

#include "grafo.h"

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <vector>

int main(){
  Grafo G = Grafo(5,'D');
  G.printGrafo();
}
```

when I try compile with command g++ main.cpp -o main.exe. I recive the following error msg:

/tmp/ccPxPLjS.o: In function main': main.cpp:(.text+0x29): undefined
  reference toGrafo::Grafo(int, char)' main.cpp:(.text+0x35):
  undefined reference to `Grafo::printGrafo()' collect2: error: ld
  returned 1 exit status

Someone may help-me with this job? >.<

答:
First of all remove first lines from Grafo.cpp file:

```<code>Grafo::Grafo(int nv,char t);
Grafo::void printGrafo();
</code>```

These are causing errors in compilation (GCC):

```<code>grafo.cpp:3:27: error: declaration of 'Grafo::Grafo(int, char)' outside of class is not definition [-fpermissive]
 Grafo::Grafo(int nv,char t);
                           ^
grafo.cpp:4:8: error: expected unqualified-id before 'void'
 Grafo::void printGrafo();
        ^~~~
</code>```

Then include all source files into compilation invocation:

```<code>g++ -o test test.cpp grafo.cpp
</code>```

This will cause sources to compile properly, if done like this:

```<code>g++ -o test test.cpp
</code>```

it will cause similar errors as described in your question:

```<code>ccVmPgnr.o:test.cpp:(.text+0x20): undefined reference to `Grafo::Grafo(int, char)'
ccVmPgnr.o:test.cpp:(.text+0x2c): undefined reference to `Grafo::printGrafo()'
</code>```

Body:
I getting a undefined reference error when I try compile the code. I only just be be to test the Grafo class fuctions

grafo.h:

#ifndef GRAFO_H
#define GRAFO_H

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <vector>

/*  Classe Grafo - Matriz de adjecencia  */
class Grafo
{
    public:
        //  Atributos
        int num_vertices;
        int *vertices;
        int **arestas;
        char tipo;

        //  assinaturas dos metodos
        Grafo(int nv,char t);
        void printGrafo();

};
#endif

grafo.cpp

#include "grafo.h"

Grafo::Grafo(int nv,char t);
Grafo::void printGrafo();

Grafo::Grafo(int nv,char t){
    num_vertices = nv;
    vertices = new int[num_vertices];
    tipo = t;

    //criar matriz
    arestas = new int *[num_vertices];
    for(int i = 0; i < num_vertices;i++){ arestas[i] = new int[num_vertices];}

    // inicializar valores da matriz
    for(int i = 0; i < num_vertices;i++){
        vertices[i] = 0;
        for(int j = 0; j < num_vertices;j++){
            arestas[i][j] = 0;
        }
    }

}

void Grafo::printGrafo(){
    std::cout << " | ";
    for(int i = 0; i < num_vertices;i++){
        std::cout << i << " ";
    }
    std::cout << std::endl;
        for(int i = -3; i < num_vertices;i++){
        std::cout << "_";
    }
    std::cout << std::endl;
    for(int i = 0; i < num_vertices;i++){
        std::cout << i << " | ";
        for(int j = 0; j < num_vertices;j++){
            std::cout << arestas[i][j] << " ";
        }
        std::cout << std::endl;
    }
}

main.cpp

#include "grafo.h"

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <vector>

int main(){
  Grafo G = Grafo(5,'D');
  G.printGrafo();
}

when I try compile with command g++ main.cpp -o main.exe. I recive the following error msg:

/tmp/ccPxPLjS.o: In function main': main.cpp:(.text+0x29): undefined
  reference toGrafo::Grafo(int, char)' main.cpp:(.text+0x35):
  undefined reference to `Grafo::printGrafo()' collect2: error: ld
  returned 1 exit status

Someone may help-me with this job? >.<

Body:
First of all remove first lines from Grafo.cpp file:

Grafo::Grafo(int nv,char t);
Grafo::void printGrafo();

These are causing errors in compilation (GCC):

grafo.cpp:3:27: error: declaration of 'Grafo::Grafo(int, char)' outside of class is not definition [-fpermissive]
 Grafo::Grafo(int nv,char t);
                           ^
grafo.cpp:4:8: error: expected unqualified-id before 'void'
 Grafo::void printGrafo();
        ^~~~

Then include all source files into compilation invocation:

g++ -o test test.cpp grafo.cpp

This will cause sources to compile properly, if done like this:

g++ -o test test.cpp

it will cause similar errors as described in your question:

ccVmPgnr.o:test.cpp:(.text+0x20): undefined reference to `Grafo::Grafo(int, char)'
ccVmPgnr.o:test.cpp:(.text+0x2c): undefined reference to `Grafo::printGrafo()'


来源: stackexchange

问:
How to dynamically match rows from two pandas dataframes
I have a large dataframe of urls and a smaller 2nd dataframe that contains columns of strings which I want to use to merge the two dataframes together. Data from the 2nd df will be used to populate the larger 1st df.

The matching strings can contain * wildcards (and more then one) but the order of the grouping still matters; so "path/*path2" would match with "exsample.com/eg_path/extrapath2.html but not exsample.com/eg_path2/path/test.html. How can I use the strings in the 2nd dataframe to merge the two dataframes together. There can be more then one matching string in the 2nd dataframe.

```<code>import pandas as pd

urls = {'url':['https://stackoverflow.com/questions/56318782/','https://www.google.com/','https://en.wikipedia.org/wiki/Python_(programming_language)','https://stackoverflow.com/questions/'],
        'hits':[1000,500,300,7]}
metadata = {'group':['group1','group2'],
            'matching_string_1':['google','wikipedia*Python_'],
            'matching_string_2':['stackoverflow*questions*56318782','']}
result = {'url':['https://stackoverflow.com/questions/56318782/','https://www.google.com/','https://en.wikipedia.org/wiki/Python_(programming_language)','https://stackoverflow.com/questions/'],
        'hits':[1000,500,300,7],
        'group':['group2','group1','group1','']}

df1 = pd.DataFrame(urls)
df2 = pd.DataFrame(metadata)

what_I_am_after = pd.DataFrame(result)
</code>```

答:
Not very robust but gives the correct answer for my example.</p>

```<code>import pandas as pd

urls = {'url':['https://stackoverflow.com/questions/56318782/','https://www.google.com/','https://en.wikipedia.org/wiki/Python_(programming_language)','https://stackoverflow.com/questions/'],
        'hits':[1000,500,300,7]}
metadata = {'group':['group1','group2'],
            'matching_string_1':['google','wikipedia*Python_'],
            'matching_string_2':['stackoverflow*questions*56318782','']}
result = {'url':['https://stackoverflow.com/questions/56318782/','https://www.google.com/','https://en.wikipedia.org/wiki/Python_(programming_language)','https://stackoverflow.com/questions/'],
        'hits':[1000,500,300,7],
        'group':['group2','group1','group1','']}

df1 = pd.DataFrame(urls)
df2 = pd.DataFrame(metadata)
results = pd.DataFrame(columns=['url','hits','group'])

for index,row in df2.iterrows():
    for x in row[1:]:
        group = x.split('*')
        rx = "".join([str(x)+".*"  if len(x) > 0 else '' for x in group])
        if rx == "":
            continue
        filter = df1['url'].str.contains(rx,na=False, regex=True)
        if filter.any():
            temp = df1[filter]
            temp['group'] = row[0]
            results = results.append(temp)

d3 = df1.merge(results,how='outer',on=['url','hits'])
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a large dataframe of urls and a smaller 2nd dataframe that contains columns of strings which I want to use to merge the two dataframes together. Data from the 2nd df will be used to populate the larger 1st df.

The matching strings can contain * wildcards (and more then one) but the order of the grouping still matters; so "path/*path2" would match with "exsample.com/eg_path/extrapath2.html but not exsample.com/eg_path2/path/test.html. How can I use the strings in the 2nd dataframe to merge the two dataframes together. There can be more then one matching string in the 2nd dataframe.

import pandas as pd

urls = {'url':['https://stackoverflow.com/questions/56318782/','https://www.google.com/','https://en.wikipedia.org/wiki/Python_(programming_language)','https://stackoverflow.com/questions/'],
        'hits':[1000,500,300,7]}
metadata = {'group':['group1','group2'],
            'matching_string_1':['google','wikipedia*Python_'],
            'matching_string_2':['stackoverflow*questions*56318782','']}
result = {'url':['https://stackoverflow.com/questions/56318782/','https://www.google.com/','https://en.wikipedia.org/wiki/Python_(programming_language)','https://stackoverflow.com/questions/'],
        'hits':[1000,500,300,7],
        'group':['group2','group1','group1','']}

df1 = pd.DataFrame(urls)
df2 = pd.DataFrame(metadata)

what_I_am_after = pd.DataFrame(result)

Body:
Not very robust but gives the correct answer for my example.

import pandas as pd

urls = {'url':['https://stackoverflow.com/questions/56318782/','https://www.google.com/','https://en.wikipedia.org/wiki/Python_(programming_language)','https://stackoverflow.com/questions/'],
        'hits':[1000,500,300,7]}
metadata = {'group':['group1','group2'],
            'matching_string_1':['google','wikipedia*Python_'],
            'matching_string_2':['stackoverflow*questions*56318782','']}
result = {'url':['https://stackoverflow.com/questions/56318782/','https://www.google.com/','https://en.wikipedia.org/wiki/Python_(programming_language)','https://stackoverflow.com/questions/'],
        'hits':[1000,500,300,7],
        'group':['group2','group1','group1','']}

df1 = pd.DataFrame(urls)
df2 = pd.DataFrame(metadata)
results = pd.DataFrame(columns=['url','hits','group'])

for index,row in df2.iterrows():
    for x in row[1:]:
        group = x.split('*')
        rx = "".join([str(x)+".*"  if len(x) > 0 else '' for x in group])
        if rx == "":
            continue
        filter = df1['url'].str.contains(rx,na=False, regex=True)
        if filter.any():
            temp = df1[filter]
            temp['group'] = row[0]
            results = results.append(temp)

d3 = df1.merge(results,how='outer',on=['url','hits'])


问:
How to return a nested list of frequency from a Python list?
From a list of cards - return a nested list of the cards with the same numbers and then the rest in a separate list.

```<code>EXAMPLE: ['6C', '7C', '7D', '8S', '6D']
</code>```

returning [['7C', '7D'], ['6C','6D'], ['8S']]

I have attempted using a while loop, but cant figure it out.

Thank you!

答:
One possible solution is to sort the list, then group the list using itertools.groupby, both by using the integer part of the string, and then grouping items with common integer elements together

```<code>from itertools import groupby
li = ['6C', '7C', '7D', '8S', '6D']

#Sort the list based on the integer part of the string
li = sorted(li, key=lambda x:int(x[0]))

#Group the list based on the integer part of the string
res = [list(group) for _, group in groupby(li, key=lambda x:int(x[0]))]
print(res)
</code>```

The output will be

```<code>[['6C', '6D'], ['7C', '7D'], ['8S']]
</code>```

Body:
From a list of cards - return a nested list of the cards with the same numbers and then the rest in a separate list.

EXAMPLE: ['6C', '7C', '7D', '8S', '6D']

returning [['7C', '7D'], ['6C','6D'], ['8S']]

I have attempted using a while loop, but cant figure it out.

Thank you!

Body:
One possible solution is to sort the list, then group the list using itertools.groupby, both by using the integer part of the string, and then grouping items with common integer elements together

from itertools import groupby
li = ['6C', '7C', '7D', '8S', '6D']

#Sort the list based on the integer part of the string
li = sorted(li, key=lambda x:int(x[0]))

#Group the list based on the integer part of the string
res = [list(group) for _, group in groupby(li, key=lambda x:int(x[0]))]
print(res)

The output will be

[['6C', '6D'], ['7C', '7D'], ['8S']]


问:
DB2 stored procedure to load data in different database
I am creating a stored procedure to load data from source database: MYDB -> target database: NEWDB.

I will load the data in tables SCHEMA1.EMPLOYEE1, SCHEMA1.EMPLOYEE2, ...

Edit 1:

```<code>CREATE or replace PROCEDURE SCHEMA1.PROC_LOAD ()
    SPECIFIC PROC_LOAD
    LANGUAGE SQL
BEGIN
    DECLARE v_table varchar(100);--
    DECLARE truncate_stmt varchar(1000);--
    DECLARE load_stmt varchar(1000);--

    for v_table as select rtrim(tabname) as tabname from syscat.tables where tabschema='SCHEMA1' and tabname like '%EMPLOYEE%'
    do
        -- Truncate the table first
        set truncate_stmt = 'ALTER TABLE SCHEMA1.'||v_table.tabname||' ACTIVATE NOT LOGGED INITIALLY WITH EMPTY TABLE';--
        prepare s1 from truncate_stmt;--
        execute s1;--

        -- Load the data
        set load_stmt = 'LOAD FROM (DATABASE MYDB SELECT * FROM SCHEMA1.'||v_table.tabname||'_HIST) OF CURSOR MESSAGES ON SERVER INSERT INTO SCHEMA1.'||v_table.tabname||' NONRECOVERABLE';--
        CALL SYSPROC.ADMIN_CMD (load_stmt);--
    end for;--
END;
</code>```

Above is the code of my db2 stored procedure, I have created it successfully, but when I call it, it returns the error:

```<code>ERROR [24501] [IBM][DB2/NT64] SQL0501N  The cursor specified in a FETCH statement or CLOSE statement is not open or a cursor variable in a cursor scalar function reference is not open.
</code>```

In the target database, I select the data from SCHEMA1.EMPLOYEE1 and it shows that the data is loaded successfully, but for EMPLOYEE2,3,..., the old data is still there, it seems that only the first table in the loop is loaded successfully.

Any idea? Also my db2 platform is db2 11.1 on luw. Thanks in advance.

答: LOAD commits implicitly, so you have to use WITH HOLD clause of the FOR statement to not close the cursor upon such a commit.

Body:
I am creating a stored procedure to load data from source database: MYDB -> target database: NEWDB.

I will load the data in tables SCHEMA1.EMPLOYEE1, SCHEMA1.EMPLOYEE2, ...

Edit 1:

CREATE or replace PROCEDURE SCHEMA1.PROC_LOAD ()
    SPECIFIC PROC_LOAD
    LANGUAGE SQL
BEGIN
    DECLARE v_table varchar(100);--
    DECLARE truncate_stmt varchar(1000);--
    DECLARE load_stmt varchar(1000);--

    for v_table as select rtrim(tabname) as tabname from syscat.tables where tabschema='SCHEMA1' and tabname like '%EMPLOYEE%'
    do
        -- Truncate the table first
        set truncate_stmt = 'ALTER TABLE SCHEMA1.'||v_table.tabname||' ACTIVATE NOT LOGGED INITIALLY WITH EMPTY TABLE';--
        prepare s1 from truncate_stmt;--
        execute s1;--

        -- Load the data
        set load_stmt = 'LOAD FROM (DATABASE MYDB SELECT * FROM SCHEMA1.'||v_table.tabname||'_HIST) OF CURSOR MESSAGES ON SERVER INSERT INTO SCHEMA1.'||v_table.tabname||' NONRECOVERABLE';--
        CALL SYSPROC.ADMIN_CMD (load_stmt);--
    end for;--
END;

Above is the code of my db2 stored procedure, I have created it successfully, but when I call it, it returns the error:

ERROR [24501] [IBM][DB2/NT64] SQL0501N  The cursor specified in a FETCH statement or CLOSE statement is not open or a cursor variable in a cursor scalar function reference is not open.

In the target database, I select the data from SCHEMA1.EMPLOYEE1 and it shows that the data is loaded successfully, but for EMPLOYEE2,3,..., the old data is still there, it seems that only the first table in the loop is loaded successfully.

Any idea? Also my db2 platform is db2 11.1 on luw. Thanks in advance.


问:
how can I test my new image in model that training with CIFAR-10?(with tensorflow)
I write code to identify objects. I want to training the model with CIFAR10 and after this I want to be able to enter new image that I photographed, and I want Let a model tell me which object is in the picture.
How can I do this?

this is my firsr code:

```<code>import keras
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from keras.datasets import cifar10

(x_train, y_train), (x_test, y_test) = cifar10.load_data()
#matplotlib inline
fig = plt.figure(figsize=(20,5))
for i in range(36):
  ax = fig.add_subplot(3, 12, i + 1, xticks=[], yticks=[])
  ax.imshow(np.squeeze(x_train[i]))
# rescale [0,255] --> [0,1]
x_train = x_train.astype('float32')/255
from keras.utils import np_utils
# one-hot encode the labels
num_classes = len(np.unique(y_train))
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
# break training set into training and validation sets
(x_train, x_valid) = x_train[5000:], x_train[:5000]
(y_train, y_valid) = y_train[5000:], y_train[:5000]
# print shape of training set
print('x_train shape:', x_train.shape)
# printing number of training, validation, and test images
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
print(x_valid.shape[0], 'validation samples')
x_test = x_test.astype('float32')/255
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
model = Sequential()
model.add(Conv2D(filters=16, kernel_size=2, padding='same',
          activation='relu',  input_shape=(32, 32, 3)))
model.add(MaxPooling2D(pool_size=2))
model.add(Conv2D(filters=32, kernel_size=2, padding='same',
                    activation='relu'))
model.add(MaxPooling2D(pool_size=2))
model.add(Conv2D(filters=64, kernel_size=2, padding='same',
           activation='relu'))
model.add(MaxPooling2D(pool_size=2))
model.add(Conv2D(filters=32, kernel_size=2, padding='same',
           activation='relu'))
model.add(MaxPooling2D(pool_size=2))
model.add(Dropout(0.3))
model.add(Flatten())
model.add(Dense(500, activation='relu'))
model.add(Dropout(0.4))
model.add(Dense(10, activation='softmax'))
model.summary()
# compile the model
model.compile(loss='categorical_crossentropy', optimizer='rmsprop',
                metrics=['accuracy'])
from keras.callbacks import ModelCheckpoint
# train the model
checkpointer = ModelCheckpoint(filepath='model.weights.best.hdf5',
                                  verbose=1, save_best_only=True)
hist = model.fit(x_train, y_train, batch_size=32, epochs=10,
                 validation_data=(x_valid, y_valid), callbacks=
                 [checkpointer],   verbose=2, shuffle=True)

score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])
</code>```

Thank you!!

答:
You can save your model and use it. You can save it as .h5 or json or yml.

```<code>from keras.models import load_model

model.save('my_model.h5')  # creates a HDF5 file 'my_model.h5'

# load new model
model2 = load_model('my_model.h5')
</code>```

Then load your image as a numpy array and re-scale it as you did x_train = x_train.astype('float32')/255, then feed it as

```<code>from keras.preprocessing.image import img_to_array, load_img

img = load_img(image_path, color_mode='grayscale')
x = img_to_array(img)
x = x.reshape((1,) + x.shape)
model.predict(x)
#or
model.predict_classes(x)
</code>```

OwnerDisplayName: Orr

Body:
I write code to identify objects. I want to training the model with CIFAR10 and after this I want to be able to enter new image that I photographed, and I want Let a model tell me which object is in the picture.
How can I do this?

this is my firsr code:

import keras
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from keras.datasets import cifar10

(x_train, y_train), (x_test, y_test) = cifar10.load_data()
#matplotlib inline
fig = plt.figure(figsize=(20,5))
for i in range(36):
  ax = fig.add_subplot(3, 12, i + 1, xticks=[], yticks=[])
  ax.imshow(np.squeeze(x_train[i]))
# rescale [0,255] --> [0,1]
x_train = x_train.astype('float32')/255
from keras.utils import np_utils
# one-hot encode the labels
num_classes = len(np.unique(y_train))
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)
# break training set into training and validation sets
(x_train, x_valid) = x_train[5000:], x_train[:5000]
(y_train, y_valid) = y_train[5000:], y_train[:5000]
# print shape of training set
print('x_train shape:', x_train.shape)
# printing number of training, validation, and test images
print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')
print(x_valid.shape[0], 'validation samples')
x_test = x_test.astype('float32')/255
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout
model = Sequential()
model.add(Conv2D(filters=16, kernel_size=2, padding='same',
          activation='relu',  input_shape=(32, 32, 3)))
model.add(MaxPooling2D(pool_size=2))
model.add(Conv2D(filters=32, kernel_size=2, padding='same',
                    activation='relu'))
model.add(MaxPooling2D(pool_size=2))
model.add(Conv2D(filters=64, kernel_size=2, padding='same',
           activation='relu'))
model.add(MaxPooling2D(pool_size=2))
model.add(Conv2D(filters=32, kernel_size=2, padding='same',
           activation='relu'))
model.add(MaxPooling2D(pool_size=2))
model.add(Dropout(0.3))
model.add(Flatten())
model.add(Dense(500, activation='relu'))
model.add(Dropout(0.4))
model.add(Dense(10, activation='softmax'))
model.summary()
# compile the model
model.compile(loss='categorical_crossentropy', optimizer='rmsprop',
                metrics=['accuracy'])
from keras.callbacks import ModelCheckpoint
# train the model
checkpointer = ModelCheckpoint(filepath='model.weights.best.hdf5',
                                  verbose=1, save_best_only=True)
hist = model.fit(x_train, y_train, batch_size=32, epochs=10,
                 validation_data=(x_valid, y_valid), callbacks=
                 [checkpointer],   verbose=2, shuffle=True)

score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])

Thank you!!

Body:
You can save your model and use it. You can save it as .h5 or json or yml.

from keras.models import load_model

model.save('my_model.h5')  # creates a HDF5 file 'my_model.h5'

# load new model
model2 = load_model('my_model.h5')

Then load your image as a numpy array and re-scale it as you did x_train = x_train.astype('float32')/255, then feed it as

from keras.preprocessing.image import img_to_array, load_img

img = load_img(image_path, color_mode='grayscale')
x = img_to_array(img)
x = x.reshape((1,) + x.shape)
model.predict(x)
#or
model.predict_classes(x)


问:
Making a folder directory from a text file using a python script
I have a text file with hundreds of lines, each line contains a number to represent the level the folder/file should be on and a folder/file name. Because the  hierarchy is too large I want to make a script to automate making this directory/sub directory.

Example text file

```<code> .0.  Folder Name a
  .1. Folder Name b
   .2. Folder Name c
   .2. Folder Name c2
  .1. Folder Name d
   .2. Folder Name e
   .2. Folder Name e2
    .3. Folder Name f
</code>```

I assume I need to read line by line and use os.mkdir, but I don't know how to step down a directory level.

```<code>#path of file
import os

with open('Tree.txt', 'r') as t:
 for line in t:
  readline(.{Level}. {FolderName})
    if Level == '0'
     os.mkdir(FolderName)
    else if Level == '1'
     # go down and os.mkdir(FolderName)
</code>```

答: To step down and step up a directory you can use os.chdir('example filepath') and os.chdir('..')

Body:
I have a text file with hundreds of lines, each line contains a number to represent the level the folder/file should be on and a folder/file name. Because the  hierarchy is too large I want to make a script to automate making this directory/sub directory.

Example text file

 .0.  Folder Name a
  .1. Folder Name b
   .2. Folder Name c
   .2. Folder Name c2
  .1. Folder Name d
   .2. Folder Name e
   .2. Folder Name e2
    .3. Folder Name f

I assume I need to read line by line and use os.mkdir, but I don't know how to step down a directory level.

#path of file
import os

with open('Tree.txt', 'r') as t:
 for line in t:
  readline(.{Level}. {FolderName})
    if Level == '0'
     os.mkdir(FolderName)
    else if Level == '1'
     # go down and os.mkdir(FolderName)


问:
Deploying Rails App on Digital Ocean and when running cap production deploy:initial I get back ---> 01 ArgumentError: Missing `secret_key_base`
Deploying Rails App on Digital Ocean and when running cap production deploy:initial I get back

01 ArgumentError: Missing secret_key_base for 'production' environment, set this string with rails credentials:edit

I thought that I've set it already:

```<code>development:
  secret_key_base: <%= ENV["132efa1cdc31b591fa97e11450182f7ece21c9409451ea74e65974a9fad9e1d27846895afe0ffc4ee09d0d87912532a8d64e9a465e3cdf4455dee4ff3830"] %>
test:
  secret_key_base: <%= ENV["1113232efa1cdc31b591fa97e11450182f7ece21c9409451ea74e65974a9fad9e1d27846895afe0ffc4ee09d0d87912532a8d64e9a465e3cdf4455dee4ff3830"] %>
production:
  secret_key_base: <%= ENV["11173232efa1cdc31b591fa97e11450182f7ece21c9409451ea74e65974a9fad9e1d27846895afe0ffc4ee09d0d87912532a8d64e9a465e3cdf4455dee4ff3830"] %>
</code>```

I am using the digital ocean rails one click with ubuntu sever

答:
Usually your secret_key_base would be stored in an environment variable, however the secret key base isn't supposed to be the name of the env key.
In your case, that's what I seem to observe.

```<code>development:
  secret_key_base: <%= ENV["132efa1cdc31b591fa97e11450182f7ece21c9409451ea74e65974a9fad9e1d27846895afe0ffc4ee09d0d87912532a8d64e9a465e3cdf4455dee4ff3830"] %>

test:
  secret_key_base: <%= ENV["1113232efa1cdc31b591fa97e11450182f7ece21c9409451ea74e65974a9fad9e1d27846895afe0ffc4ee09d0d87912532a8d64e9a465e3cdf4455dee4ff3830"] %>

production:
  secret_key_base: <%= ENV["11173232efa1cdc31b591fa97e11450182f7ece21c9409451ea74e65974a9fad9e1d27846895afe0ffc4ee09d0d87912532a8d64e9a465e3cdf4455dee4ff3830"] %>
</code>```

So, here's what I'd propose, instead of setting your secret as the key of your env variable, you'd probably just want to do something like:

```<code>secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>
</code>```

Then, you'd want to set your environment variable in your digital ocean instance.

I've not used Capistrano before, but take a look at default_env in https://capistranorb.com/documentation/getting-started/configuration/
and Capistrano and environment variables

In your case, I figured you'd probably want to do something along the lines of

```<code>set :default_env, {
  'SECRET_KEY_BASE' => '11173232efa1cdc31b591fa97e11450182f7ece21c9409451ea74e65974a9fad9e1d27846895afe0ffc4ee09d0d87912532a8d64e9a465e3cdf4455dee4ff3830'
}
</code>```

Let me know if that helps

Body:
Deploying Rails App on Digital Ocean and when running cap production deploy:initial I get back

01 ArgumentError: Missing secret_key_base for 'production' environment, set this string with rails credentials:edit

I thought that I've set it already:

development:
  secret_key_base: <%= ENV["132efa1cdc31b591fa97e11450182f7ece21c9409451ea74e65974a9fad9e1d27846895afe0ffc4ee09d0d87912532a8d64e9a465e3cdf4455dee4ff3830"] %>
test:
  secret_key_base: <%= ENV["1113232efa1cdc31b591fa97e11450182f7ece21c9409451ea74e65974a9fad9e1d27846895afe0ffc4ee09d0d87912532a8d64e9a465e3cdf4455dee4ff3830"] %>
production:
  secret_key_base: <%= ENV["11173232efa1cdc31b591fa97e11450182f7ece21c9409451ea74e65974a9fad9e1d27846895afe0ffc4ee09d0d87912532a8d64e9a465e3cdf4455dee4ff3830"] %>

I am using the digital ocean rails one click with ubuntu sever

Body:
Usually your secret_key_base would be stored in an environment variable, however the secret key base isn't supposed to be the name of the env key.
In your case, that's what I seem to observe.

development:
  secret_key_base: <%= ENV["132efa1cdc31b591fa97e11450182f7ece21c9409451ea74e65974a9fad9e1d27846895afe0ffc4ee09d0d87912532a8d64e9a465e3cdf4455dee4ff3830"] %>

test:
  secret_key_base: <%= ENV["1113232efa1cdc31b591fa97e11450182f7ece21c9409451ea74e65974a9fad9e1d27846895afe0ffc4ee09d0d87912532a8d64e9a465e3cdf4455dee4ff3830"] %>

production:
  secret_key_base: <%= ENV["11173232efa1cdc31b591fa97e11450182f7ece21c9409451ea74e65974a9fad9e1d27846895afe0ffc4ee09d0d87912532a8d64e9a465e3cdf4455dee4ff3830"] %>

So, here's what I'd propose, instead of setting your secret as the key of your env variable, you'd probably just want to do something like:

secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>

Then, you'd want to set your environment variable in your digital ocean instance.

I've not used Capistrano before, but take a look at default_env in https://capistranorb.com/documentation/getting-started/configuration/
and Capistrano and environment variables

In your case, I figured you'd probably want to do something along the lines of

set :default_env, {
  'SECRET_KEY_BASE' => '11173232efa1cdc31b591fa97e11450182f7ece21c9409451ea74e65974a9fad9e1d27846895afe0ffc4ee09d0d87912532a8d64e9a465e3cdf4455dee4ff3830'
}

Let me know if that helps


问:
Blocking locks created due to inactive session in last 2 months
How to find the details of blocking locks due to inactive session for last 2 months ? Please help with a PL -sql code</p>

答:
You can track the blocking session with such a query below

```<code>select ora_database_name dbname,
       v.inst_id,
       v.sid,
       v.serial#,
       v.status,
       v.username,
       v.blocking_session_status,
       v.final_blocking_session,
       v.blocking_session,
       v.blocking_instance,
       v.logon_time,
       floor(v.last_call_et / 60) "Duration (Min.)",
       nvl(v.module, v.program) Module_Info,
       nvl(v.client_info, v.osuser) Client_Info,
       v.machine,
       v.action
  from gv$session v --> gv$session is used for RAC systems
 where (v.username not like 'SYS%' and v.username != 'DBSNMP')
   and v.status = 'ACTIVE'
   and v.blocking_session is not null
 --and sid = &sid
 --and username = upper('&schema_name')
 --and v.osuser like '%'||'&os_user'||'%'
 --and lower(nvl(v.client_info,v.osuser)) like lower('%'||'&cli_info'||'%')
 --and lower(module) like lower('%'||'&modul_name'||'%')
 --and v.inst_id = '&inst_id'
 order by "Duration (Min.)", v.username, v.logon_time desc
 -- ordering prominently by being hanged duration
</code>```

You can make active the commented out options whatever you need.

Body:
You can track the blocking session with such a query below

select ora_database_name dbname,
       v.inst_id,
       v.sid,
       v.serial#,
       v.status,
       v.username,
       v.blocking_session_status,
       v.final_blocking_session,
       v.blocking_session,
       v.blocking_instance,
       v.logon_time,
       floor(v.last_call_et / 60) "Duration (Min.)",
       nvl(v.module, v.program) Module_Info,
       nvl(v.client_info, v.osuser) Client_Info,
       v.machine,
       v.action
  from gv$session v --> gv$session is used for RAC systems
 where (v.username not like 'SYS%' and v.username != 'DBSNMP')
   and v.status = 'ACTIVE'
   and v.blocking_session is not null
 --and sid = &sid
 --and username = upper('&schema_name')
 --and v.osuser like '%'||'&os_user'||'%'
 --and lower(nvl(v.client_info,v.osuser)) like lower('%'||'&cli_info'||'%')
 --and lower(module) like lower('%'||'&modul_name'||'%')
 --and v.inst_id = '&inst_id'
 order by "Duration (Min.)", v.username, v.logon_time desc
 -- ordering prominently by being hanged duration

You can make active the commented out options whatever you need.


问:
absolute positioned child div width, getting out of relative positioned container
I know it's very common question but could find the solution!
A div which has position: relative and a div inside it has position: absolute and width: 100% just overflowing it's parent. I don't know what's I'm missing.

what I have:

```<code>.parent-div {
  position: relative;
  overflow: hidden;
}

.child-div {
  position: absolute;
  width: 100%
  max-width: 100%;
  box-sizing: border-box;
}
</code>```

Note: here parent div is bootstrap list-group-item element

Any help would be appreciable. Thanks!

UPDATE:

Issue has been resolved! It's because of that bootstrap group. So, I've took another wrapper and let it's position relative and it's now working perfectly!

答: As far as I can see, the width on your parent div is missing, so the 100% width on the child div gets his own life.</p>

Body:
I know it's very common question but could find the solution!
A div which has position: relative and a div inside it has position: absolute and width: 100% just overflowing it's parent. I don't know what's I'm missing.

what I have:

.parent-div {
  position: relative;
  overflow: hidden;
}

.child-div {
  position: absolute;
  width: 100%
  max-width: 100%;
  box-sizing: border-box;
}

Note: here parent div is bootstrap list-group-item element

Any help would be appreciable. Thanks!

UPDATE:

Issue has been resolved! It's because of that bootstrap group. So, I've took another wrapper and let it's position relative and it's now working perfectly!


问:
Getting Error "Exception in thread "main" java.lang.ExceptionInInitializerError"
I am trying to initialize HashMap with Enum Month. However, getting an error like: "Exception in thread "main" java.lang.ExceptionInInitializerError". Please let me know why I am getting this error. I am getting this in static main class method and for line ChatGroups.initializeMap();

```<code>package static_initialization;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

public class ChatGroups {
    public static final Map<String, Month> months = new HashMap<String, Month>() {{
        months.put("Jan", Month.January);
        months.put("Feb", Month.February);
        months.put("Mar", Month.March);
        months.put("Apr", Month.April);
        months.put("Jun", Month.June);
        months.put("Jul", Month.July);
        months.put("Aug", Month.August);
        months.put("Sep", Month.September);
        months.put("Oct", Month.October);
        months.put("Nov", Month.November);
        months.put("Dec", Month.December);
    }};

    public static void initializeMap() {
        System.out.println();
    }
}

package static_initialization;

public enum Month {
    January(0),
    February(1),
    March(2),
    April(3),
    May(4),
    June(5),
    July(6),
    August(7),
    September(8),
    October(9),
    November(10),
    December(11);

    private int month;

    Month(int i) {
        month = i;
    }
}

package static_initialization;

public class Main {
    public static void main(String[] args) {
        initializeMaps();
    }
    public static void initializeMaps() {

        try {
            ChatGroups.initializeMap();
        } catch (Exception ex) {
            System.out.println("Neelabh exception = " + ex);
        }
    }
}
</code>```

Please find the stack trace

```<code>Exception in thread "main" java.lang.ExceptionInInitializerError
    at static_initialization.Main.initializeMaps(Main.java:10)
    at static_initialization.Main.main(Main.java:5)
Caused by: java.lang.NullPointerException
    at static_initialization.ChatGroups$1.<init>(ChatGroups.java:9)
    at static_initialization.ChatGroups.<clinit>(ChatGroups.java:8)
</code>```

答:
It should be:

```<code>public static final Map<String, Month> months = new HashMap<String, Month>() {{
    put("Jan", Month.January);
    put("Feb", Month.February);
    put("Mar", Month.March);
    put("Apr", Month.April);
    put("Jun", Month.June);
    put("Jul", Month.July);
    put("Aug", Month.August);
    put("Sep", Month.September);
    put("Oct", Month.October);
    put("Nov", Month.November);
    put("Dec", Month.December);
}};
</code>```

months.put() leads to NullPointerException, since the static variable months is still null when the put statements are executed.

As an alternative, avoid creating an anonymous class instance, and instead write:

```<code>public static final Map<String, Month> months = new HashMap<String, Month>();
static {
    months.put("Jan", Month.January);
    months.put("Feb", Month.February);
    months.put("Mar", Month.March);
    months.put("Apr", Month.April);
    months.put("Jun", Month.June);
    months.put("Jul", Month.July);
    months.put("Aug", Month.August);
    months.put("Sep", Month.September);
    months.put("Oct", Month.October);
    months.put("Nov", Month.November);
    months.put("Dec", Month.December);
}
</code>```

Body:
I am trying to initialize HashMap with Enum Month. However, getting an error like: "Exception in thread "main" java.lang.ExceptionInInitializerError". Please let me know why I am getting this error. I am getting this in static main class method and for line ChatGroups.initializeMap();

package static_initialization;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

public class ChatGroups {
    public static final Map<String, Month> months = new HashMap<String, Month>() {{
        months.put("Jan", Month.January);
        months.put("Feb", Month.February);
        months.put("Mar", Month.March);
        months.put("Apr", Month.April);
        months.put("Jun", Month.June);
        months.put("Jul", Month.July);
        months.put("Aug", Month.August);
        months.put("Sep", Month.September);
        months.put("Oct", Month.October);
        months.put("Nov", Month.November);
        months.put("Dec", Month.December);
    }};

    public static void initializeMap() {
        System.out.println();
    }
}

package static_initialization;

public enum Month {
    January(0),
    February(1),
    March(2),
    April(3),
    May(4),
    June(5),
    July(6),
    August(7),
    September(8),
    October(9),
    November(10),
    December(11);

    private int month;

    Month(int i) {
        month = i;
    }
}

package static_initialization;

public class Main {
    public static void main(String[] args) {
        initializeMaps();
    }
    public static void initializeMaps() {

        try {
            ChatGroups.initializeMap();
        } catch (Exception ex) {
            System.out.println("Neelabh exception = " + ex);
        }
    }
}

Please find the stack trace

Exception in thread "main" java.lang.ExceptionInInitializerError
    at static_initialization.Main.initializeMaps(Main.java:10)
    at static_initialization.Main.main(Main.java:5)
Caused by: java.lang.NullPointerException
    at static_initialization.ChatGroups$1.<init>(ChatGroups.java:9)
    at static_initialization.ChatGroups.<clinit>(ChatGroups.java:8)

Body:
It should be:

public static final Map<String, Month> months = new HashMap<String, Month>() {{
    put("Jan", Month.January);
    put("Feb", Month.February);
    put("Mar", Month.March);
    put("Apr", Month.April);
    put("Jun", Month.June);
    put("Jul", Month.July);
    put("Aug", Month.August);
    put("Sep", Month.September);
    put("Oct", Month.October);
    put("Nov", Month.November);
    put("Dec", Month.December);
}};

months.put() leads to NullPointerException, since the static variable months is still null when the put statements are executed.

As an alternative, avoid creating an anonymous class instance, and instead write:

public static final Map<String, Month> months = new HashMap<String, Month>();
static {
    months.put("Jan", Month.January);
    months.put("Feb", Month.February);
    months.put("Mar", Month.March);
    months.put("Apr", Month.April);
    months.put("Jun", Month.June);
    months.put("Jul", Month.July);
    months.put("Aug", Month.August);
    months.put("Sep", Month.September);
    months.put("Oct", Month.October);
    months.put("Nov", Month.November);
    months.put("Dec", Month.December);
}


问:
Getting letters in a string. Why my code didn't work well?
I am new to java and I barely have the time to study it. Actually, my question is a little bit awkward and meaningless. I am trying to get letters from user input. I know that there are more efficient ways to do it, but I only want to know what is wrong with this method. The problem is when I write a string that doesn't contain any space the program is fine but if I write one with spaces it stops work.

```<code>Scanner qx = new Scanner(System.in);
String a = qx.next();
for(int b = 0; b<a.length();b++){
    char z = a.charAt(b);
    System.out.print(z + " ");
    }
</code>```

For example: When I wrote "Hi there" (without quotes)

I expect the output of "H i t h e r e"

But it only shows "H i "

İf I would have written "Hithere"
it would show "H i t h e r e "

So why is there a difference between the one has spaces and the one doesn't?

Also, I am sorry for my grammar. I tried to do my best but I haven't practised for a long time.

答:
next returns any string up to a whitespace character (space, tab, enter).

You need to use nextLine which returns any string up to a carriage return (aka enter).

Body:
I am new to java and I barely have the time to study it. Actually, my question is a little bit awkward and meaningless. I am trying to get letters from user input. I know that there are more efficient ways to do it, but I only want to know what is wrong with this method. The problem is when I write a string that doesn't contain any space the program is fine but if I write one with spaces it stops work.

Scanner qx = new Scanner(System.in);
String a = qx.next();
for(int b = 0; b<a.length();b++){
    char z = a.charAt(b);
    System.out.print(z + " ");
    }

For example: When I wrote "Hi there" (without quotes)

I expect the output of "H i t h e r e"

But it only shows "H i "

İf I would have written "Hithere"
it would show "H i t h e r e "

So why is there a difference between the one has spaces and the one doesn't?

Also, I am sorry for my grammar. I tried to do my best but I haven't practised for a long time.


问:
`APP_INITIALIZER` - by User choice, Is it possible?
I am implemented azure and adal.js with my application. this application used by 2 group of people. so I am keeping 2 separate configuration. the MsAdalAngular6Module takes the configuration on app initiation itself.

But I require, let the app stop the initiation until the login option available in screen, so the user let select their group, then service can supply the config what they required for app initialization.

Is it possible with Angular? or what is the correct approach to initialize the app with different configurations by user choice?

I tried with provider but getting error, Error: StaticInjectorError(AppModule)[InjectionToken
I added both service and login component in deps:[] array. how to come up with solution here?

Any one advice me please?

here is my try:

```<code>providers: [
    {
      provide: APP_INITIALIZER,
      useFactory: initializeApp,
      multi: true,
      deps: [AppConfig, SignInComponent] //added both service and component throw error..
    },
    MsAdalAngular6Service,
    {
      provide: 'adalConfig',
      useFactory: getAdalConfig,
      deps: []
    },
    {
      provide: HTTP_INTERCEPTORS,
      useClass: InsertAuthTokenInterceptor,
      multi: true
    }
  ],
</code>```

答:
To get this work, I created a custom service and implemented. it works fine for me.

here is my service file.ts:

```<code>import { Injectable } from '@angular/core';
import { Store, select } from '@ngrx/store';
import { StateShared } from "./../models/models";
import * as $ from 'jquery';

@Injectable({
    providedIn: 'root'
})
export class AppConfig  {

    value:boolean = true;
    option:string;
    popup = `
    <div class="site-wrapper"
        style="display:flex;flex-direction:column;
        min-height:100vh;border:0.5px solid rgba(0,0,0,0)">
    <div Id="optionHolder" class="main-section" style="
        flex: 1;
        display: flex;
        flex-direction:row;
        align-items: center;
        justify-content: center;
        padding:0 15px;
    ">

        <div class="singin-options" style="
            border: 3px dotted gray;
            display: flex;
            flex-direction:column;
            padding:1rem;

        ">
            <div class="form-check form-check-inline" style="
             margin-bottom: 1rem;
            ">
                <input class="form-check-input" (change)="onLoginChange($event)" value="CTS" type="radio" name="loginOption" id="inlineRadio1">
                <label class="form-check-label" for="inlineRadio1">Login as CTS Member</label>
            </div>
            <div class="form-check form-check-inline">
                <input class="form-check-input" (change)="onLoginChange($event)" value="IBO" type="radio" name="loginOption" id="inlineRadio2">
                <label class="form-check-label" for="inlineRadio2">Login as IBO Member</label>
            </div>
        </div>
        <div class="signin" style="padding:1rem;">
            <button type="button" class="btn btn-success">Sign In</button>
        </div>

    </div></div>`

    constructor(private store:Store<StateShared>){}

    userOption:any;

    setUserOption() {

        let that = this;

        if(!this.value) return;

        return new Promise((resolve, reject) => {

            if(!localStorage.getItem("name")){

                $('body').append(this.popup);

                $("input[name=loginOption]:radio").change(function (event) {
                    that.userOption =  $(event.target).val();
                    $("button").prop('disabled', false);
                })

                $("button").prop('disabled', true);

                $("button").click(function () {
                    that.value = false;
                    localStorage.setItem("name", that.userOption);
                    resolve(true);

                })
            }

            if(localStorage.getItem("name")){
                resolve(true);
            }

        });
    }

    getUserOption(){

        $('body #optionWrapper').remove();

        switch (localStorage.getItem("name")) {
            case "CTS":
                return {
                    tenant: 'de08c407-19b9-427d-9fe8-edf254300ca7',
                    clientId: '828002a4-149f-478c-a318-933ad52b4c4f',
                    redirectUri: window.location.origin,
                    endpoints: {
                        "https://iboconfigservice.azurewebsites.net/api/":"828002a4-149f-478c-a318-933ad52b4c4f"
                    },
                    navigateToLoginRequestUrl: false,
                    cacheLocation: 'localStorage',
                    expireOffsetSeconds: 600,
                    postLogoutRedirectUri: window.location.origin
                };

            case "IBO":
                return {
                    tenant: 'intbacdev.onmicrosoft.com',
                    clientId: '5a5e1a7e-b31d-47bc-9be4-5a107f67fedb',
                    redirectUri: window.location.origin,
                    endpoints: {
                        "https://iboconfigservice.azurewebsites.net/api/":"828002a4-149f-478c-a318-933ad52b4c4f"
                    },
                    navigateToLoginRequestUrl: false,
                    cacheLocation: 'localStorage',
                    expireOffsetSeconds: 600,
                    postLogoutRedirectUri: window.location.origin
                };

            default:
                // code...
                break;
        }

    }

}
</code>```

Body:
I am implemented azure and adal.js with my application. this application used by 2 group of people. so I am keeping 2 separate configuration. the MsAdalAngular6Module takes the configuration on app initiation itself.

But I require, let the app stop the initiation until the login option available in screen, so the user let select their group, then service can supply the config what they required for app initialization.

Is it possible with Angular? or what is the correct approach to initialize the app with different configurations by user choice?

I tried with provider but getting error, Error: StaticInjectorError(AppModule)[InjectionToken
I added both service and login component in deps:[] array. how to come up with solution here?

Any one advice me please?

here is my try:

providers: [
    {
      provide: APP_INITIALIZER,
      useFactory: initializeApp,
      multi: true,
      deps: [AppConfig, SignInComponent] //added both service and component throw error..
    },
    MsAdalAngular6Service,
    {
      provide: 'adalConfig',
      useFactory: getAdalConfig,
      deps: []
    },
    {
      provide: HTTP_INTERCEPTORS,
      useClass: InsertAuthTokenInterceptor,
      multi: true
    }
  ],

Body:
To get this work, I created a custom service and implemented. it works fine for me.

here is my service file.ts:

import { Injectable } from '@angular/core';
import { Store, select } from '@ngrx/store';
import { StateShared } from "./../models/models";
import * as $ from 'jquery';

@Injectable({
    providedIn: 'root'
})
export class AppConfig  {

    value:boolean = true;
    option:string;
    popup = `
    <div class="site-wrapper"
        style="display:flex;flex-direction:column;
        min-height:100vh;border:0.5px solid rgba(0,0,0,0)">
    <div Id="optionHolder" class="main-section" style="
        flex: 1;
        display: flex;
        flex-direction:row;
        align-items: center;
        justify-content: center;
        padding:0 15px;
    ">

        <div class="singin-options" style="
            border: 3px dotted gray;
            display: flex;
            flex-direction:column;
            padding:1rem;

        ">
            <div class="form-check form-check-inline" style="
             margin-bottom: 1rem;
            ">
                <input class="form-check-input" (change)="onLoginChange($event)" value="CTS" type="radio" name="loginOption" id="inlineRadio1">
                <label class="form-check-label" for="inlineRadio1">Login as CTS Member</label>
            </div>
            <div class="form-check form-check-inline">
                <input class="form-check-input" (change)="onLoginChange($event)" value="IBO" type="radio" name="loginOption" id="inlineRadio2">
                <label class="form-check-label" for="inlineRadio2">Login as IBO Member</label>
            </div>
        </div>
        <div class="signin" style="padding:1rem;">
            <button type="button" class="btn btn-success">Sign In</button>
        </div>

    </div></div>`

    constructor(private store:Store<StateShared>){}

    userOption:any;

    setUserOption() {

        let that = this;

        if(!this.value) return;

        return new Promise((resolve, reject) => {

            if(!localStorage.getItem("name")){

                $('body').append(this.popup);

                $("input[name=loginOption]:radio").change(function (event) {
                    that.userOption =  $(event.target).val();
                    $("button").prop('disabled', false);
                })

                $("button").prop('disabled', true);

                $("button").click(function () {
                    that.value = false;
                    localStorage.setItem("name", that.userOption);
                    resolve(true);

                })
            }

            if(localStorage.getItem("name")){
                resolve(true);
            }

        });
    }

    getUserOption(){

        $('body #optionWrapper').remove();

        switch (localStorage.getItem("name")) {
            case "CTS":
                return {
                    tenant: 'de08c407-19b9-427d-9fe8-edf254300ca7',
                    clientId: '828002a4-149f-478c-a318-933ad52b4c4f',
                    redirectUri: window.location.origin,
                    endpoints: {
                        "https://iboconfigservice.azurewebsites.net/api/":"828002a4-149f-478c-a318-933ad52b4c4f"
                    },
                    navigateToLoginRequestUrl: false,
                    cacheLocation: 'localStorage',
                    expireOffsetSeconds: 600,
                    postLogoutRedirectUri: window.location.origin
                };

            case "IBO":
                return {
                    tenant: 'intbacdev.onmicrosoft.com',
                    clientId: '5a5e1a7e-b31d-47bc-9be4-5a107f67fedb',
                    redirectUri: window.location.origin,
                    endpoints: {
                        "https://iboconfigservice.azurewebsites.net/api/":"828002a4-149f-478c-a318-933ad52b4c4f"
                    },
                    navigateToLoginRequestUrl: false,
                    cacheLocation: 'localStorage',
                    expireOffsetSeconds: 600,
                    postLogoutRedirectUri: window.location.origin
                };

            default:
                // code...
                break;
        }

    }

}


问:
Android window title bar icon is causing background for list view items
Programmatic setting the window title bar icon is causing every list view item has tile bar icon as background.

setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.ball);

How can i remove the listview background image or set the window title bar icon any other way than programmatic?

With window title icon set

With out window title icon

--UPDATE

```<code><?xml version="1.0" encoding="utf-8"?>
<!-- Sets the text styles -->
<resources>
     <style name="CustomWindowTitleText" parent="android:TextAppearance.WindowTitle">
          <item name="android:textSize">24dip</item>
          <item name="android:textColor">#ffffff</item>
          <item name="android:textStyle">bold</item>
          <item name="android:typeface">normal</item>
     </style>
     <!-- Changes the background color of the title bar -->
     <style name="CustomWindowTitleBackground">
           <item name="android:background">@drawable/bg_gradient_05</item>
           <item name="android:paddingLeft">10dp</item>
     </style>
     <!-- Set the theme for the window title -->
     <!-- NOTE: setting android:textAppearence to style defined above -->
     <style name="CustomWindowTitle" parent="android:WindowTitle">
          <item name="android:textAppearance">@style/CustomWindowTitleText</item>
          <item name="android:shadowDx">0</item>
          <item name="android:shadowDy">0</item>
          <item name="android:shadowRadius">0</item>
          <item name="android:shadowColor">#a0a0a0</item>
      </style>
      <!-- Override properties in the default theme -->
      <!-- NOTE: you must explicitly the windowTitleSize property, the title bar will not re-size automatically, text will be clipped -->
      <style name="CustomTheme" parent="android:Theme">
           <item name="android:windowTitleSize">50dip</item>
           <item name="android:windowTitleStyle">@style/CustomWindowTitle</item>
           <item name="android:windowTitleBackgroundStyle">@style/CustomWindowTitleBackground</item>
      </style>
</resources>
</code>```

答:
Use the  following code

```<code>requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.my_layout);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
</code>```

Please be sure that you are using requestWindowFeature before setContentView.Here  in R.layout.custom_title  use your custom title xml.

I think this will help you.

ContentLicense: CC BY-SA 3.0

Body:
Programmatic setting the window title bar icon is causing every list view item has tile bar icon as background.

setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.ball);

How can i remove the listview background image or set the window title bar icon any other way than programmatic?

With window title icon set

With out window title icon

--UPDATE

<?xml version="1.0" encoding="utf-8"?>

<resources>

</resources>

Body:
Use the  following code

requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.my_layout);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);

Please be sure that you are using requestWindowFeature before setContentView.Here  in R.layout.custom_title  use your custom title xml.

I think this will help you.


问:
$request->request->replace() what does it do?
I was going through some code in symfony, and I found

$request->request->replace()

Actually, a form is posted and its value is fetched in a function say,

```<code>public function someFunction(Request $request){
    $data = $request->request->all() ? : json_decode($request->getContent(), true);
    $request->request->replace($data);
}
</code>```

When I dumped,

$request->request->replace($data)

The result is null. I didn't understand why is it used and what are its benefits?

I searched about it, some say it is used to sanitise the data, some say we should not use it as replaces all of the parameters in the request instead we should use set method.

And I did not get any of it as I am new to symfony.

What does $request->request->replace() does with the parameter provided to it?

答:
Your $request is an instance of Symfony\Component\HttpFoundation\Request
. Using $request you have access to properties such as request, query, cookies, attributes, files, server, headers. Each of these properties is of type Symfony\Component\HttpFoundation\ParameterBag. Instance of ParameterBag provides access to request parameters using method $request->request->all(). This method will return 'parameters' property of ParameterBag instance.

The $request->request->replace($data) will set 'parameters' property in ParameterBag instance to $data.

Also replace() method does not have any return type that's why when you dumped $request->request->replace($data) you got null as output.

If you want to add some extra parameters to your request then replace() is not the right choice rather you should use set() method in ParameterBag.

Body:
I was going through some code in symfony, and I found

$request->request->replace()

Actually, a form is posted and its value is fetched in a function say,

public function someFunction(Request $request){
    $data = $request->request->all() ? : json_decode($request->getContent(), true);
    $request->request->replace($data);
}

When I dumped,

$request->request->replace($data)

The result is null. I didn't understand why is it used and what are its benefits?

I searched about it, some say it is used to sanitise the data, some say we should not use it as replaces all of the parameters in the request instead we should use set method.

And I did not get any of it as I am new to symfony.

What does $request->request->replace() does with the parameter provided to it?


问:
Sorting using Mongo template not working in java
Sorting using MongoTemplate not working in java.

`query.with(new Sort(Sort.Direction.DESC, "numberOfVotes"));

{
            "ideaId": "2",
            "numberOfVotes": "5",
  },
  {
            "ideaId": "3",
            "numberOfVotes": "5",
  },
 {
            "ideaId": "16",
            "numberOfVotes": "17",
  },

ideaId is the primary key.

答:
I think the code should be like this:
 query.with(Sort.by(Direction.DESC, "numberOfVotes")); this. Can you please try with this?


问:
Clarification on instructions for backend Code in Wix
I'm trying to integrate backend code into a Wix site. Im not too picky about how I want to do this, or what language to write in (ideally, I have a locally-hosted Java code that I'd love to simply call). I wouldn't mind re-writing it in JavaScript though, or another language. But before I decide that I'm confused about my options. I can code but I'm new to the concepts like modules, APIs, & servers.

According to my research, back-end code with Wix is supposed to be easy (or at least do-able and not THAT complicated)....

From this webpage https://support.wix.com/en/article/corvid-calling-server-side-code-from-the-front-end-with-web-modules,

"Web modules are exclusive to Corvid and enable you to write functions that run server-side in the backend, and easily call them in your client-side code. With web modules you can import functions from backend into files or scripts in public, knowing they will run server-side. Corvid handles all the client-server communication required to enable this access."

And from this: https://www.sitepoint.com/what-is-wix-code/

"It’s serverless: All this added functionality comes in a serverless environment that lets you get your work done without any of the normal full-stack development headaches.
Just code and go: Wix Code has a built-in, online IDE and backend so you can just add the code you need to your page or your site, publish, and you’re live."

So, I thought they have a backend IDE where I can write backend code directly, or I could call my Java program. But, as I tried doing this and finding tutorials, it seems I can really only do this by calling a public API from the backend...?

https://youtu.be/tuu0D1izrUU

But ive also read (and someone who supposedly has done it before told me this) that Wix integrates with node.js, which is a backend version of JavaScript.

Can I use a Wix domain for a NodeJS app?

But, when I go into my Wix site I cannot find any option for using Node JS, and doing research on that gives me no useful results.

So, I'm thoroughly confused on what the capabilities are here. Can someone help me make sense of this?

Why are there no tutorials showing explicit code in the Corvid backend module? What's stopping me from simply writing my Java program there in a module? Do I really need an API endpoint to call and pass to the front end?

Is Node JS supported or not - has anyone done this before?

Also, in one link above they said everything is "serverless". But if I have to set up my own API endpoint won't I need to set up my own server??

答:
There are basically two ways to go about this, which you seem to have already discovered.

Write your backend code in your Wix site. Indeed, the backend is built on Node.js as you can see here. Using this approach you will have to use JavaScript.  As you seem to have found, you write this code in the Backend section of your site in a Web Module. Pros: you don't need to worry about managing a server and all your code is in one place.

Expose your already existing Java code as an API that your Wix site can call using the wix-fetch API. Pros: you don't need to rewrite your code.


问:
how to color second p tag in html without using any style and class?
I have 3 p tags,

```<code><p> hi </p>
<p>hello</P>
<p>bye</P>
</code>```

I want to color the 2nd p tag into red by only using pure css(not using any javascript).
without using any inline style and class how can i achieve this?

```<code><p> hi </p>
<p>hello</P>
<p>bye</P>
</code>```

答:
Use :nth-child:

p:nth-child(2) {
  color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>hi</p>
<p>hello</p>
<p>bye</p></code>```

However, as suggested by Hao Wu, it's better to use :nth-of-type if you're looking for a certain tag (not a certain child):

p:nth-of-type(2) {
  color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>hi</p>
<p>hello</p>
<p>bye</p></code>```

Body:
I have 3 p tags,

 hi

hello

bye

I want to color the 2nd p tag into red by only using pure css(not using any javascript).
without using any inline style and class how can i achieve this?

 hi

hello

bye

Body:
Use :nth-child:

p:nth-child(2) {
  color: red;
}

<p>hi</p>
<p>hello</p>
<p>bye</p>

However, as suggested by Hao Wu, it's better to use :nth-of-type if you're looking for a certain tag (not a certain child):

p:nth-of-type(2) {
  color: red;
}

<p>hi</p>
<p>hello</p>
<p>bye</p>


问:
How Can I output the response to text file and open the text file when done
I want to modify a Perl script to save the result to text file output.txt and open the results output.txt when task is done

I have tried used "use strict;
use warnings;" and other methods but I keep getting an errors' The Last error was "Couldn't open output.txt"

```<code>#!/usr/bin/perl

use HTTP::Request;
use LWP::UserAgent;

system('cls');
system "color c";
print"\n";
print" |||||||||||||||||Robots scanner|||||||||||||||||||||";
print "\n";

print " Scan Your site Site\n\n Example: www.test.com \n\n-> ";

$site=<STDIN>;
chomp $site;

if($site !~ /http:\/\//) { $site = "http://$site/"; };

print "\n";

@path = ('robotx.txt','robots.txt','robot.txt','search',);

foreach $robots(@path){

  $url = $site.$robots;
  $req = HTTP::Request->new(GET=>$url);
  $useragent = LWP::UserAgent->new();

  $response = $useragent->request($req);
  my $filename = 'report.txt';
  open(my $fh, '>', $filename) or die "Could not open file '$filename' $!";
  if ($response->is_success){

    print  ">>>>>>Robots Found !!!>>>: $url\n";
    print $fh "out put has been generated by perl\n"; # THIS DOESN'T WORK THE report.txt is empty
    print "done\n";

  }else{
    print "NotFound : $robots\n";
    print "done\n";
    # I want to open the file from windows explorer automatically here when its done
    close $fh;
  }

}
</code>```

after running cmd as Admin , as you can see the report.txt file shows empty
I expect to see the out put of the Response

I also want perl to open the report.txt ( without going to windows explorer and opening it manually by the user )  I want it automatically open when its done but I wasn't able to achieve that.

Thanks!

答:
Try changing open(my $fh, '>', $filename) to open(my $fh, '>>', $filename) (two arrows instead of one. This will add each new entry instead of delete the last one.

Here are some answers on opening Windows files with Perl:

How to run an executable file using Perl on Windows XP?

Body:
I want to modify a Perl script to save the result to text file output.txt and open the results output.txt when task is done

I have tried used "use strict;
use warnings;" and other methods but I keep getting an errors' The Last error was "Couldn't open output.txt"

#!/usr/bin/perl

use HTTP::Request;
use LWP::UserAgent;

system('cls');
system "color c";
print"\n";
print" |||||||||||||||||Robots scanner|||||||||||||||||||||";
print "\n";

print " Scan Your site Site\n\n Example: www.test.com \n\n-> ";

$site=<STDIN>;
chomp $site;

if($site !~ /http:\/\//) { $site = "http://$site/"; };

print "\n";

@path = ('robotx.txt','robots.txt','robot.txt','search',);

foreach $robots(@path){

  $url = $site.$robots;
  $req = HTTP::Request->new(GET=>$url);
  $useragent = LWP::UserAgent->new();

  $response = $useragent->request($req);
  my $filename = 'report.txt';
  open(my $fh, '>', $filename) or die "Could not open file '$filename' $!";
  if ($response->is_success){

    print  ">>>>>>Robots Found !!!>>>: $url\n";
    print $fh "out put has been generated by perl\n"; # THIS DOESN'T WORK THE report.txt is empty
    print "done\n";

  }else{
    print "NotFound : $robots\n";
    print "done\n";
    # I want to open the file from windows explorer automatically here when its done
    close $fh;
  }

}

after running cmd as Admin , as you can see the report.txt file shows empty
I expect to see the out put of the Response

I also want perl to open the report.txt ( without going to windows explorer and opening it manually by the user )  I want it automatically open when its done but I wasn't able to achieve that.

Thanks!


问:
result_array value are not showing inside foreach loop in codeigniter
I simply fire a select query using Codeigniter where all values are showing when I am using print_r function but when I use foreach loop then no value is showing I don't know what is the problem is? How can I fix this problem?

```<code>$this->db->select('*');
    $this->db->from('user_detail');
    $where = "jid='".$jid_final."' and cid='".$cid_final."' and offer='1'";
    $this->db->where($where);
    $sql_user = $this->db->get();
    $result_user = $sql_user->result_array();
    print_r($result_user);
    foreach($result_user as $row_user)
    {

        $user_data = '<tr>
                        <td class="td">'.$row_user['uid'].'</td>
                        <td class="td">'.$row_user['fname'].' '.$row_user['lname'].'</td>
                        <td class="td">'.$row_user['email'].'</td>
                        <td class="td">'.$row_user['phone'].'</td>
                    </tr>';
    }
    echo $user_data;
</code>```

Thank You

答:
Use Below query, need to check if data in table or not and then pass it to foreach loop.

```<code> $user_data = '';
 $this->db->select('*');
    $where = "jid='".$jid_final."' and cid='".$cid_final."' and offer='1'";
    $this->db->where($where, NULL, FALSE);
    $result_user = $this->db->get('user_detail')->result_array();

    if($result_user) {
    foreach($result_user as $row_user)
    {

        $user_data .= '<tr>
                        <td class="td">'.$row_user['uid'].'</td>
                        <td class="td">'.$row_user['fname'].' '.$row_user['lname'].'</td>
                        <td class="td">'.$row_user['email'].'</td>
                        <td class="td">'.$row_user['phone'].'</td>
                    </tr>';
    }
     echo $user_data;
    } else {
     echo "no data found";
    }
</code>```

Body:
I simply fire a select query using Codeigniter where all values are showing when I am using print_r function but when I use foreach loop then no value is showing I don't know what is the problem is? How can I fix this problem?

$this->db->select('*');
    $this->db->from('user_detail');
    $where = "jid='".$jid_final."' and cid='".$cid_final."' and offer='1'";
    $this->db->where($where);
    $sql_user = $this->db->get();
    $result_user = $sql_user->result_array();
    print_r($result_user);
    foreach($result_user as $row_user)
    {

        $user_data = '

                        '.$row_user['uid'].'
                        '.$row_user['fname'].' '.$row_user['lname'].'
                        '.$row_user['email'].'
                        '.$row_user['phone'].'

';
    }
    echo $user_data;

Thank You

Body:
Use Below query, need to check if data in table or not and then pass it to foreach loop.

 $user_data = '';
 $this->db->select('*');
    $where = "jid='".$jid_final."' and cid='".$cid_final."' and offer='1'";
    $this->db->where($where, NULL, FALSE);
    $result_user = $this->db->get('user_detail')->result_array();

    if($result_user) {
    foreach($result_user as $row_user)
    {

        $user_data .= '<tr>
                        <td class="td">'.$row_user['uid'].'</td>
                        <td class="td">'.$row_user['fname'].' '.$row_user['lname'].'</td>
                        <td class="td">'.$row_user['email'].'</td>
                        <td class="td">'.$row_user['phone'].'</td>
                    </tr>';
    }
     echo $user_data;
    } else {
     echo "no data found";
    }


答:
Try to concatenate the values with .

```<code>$user_data = '';
if(isseet($result_user) && count($result_user) > 0){
foreach($result_user as $row_user)
{

    $user_data .= '<tr>
                    <td class="td">'.$row_user['uid'].'</td>
                    <td class="td">'.$row_user['fname'].' '.$row_user['lname'].'</td>
                    <td class="td">'.$row_user['email'].'</td>
                    <td class="td">'.$row_user['phone'].'</td>
                </tr>';
}
    echo $user_data;
}else{
    echo 'Record not found';
}
</code>```

Title: result_array value are not showing inside foreach loop in codeigniter

Body:
Try to concatenate the values with .

$user_data = '';
if(isseet($result_user) && count($result_user) > 0){
foreach($result_user as $row_user)
{

    $user_data .= '<tr>
                    <td class="td">'.$row_user['uid'].'</td>
                    <td class="td">'.$row_user['fname'].' '.$row_user['lname'].'</td>
                    <td class="td">'.$row_user['email'].'</td>
                    <td class="td">'.$row_user['phone'].'</td>
                </tr>';
}
    echo $user_data;
}else{
    echo 'Record not found';
}


问:
Java programming, opencv unsatisfied link error
OpenCV libraries gives unsatisfied link error in capturing a video stream.

Where should be the opencv 3.2.0 libraries? What is the correct path for  packages of opencv classes?

Code where to generate this error:

```<code>package opencv;

import org.opencv.core.*;

import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.videoio.VideoCapture;
public class VideoCap
{

    public static void main (String args[]){

        System.loadLibrary(Core.NATIVE_LIBRARY_NAME); // error

        VideoCapture camera = new VideoCapture(0);

        if(!camera.isOpened()){
            System.out.println("Error");
        }
    else {
            Mat frame = new Mat();
            while(true){
                if (camera.read(frame)){
                    System.out.println("Frame Obtained");
                    System.out.println("Captured Frame Width " +
                    frame.width() + " Height " + frame.height());
                    Imgcodecs.imwrite("camera.jpg", frame);
                    System.out.println("OK");
                    break;
                }
            }
        }
        camera.release();
    }
}
</code>```

The exception is:

```<code>Exception in thread "main" java.lang.UnsatisfiedLinkError:
    no opencv_java320 in java.library.path
    at java.lang.ClassLoader.loadLibrary(Unknown Source)
    at java.lang.Runtime.loadLibrary0(Unknown Source)
    at java.lang.System.loadLibrary(Unknown Source)
    at opencv.VideoCap.main(VideoCap.java:9)
</code>```

答:
The following picture is my contents of a directory in which opencv 4.0.1 installed with a tesseract library. I built it with a mingw32 gcc compiler on a windows actually 10.

I think you have at least two file opencv_javaXXX_dll and opencv-XXX.jar.

I have built the opencv library with mingw32 gcc compiler on Windows 10
So, i must set the bin directory where mingw32 installed and java.

I set the variables on a cmd window,

```<code>SET MINGW_HOME=D:/DEV/SDK/msys32/mingw32
SET JAVA_HOME=D:/DEV/SDK/JDK/jdk1.8.0_152
SET PATH=%MINGW_HOME%/bin;%JAVA_HOME%/bin
</code>```

Here are my test commands.

```<code>C:\Windows\System32\cmd.exe /C "javac -cp .;opencv-410.jar -d . *.java & java -Djava.library.path=. -cp .;opencv-410.jar VideoCap"
</code>```

There are three possible cases.

1. Can't find dependent libraries problem.

This problem indicates that you have some libraries missing.

In this case, I should get this message if i don't have a libtesseract40.dll in the same directory or system's path.

2. An unsatisfied link error with a library name.

This commonly occurred when a name of library mismatched.
I will get the error if i have a libopencv_java410.dll as a library name.

3. An unsatisfied link error with a method name.

If you have still got another unsatisfied link - method name.

For example,

java.lang.UnsatisfiedLinkError: org.opencv.core.Mat.n_eye(III)J

I think this will be complicate problem.

You might have your library compile and build from the scratch.

On a windows os, I had to add a build flag at following line in a CMakefile.txt.

I added a '--add-stdcall-alias' flag.

A location of a CMakefile.txt:

[~opencv-4.1.0 source directory]\modules\java\jni\CMakefile.txt

```<code>  elseif(((CV_GCC OR CV_CLANG OR UNIX) OR (OPENCV_FORCE_FAT_JAVA_LIB_LD_RULES)) AND (NOT OPENCV_SKIP_FAT_JAVA_LIB_LD_RULES))
    ocv_target_link_libraries(${the_module} LINK_PRIVATE -Wl,-whole-archive ${__deps} -Wl,-no-whole-archive -Wl,--add-stdcall-alias)
</code>```

The complete test code is as following:

```<code>//A test code for the opencv 4.0.1
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.videoio.VideoCapture;

public class HelloCV {

    public static void test1(){
       System.load(new java.io.File(".").getAbsolutePath() + java.io.File.separator + "opencv_java410.dll");

        VideoCapture camera = new VideoCapture(0);

        if(!camera.isOpened()){
            System.out.println("Error");
        }
        else {
            Mat frame = new Mat();
            while(true){
                if (camera.read(frame)){
                    System.out.println("Frame Obtained");
                    System.out.println("Captured Frame Width " +
                    frame.width() + " Height " + frame.height());
                    Imgcodecs.imwrite("camera.jpg", frame);
                    System.out.println("OK");
                    break;
                }
            }
        }
        camera.release();
    }

    public static void test2(){
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME); // error

        VideoCapture camera = new VideoCapture(0);

        if(!camera.isOpened()){
            System.out.println("Error");
        }
        else {
            Mat frame = new Mat();
            while(true){
                if (camera.read(frame)){
                    System.out.println("Frame Obtained");
                    System.out.println("Captured Frame Width " +
                    frame.width() + " Height " + frame.height());
                    Imgcodecs.imwrite("camera.jpg", frame);
                    System.out.println("OK");
                    break;
                }
            }
        }
        camera.release();
    }

    public static void main (String args[]){
        test1();
        test2();
    }
}
</code>```

Body:
OpenCV libraries gives unsatisfied link error in capturing a video stream.

Where should be the opencv 3.2.0 libraries? What is the correct path for  packages of opencv classes?

Code where to generate this error:

package opencv;

import org.opencv.core.*;

import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.videoio.VideoCapture;
public class VideoCap
{

    public static void main (String args[]){

        System.loadLibrary(Core.NATIVE_LIBRARY_NAME); // error

        VideoCapture camera = new VideoCapture(0);

        if(!camera.isOpened()){
            System.out.println("Error");
        }
    else {
            Mat frame = new Mat();
            while(true){
                if (camera.read(frame)){
                    System.out.println("Frame Obtained");
                    System.out.println("Captured Frame Width " +
                    frame.width() + " Height " + frame.height());
                    Imgcodecs.imwrite("camera.jpg", frame);
                    System.out.println("OK");
                    break;
                }
            }
        }
        camera.release();
    }
}

The exception is:

Exception in thread "main" java.lang.UnsatisfiedLinkError:
    no opencv_java320 in java.library.path
    at java.lang.ClassLoader.loadLibrary(Unknown Source)
    at java.lang.Runtime.loadLibrary0(Unknown Source)
    at java.lang.System.loadLibrary(Unknown Source)
    at opencv.VideoCap.main(VideoCap.java:9)

Body:
The following picture is my contents of a directory in which opencv 4.0.1 installed with a tesseract library. I built it with a mingw32 gcc compiler on a windows actually 10.

I think you have at least two file opencv_javaXXX_dll and opencv-XXX.jar.

I have built the opencv library with mingw32 gcc compiler on Windows 10
So, i must set the bin directory where mingw32 installed and java.

I set the variables on a cmd window,

SET MINGW_HOME=D:/DEV/SDK/msys32/mingw32
SET JAVA_HOME=D:/DEV/SDK/JDK/jdk1.8.0_152
SET PATH=%MINGW_HOME%/bin;%JAVA_HOME%/bin

Here are my test commands.

C:\Windows\System32\cmd.exe /C "javac -cp .;opencv-410.jar -d . *.java & java -Djava.library.path=. -cp .;opencv-410.jar VideoCap"

There are three possible cases.

1. Can't find dependent libraries problem.

This problem indicates that you have some libraries missing.

In this case, I should get this message if i don't have a libtesseract40.dll in the same directory or system's path.

2. An unsatisfied link error with a library name.

This commonly occurred when a name of library mismatched.
I will get the error if i have a libopencv_java410.dll as a library name.

3. An unsatisfied link error with a method name.

If you have still got another unsatisfied link - method name.

For example,

java.lang.UnsatisfiedLinkError: org.opencv.core.Mat.n_eye(III)J

I think this will be complicate problem.

You might have your library compile and build from the scratch.

On a windows os, I had to add a build flag at following line in a CMakefile.txt.

I added a '--add-stdcall-alias' flag.

A location of a CMakefile.txt:

[~opencv-4.1.0 source directory]\modules\java\jni\CMakefile.txt

  elseif(((CV_GCC OR CV_CLANG OR UNIX) OR (OPENCV_FORCE_FAT_JAVA_LIB_LD_RULES)) AND (NOT OPENCV_SKIP_FAT_JAVA_LIB_LD_RULES))
    ocv_target_link_libraries(${the_module} LINK_PRIVATE -Wl,-whole-archive ${__deps} -Wl,-no-whole-archive -Wl,--add-stdcall-alias)

The complete test code is as following:

//A test code for the opencv 4.0.1
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.videoio.VideoCapture;

public class HelloCV {

    public static void test1(){
       System.load(new java.io.File(".").getAbsolutePath() + java.io.File.separator + "opencv_java410.dll");

        VideoCapture camera = new VideoCapture(0);

        if(!camera.isOpened()){
            System.out.println("Error");
        }
        else {
            Mat frame = new Mat();
            while(true){
                if (camera.read(frame)){
                    System.out.println("Frame Obtained");
                    System.out.println("Captured Frame Width " +
                    frame.width() + " Height " + frame.height());
                    Imgcodecs.imwrite("camera.jpg", frame);
                    System.out.println("OK");
                    break;
                }
            }
        }
        camera.release();
    }

    public static void test2(){
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME); // error

        VideoCapture camera = new VideoCapture(0);

        if(!camera.isOpened()){
            System.out.println("Error");
        }
        else {
            Mat frame = new Mat();
            while(true){
                if (camera.read(frame)){
                    System.out.println("Frame Obtained");
                    System.out.println("Captured Frame Width " +
                    frame.width() + " Height " + frame.height());
                    Imgcodecs.imwrite("camera.jpg", frame);
                    System.out.println("OK");
                    break;
                }
            }
        }
        camera.release();
    }

    public static void main (String args[]){
        test1();
        test2();
    }
}


问:
How to pass the url from json data to a div dynamically using jquery?
I have the json file which contains id and url of few videos. Now I should read the url from json file and pass it to a div src. By clicking the div itself the video should be load into another div.

below mentioned is my html where I read the json data and append to the "href"

```<code><div class="div1" style="padding-left:inherit">
<div href="#">
</div>
</div>
</code>```

Now, I need to pass the href from this div to src in the below,

```<code><iframe id="videoplayerDiv" src="" scrolling="no" frameborder="no" align="center" height="100%" width="100%" allowfullscreen></iframe>
</code>```

and script for add src is that,

```<code>$(document).ready(function () {
    $.getJSON('/video.json', function (data) {
        $('.div1').click(function (el) {
            $("#videoplayerDiv").attr("src", $(this).attr(url));
        });
    });
});
</code>```

Can anyone please help to resolve this?

答:
assuming you json is something like below.

```<code>var jsonData=[{id:1,"url":"www.youtube.com"},{id:2,"url":"www.youtube.com/1"}];
$(document).ready(function () {
$.getJSON('/video.json', function (data) {
    if(data){
       data.forEach(function(i,o){
           var _div=$("<div/>",{id:o.id});
           _div.attr("url",o.url);
           _div.on('click',function(){
                $("#videoplayerDiv").attr("src", $(this).attr("url"));
           });
           $("#div1").append(_div)
       });
      }

   });
});
</code>```

and your html

```<code><div class="div1" id='div1' style="padding-left:inherit"></div>
</code>```

Body:
I have the json file which contains id and url of few videos. Now I should read the url from json file and pass it to a div src. By clicking the div itself the video should be load into another div.

below mentioned is my html where I read the json data and append to the "href"

Now, I need to pass the href from this div to src in the below,

and script for add src is that,

$(document).ready(function () {
    $.getJSON('/video.json', function (data) {
        $('.div1').click(function (el) {
            $("#videoplayerDiv").attr("src", $(this).attr(url));
        });
    });
});

Can anyone please help to resolve this?

Body:
assuming you json is something like below.

var jsonData=[{id:1,"url":"www.youtube.com"},{id:2,"url":"www.youtube.com/1"}];
$(document).ready(function () {
$.getJSON('/video.json', function (data) {
    if(data){
       data.forEach(function(i,o){
           var _div=$("<div/>",{id:o.id});
           _div.attr("url",o.url);
           _div.on('click',function(){
                $("#videoplayerDiv").attr("src", $(this).attr("url"));
           });
           $("#div1").append(_div)
       });
      }

   });
});

and your html

<div class="div1" id='div1' style="padding-left:inherit"></div>


问:
UIView setting constraints
I am having trouble creating a UIView instance programmatically. I have a function that returns the view so that I can use it in an NSAttachment inside a UITextView.

This is what I am trying to achieve:

This is what I am getting in the simulator:

Code Below:

```<code>let fullView = UIView()
    let firstButton = UIButton()
    let secondButton = UIButton()
    let thirdTextView = UITextView()

    fullView.frame = CGRect(x: 0, y: 0, width: textView.frame.width, height: 90)
    fullView.backgroundColor = UIColor(red:0.82, green:0.83, blue:0.85, alpha:1.0)

    firstButton.setTitle(text1, for: .normal)
    firstButton.setTitleColor(.black, for: .normal)
    firstButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium)
    firstButton.contentHorizontalAlignment = .left

    secondButton.setTitle("Button2", for: .normal)
    secondButton.setTitleColor(.black, for: .normal)
    secondButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium)
    secondButton.contentHorizontalAlignment = .right

    thirdTextView.text = text2

    let descriptionBarStackView = UIStackView()
    descriptionBarStackView.axis = .horizontal
    descriptionBarStackView.alignment = .fill
    descriptionBarStackView.distribution = .fillProportionally

    descriptionBarStackView.addArrangedSubview(firstButton)
    descriptionBarStackView.addArrangedSubview(secondButton)

    let viewWithStackViews = UIStackView()
    viewWithStackViews.axis = .vertical
    viewWithStackViews.alignment = .fill // .leading .firstBaseline .center .trailing .lastBaseline
    viewWithStackViews.distribution = .fillEqually
    viewWithStackViews.addArrangedSubview(descriptionBarStackView)
    viewWithStackViews.addArrangedSubview(thirdTextView)

    fullView.addSubview(viewWithStackViews)

    descriptionBarStackView.translatesAutoresizingMaskIntoConstraints = false
    thirdTextView.translatesAutoresizingMaskIntoConstraints = false
    viewWithStackViews.translatesAutoresizingMaskIntoConstraints = false

    NSLayoutConstraint.activate([
    viewWithStackViews.topAnchor.constraint(equalTo: fullView.topAnchor, constant: 5),
    viewWithStackViews.leadingAnchor.constraint(equalTo: fullView.leadingAnchor, constant: 5),
    viewWithStackViews.trailingAnchor.constraint(equalTo: fullView.trailingAnchor, constant: 5),
    viewWithStackViews.bottomAnchor.constraint(equalTo: fullView.bottomAnchor, constant: 5),
    ])
</code>```

Edit:

答:
Check this updated method

```<code>func customView(){

let fullView = UIView()
let firstButton = UIButton()
let secondButton = UIButton()
let thirdTextView = UITextView()

fullView.frame = CGRect(x: 0, y: 0, width: mainView.frame.width, height: mainView.frame.height)
fullView.backgroundColor = UIColor(red:0.82, green:0.83, blue:0.85, alpha:1.0)

firstButton.setTitle("Button1", for: .normal)
firstButton.setTitleColor(.black, for: .normal)
firstButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium)
firstButton.contentHorizontalAlignment = .left
firstButton.backgroundColor = .clear

secondButton.setTitle("Button2", for: .normal)
secondButton.setTitleColor(.black, for: .normal)
secondButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium)
secondButton.contentHorizontalAlignment = .right
secondButton.backgroundColor = .clear

thirdTextView.text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
thirdTextView.backgroundColor = .clear

let descriptionBarStackView = UIStackView()
descriptionBarStackView.axis = .horizontal
descriptionBarStackView.alignment = .fill
descriptionBarStackView.distribution = .fillProportionally
descriptionBarStackView.isLayoutMarginsRelativeArrangement = true
descriptionBarStackView.directionalLayoutMargins = NSDirectionalEdgeInsets(top: 0, leading: 5, bottom: 0, trailing: 5)

descriptionBarStackView.addArrangedSubview(firstButton)
descriptionBarStackView.addArrangedSubview(secondButton)

let viewWithStackViews = UIStackView()
viewWithStackViews.axis = .vertical
viewWithStackViews.alignment = .fill // .leading .firstBaseline .center .trailing .lastBaseline
viewWithStackViews.distribution = .fill
viewWithStackViews.addArrangedSubview(descriptionBarStackView)
viewWithStackViews.addArrangedSubview(thirdTextView)

fullView.addSubview(viewWithStackViews)

descriptionBarStackView.translatesAutoresizingMaskIntoConstraints = false
thirdTextView.translatesAutoresizingMaskIntoConstraints = false
viewWithStackViews.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint(item: descriptionBarStackView, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: 30).isActive = true
NSLayoutConstraint.activate([
    viewWithStackViews.topAnchor.constraint(equalTo: fullView.topAnchor, constant: 0),
    viewWithStackViews.leadingAnchor.constraint(equalTo: fullView.leadingAnchor, constant: 0),
    viewWithStackViews.trailingAnchor.constraint(equalTo: fullView.trailingAnchor, constant: 0),
    viewWithStackViews.bottomAnchor.constraint(equalTo: fullView.bottomAnchor, constant: 0),
    ])

fullView.layer.cornerRadius = 5
mainView.addSubview(fullView)
</code>```

}

here i have listed changes

mainView.frame.height full height based on main text view

firstButton.backgroundColor = .clear

secondButton.backgroundColor = .clear

thirdTextView.backgroundColor = .clear

margin for button
descriptionBarStackView.isLayoutMarginsRelativeArrangement = true
descriptionBarStackView.directionalLayoutMargins = NSDirectionalEdgeInsets(top: 0, leading: 5, bottom: 0, trailing: 5)

NSLayoutConstraint constraint zero to all in full view

fullView.layer.cornerRadius = 5

thats it here is result..

Title: UIView setting constraints

Body:
I am having trouble creating a UIView instance programmatically. I have a function that returns the view so that I can use it in an NSAttachment inside a UITextView.

This is what I am trying to achieve:

This is what I am getting in the simulator:

Code Below:

let fullView = UIView()
    let firstButton = UIButton()
    let secondButton = UIButton()
    let thirdTextView = UITextView()

    fullView.frame = CGRect(x: 0, y: 0, width: textView.frame.width, height: 90)
    fullView.backgroundColor = UIColor(red:0.82, green:0.83, blue:0.85, alpha:1.0)

    firstButton.setTitle(text1, for: .normal)
    firstButton.setTitleColor(.black, for: .normal)
    firstButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium)
    firstButton.contentHorizontalAlignment = .left

    secondButton.setTitle("Button2", for: .normal)
    secondButton.setTitleColor(.black, for: .normal)
    secondButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium)
    secondButton.contentHorizontalAlignment = .right

    thirdTextView.text = text2

    let descriptionBarStackView = UIStackView()
    descriptionBarStackView.axis = .horizontal
    descriptionBarStackView.alignment = .fill
    descriptionBarStackView.distribution = .fillProportionally

    descriptionBarStackView.addArrangedSubview(firstButton)
    descriptionBarStackView.addArrangedSubview(secondButton)

    let viewWithStackViews = UIStackView()
    viewWithStackViews.axis = .vertical
    viewWithStackViews.alignment = .fill // .leading .firstBaseline .center .trailing .lastBaseline
    viewWithStackViews.distribution = .fillEqually
    viewWithStackViews.addArrangedSubview(descriptionBarStackView)
    viewWithStackViews.addArrangedSubview(thirdTextView)

    fullView.addSubview(viewWithStackViews)

    descriptionBarStackView.translatesAutoresizingMaskIntoConstraints = false
    thirdTextView.translatesAutoresizingMaskIntoConstraints = false
    viewWithStackViews.translatesAutoresizingMaskIntoConstraints = false

    NSLayoutConstraint.activate([
    viewWithStackViews.topAnchor.constraint(equalTo: fullView.topAnchor, constant: 5),
    viewWithStackViews.leadingAnchor.constraint(equalTo: fullView.leadingAnchor, constant: 5),
    viewWithStackViews.trailingAnchor.constraint(equalTo: fullView.trailingAnchor, constant: 5),
    viewWithStackViews.bottomAnchor.constraint(equalTo: fullView.bottomAnchor, constant: 5),
    ])

Edit:

Body:
Check this updated method

func customView(){

let fullView = UIView()
let firstButton = UIButton()
let secondButton = UIButton()
let thirdTextView = UITextView()

fullView.frame = CGRect(x: 0, y: 0, width: mainView.frame.width, height: mainView.frame.height)
fullView.backgroundColor = UIColor(red:0.82, green:0.83, blue:0.85, alpha:1.0)

firstButton.setTitle("Button1", for: .normal)
firstButton.setTitleColor(.black, for: .normal)
firstButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium)
firstButton.contentHorizontalAlignment = .left
firstButton.backgroundColor = .clear

secondButton.setTitle("Button2", for: .normal)
secondButton.setTitleColor(.black, for: .normal)
secondButton.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.medium)
secondButton.contentHorizontalAlignment = .right
secondButton.backgroundColor = .clear

thirdTextView.text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum."
thirdTextView.backgroundColor = .clear

let descriptionBarStackView = UIStackView()
descriptionBarStackView.axis = .horizontal
descriptionBarStackView.alignment = .fill
descriptionBarStackView.distribution = .fillProportionally
descriptionBarStackView.isLayoutMarginsRelativeArrangement = true
descriptionBarStackView.directionalLayoutMargins = NSDirectionalEdgeInsets(top: 0, leading: 5, bottom: 0, trailing: 5)

descriptionBarStackView.addArrangedSubview(firstButton)
descriptionBarStackView.addArrangedSubview(secondButton)

let viewWithStackViews = UIStackView()
viewWithStackViews.axis = .vertical
viewWithStackViews.alignment = .fill // .leading .firstBaseline .center .trailing .lastBaseline
viewWithStackViews.distribution = .fill
viewWithStackViews.addArrangedSubview(descriptionBarStackView)
viewWithStackViews.addArrangedSubview(thirdTextView)

fullView.addSubview(viewWithStackViews)

descriptionBarStackView.translatesAutoresizingMaskIntoConstraints = false
thirdTextView.translatesAutoresizingMaskIntoConstraints = false
viewWithStackViews.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint(item: descriptionBarStackView, attribute: NSLayoutConstraint.Attribute.height, relatedBy: NSLayoutConstraint.Relation.equal, toItem: nil, attribute: NSLayoutConstraint.Attribute.notAnAttribute, multiplier: 1, constant: 30).isActive = true
NSLayoutConstraint.activate([
    viewWithStackViews.topAnchor.constraint(equalTo: fullView.topAnchor, constant: 0),
    viewWithStackViews.leadingAnchor.constraint(equalTo: fullView.leadingAnchor, constant: 0),
    viewWithStackViews.trailingAnchor.constraint(equalTo: fullView.trailingAnchor, constant: 0),
    viewWithStackViews.bottomAnchor.constraint(equalTo: fullView.bottomAnchor, constant: 0),
    ])

fullView.layer.cornerRadius = 5
mainView.addSubview(fullView)

}

here i have listed changes

mainView.frame.height full height based on main text view

firstButton.backgroundColor = .clear

secondButton.backgroundColor = .clear

thirdTextView.backgroundColor = .clear

margin for button
descriptionBarStackView.isLayoutMarginsRelativeArrangement = true
descriptionBarStackView.directionalLayoutMargins = NSDirectionalEdgeInsets(top: 0, leading: 5, bottom: 0, trailing: 5)

NSLayoutConstraint constraint zero to all in full view

fullView.layer.cornerRadius = 5

thats it here is result..