问:
writing data to file with multithredding python
i am calling a function vision to process images, i want to process a huge amount of images and write the data to file. i am using multithreading and running 4 threads and passing a different list of imagename to each thread but when i write the data to file it is overwriting and showing result of only one thread.
how can process these images faster and write the data of coming from function in a file.
this is my vision function.

```<code>def vision(filelist):
    from google.cloud import vision
    from google.cloud.vision import types
    os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = r'Logo Detection-ecc10ae26b70.json'
    global lck
    global df
    global dff
    lck.acquire()
    for i in range(len(onlyfiles)):
        imagepath=batch_folder+"\\"+onlyfiles[i]
        with io.open(onlyfiles[i], 'rb') as image_file:
            content = image_file.read()
            logolist=[]
            labellist=[]
            objectlist=[]
            image = vision.types.Image(content=content)
            response = client.logo_detection(image=image)
            logos = response.logo_annotations
            response = client.label_detection(image=image)
            labels = response.label_annotations
            objects = client.object_localization(image=image).localized_object_annotations

            for logo in logos:
                logolist.append(logo.description)
            for label in labels:
                labellist.append(label.description)
            for obj in objects:
                objectlist.append(obj.name)
            logolist2.append(logolist)
            labellist2.append(labellist)
            objectlist2.append(objectlist)
            dff=[]
            lck.acquire()
            dff = pd.DataFrame(list(zip(onlyfiles,logolist2,labellist2,objectlist2)),columns =['filename', 'logo','label','object'])
            df.append(dff,ignore_index=True)
            lck.release()

    df.to_csv(csvadd, index=False)

############image reading and divding data for threads#################
batch_folder='D:\\Projects\\VAT\\fakedetection\\keyframe\\ffmpeg-4.2.1-win64-static\\video'
onlyfiles = fnmatch.filter(os.listdir(batch_folder), '*.jpg')
countofimage=len(onlyfiles)
division=int(countofimage/4)
index1=[0,division]
index2=[division+1,division+division]
index3=[division+division+1,division+division+division]
index4=[division+division+division+1,division+division+division+division]
threadfile1=onlyfiles[index1[0]:index1[1]]
threadfile2=onlyfiles[index2[0]:index2[1]]
threadfile3=onlyfiles[index3[0]:index3[1]]
threadfile4=onlyfiles[index4[0]:index4[1]]

t1 = threading.Thread(target=vision, args=(threadfile1,))
t2 = threading.Thread(target=vision, args=(threadfile2,))
t3 = threading.Thread(target=vision, args=(threadfile3,))
t4 = threading.Thread(target=vision, args=(threadfile4,))

# starting thread 1
t1.start()
# starting thread 2
t2.start()
t3.start()
t4.start()

# wait until thread 1 is completely executed
t1.join()
# wait until thread 2 is completely executed
t2.join()
t3.join()
t4.join()
# both threads completely executed
print("Done!")
</code>```

i tired lock and global df but the output is not coming from all threads in the file.if there is any improvement needed for this code which can process faster please suggest and help to write data coming from threads to a file
the code is working fine no error. i am just not just getting proper output

答:
Working on files concurrently is a standard problem in multithreading. If not handled correctly, things like lost update problems will arise like it does in yor case.

Using locks is one approach to ensure that all updates will appear in the file. However, if you use a lock, other threads will have to wait until the lock is released before they can write to the file. Depending on the duration of the locking per thread the program could end up performing like a single thread application in the worst case.

My approach to solve your problem does not depend on locks at all: Would it be possible for you to write the outputs of the different threads to different files first and merge the output files afterwards? This way, you won't have to worry about lost updates.

Body:
i am calling a function vision to process images, i want to process a huge amount of images and write the data to file. i am using multithreading and running 4 threads and passing a different list of imagename to each thread but when i write the data to file it is overwriting and showing result of only one thread.
how can process these images faster and write the data of coming from function in a file.
this is my vision function.

def vision(filelist):
    from google.cloud import vision
    from google.cloud.vision import types
    os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = r'Logo Detection-ecc10ae26b70.json'
    global lck
    global df
    global dff
    lck.acquire()
    for i in range(len(onlyfiles)):
        imagepath=batch_folder+"\\"+onlyfiles[i]
        with io.open(onlyfiles[i], 'rb') as image_file:
            content = image_file.read()
            logolist=[]
            labellist=[]
            objectlist=[]
            image = vision.types.Image(content=content)
            response = client.logo_detection(image=image)
            logos = response.logo_annotations
            response = client.label_detection(image=image)
            labels = response.label_annotations
            objects = client.object_localization(image=image).localized_object_annotations

            for logo in logos:
                logolist.append(logo.description)
            for label in labels:
                labellist.append(label.description)
            for obj in objects:
                objectlist.append(obj.name)
            logolist2.append(logolist)
            labellist2.append(labellist)
            objectlist2.append(objectlist)
            dff=[]
            lck.acquire()
            dff = pd.DataFrame(list(zip(onlyfiles,logolist2,labellist2,objectlist2)),columns =['filename', 'logo','label','object'])
            df.append(dff,ignore_index=True)
            lck.release()

    df.to_csv(csvadd, index=False)

############image reading and divding data for threads#################
batch_folder='D:\\Projects\\VAT\\fakedetection\\keyframe\\ffmpeg-4.2.1-win64-static\\video'
onlyfiles = fnmatch.filter(os.listdir(batch_folder), '*.jpg')
countofimage=len(onlyfiles)
division=int(countofimage/4)
index1=[0,division]
index2=[division+1,division+division]
index3=[division+division+1,division+division+division]
index4=[division+division+division+1,division+division+division+division]
threadfile1=onlyfiles[index1[0]:index1[1]]
threadfile2=onlyfiles[index2[0]:index2[1]]
threadfile3=onlyfiles[index3[0]:index3[1]]
threadfile4=onlyfiles[index4[0]:index4[1]]

t1 = threading.Thread(target=vision, args=(threadfile1,))
t2 = threading.Thread(target=vision, args=(threadfile2,))
t3 = threading.Thread(target=vision, args=(threadfile3,))
t4 = threading.Thread(target=vision, args=(threadfile4,))

# starting thread 1
t1.start()
# starting thread 2
t2.start()
t3.start()
t4.start()

# wait until thread 1 is completely executed
t1.join()
# wait until thread 2 is completely executed
t2.join()
t3.join()
t4.join()
# both threads completely executed
print("Done!")

i tired lock and global df but the output is not coming from all threads in the file.if there is any improvement needed for this code which can process faster please suggest and help to write data coming from threads to a file
the code is working fine no error. i am just not just getting proper output


来源: stackexchange

问:
Run tab disappeared in Intellij
In one of my projects the Run tab on the bottom of the screen disappeared recently in IntelliJ Ultimate. When I run the project Services tab opens by default.

Run doesn't present in View -> Tool Windows neither.

If I open another project Run tab is there.

Any ideas how to make it back ?

答: As y.bedrov suggested in the comment to the question I checked Run/Debug Configurations and found in the list Spring Boot option. After I removed it Run tab came back.

ContentLicense: CC BY-SA 4.0

Title: Run tab disappeared in Intellij


问:
universal linking (deeplinking) for unity IOS
Has anyone worked with unity deeplinking. I am following all the documentation and able to trigger the application using urlschemes or universal links. But my unity application is not able to receive the intents.

I even tried Application.absoluteurl but it still returns empty.

Some help here please.

答:
What you need to do is enter the application’s URL which need to open from your app in info.plist under URLSchemes.

```<code>url.scheme = “com.myApp”
url.host = “profile”
parameters = [ “user” : “Joy” ]
</code>```

Then In appDelegate add this code:

```<code>func application(_ app: UIApplication, open url: URL,
options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
if let scheme = url.scheme,
scheme.localizedCaseInsensitiveCompare("com.myApp") == .orderedSame,
let view = url.host {

var parameters: [String: String] = [ : ]
URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems?.forEach {
parameters[$0.name] = $0.value
}

redirect(to: view, with: parameters)
}
return true
}
</code>```

Body:
What you need to do is enter the application’s URL which need to open from your app in info.plist under URLSchemes.

url.scheme = “com.myApp”
url.host = “profile”
parameters = [ “user” : “Joy” ]

Then In appDelegate add this code:

func application(_ app: UIApplication, open url: URL,
options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
if let scheme = url.scheme,
scheme.localizedCaseInsensitiveCompare("com.myApp") == .orderedSame,
let view = url.host {

var parameters: [String: String] = [ : ]
URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems?.forEach {
parameters[$0.name] = $0.value
}

redirect(to: view, with: parameters)
}
return true
}


问:
Can jsPDF do page breaks?
I am trying to implement the creation of a PDF document on the front end using jsPDF that is currently done on the back end using SSRS (SQL Server Reporting Service).

The issue is pagination. As near as I can tell there is no "easy" way to get jsPDF to break up an HTML document into pages based upon the size set in the jsPDF constructor.

Is there a way to do that? To take a pregenerated  HTML document and pass it along with a page size definition to jsPDF so that it will be able to break up the document into the appropriate number of pages of that size?

var doc = new jsPDF('p', 'in', [8.5, 11]);

```<code>doc.addHTML($('#pregeneratedModal'),
    function () {
        doc.save('Test.pdf');
    });
</code>```

This is not working for me, but is there a way to do the thing I describe above?

答:
Please use this.</p>

```<code>doc.addPage();
</code>```

Title: Can jsPDF do page breaks?

Body:
I am trying to implement the creation of a PDF document on the front end using jsPDF that is currently done on the back end using SSRS (SQL Server Reporting Service).

The issue is pagination. As near as I can tell there is no "easy" way to get jsPDF to break up an HTML document into pages based upon the size set in the jsPDF constructor.

Is there a way to do that? To take a pregenerated  HTML document and pass it along with a page size definition to jsPDF so that it will be able to break up the document into the appropriate number of pages of that size?

var doc = new jsPDF('p', 'in', [8.5, 11]);

doc.addHTML($('#pregeneratedModal'),
    function () {
        doc.save('Test.pdf');
    });

This is not working for me, but is there a way to do the thing I describe above?

Body:
Please use this.

doc.addPage();


问:
Round Down Decimal Places Javascript
I need a rounding down many many decimal places down, basically roundTo but supposedly rounding down at the spot. Example,

```<code>take the number, 1.087179939485353505
but to the fifth place, with roundTo of 6
roundTo(1.087179939485353505, 6) is 1.08718
</code>```

I need 1.08717 not 1.08718 in javascript.

```<code>var Variable = roundTo(Variable / 1000000000000000000, 6);
</code>```

Resolved
There seems to be no native javascript decimal rounding function that rounds down. One of two options are available.

Convert to string and manipulate the data that way (makes the most sense).

Utilize a number and multiply, floor then re-divide again for your number

答:
You could use regex to get 5 decimals

function roundTo(number) {
    var result= number.toString().match(/^\d+(\.\d{0,5})/)[0];
    console.log(result);
}

roundTo(1.087179939485353505);```

Title: Round Down Decimal Places Javascript

Body:
I need a rounding down many many decimal places down, basically roundTo but supposedly rounding down at the spot. Example,

take the number, 1.087179939485353505
but to the fifth place, with roundTo of 6
roundTo(1.087179939485353505, 6) is 1.08718

I need 1.08717 not 1.08718 in javascript.

var Variable = roundTo(Variable / 1000000000000000000, 6);

Resolved
There seems to be no native javascript decimal rounding function that rounds down. One of two options are available.

Convert to string and manipulate the data that way (makes the most sense).

Utilize a number and multiply, floor then re-divide again for your number


问:
Redux reducer limitation
I'm currently using React + Redux in my app. When my user login I make all calls to API to stock the data in different reducers.

I recently added a personalized picture that goes into that reducer in base64 format. With that change, if a user has 3/4 pictures if their is a reload, the application reducer where pictures are become empty, as if a limitation was touch.

How should I proceed? One call by webpage? One specific call for the picture page?

Thank you

答: Redux state will always be reset, after a refresh. If you want to persist something to stay there after a refresh, you need to use redux-persist, or sessionStorage/localStorage. If you want to make sure that the user info stays up to date, you could make the call, to fetch the user data, in the componendDidMount function of the root component (the app component that gets rendered for each page), so that it gets called after every refresh, on each page. </p>

Title: Redux reducer limitation


问:
Java 8 shows this error. Local variable itemList defined in an enclosing scope must be final or effectively final
I am writing the code using java 8 but I iterate a List and then find RestaurantOrderBook using category type. and put that List into a Map. it shows this error:

Local variable itemList defined in an enclosing scope must be final or effectively final

```<code>Query query = new Query();
String categ = category;
query.addCriteria(Criteria.where("restaurantId").is(restaurantId));

List<RestaurantOrderBook> itemList = new ArrayList<RestaurantOrderBook>();
itemList = mongoTemplate.find(query, RestaurantOrderBook.class);
System.out.println("size : " + itemList.size());
Map<String , List<RestaurantOrderBook>> map = new HashMap<String , List<RestaurantOrderBook>>();
        Arrays.asList("TakeAway", "Dining").forEach(e ->{

//Following line throws error:
List<RestaurantOrderBook> list  = itemList.stream().filter(a -> !a.getOrderType().isEmpty() && a.getOrderType().equals(e)).collect(Collectors.toList());
                map.put(e, list);
        });
</code>```

I have an another situation:

```<code>@Override
    public EventReportRewardsPoints eventReportRewardsPoints(String organizerId) {
        try{
            List<Event> listOfEvents = eventRepo.findByOrganizerId(organizerId);
            EventReportRewardsPoints eventTransReport = new EventReportRewardsPoints();
            Integer soldTics = 0;
            Double totalRevenue = 0d;
            Integer soldToday  = 0;

            Integer findTotalAvailableTics = 0;
            Integer findTotalQtytics = 0;

            for (Event event : listOfEvents) {
                List<EventTicket> eventTicket = eventTicketRepo.findByEventId(event.getId());

                Integer sumOfAvailabletics = eventTicket.stream()
                        .mapToInt(EventTicket::getRemainingTickets).sum();
                findTotalAvailableTics = findTotalAvailableTics + sumOfAvailabletics;

                Integer sumOfQtytics = eventTicket.stream().mapToInt(EventTicket::getQty).sum();
                findTotalQtytics  = findTotalQtytics + sumOfQtytics;

                List<EventTicketBook> listOfEventsTic = eventTicketBookRepository.findByEventId(event.getId());
                for (EventTicketBook eventTicketBook : listOfEventsTic) {
                    Double sumOfSales = eventTicketBook.getTickets().stream().mapToDouble(EventTicket::getPrice).sum();
                    totalRevenue = totalRevenue + sumOfSales;
                    Date now = new Date();
                    System.out.println("create date : " + eventTicketBook.getCreateOn());
                    /*if(now.compareTo(eventTicketBook.getCreateOn()) == 0){
                        Integer sumOfSoldToday = eventTicketBook.getTickets().stream().mapToInt(EventTicket::getQty).sum();
                        soldToday = soldToday + sumOfSoldToday;
                    }*/
                }
            }
            System.out.println("findTotalQtytics : " + findTotalQtytics);
            System.out.println("findTotalAvailableTics : " + findTotalAvailableTics);
            soldTics = findTotalQtytics - findTotalAvailableTics;
            eventTransReport.setTotalRevenue(totalRevenue);
            eventTransReport.setSoldToday(soldToday);
            eventTransReport.setTicketsSold(soldTics);
            return eventTransReport;
        }catch(Exception e ){
            e.printStackTrace();
        }
        return null;
    }
</code>```

How do i achive this using lamda expression.??

答:
As noted in the accepted answer by wumpz, the reason is that the variable being used has to be final or effectively final.

I would like to add the reason as to why it is so:

When we write a Lambda expression, we are effectively authoring an anonymous inner class. For Ex:

```<code>@FunctionalInterface
interface MyInterface{
    public void print();
}
</code>```

Used in our code as:

```<code>public static void main(String[] args) {
        int i = 6;

        new MyInterface() {
            @Override
            public void print() {
                System.out.println(++i); // Remove ++ to resolve error
            }
        }.print();
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am writing the code using java 8 but I iterate a List and then find RestaurantOrderBook using category type. and put that List into a Map. it shows this error:

Local variable itemList defined in an enclosing scope must be final or effectively final

Query query = new Query();
String categ = category;
query.addCriteria(Criteria.where("restaurantId").is(restaurantId));

List<RestaurantOrderBook> itemList = new ArrayList<RestaurantOrderBook>();
itemList = mongoTemplate.find(query, RestaurantOrderBook.class);
System.out.println("size : " + itemList.size());
Map<String , List<RestaurantOrderBook>> map = new HashMap<String , List<RestaurantOrderBook>>();
        Arrays.asList("TakeAway", "Dining").forEach(e ->{

//Following line throws error:
List<RestaurantOrderBook> list  = itemList.stream().filter(a -> !a.getOrderType().isEmpty() && a.getOrderType().equals(e)).collect(Collectors.toList());
                map.put(e, list);
        });

I have an another situation:

@Override
    public EventReportRewardsPoints eventReportRewardsPoints(String organizerId) {
        try{
            List<Event> listOfEvents = eventRepo.findByOrganizerId(organizerId);
            EventReportRewardsPoints eventTransReport = new EventReportRewardsPoints();
            Integer soldTics = 0;
            Double totalRevenue = 0d;
            Integer soldToday  = 0;

            Integer findTotalAvailableTics = 0;
            Integer findTotalQtytics = 0;

            for (Event event : listOfEvents) {
                List<EventTicket> eventTicket = eventTicketRepo.findByEventId(event.getId());

                Integer sumOfAvailabletics = eventTicket.stream()
                        .mapToInt(EventTicket::getRemainingTickets).sum();
                findTotalAvailableTics = findTotalAvailableTics + sumOfAvailabletics;

                Integer sumOfQtytics = eventTicket.stream().mapToInt(EventTicket::getQty).sum();
                findTotalQtytics  = findTotalQtytics + sumOfQtytics;

                List<EventTicketBook> listOfEventsTic = eventTicketBookRepository.findByEventId(event.getId());
                for (EventTicketBook eventTicketBook : listOfEventsTic) {
                    Double sumOfSales = eventTicketBook.getTickets().stream().mapToDouble(EventTicket::getPrice).sum();
                    totalRevenue = totalRevenue + sumOfSales;
                    Date now = new Date();
                    System.out.println("create date : " + eventTicketBook.getCreateOn());
                    /*if(now.compareTo(eventTicketBook.getCreateOn()) == 0){
                        Integer sumOfSoldToday = eventTicketBook.getTickets().stream().mapToInt(EventTicket::getQty).sum();
                        soldToday = soldToday + sumOfSoldToday;
                    }*/
                }
            }
            System.out.println("findTotalQtytics : " + findTotalQtytics);
            System.out.println("findTotalAvailableTics : " + findTotalAvailableTics);
            soldTics = findTotalQtytics - findTotalAvailableTics;
            eventTransReport.setTotalRevenue(totalRevenue);
            eventTransReport.setSoldToday(soldToday);
            eventTransReport.setTicketsSold(soldTics);
            return eventTransReport;
        }catch(Exception e ){
            e.printStackTrace();
        }
        return null;
    }

How do i achive this using lamda expression.??

Body:
As noted in the accepted answer by wumpz, the reason is that the variable being used has to be final or effectively final.

I would like to add the reason as to why it is so:

When we write a Lambda expression, we are effectively authoring an anonymous inner class. For Ex:

@FunctionalInterface
interface MyInterface{
    public void print();
}

Used in our code as:

public static void main(String[] args) {
        int i = 6;

        new MyInterface() {
            @Override
            public void print() {
                System.out.println(++i); // Remove ++ to resolve error
            }
        }.print();
    }


问:
Eclipse C++ build problem

I've just written a simple program in C++ in Eclipse on Ubuntu. But when I press Ctrl+B or select the build all button no binary file is build, and so when I try to run the project I receive the error message: Launch failed. binary not found.

what should I do?

thanx!

答: You'll have to manually configure the 'run configuration' you use to run the program to find the binary to execute. If there are no compilation errors, it should have created an executable somewhere.</p>

ContentLicense: CC BY-SA 2.5

Title: Eclipse C++ build problem


问:
Fastify schema validation multipart/form-data (body should be object)
Multipart form data file uplaod time comming error body should be object, and i am using ajv plugin also, still i am using same issue. below is my reference code.

app.js

```<code>const fastify = require('fastify')({
    logger: true
});

const Ajv = require('ajv');
const ajv = new Ajv({
    useDefaults: true,
    coerceTypes: true,
    $data: true,
    extendRefs: true
});

ajv.addKeyword("isFileType", {
    compile: (schema, parent, it) => {
        parent.type = "file";
        delete parent.isFileType;
        return () => true;
    },
});

fastify.setSchemaCompiler((schema) => ajv.compile(schema));
</code>```

routes.js

```<code>schema: {
    tags: [{
        name: 'Category'
    }],
    description: 'Post category data',
    consumes: ['multipart/form-data'],
    body: {
        type: 'object',
        isFileType: true,
        properties: {
            name: {
                type: 'string'
            },
            thumb_url: {
                isFileType: true,
                type: 'object'
            },
            img_url: {
                isFileType: true,
                type: 'object'
            },
            status: {
                type: 'number',
                enum: [0, 1],
                default: 1
            }
        },
        required: ['name', 'thumb_url', 'img_url']
    },
    response: {
        201: {
            type: 'object',
            properties: categoryProperties
        }
    }
}
</code>```

response

```<code>{
    "statusCode": 400,
    "error": "Bad Request",
    "message": "body should be object"
}
</code>```

I suspect the error is in the way I send the data, but I am having trouble figuring it out. I have read about this error and it seems to be generated when an object is passed to formData, but I am sending a string so I don't understand why it happens. thanks in advance!

答:
I think your configuration to manage multipart is wrong and the schema should be fixed as this working example:

const fastify = require('fastify')({ logger: true })

fastify.register(require('fastify-multipart'), {
  addToBody: true
})

const Ajv = require('ajv')
const ajv = new Ajv({
  useDefaults: true,
  coerceTypes: true,
  $data: true,
  extendRefs: true
})

ajv.addKeyword('isFileType', {
  compile: (schema, parent, it) => {
    parent.type = 'file'
    delete parent.isFileType
    return () => true
  }
})

fastify.setSchemaCompiler((schema) => ajv.compile(schema))

fastify.post('/', {
  schema: {
    tags: [{
      name: 'Category'
    }],
    description: 'Post category data',
    consumes: ['multipart/form-data'],
    body: {
      type: 'object',
      properties: {
        name: { type: 'string' },
        thumb_url: { isFileType: true },
        img_url: { isFileType: true },
        status: {
          type: 'number',
          enum: [0, 1],
          default: 1
        }
      },
      required: ['name', 'thumb_url', 'img_url']
    }
  }
}, async (req, reply) => {
  let filepath = path.join(__dirname, `${req.body.thumb_url[0].filename}-${Date.now()}`)
  await fs.writeFile(filepath, (req.body.thumb_url[0].data))

  filepath = path.join(__dirname, `${req.body.img_url[0].filename}-${Date.now()}`)
  await fs.writeFile(filepath, (req.body.img_url[0].data))

  return req.body
})

fastify.listen(3000)
```

<p>Call it with this request:</p>

```curl -X POST \
  http://127.0.0.1:3000/ \
  -H 'content-type: multipart/form-data' \
  -F 'thumb_url=@/home/wks/example-file' \
  -F 'img_url=@/home/wks/example-file' \
  -F 'name=fooo'
```

<p>You will get:</p>

```{
   "thumb_url":[
      {
         "data":{
            "type":"Buffer",
            "data":[
               97,
               115,
               100,
               10
            ]
         },
         "filename":"example-file",
         "encoding":"7bit",
         "mimetype":"application/octet-stream",
         "limit":false
      }
   ],
   "img_url":[
      {
         "data":{
            "type":"Buffer",
            "data":[
               97,
               115,
               100,
               10
            ]
         },
         "filename":"example-file",
         "encoding":"7bit",
         "mimetype":"application/octet-stream",
         "limit":false
      }
   ],
   "name":"foo",
   "status":1
}
```

Body:
Multipart form data file uplaod time comming error body should be object, and i am using ajv plugin also, still i am using same issue. below is my reference code.

app.js

const fastify = require('fastify')({
    logger: true
});

const Ajv = require('ajv');
const ajv = new Ajv({
    useDefaults: true,
    coerceTypes: true,
    $data: true,
    extendRefs: true
});

ajv.addKeyword("isFileType", {
    compile: (schema, parent, it) => {
        parent.type = "file";
        delete parent.isFileType;
        return () => true;
    },
});

fastify.setSchemaCompiler((schema) => ajv.compile(schema));

routes.js

schema: {
    tags: [{
        name: 'Category'
    }],
    description: 'Post category data',
    consumes: ['multipart/form-data'],
    body: {
        type: 'object',
        isFileType: true,
        properties: {
            name: {
                type: 'string'
            },
            thumb_url: {
                isFileType: true,
                type: 'object'
            },
            img_url: {
                isFileType: true,
                type: 'object'
            },
            status: {
                type: 'number',
                enum: [0, 1],
                default: 1
            }
        },
        required: ['name', 'thumb_url', 'img_url']
    },
    response: {
        201: {
            type: 'object',
            properties: categoryProperties
        }
    }
}

response

{
    "statusCode": 400,
    "error": "Bad Request",
    "message": "body should be object"
}

I suspect the error is in the way I send the data, but I am having trouble figuring it out. I have read about this error and it seems to be generated when an object is passed to formData, but I am sending a string so I don't understand why it happens. thanks in advance!

Body:
I think your configuration to manage multipart is wrong and the schema should be fixed as this working example:

const fastify = require('fastify')({ logger: true })

fastify.register(require('fastify-multipart'), {
  addToBody: true
})

const Ajv = require('ajv')
const ajv = new Ajv({
  useDefaults: true,
  coerceTypes: true,
  $data: true,
  extendRefs: true
})

ajv.addKeyword('isFileType', {
  compile: (schema, parent, it) => {
    parent.type = 'file'
    delete parent.isFileType
    return () => true
  }
})

fastify.setSchemaCompiler((schema) => ajv.compile(schema))

fastify.post('/', {
  schema: {
    tags: [{
      name: 'Category'
    }],
    description: 'Post category data',
    consumes: ['multipart/form-data'],
    body: {
      type: 'object',
      properties: {
        name: { type: 'string' },
        thumb_url: { isFileType: true },
        img_url: { isFileType: true },
        status: {
          type: 'number',
          enum: [0, 1],
          default: 1
        }
      },
      required: ['name', 'thumb_url', 'img_url']
    }
  }
}, async (req, reply) => {
  let filepath = path.join(__dirname, `${req.body.thumb_url[0].filename}-${Date.now()}`)
  await fs.writeFile(filepath, (req.body.thumb_url[0].data))

  filepath = path.join(__dirname, `${req.body.img_url[0].filename}-${Date.now()}`)
  await fs.writeFile(filepath, (req.body.img_url[0].data))

  return req.body
})

fastify.listen(3000)

Call it with this request:

curl -X POST \
  http://127.0.0.1:3000/ \
  -H 'content-type: multipart/form-data' \
  -F 'thumb_url=@/home/wks/example-file' \
  -F 'img_url=@/home/wks/example-file' \
  -F 'name=fooo'

You will get:

{
   "thumb_url":[
      {
         "data":{
            "type":"Buffer",
            "data":[
               97,
               115,
               100,
               10
            ]
         },
         "filename":"example-file",
         "encoding":"7bit",
         "mimetype":"application/octet-stream",
         "limit":false
      }
   ],
   "img_url":[
      {
         "data":{
            "type":"Buffer",
            "data":[
               97,
               115,
               100,
               10
            ]
         },
         "filename":"example-file",
         "encoding":"7bit",
         "mimetype":"application/octet-stream",
         "limit":false
      }
   ],
   "name":"foo",
   "status":1
}


问:
How to locate an element inside iFrame using Selenium and Python
This is the ifram source code:

```<code><iframe sandbox="allow-scripts allow-same-origin" class="credit-card-iframe mt1 u-full-width prl2-sm" src="https://paymentcc.nike.com/services/default?id=3f42d8c5-74ee-4d08-95aa-bb6ea4949f9f&ctx=checkout&language=en-GB&maskerEnabled=true" frameborder="0" scrolling="no" xpath="1"></iframe>
</code>```

This is the element i want;

```<code><input maxlength="20" class="mod-ncss-input ncss-input pt2-sm pr4-sm pb2-sm pl4-sm" id="creditCardNumber" onautocomplete="off" value="" type="tel" tabindex="0" data-shortname="cc">
</code>```

This is my code:

```<code>browser.switch_to.frame(browser.find_element_by_xpath("//iframe[@class='credit-card-iframe mt1 u-full-width prl2-sm']"))
browser.implicitly_wait(10)
card = browser.find_element_by_xpath("//input[@id='creditCardNumber']")
card.send_keys("35663565444")
</code>```

This is the error:

```<code>selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//input[@id='creditCardNumber']"}
</code>```

Also if I have to scroll on a page to see something can the element still be picked up thanks.

答:
As the the desired element is within an  so to invoke click() on the element you have to:

Induce WebDriverWait for the desired frame to be available and switch to it.

Induce WebDriverWait for the desired element to be clickable.

You can use the following  Locator Strategies::

Using XPATH:

```<code>WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@sandbox='allow-scripts allow-same-origin' and contains(@class, 'credit-card-iframe')]")))
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//input[@id='creditCardNumber' and @data-shortname='cc']"))).send_keys("35663565444")
</code>```

Note : You have to add the following imports :

```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
</code>```

Reference

You can find a relevant discussion in:

Ways to deal with #document under iframe

Body:
This is the ifram source code:

This is the element i want;

<input maxlength="20" class="mod-ncss-input ncss-input pt2-sm pr4-sm pb2-sm pl4-sm" id="creditCardNumber" onautocomplete="off" value="" type="tel" tabindex="0" data-shortname="cc">

This is my code:

browser.switch_to.frame(browser.find_element_by_xpath("//iframe[@class='credit-card-iframe mt1 u-full-width prl2-sm']"))
browser.implicitly_wait(10)
card = browser.find_element_by_xpath("//input[@id='creditCardNumber']")
card.send_keys("35663565444")

This is the error:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//input[@id='creditCardNumber']"}

Also if I have to scroll on a page to see something can the element still be picked up thanks.

Body:
As the the desired element is within an <iframe> so to invoke click() on the element you have to:

Induce WebDriverWait for the desired frame to be available and switch to it.

Induce WebDriverWait for the desired element to be clickable.

You can use the following  Locator Strategies::

Using XPATH:

WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@sandbox='allow-scripts allow-same-origin' and contains(@class, 'credit-card-iframe')]")))
WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//input[@id='creditCardNumber' and @data-shortname='cc']"))).send_keys("35663565444")

Note : You have to add the following imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

Reference

You can find a relevant discussion in:

Ways to deal with #document under iframe


问:
Display data based on the value of the key
I have one column(Date) in the table which has some icons and text coming from a dictionary. the table looks like as shown in the below picture. the key 'date' has values of font awesome icon class and normal date string. so i am struggling to get a way to implement date column. here the advantage is i can modify dictionary however i want like i can add, delete or changing the key value pairs to achieve the goal. Thanks in advance.

stackblitz link

 data = [
    {
    'date':'fa-refresh',
    'name':"Bengaluru",
    'entities': 14,
    'details':'Lorem Ipsum , Lorem Ipsum',
    'actions':'fa fa-envelope-o',
    'color':'text-primary'
},
{
  'date':'fa-refresh',
  'name':"Hyderabad",
  'entities': 17,
  'details':'Lorem Ipsum,Lorem Ipsum, Ipsum',
  'actions':'fa fa-envelope-o',
  'color':'text-primary'

},
{
  'date':'Nov 4',
  'name':"Mumbai",
  'entities': 20,
  'details':'Lorem Ipsum,Lorem ,Lorem Ipsum',
  'actions':'fa fa-envelope-o,fa fa-share-alt,fa fa-trash-o,fa fa-pencil'

},
{
  'date':'Nov 5',
  'name':"Kerala",
  'entities': 10,
  'details':'Lorem ,Lorem Ipsum,Lorem Ipsum',
  'actions':'fa fa-envelope-o,fa fa-share-alt,fa fa-trash-o,fa fa-pencil'

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>      <table class="table table-hover">
        <tr>
          <th class="text">Date</th>
          <th class="text">List Name</th>
          <th class="text">No. of Entities</th>
          <th class="text">Actions</th>
          <th class="text"></th>

        </tr>
        <tbody>
          <tr *ngFor="let items of data | filter: search">
            <td class="text-dark font-weight-bold"> {{items.date}}</td>
            <td  class=" font-weight-bold tablename {{items.color}}">{{ items.name }}</td>
            <td  class="text-dark font-weight-bold">{{ items.entities }}</td>

            <td>
              <span *ngFor="let x of items.actions.split(',')">
                  <i class="{{x}} tableicons"></i>
              </span>
          </td>            <td>
              <button type="button" class="btn btn-outline-secondary" (click)="getdetails(items)">
                Details
              </button>
            </td>
          </tr>
        </tbody>
      </table></code>```

答:
You could change your first td like,

```<code><td class="text-dark font-weight-bold">
    <span *ngIf="items.date.startsWith('fa-')">
       <i [ngClass]="'fa '+items.date"> </i>
    </span>
    <span *ngIf="!items.date.startsWith('fa-')">
       {{items.date}}
    </span>
</td>
</code>```

Conditionally, the font-awesome-icon will be rendered if the date key has value starts with fa- else the date will be displayed..

Forked stackblitz here ...

Body:
I have one column(Date) in the table which has some icons and text coming from a dictionary. the table looks like as shown in the below picture. the key 'date' has values of font awesome icon class and normal date string. so i am struggling to get a way to implement date column. here the advantage is i can modify dictionary however i want like i can add, delete or changing the key value pairs to achieve the goal. Thanks in advance.

stackblitz link

 data = [
    {
    'date':'fa-refresh',
    'name':"Bengaluru",
    'entities': 14,
    'details':'Lorem Ipsum , Lorem Ipsum',
    'actions':'fa fa-envelope-o',
    'color':'text-primary'
},
{
  'date':'fa-refresh',
  'name':"Hyderabad",
  'entities': 17,
  'details':'Lorem Ipsum,Lorem Ipsum, Ipsum',
  'actions':'fa fa-envelope-o',
  'color':'text-primary'

},
{
  'date':'Nov 4',
  'name':"Mumbai",
  'entities': 20,
  'details':'Lorem Ipsum,Lorem ,Lorem Ipsum',
  'actions':'fa fa-envelope-o,fa fa-share-alt,fa fa-trash-o,fa fa-pencil'

},
{
  'date':'Nov 5',
  'name':"Kerala",
  'entities': 10,
  'details':'Lorem ,Lorem Ipsum,Lorem Ipsum',
  'actions':'fa fa-envelope-o,fa fa-share-alt,fa fa-trash-o,fa fa-pencil'

}

          Date
          List Name
          No. of Entities
          Actions

             {{items.date}}
            {{ items.name }}
            {{ items.entities }}

              <button type="button" class="btn btn-outline-secondary" (click)="getdetails(items)">
                Details
              </button>

Body:
You could change your first td like,

<td class="text-dark font-weight-bold">
    <span *ngIf="items.date.startsWith('fa-')">
       <i [ngClass]="'fa '+items.date"> </i>
    </span>
    <span *ngIf="!items.date.startsWith('fa-')">
       {{items.date}}
    </span>
</td>

Conditionally, the font-awesome-icon will be rendered if the date key has value starts with fa- else the date will be displayed..

Forked stackblitz here ...


问:
how to make scrollable button in android
Hello i'm trying to make an equalizer for my app but i can't figure out how to make the buttons. I don't really know how to explain myself so here is a picture that reveals more than my words:

Do i need animations? Can you guys point me in the right direction?

Thanks in advance.

答: I think you mean a SeekBar. It's the JSlider of Android.</p>


问:
How to select elements from array in Julia matching predicate?
Julia appears to have a lot of Matlab like features.  I'd like to select from an array using a predicate.  In Matlab I can do this like:

```<code>>> a = 2:7 ;
>> a > 4

ans =

     0     0     0     1     1     1

>> a(a>4)

ans =

     5     6     7
</code>```

I found a kind of clunky seeming way to do part of this in Julia:

```<code>julia> a = 2:7
2:7

julia> [int(x > 3) for x in a]
6-element Array{Any,1}:
 0
 0
 1
 1
 1
 1
</code>```

(Using what wikipedia calls list comprehension).  I haven't figured out how to apply a set like this to select with in Julia, but may be barking up the wrong tree.  How would one do a predicate selection from an array in Julia?

答:
I'm currently using Julia 1.3.1 and some syntax has changed compared to earlier answers. To filter an array on multiple conditions I had to do:

```<code>x = range(0,1,length=100)
x[(x .> 0.4) .& (x .< 0.51)]
</code>```

note the '.&' needed to do the AND operator.

Body:
Julia appears to have a lot of Matlab like features.  I'd like to select from an array using a predicate.  In Matlab I can do this like:

>> a = 2:7 ;
>> a > 4

ans =

     0     0     0     1     1     1

>> a(a>4)

ans =

     5     6     7

I found a kind of clunky seeming way to do part of this in Julia:

julia> a = 2:7
2:7

julia> [int(x > 3) for x in a]
6-element Array{Any,1}:
 0
 0
 1
 1
 1
 1

(Using what wikipedia calls list comprehension).  I haven't figured out how to apply a set like this to select with in Julia, but may be barking up the wrong tree.  How would one do a predicate selection from an array in Julia?

Body:
I'm currently using Julia 1.3.1 and some syntax has changed compared to earlier answers. To filter an array on multiple conditions I had to do:

x = range(0,1,length=100)
x[(x .> 0.4) .& (x .< 0.51)]

note the '.&' needed to do the AND operator.


问:
Why is Vuex not detected after refresh page? (nuxt)
Vuex is not detected after refresh, but all data is output to the console. Also after refresh, some components behave incorrectly. For example, I use vee-validate and all the rules and fields I get from the back, after refresh the validation rules disappear, but the fields are displayed

Vuex works on all pages but after refresh only on the home page

stroe/index.js

```<code>export const state = () => ({});

const map = {
  ru: "ru",
  uk: "uk-ua"
};

export const getters = {
  lang(state) {
    return map[state.i18n.locale];
  }
};

export const mutations = {};

export const actions = {
  async nuxtServerInit({ state, dispatch }) {
    try {
      await dispatch('category/getCategories', {
      });
    } catch (err) {
      console.log('nuxt server init error', err);
    }
  }
};
</code>```

home page (everything works)

```<code><template>
  <div>
    <main class="home-page">
      <banner />
      <section class="home_page">
        <div class="container">
          <phone-pay />
          <card-pay />
          <categories :categories="categories" :services="services" />
          <main-banner />
        </div>
      </section>
    </main>
  </div>
</template>

<script>
import Banner from "@/components/Index/Banner";
import PhonePay from "@/components/Index/PhonePay";
import CardPay from "@/components/Index/CardPay";
import Categories from "@/components/Index/Categories";
import MainBanner from "@/components/Index/MainBanner";

export default {
  components: {
    Banner,
    PhonePay,
    CardPay,
    Categories,
    MainBanner
  },

  async asyncData({ store, app: { $api }, error, req }) {
    try {
      const {
        data: { data: categories, included: services }
      } = await $api.CategoryProvider.getPopularCategories({
        params: {
          include: "services"
        }
      });
      return {
        lang: store.getters.lang,
        categories,
        services
      };
    } catch (e) {
      console.log("error index", e);
      error({ statusCode: 404, message: "Page not found" });
    }
  }
};
</script>
</code>```

category (does not work)

```<code><template>
  <services-viewer :initial-services="initialServices" :category="category" :init-meta="initMeta" />
</template>
<script>
import ServicesViewer from "@/components/UI/ServicesViewer";

export default {
  components: {
    ServicesViewer
  },
  async asyncData({ store, route, error, app: { $api } }) {
    try {
      const {
        data: { data: initialServices, meta: initMeta }
      } = await $api.ServiceProvider.getServices({
        params: {
          "filter[category_slug]": route.params.id,
          include: "category"
          // "page[size]": serviceConfig.SERVICE_PAGINATION_PAGE_SIZE
        }
      });
      await store.dispatch("category/getCategories", {
        params: {}
      });

      const category = store.state.category.categories.find(
        ({ attributes: { slug } }) => slug === route.params.id
      );

      return {
        initialServices,
        category,
        initMeta
      };
    } catch (e) {
      const statusCode = e && e.statusCode ? e.statusCode : 404;
      error({ statusCode });
    }
  }
};
</script>
</code>```

答: I solved it. It was my mistake. I have a parallax plugin that works on the home page, but if you go to another page and refresh, the plugin starts and cannot find the item and breaks the page.</p>

Body:
Vuex is not detected after refresh, but all data is output to the console. Also after refresh, some components behave incorrectly. For example, I use vee-validate and all the rules and fields I get from the back, after refresh the validation rules disappear, but the fields are displayed

Vuex works on all pages but after refresh only on the home page

stroe/index.js

export const state = () => ({});

const map = {
  ru: "ru",
  uk: "uk-ua"
};

export const getters = {
  lang(state) {
    return map[state.i18n.locale];
  }
};

export const mutations = {};

export const actions = {
  async nuxtServerInit({ state, dispatch }) {
    try {
      await dispatch('category/getCategories', {
      });
    } catch (err) {
      console.log('nuxt server init error', err);
    }
  }
};

home page (everything works)

<template>

      <banner />

          <phone-pay />
          <card-pay />
          <categories :categories="categories" :services="services" />

</template>

category (does not work)

<template>
  <services-viewer :initial-services="initialServices" :category="category" :init-meta="initMeta" />
</template>


问:
Fishpig authentication not working on Magento 2
I'm in the process of installing Fishpig to my Magneto 2 installation via the composer. I'm on Magneto v 2.3.3 with Ubuntu 18 and PHP 7.3.14

Im following their installation guideline:

https://fishpig.co.uk/magento/wordpress-integration/root/installation/#composer

My problem is that it require authentication.

I followed the guidelines of Github and created my own personal access token to use as password. But no matter what value I use for the Username I stil get "Invalid credentials"
I have tried my Github username, my email, my magento 2 admin username. What am I missing?

https://help.github.com/en/github/authenticating-to-github/creating-a-personal-access-token-for-the-command-line

答:
fishpig/magento2-wordpress-integration-root is a premium extension offered by https://fishpig.co.uk/ and is retrieved from the private FishPig repo.

You can generate access details for this at https://fishpig.co.uk/downloads


问:
How can I debug System.DllNotFoundException when missing DLL is not reported?
I'm maintaining a small .NET application that loads a GeckoFX webview in a .NET shell. It works on the vast majority of machines but on one specific 64 bit Windows 7 machine it reports the following exception:

```<code>Description:
 Stopped working

Problem signature:
 Problem Event Name:   CLR20r3
 Problem Signature 01: monoclecatdesktop.exe
 Problem Signature 02: 1.0.0.0
 Problem Signature 03: 4db67550
 Problem Signature 04: Skybound.Gecko
 Problem Signature 05: 1.9.1.0
 Problem Signature 06: 4db625ff
 Problem Signature 07: 54
 Problem Signature 08: 87
 Problem Signature 09: System.DllNotFoundException
 OS Version:   6.1.7600.2.0.0.768.3
 Locale ID:    4105
</code>```

I tried using Dependency Walker to locate the missing DLL, but nothing jumped out at me. I am pretty new to Windows programming so I'm not sure where to begin debugging this. Any advice is appreciated!

答: If you can use process monitor. Put on a filter excluding everything but your process. Then look for results that aren't SUCCESS. </p>

Body:
I'm maintaining a small .NET application that loads a GeckoFX webview in a .NET shell. It works on the vast majority of machines but on one specific 64 bit Windows 7 machine it reports the following exception:

Description:
 Stopped working

Problem signature:
 Problem Event Name:   CLR20r3
 Problem Signature 01: monoclecatdesktop.exe
 Problem Signature 02: 1.0.0.0
 Problem Signature 03: 4db67550
 Problem Signature 04: Skybound.Gecko
 Problem Signature 05: 1.9.1.0
 Problem Signature 06: 4db625ff
 Problem Signature 07: 54
 Problem Signature 08: 87
 Problem Signature 09: System.DllNotFoundException
 OS Version:   6.1.7600.2.0.0.768.3
 Locale ID:    4105

I tried using Dependency Walker to locate the missing DLL, but nothing jumped out at me. I am pretty new to Windows programming so I'm not sure where to begin debugging this. Any advice is appreciated!


问:
Git: Error on pushing local repo unrelated histories error

So me and my colleague were working on a project everything was working fine.

We both were working on the same github repository.

Now he made some changes on his local copy and didnt commit and went on a vacation.

And i made 2-3 commits on master branch.

Now when he came he made commit on his local repo but is unable to push on remote repository.

How to merge the changes made by us so that no ones changes gets lost

答: Git is preventing your colleague from pushing their changes without your changes since that would lose your changes. Your colleague needs to git pull --rebase the changes from origin/master into their local master, then resolve any conflicts if they’re present, then git push so their changes are on top of your changes.


问:
Close dropdown upon clicking another
I a working on a to make a reponsive dropdown navigation bar with vanilla JavaScript. In mobile view I want that upon click one dropdown the another should close. JavaScript here:

```<code>dropbtns.forEach(link => {
  link.addEventListener("click", function(e) {
    e.currentTarget.nextElementSibling.classList.toggle("showdd");
  });
});
</code>```

and show dropdown:

```<code>  .showdd {
    height: auto;
  }
</code>```

html code:

```<code><div class="nav-container">
    <div class="brand">
        <a href="#!">Logo</a>
    </div>
    <nav>
        <div class="nav-mobile"><a id="nav-toggle" href="#!"><span></span></a></div>
        <ul id="nav-list">
            <li>
                <a href="#!">Home</a>
            </li>
            <li>
                <a href="#!">About</a>
            </li>
            <li class="dropdown">
                <a href="#!" class='dropbtn'>Services <i class="fas fa-sort-down"></i></a>
                <ul class="nav-dropdown">
                    <li>
                        <a href="#!">Web Design</a>
                    </li>
                    <li>
                        <a href="#!">Web Development</a>
                    </li>
                    <li>
                        <a href="#!">Graphic Design</a>
                    </li>
                </ul>
            </li>
            <li>
                <a href="#!">Pricing</a>
            </li>
            <li class="dropdown">
                <a href="#!" class='dropbtn'>Portfolio <i class="fas fa-sort-down"></i></a>
                <ul class="nav-dropdown">
                    <li>
                        <a href="#!">Web Design</a>
                    </li>
                    <li>
                        <a href="#!">Web Development</a>
                    </li>
                    <li>
                        <a href="#!">Graphic Design</a>
                    </li>
                </ul>
            </li>
            <li>
                <a href="#!">Contact</a>
            </li>
        </ul>
    </nav>
</div>
</code>```

full code can be find here.

答:
It works on your Codepen after I edit the following line.

```<code>links.forEach(link => {
  link.addEventListener("click", function(e) {
    links.forEach(link => {
      link.nextElementSibling.classList.remove("showdd"); // Here
    });
    e.currentTarget.nextElementSibling.classList.toggle("show");
  });
});
</code>```

By the way, what is "showdd"?

Title: Close dropdown upon clicking another

Body:
I a working on a to make a reponsive dropdown navigation bar with vanilla JavaScript. In mobile view I want that upon click one dropdown the another should close. JavaScript here:

dropbtns.forEach(link => {
  link.addEventListener("click", function(e) {
    e.currentTarget.nextElementSibling.classList.toggle("showdd");
  });
});

and show dropdown:

  .showdd {
    height: auto;
  }

html code:

        Logo

                Home

                About

                Services

                        Web Design

                        Web Development

                        Graphic Design

                Pricing

                Portfolio

                        Web Design

                        Web Development

                        Graphic Design

                Contact

full code can be find here.

Body:
It works on your Codepen after I edit the following line.

links.forEach(link => {
  link.addEventListener("click", function(e) {
    links.forEach(link => {
      link.nextElementSibling.classList.remove("showdd"); // Here
    });
    e.currentTarget.nextElementSibling.classList.toggle("show");
  });
});

By the way, what is "showdd"?


问:
are there any boto3 + MFA examples out there?
I found an example for boto + MFA:

http://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_mfa_sample-code.html

But I cannot find an example of how to do it with boto3. Any equivalent boto3 examples?

Thanks!

答:
In addition to answers by Zoltan, and Fauxsys, this could be another way to create AWS client

import boto3

mfa_otp = raw_input("Enter the MFA code: ")

client = boto3.client('sts')

mfa_creds = client.get_session_token(
    DurationSeconds=36000,
    SerialNumber='<MFA serial number>',
    TokenCode=mfa_otp
)

boto3 \
    .client(service_name="<service name e.g. secretsmanager>",
            region_name='us-west-2',
            aws_access_key_id=mfa_creds['Credentials']['AccessKeyId'],
            aws_secret_access_key=mfa_creds['Credentials']['SecretAccessKey'],
            aws_session_token=mfa_creds['Credentials']['SessionToken'])

```

If you're not using MFA, you can omit those parts and it'll still work.

Body:
In addition to answers by Zoltan, and Fauxsys, this could be another way to create AWS client

import boto3

mfa_otp = raw_input("Enter the MFA code: ")

client = boto3.client('sts')

mfa_creds = client.get_session_token(
    DurationSeconds=36000,
    SerialNumber='<MFA serial number>',
    TokenCode=mfa_otp
)

boto3 \
    .client(service_name="<service name e.g. secretsmanager>",
            region_name='us-west-2',
            aws_access_key_id=mfa_creds['Credentials']['AccessKeyId'],
            aws_secret_access_key=mfa_creds['Credentials']['SecretAccessKey'],
            aws_session_token=mfa_creds['Credentials']['SessionToken'])

If you're not using MFA, you can omit those parts and it'll still work.


问:
How to update array data in main CPLEX
I am trying to create a model in CPLEX 12.10 using OPL.

What I have done until now is creating the model and writing the flow-control/main part to generate new models. I have a problem when it comes to updating the values in the new array (the dimension of the arrays increases at each iteration). I have the following parameters whose size depends on the value of 3 sets:

float Par1[Set1]=...;

float Par2[Set1][Set2]=...;

float Par3[Set1]=...;

float Par4[Set1][Set2][Set3]=...;

I have the following code in the flow-control part:

```<code>main {
    var mod = thisOplModel.modelDefinition;
    var dat = thisOplModel.dataElements;
    for (var sizenumSet1 = 2; sizenumSet1 <= 10; sizenumSet1 += 2) {
    for (var sizenumSet2 = 1; sizenumSet2 <= 5; sizenumSet2 +=1) {
      for (var sizenumSet3 = 1; sizenumSet3 <=5; sizenumSet3 +=1) {
        var MyCplex = new IloCplex();
        var opl = new IloOplModel(mod, MyCplex);
        dat.numSet1=sizenumSet1;
        dat.numSet2=sizenumSet2;
        dat.numSet3=sizenumSet3;
        opl.addDataSource(dat);
        opl.generate();
        for (var k in sizenumSet1){
            //random values for Par1[Set1]
            dat.Par1[k]= 10 + Opl.rand(100);
            writeln(Par1);
            //random values for Par2[Set1][Set2]
            for (var m in sizenumSet2){
                dat.Par2[k][m]= 1 + Opl.rand(5);
                writeln(Par2);
                    for (var j in sizenumSet3) {
                        //random values for Par4[Set1][Set2][Set3]
                        dat.Par4[k][m][j] = 1 + Opl.rand(10);
                        writeln(Par4);
            }
        }
            //random values for Par3[Set1]
            dat.Par3[k]= 1 + Opl.rand(5);
            writeln(Par3);
        }
        if (MyCplex.solve()) {
         writeln("Solution: ", MyCplex.getObjValue(),
        " / sizeSet1: ", sizenumSet1,
        " / sizeSet2: ", sizenumSet2,
        " / sizeSet3: ", sizenumSet3,
        " / time: ", MyCplex.getCplexTime());
        }
        opl.end();
        MyCplex.end();
        }
    }
    }
}
</code>```

Running this code I obtain the following error:

```<code>Scripting runtime error: Index out of bound for array "Par1", "toString".
</code>```

So I have two questions:

How do I solve this error?

How do I update values in Par1 according to the size of the sets?

Thank you

UPDATE WITH THE CODE:

sub.mod

```<code>//set
{int} subrow = ...;
{int} subcol = ...;
int y[subrow][subcol]=...;

//preprocessing
execute{
    writeln("y=",y);
}

//decisional variables
dvar float x;

//model
maximize x;
subject to {
  x<=sum(i in subrow, j in subcol) y[i][j];
}

//postprocessing
execute{
    writeln("x=",x);
}
</code>```

main.mod

```<code>{int} row={};
{int} col={};
int numrow = 2;
int numcol = 2;
int ar[1..numrow][1..numcol];

main {
  var source = new IloOplModelSource("sub.mod");
  var cplex = new IloCplex();
  var def = new IloOplModelDefinition(source);
  for (var dimrow=1; dimrow<=2; dimrow+=1){
    for (var dimcol=1; dimcol<=2; dimcol+=1){
        var opl = new IloOplModel(def,cplex);
        var data2 = new IloOplDataElements();
      for(var i=1; i<=dimrow; i+=1){
         for(var j=1; j<=dimcol; j+=1){
            data2.subrow = thisOplModel.row;
            data2.subrow.add(dimrow);
            data2.subcol = thisOplModel.col;
            data2.subcol.add(dimcol);
            data2.y = thisOplModel.ar;
            data2.y[i][j] = Opl.rand(10);
            }
        }
    }
  }
        opl.addDataSource(data2);
        opl.generate();
        if (cplex.solve()) {
            writeln("OBJ = " + cplex.getObjValue());
        } else {
            writeln("No solution");
        }
        data2.end();
        opl.end();
}
</code>```

In the end I always obtain a matrix of the dimensions declared in numrow = 2 and numcol = 2. I am not able to change the value. If I change it and it is not aligned with the ones in the "for" cyles, then I have an error (out of bound).

答:
you can grow the matrix as you like.
Let me update my example:

sub.mod

```<code>{int} row=...;
    {int} col=...;

int y[row][col]=...;

execute
{
  writeln("row=",row);
  writeln("col=",col);
//writeln("y=",y);
}

dvar float x;

maximize x;
subject to {
   x<=sum(i in row, j in col) y[i][j];
}

execute
{
writeln("x=",x);
}
</code>```

and then

```<code>{int} set1={};
{int} set2={};
int ar[1..11][1..11];

main {
  var source = new IloOplModelSource("sub.mod");
  var cplex = new IloCplex();
  var def = new IloOplModelDefinition(source);

  for(var k=1;k<=5;k++)
  {
  var opl = new IloOplModel(def,cplex);

  var data2= new IloOplDataElements();

data2.row=thisOplModel.set1;

data2.row.add(k+2);
data2.row.add(k+3);
data2.col=thisOplModel.set2;
if (k!=1) data2.col.remove(Opl.first(data2.col));
data2.col.add(2*k);
data2.col.add(2*k+1);
data2.y=thisOplModel.ar;
for(var a in data2.row) for(var b in data2.col) data2.y[a][b]=a+b;
  opl.addDataSource(data2);
  opl.generate();

  if (cplex.solve()) {
     writeln("OBJ = " + cplex.getObjValue());
  } else {
     writeln("No solution");
  }
data2.end();
 opl.end();

}

}
</code>```

and you get

```<code>row= {3 4}
col= {2 3}
OBJ = 24
row= {3 4 5}
col= {3 4 5}
OBJ = 72
row= {3 4 5 6}
col= {4 5 6 7}
OBJ = 160
row= {3 4 5 6 7}
col= {5 6 7 8 9}
OBJ = 300
row= {3 4 5 6 7 8}
col= {6 7 8 9 10 11}
OBJ = 504
</code>```

and you can see that the matrix is getting bigger and bigger

Title: How to update array data in main CPLEX

Body:
I am trying to create a model in CPLEX 12.10 using OPL.

What I have done until now is creating the model and writing the flow-control/main part to generate new models. I have a problem when it comes to updating the values in the new array (the dimension of the arrays increases at each iteration). I have the following parameters whose size depends on the value of 3 sets:

float Par1[Set1]=...;

float Par2[Set1][Set2]=...;

float Par3[Set1]=...;

float Par4[Set1][Set2][Set3]=...;

I have the following code in the flow-control part:

main {
    var mod = thisOplModel.modelDefinition;
    var dat = thisOplModel.dataElements;
    for (var sizenumSet1 = 2; sizenumSet1 <= 10; sizenumSet1 += 2) {
    for (var sizenumSet2 = 1; sizenumSet2 <= 5; sizenumSet2 +=1) {
      for (var sizenumSet3 = 1; sizenumSet3 <=5; sizenumSet3 +=1) {
        var MyCplex = new IloCplex();
        var opl = new IloOplModel(mod, MyCplex);
        dat.numSet1=sizenumSet1;
        dat.numSet2=sizenumSet2;
        dat.numSet3=sizenumSet3;
        opl.addDataSource(dat);
        opl.generate();
        for (var k in sizenumSet1){
            //random values for Par1[Set1]
            dat.Par1[k]= 10 + Opl.rand(100);
            writeln(Par1);
            //random values for Par2[Set1][Set2]
            for (var m in sizenumSet2){
                dat.Par2[k][m]= 1 + Opl.rand(5);
                writeln(Par2);
                    for (var j in sizenumSet3) {
                        //random values for Par4[Set1][Set2][Set3]
                        dat.Par4[k][m][j] = 1 + Opl.rand(10);
                        writeln(Par4);
            }
        }
            //random values for Par3[Set1]
            dat.Par3[k]= 1 + Opl.rand(5);
            writeln(Par3);
        }
        if (MyCplex.solve()) {
         writeln("Solution: ", MyCplex.getObjValue(),
        " / sizeSet1: ", sizenumSet1,
        " / sizeSet2: ", sizenumSet2,
        " / sizeSet3: ", sizenumSet3,
        " / time: ", MyCplex.getCplexTime());
        }
        opl.end();
        MyCplex.end();
        }
    }
    }
}

Running this code I obtain the following error:

Scripting runtime error: Index out of bound for array "Par1", "toString".

So I have two questions:

How do I solve this error?

How do I update values in Par1 according to the size of the sets?

Thank you

UPDATE WITH THE CODE:

sub.mod

//set
{int} subrow = ...;
{int} subcol = ...;
int y[subrow][subcol]=...;

//preprocessing
execute{
    writeln("y=",y);
}

//decisional variables
dvar float x;

//model
maximize x;
subject to {
  x<=sum(i in subrow, j in subcol) y[i][j];
}

//postprocessing
execute{
    writeln("x=",x);
}

main.mod

{int} row={};
{int} col={};
int numrow = 2;
int numcol = 2;
int ar[1..numrow][1..numcol];

main {
  var source = new IloOplModelSource("sub.mod");
  var cplex = new IloCplex();
  var def = new IloOplModelDefinition(source);
  for (var dimrow=1; dimrow<=2; dimrow+=1){
    for (var dimcol=1; dimcol<=2; dimcol+=1){
        var opl = new IloOplModel(def,cplex);
        var data2 = new IloOplDataElements();
      for(var i=1; i<=dimrow; i+=1){
         for(var j=1; j<=dimcol; j+=1){
            data2.subrow = thisOplModel.row;
            data2.subrow.add(dimrow);
            data2.subcol = thisOplModel.col;
            data2.subcol.add(dimcol);
            data2.y = thisOplModel.ar;
            data2.y[i][j] = Opl.rand(10);
            }
        }
    }
  }
        opl.addDataSource(data2);
        opl.generate();
        if (cplex.solve()) {
            writeln("OBJ = " + cplex.getObjValue());
        } else {
            writeln("No solution");
        }
        data2.end();
        opl.end();
}

In the end I always obtain a matrix of the dimensions declared in numrow = 2 and numcol = 2. I am not able to change the value. If I change it and it is not aligned with the ones in the "for" cyles, then I have an error (out of bound).

Body:
you can grow the matrix as you like.
Let me update my example:

sub.mod

{int} row=...;
    {int} col=...;

int y[row][col]=...;

execute
{
  writeln("row=",row);
  writeln("col=",col);
//writeln("y=",y);
}

dvar float x;

maximize x;
subject to {
   x<=sum(i in row, j in col) y[i][j];
}

execute
{
writeln("x=",x);
}

and then

{int} set1={};
{int} set2={};
int ar[1..11][1..11];

main {
  var source = new IloOplModelSource("sub.mod");
  var cplex = new IloCplex();
  var def = new IloOplModelDefinition(source);

  for(var k=1;k<=5;k++)
  {
  var opl = new IloOplModel(def,cplex);

  var data2= new IloOplDataElements();

data2.row=thisOplModel.set1;

data2.row.add(k+2);
data2.row.add(k+3);
data2.col=thisOplModel.set2;
if (k!=1) data2.col.remove(Opl.first(data2.col));
data2.col.add(2*k);
data2.col.add(2*k+1);
data2.y=thisOplModel.ar;
for(var a in data2.row) for(var b in data2.col) data2.y[a][b]=a+b;
  opl.addDataSource(data2);
  opl.generate();

  if (cplex.solve()) {
     writeln("OBJ = " + cplex.getObjValue());
  } else {
     writeln("No solution");
  }
data2.end();
 opl.end();

}

}

and you get

row= {3 4}
col= {2 3}
OBJ = 24
row= {3 4 5}
col= {3 4 5}
OBJ = 72
row= {3 4 5 6}
col= {4 5 6 7}
OBJ = 160
row= {3 4 5 6 7}
col= {5 6 7 8 9}
OBJ = 300
row= {3 4 5 6 7 8}
col= {6 7 8 9 10 11}
OBJ = 504

and you can see that the matrix is getting bigger and bigger


问:
How can I make ON UPDATE CURRENT TIMESTAMP optional?
When I append,

```<code>ON UPDATE CURRENT_TIMESTAMP
</code>```

I know the column will be updated when the row is updated.

Is there any way to make the clause optional?

I mean a way to update the column only when client didn't send the column value.

答:
Use trigger logic:

```<code>CREATE TRIGGER tr
BEFORE UPDATE
ON tablename
FOR EACH ROW
SET NEW.datetimefield = COALESCE(NEW.datetimefield, CURRENT_TIMESTAMP);
</code>```

Do not forget to remove ON UPDATE attribute from field definition.

Body:
When I append,

ON UPDATE CURRENT_TIMESTAMP

I know the column will be updated when the row is updated.

Is there any way to make the clause optional?

I mean a way to update the column only when client didn't send the column value.

Body:
Use trigger logic:

CREATE TRIGGER tr
BEFORE UPDATE
ON tablename
FOR EACH ROW
SET NEW.datetimefield = COALESCE(NEW.datetimefield, CURRENT_TIMESTAMP);

Do not forget to remove ON UPDATE attribute from field definition.


问:
C/C++: goto into the for loop
I have a bit unusual situation - I want to use goto statement to jump into the loop, not to jump out from it.

There are strong reasons to do so - this code must be part of some function which makes some calculations after the first call, returns with request for new data and needs one more call to continue. Function pointers (obvious solution) can't be used because we need interoperability with code which does not support function pointers.

I want to know whether code below is safe, i.e. it will be correctly compiled by all standard-compliant C/C++ compilers (we need both C and C++).

```<code>function foo(int not_a_first_call, int *data_to_request, ...other parameters... )
{
    if( not_a_first_call )
        goto request_handler;
    for(i=0; i<n; i++)
    {
        *data_to_request = i;
        return;
request_handler:
        ...process data...
    }
}
</code>```

I've studied standards, but there isn't much information about such use case. I also wonder whether replacing for by equivalent while will be beneficial from the portability point of view.

Thanks in advance.

UPD: Thanks to all who've commented!

to all commenters :) yes, I understand that I can't jump over initializers of local variables and that I have to save/restore i on each call.

about strong reasons :) This code must implement reverse communication interface. Reverse communication is a coding pattern which tries to avoid using function pointers. Sometimes it have to be used because of legacy code which expects that you will use it.

Unfortunately, r-comm-interface can't be implemented in a nice way. You can't use function pointers and you can't easily split work into several functions.

答:
Seems perfectly legal.

From a draft of the C99 standard http://std.dkuug.dk/JTC1/SC22/WG14/www/docs/n843.htm in the section on the goto statement:

```<code>[#3] EXAMPLE 1 It is sometimes convenient to jump  into  the
   middle  of  a  complicated set of statements.  The following
   outline presents one possible approach to a problem based on
   these three assumptions:

     1.  The  general initialization code accesses objects only
         visible to the current function.

     2.  The  general  initialization  code  is  too  large  to
         warrant duplication.

     3.  The  code  to  determine  the next operation is at the
         head of the loop.  (To  allow  it  to  be  reached  by
         continue statements, for example.)

           /* ... */
           goto first_time;
           for (;;) {
                   // determine next operation
                   /* ... */
                   if (need to reinitialize) {
                           // reinitialize-only code
                           /* ... */
                   first_time:
                           // general initialization code
                           /* ... */
                           continue;
                   }
                   // handle other operations
                   /* ... */
           }
</code>```

Next, we look at the for loop statement:

```<code>[#1]  Except for the behavior of a continue statement in the |
   loop body, the statement

           for ( clause-1 ; expr-2 ; expr-3 ) statement

   and the sequence of statements

           {
                   clause-1 ;
                   while ( expr-2 ) {
                           statement
                           expr-3 ;
                   }
           }
</code>```

Putting the two together with your problem tells you that you are jumping past

```<code>i=0;
</code>```

into the middle of a while loop. You will execute

```<code>...process data...
</code>```

and then

```<code>i++;
</code>```

before flow of control jumps to the test in the while/for loop

```<code>i<n;
</code>```

Title: C/C++: goto into the for loop

Body:
I have a bit unusual situation - I want to use goto statement to jump into the loop, not to jump out from it.

There are strong reasons to do so - this code must be part of some function which makes some calculations after the first call, returns with request for new data and needs one more call to continue. Function pointers (obvious solution) can't be used because we need interoperability with code which does not support function pointers.

I want to know whether code below is safe, i.e. it will be correctly compiled by all standard-compliant C/C++ compilers (we need both C and C++).

function foo(int not_a_first_call, int *data_to_request, ...other parameters... )
{
    if( not_a_first_call )
        goto request_handler;
    for(i=0; i<n; i++)
    {
        *data_to_request = i;
        return;
request_handler:
        ...process data...
    }
}

I've studied standards, but there isn't much information about such use case. I also wonder whether replacing for by equivalent while will be beneficial from the portability point of view.

Thanks in advance.

UPD: Thanks to all who've commented!

to all commenters :) yes, I understand that I can't jump over initializers of local variables and that I have to save/restore i on each call.

about strong reasons :) This code must implement reverse communication interface. Reverse communication is a coding pattern which tries to avoid using function pointers. Sometimes it have to be used because of legacy code which expects that you will use it.

Unfortunately, r-comm-interface can't be implemented in a nice way. You can't use function pointers and you can't easily split work into several functions.

Body:
Seems perfectly legal.

From a draft of the C99 standard http://std.dkuug.dk/JTC1/SC22/WG14/www/docs/n843.htm in the section on the goto statement:

[#3] EXAMPLE 1 It is sometimes convenient to jump  into  the
   middle  of  a  complicated set of statements.  The following
   outline presents one possible approach to a problem based on
   these three assumptions:

     1.  The  general initialization code accesses objects only
         visible to the current function.

     2.  The  general  initialization  code  is  too  large  to
         warrant duplication.

     3.  The  code  to  determine  the next operation is at the
         head of the loop.  (To  allow  it  to  be  reached  by
         continue statements, for example.)

           /* ... */
           goto first_time;
           for (;;) {
                   // determine next operation
                   /* ... */
                   if (need to reinitialize) {
                           // reinitialize-only code
                           /* ... */
                   first_time:
                           // general initialization code
                           /* ... */
                           continue;
                   }
                   // handle other operations
                   /* ... */
           }

Next, we look at the for loop statement:

[#1]  Except for the behavior of a continue statement in the |
   loop body, the statement

           for ( clause-1 ; expr-2 ; expr-3 ) statement

   and the sequence of statements

           {
                   clause-1 ;
                   while ( expr-2 ) {
                           statement
                           expr-3 ;
                   }
           }

Putting the two together with your problem tells you that you are jumping past

i=0;

into the middle of a while loop. You will execute

...process data...

and then

i++;

before flow of control jumps to the test in the while/for loop

i<n;


问:
Use value from one cell to define "coordinates" of another cell
I want to use the value of one cell, e.g. 3 to specifiy the coordinates of another cell.

This is what I tried:

```<code>Wert = Range("E22").Value
Sheets("Tabelle2").Range("A1:BWert").Copy
</code>```

答:
When cell coordinates are calculated you will find it more expedient to specify cells as `Cells([Row], [Column]) and define a range by its first and last cell. When you employ this syntax your task would be solved like this:-

```<code>With Sheets("Tabelle2")
    .Range(.Cells(1, 1), .Cells(Wert, 2)).Copy
End With
</code>```

The variation below is equivalent and perhaps easier to read for a beginner. However it is logically inconsistent because column letters can't be calculated.

```<code>With Sheets("Tabelle2")
    .Range(.Cells(1, "A), .Cells(Wert, "B")).Copy
End With
</code>```

Body:
I want to use the value of one cell, e.g. 3 to specifiy the coordinates of another cell.

This is what I tried:

Wert = Range("E22").Value
Sheets("Tabelle2").Range("A1:BWert").Copy

Body:
When cell coordinates are calculated you will find it more expedient to specify cells as `Cells([Row], [Column]) and define a range by its first and last cell. When you employ this syntax your task would be solved like this:-

With Sheets("Tabelle2")
    .Range(.Cells(1, 1), .Cells(Wert, 2)).Copy
End With

The variation below is equivalent and perhaps easier to read for a beginner. However it is logically inconsistent because column letters can't be calculated.

With Sheets("Tabelle2")
    .Range(.Cells(1, "A), .Cells(Wert, "B")).Copy
End With


问:
MongoDB $lookup not using index
I'm writing a query that requires a $lookup between two tables and as I understand it, it's essential that the foreignField have an index in order to perform this join in a timely fashion. However, even after adding an index on the field, the query is still falling back to COLLSCAN.

```<code>db.users.aggregate([
  {$lookup:{ from: "transactions", localField: '_id', foreignField: 'uid', as: 'transaction' }},
  { $match: { transaction: { "$size" : 0} } },
  { $count: "total"},
], { explain: true })
</code>```

This returns:

```<code>"queryPlanner" : {
    "plannerVersion" : 1,
    "namespace" : "test.users",
    "indexFilterSet" : false,
    "parsedQuery" : {

    },
    "winningPlan" : {
        "stage" : "COLLSCAN",
        "direction" : "forward"
    },
    "rejectedPlans" : [ ]
}
</code>```

As I mentioned, I do have the uid field indexed in the transactions collection:

```<code>> db.transactions.getIndexes()
[
    {
        "v" : 1,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_",
        "ns" : "test.transactions"
    },
    {
        "v" : 1,
        "key" : {
            "uid" : 1
        },
        "name" : "uid_1",
        "ns" : "test.transactions"
    }
]
</code>```

The query takes a few minutes to run in a DB of approximately 7M documents. I'm using MongoDB v3.4.7. Any idea as to what I could be doing wrong? Thanks in advance!

答:
Because your aggregation pipeline first stage has no $match or $sort
 or $geoNear query on indexed key and In $match stage you didn't query on any index key.

Case 1: If you do $match on indexed key in first stage, WinningPlan stage will be "FETCH" and stage of inputStage will be "IXSCAN"

```<code>"winningPlan" : {
    "stage" : "FETCH",
    "inputStage" : {
            "stage" : "IXSCAN",
        ...
    }
}
</code>```

Case 2: If you do $match on non-indexed key in first stage, WinningPlan stage will be "COLLSCAN"

```<code>"winningPlan" : {
    "stage" : "COLLSCAN"
}
</code>```

Case 3: If You do $match on index key after lookup (according to your query), WinningPlan stage will be "FETCH" and inputStage will be "IXSCAN".

Case 4: If You do $match on non-index key after lookup (just you did), WinningPlan stage will be "COLLSCAN".

For 7M record, you must use index in your queries. Don't do too much indexing, because they will stored in the RAM and you can't use $ne or $nin on indexed key properly.

Mongodb Docs: Optimizing Aggregation Pipeline

Mongodb Docs: Indexing Strategies

Title: MongoDB $lookup not using index

Body:
I'm writing a query that requires a $lookup between two tables and as I understand it, it's essential that the foreignField have an index in order to perform this join in a timely fashion. However, even after adding an index on the field, the query is still falling back to COLLSCAN.

db.users.aggregate([
  {$lookup:{ from: "transactions", localField: '_id', foreignField: 'uid', as: 'transaction' }},
  { $match: { transaction: { "$size" : 0} } },
  { $count: "total"},
], { explain: true })

This returns:

"queryPlanner" : {
    "plannerVersion" : 1,
    "namespace" : "test.users",
    "indexFilterSet" : false,
    "parsedQuery" : {

    },
    "winningPlan" : {
        "stage" : "COLLSCAN",
        "direction" : "forward"
    },
    "rejectedPlans" : [ ]
}

As I mentioned, I do have the uid field indexed in the transactions collection:

> db.transactions.getIndexes()
[
    {
        "v" : 1,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_",
        "ns" : "test.transactions"
    },
    {
        "v" : 1,
        "key" : {
            "uid" : 1
        },
        "name" : "uid_1",
        "ns" : "test.transactions"
    }
]

The query takes a few minutes to run in a DB of approximately 7M documents. I'm using MongoDB v3.4.7. Any idea as to what I could be doing wrong? Thanks in advance!

Body:
Because your aggregation pipeline first stage has no $match or $sort
 or $geoNear query on indexed key and In $match stage you didn't query on any index key.

Case 1: If you do $match on indexed key in first stage, WinningPlan stage will be "FETCH" and stage of inputStage will be "IXSCAN"

"winningPlan" : {
    "stage" : "FETCH",
    "inputStage" : {
            "stage" : "IXSCAN",
        ...
    }
}

Case 2: If you do $match on non-indexed key in first stage, WinningPlan stage will be "COLLSCAN"

"winningPlan" : {
    "stage" : "COLLSCAN"
}

Case 3: If You do $match on index key after lookup (according to your query), WinningPlan stage will be "FETCH" and inputStage will be "IXSCAN".

Case 4: If You do $match on non-index key after lookup (just you did), WinningPlan stage will be "COLLSCAN".

For 7M record, you must use index in your queries. Don't do too much indexing, because they will stored in the RAM and you can't use $ne or $nin on indexed key properly.

Mongodb Docs: Optimizing Aggregation Pipeline

Mongodb Docs: Indexing Strategies


问:
PHP push values into associative array
I can't find an answer to this anywhere.

```<code>foreach ($multiarr as $array) {
   foreach ($array as $key=>$val) {
      $newarray[$key] = $val;
   }
}
</code>```

say $key has duplicate names, so when I am trying to push into $newarray it actually looks like this:

```<code>$newarray['Fruit'] = 'Apples';
$newarray['Fruit'] = 'Bananas';
$newarray['Fruit'] = 'Oranges';
</code>```

The problem is, the above example just replaces the old value, instead of pushing into it.

Is it possible to push values like this?

答:
I'll offer an alternative to moonwave99's answer and explain how it is subtly different.

The following technique unpacks the indexed array of associative arrays and serves each subarray as a separate parameter to array_merge_recursive() which performs the merging "magic".

Code: (Demo)

```<code>$multiarr = [
    ['Fruit' => 'Apples'],
    ['Fruit' => 'Bananas'],
    ['Fruit' => 'Oranges'],
    ['Veg'   => 'Carrot'],
    //['Veg'   => 'Leek'],
];

var_export(
    array_merge_recursive(...$multiarr)
);
</code>```

As you recursively merge, if there is only one value for a respective key, then a subarray is not used, if there are multiple values for a key, then a subarray is used.

See this action by uncommenting the Leek element.

p.s.  If you know that you are only targetting a single column of data and you know the key that you are targetting, then array_column() would be a wise choice.

Code: (Demo)

```<code>var_export(
    ['Fruit' => array_column($multiarr, 'Fruit')]
);
</code>```

Title: PHP push values into associative array

Body:
I can't find an answer to this anywhere.

foreach ($multiarr as $array) {
   foreach ($array as $key=>$val) {
      $newarray[$key] = $val;
   }
}

say $key has duplicate names, so when I am trying to push into $newarray it actually looks like this:

$newarray['Fruit'] = 'Apples';
$newarray['Fruit'] = 'Bananas';
$newarray['Fruit'] = 'Oranges';

The problem is, the above example just replaces the old value, instead of pushing into it.

Is it possible to push values like this?

Body:
I'll offer an alternative to moonwave99's answer and explain how it is subtly different.

The following technique unpacks the indexed array of associative arrays and serves each subarray as a separate parameter to array_merge_recursive() which performs the merging "magic".

Code: (Demo)

$multiarr = [
    ['Fruit' => 'Apples'],
    ['Fruit' => 'Bananas'],
    ['Fruit' => 'Oranges'],
    ['Veg'   => 'Carrot'],
    //['Veg'   => 'Leek'],
];

var_export(
    array_merge_recursive(...$multiarr)
);

As you recursively merge, if there is only one value for a respective key, then a subarray is not used, if there are multiple values for a key, then a subarray is used.

See this action by uncommenting the Leek element.

p.s.  If you know that you are only targetting a single column of data and you know the key that you are targetting, then array_column() would be a wise choice.

Code: (Demo)

var_export(
    ['Fruit' => array_column($multiarr, 'Fruit')]
);


问:
ERROR in Cannot assign to a reference or variable
If I set full template type check

```<code>    {
        "compileOnSave": false,
        "compilerOptions": {
            ///...
            "target": "es6",
            "typeRoots": ["node_modules/@types"],
            "lib": ["es2018", "dom"],
        },
        "angularCompilerOptions": {
            "fullTemplateTypeCheck": true,
            "enableIvy": false
        }
    }
</code>```

I get this error:

ERROR in Cannot assign to a reference or variable

So how can I figure out where exactly the problem is?

i have a big project.

答:
Comments are not supported with JSON. Additionally, there is a syntax error with your code because of a wrong 'comma'.
Your code should be like that:</p>

```<code>{
    "compileOnSave": false,
    "compilerOptions": {
        "target": "es6",
        "typeRoots": ["node_modules/@types"],
        "lib": ["es2018", "dom"]
    },
    "angularCompilerOptions": {
        "fullTemplateTypeCheck": true,
        "enableIvy": false
    }
}
</code>```

Body:
If I set full template type check

    {
        "compileOnSave": false,
        "compilerOptions": {
            ///...
            "target": "es6",
            "typeRoots": ["node_modules/@types"],
            "lib": ["es2018", "dom"],
        },
        "angularCompilerOptions": {
            "fullTemplateTypeCheck": true,
            "enableIvy": false
        }
    }

I get this error:

ERROR in Cannot assign to a reference or variable

So how can I figure out where exactly the problem is?

i have a big project.

Body:
Comments are not supported with JSON. Additionally, there is a syntax error with your code because of a wrong 'comma'.
Your code should be like that:

{
    "compileOnSave": false,
    "compilerOptions": {
        "target": "es6",
        "typeRoots": ["node_modules/@types"],
        "lib": ["es2018", "dom"]
    },
    "angularCompilerOptions": {
        "fullTemplateTypeCheck": true,
        "enableIvy": false
    }
}


问:
Gradle: How to get rid of duplicate classes error
I am getting the following duplicate class error when I run my Android application (I didn't include all the errors, but the duplicate errors are all coming from org.apache.commons.lang3.* and org.apache.commons.logging.*):

```<code>Duplicate class org.apache.commons.lang3.AnnotationUtils found in modules commons-lang3-3.4.jar (org.apache.commons:commons-lang3:3.4) and commons-lang3-3.7.jar (commons-lang3-3.7.jar)
Duplicate class org.apache.commons.lang3.AnnotationUtils$1 found in modules commons-lang3-3.4.jar (org.apache.commons:commons-lang3:3.4) and commons-lang3-3.7.jar (commons-lang3-3.7.jar)
...........
Duplicate class org.apache.commons.logging.impl.WeakHashtable found in modules commons-logging-1.2.jar (commons-logging-1.2.jar) and commons-logging-1.2.jar (commons-logging:commons-logging:1.2)
Duplicate class org.apache.commons.logging.impl.WeakHashtable$1 found in modules commons-logging-1.2.jar (commons-logging-1.2.jar) and commons-logging-1.2.jar (commons-logging:commons-logging:1.2)
Duplicate class org.apache.commons.logging.impl.WeakHashtable$Entry found in modules commons-logging-1.2.jar (commons-logging-1.2.jar) and commons-logging-1.2.jar (commons-logging:commons-logging:1.2)
Duplicate class org.apache.commons.logging.impl.WeakHashtable$Referenced found in modules commons-logging-1.2.jar (commons-logging-1.2.jar) and commons-logging-1.2.jar (commons-logging:commons-logging:1.2)
Duplicate class org.apache.commons.logging.impl.WeakHashtable$WeakKey found in modules commons-logging-1.2.jar (commons-logging-1.2.jar) and commons-logging-1.2.jar (commons-logging:commons-logging:1.2)
</code>```

The error stems from this line of code in the gradle (I need to use the docx4j library because my app has to read in the contents of MS Word files selected by the user):

```<code>implementation "org.docx4j:docx4j:3.3.0"
</code>```

Below is the complete code of my gradle file:

```<code>apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "com.example.diffchecker"
        minSdkVersion 21
        targetSdkVersion 29
        multiDexEnabled true
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'io.github.java-diff-utils:java-diff-utils:4.5'
    // For developers using AndroidX in their applications
    implementation 'pub.devrel:easypermissions:3.0.0'
    // For developers using the Android Support Library
    implementation 'pub.devrel:easypermissions:2.0.1'
    implementation 'com.google.android.gms:play-services-ads:18.3.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation files('libs/commons-text-1.2.jar')
    //Thanks for using https://jar-download.com
    implementation 'org.webjars.bowergithub.telecomsante:pdf-viewer:2.2.0'
    implementation 'com.tom_roush:pdfbox-android:1.8.10.1'
    implementation 'com.bskim:maxheightscrollview:1.0.0@aar'
    implementation 'androidx.gridlayout:gridlayout:1.0.0'

    implementation files('libs/commons-logging-1.2.jar')
    implementation files('libs/commons-lang3-3.7.jar')

    // Docx4j is the library used to read Word documents
    // https://mvnrepository.com/artifact/org.docx4j/docx4j
    implementation "org.docx4j:docx4j:3.3.0"
}
</code>```

How do I use the docx4j library in my gradle without running into duplicate conflicts with the commons-lang3 and commons-logging libraries?

答:
I think I found a similar way of what we did at the beginning but this time with both exclusions.

Try this:

```<code>implementation ('org.docx4j:docx4j:3.3.0') {
    ['org.apache.commons','commons-logging'].each {
        exclude group: "$it"
    }
}
</code>```

Body:
I am getting the following duplicate class error when I run my Android application (I didn't include all the errors, but the duplicate errors are all coming from org.apache.commons.lang3.* and org.apache.commons.logging.*):

Duplicate class org.apache.commons.lang3.AnnotationUtils found in modules commons-lang3-3.4.jar (org.apache.commons:commons-lang3:3.4) and commons-lang3-3.7.jar (commons-lang3-3.7.jar)
Duplicate class org.apache.commons.lang3.AnnotationUtils$1 found in modules commons-lang3-3.4.jar (org.apache.commons:commons-lang3:3.4) and commons-lang3-3.7.jar (commons-lang3-3.7.jar)
...........
Duplicate class org.apache.commons.logging.impl.WeakHashtable found in modules commons-logging-1.2.jar (commons-logging-1.2.jar) and commons-logging-1.2.jar (commons-logging:commons-logging:1.2)
Duplicate class org.apache.commons.logging.impl.WeakHashtable$1 found in modules commons-logging-1.2.jar (commons-logging-1.2.jar) and commons-logging-1.2.jar (commons-logging:commons-logging:1.2)
Duplicate class org.apache.commons.logging.impl.WeakHashtable$Entry found in modules commons-logging-1.2.jar (commons-logging-1.2.jar) and commons-logging-1.2.jar (commons-logging:commons-logging:1.2)
Duplicate class org.apache.commons.logging.impl.WeakHashtable$Referenced found in modules commons-logging-1.2.jar (commons-logging-1.2.jar) and commons-logging-1.2.jar (commons-logging:commons-logging:1.2)
Duplicate class org.apache.commons.logging.impl.WeakHashtable$WeakKey found in modules commons-logging-1.2.jar (commons-logging-1.2.jar) and commons-logging-1.2.jar (commons-logging:commons-logging:1.2)

The error stems from this line of code in the gradle (I need to use the docx4j library because my app has to read in the contents of MS Word files selected by the user):

implementation "org.docx4j:docx4j:3.3.0"

Below is the complete code of my gradle file:

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "com.example.diffchecker"
        minSdkVersion 21
        targetSdkVersion 29
        multiDexEnabled true
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'io.github.java-diff-utils:java-diff-utils:4.5'
    // For developers using AndroidX in their applications
    implementation 'pub.devrel:easypermissions:3.0.0'
    // For developers using the Android Support Library
    implementation 'pub.devrel:easypermissions:2.0.1'
    implementation 'com.google.android.gms:play-services-ads:18.3.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation files('libs/commons-text-1.2.jar')
    //Thanks for using https://jar-download.com
    implementation 'org.webjars.bowergithub.telecomsante:pdf-viewer:2.2.0'
    implementation 'com.tom_roush:pdfbox-android:1.8.10.1'
    implementation 'com.bskim:maxheightscrollview:1.0.0@aar'
    implementation 'androidx.gridlayout:gridlayout:1.0.0'

    implementation files('libs/commons-logging-1.2.jar')
    implementation files('libs/commons-lang3-3.7.jar')

    // Docx4j is the library used to read Word documents
    // https://mvnrepository.com/artifact/org.docx4j/docx4j
    implementation "org.docx4j:docx4j:3.3.0"
}

How do I use the docx4j library in my gradle without running into duplicate conflicts with the commons-lang3 and commons-logging libraries?

Body:
I think I found a similar way of what we did at the beginning but this time with both exclusions.

Try this:

implementation ('org.docx4j:docx4j:3.3.0') {
    ['org.apache.commons','commons-logging'].each {
        exclude group: "$it"
    }
}


问:
How to do Verilog variable part select with % on both sides of colon?
I understand that for variable part select, there can't be a variable on both sides of the colon:

```<code>a_vect[ 8*i +: 8] // == a_vect[(8*i+7) : 8*i]
</code>```

However, I need to convert this code:

```<code>a_vect[(i*16+3)%64 : (i*16)%64]
</code>```

How do I deal with the "%64" on both sides of the colon?

Body:
I understand that for variable part select, there can't be a variable on both sides of the colon:

a_vect[ 8*i +: 8] // == a_vect[(8*i+7) : 8*i]

However, I need to convert this code:

a_vect[(i*16+3)%64 : (i*16)%64]

How do I deal with the "%64" on both sides of the colon?

Body:
a_vect[(i*16+3)%64 : (i*16)%64]

when elaborated

i=0 ==> a_vect[3:0]
i=1 ==> a_vect[19:16]
i=2 ==> a_vect[35:32]
i=3 ==> a_vect[51:48]
i=4 ==> a_vect[3:0]

u can use this type

  for(genvar i=0;i<64;i+16)
        a_vect[i+:4]


问:
Refactor jQuery $(this) into Vanila Js
I refactoring jQuery to Vanila JS, but i can't figure out how.

Let say i have the following jQuery code

```<code> $('#simple').find('.single').each(function(){
    // I want to refactor $(this) into Vanilla JS
    var txt = $(this).find('.text').text();
  })

</code>```

Let say i refactoring jQuery code into Vanilla Js but it does not work.

```<code> document.getElementById('simple').queryAll('.single').forEach(function(){
   // It does not work this line
   var txt = document.getElementById(this).find('.text').text();
  })
</code>```

What is the real syntax? what is the equivalent of $(this) in Vanilla Js?

答:
You can convert this Jquery code

```<code>$('#simple').find('.single').each(function(){
    // I want to refactor $(this) into Vanilla JS
    var txt = $(this).find('.text').text();
  })
</code>```

In vanilla js as follow

```<code>document.querySelectorAll('#simple .single').forEach(function(elm){
  var textElm = elm.querySelector('.text');
  var txt = textElm && textElm.innerText;
})
</code>```

I hope this will help you :)

Title: Refactor jQuery $(this) into Vanila Js

Body:
I refactoring jQuery to Vanila JS, but i can't figure out how.

Let say i have the following jQuery code

 $('#simple').find('.single').each(function(){
    // I want to refactor $(this) into Vanilla JS
    var txt = $(this).find('.text').text();
  })

Let say i refactoring jQuery code into Vanilla Js but it does not work.

 document.getElementById('simple').queryAll('.single').forEach(function(){
   // It does not work this line
   var txt = document.getElementById(this).find('.text').text();
  })

What is the real syntax? what is the equivalent of $(this) in Vanilla Js?

Body:
You can convert this Jquery code

$('#simple').find('.single').each(function(){
    // I want to refactor $(this) into Vanilla JS
    var txt = $(this).find('.text').text();
  })

In vanilla js as follow

document.querySelectorAll('#simple .single').forEach(function(elm){
  var textElm = elm.querySelector('.text');
  var txt = textElm && textElm.innerText;
})

I hope this will help you :)