问:
Relationships GraphQL
The second week I try to link two collections in the apollo-server-express / MongoDB / Mongoose / GraphQL stack, but I do not understand how. I found a similar lesson with the REST API, what I need is called Relationships. I need this, but in GraphQL

watch video

How to add cars to the User?
I collected the test server, the code is here: https://github.com/gHashTag/test-graphql-server
Help

答:
I have cloned your project and implemented some code and here what I changed to make relationship works. Note, I just did a basic code without validation or advance dataloader just to make sure non-complexity. Hope it can help.

src/graphql/resolvers/car-resolvers.js

```<code>import Car from '../../models/Car'
import User from '../../models/User'

export default {
  getCar: (_, { _id }) => Car.findById(_id),
  getCars: () => Car.find({}),
  getCarsByUser: (user, {}) =>  Car.find({seller: user._id }), // for relationship
  createCar: async (_, args) => {
    // Create new car
    return await Car.create(args)
  }
}
</code>```

src/graphql/resolvers/user-resolvers.js

```<code>import User from '../../models/User'

export default {
  getUser: (_, { _id }) => User.findById(_id),
  getUsers: () => User.find({}),
  getUserByCar: (car, args) => User.findById(car.seller), // for relationship
  createUser: (_, args) => {
    return User.create(args)
  }
}
</code>```

src/graphql/resolvers/index.js

```<code>import UserResolvers from './user-resolvers'
import CarResolvers from './car-resolvers'

export default {
  User:{
    cars: CarResolvers.getCarsByUser  // tricky part to link query relation ship between User and Car
  },
  Car:{
    seller: UserResolvers.getUserByCar  // tricky part to link query relation ship between User and Car
  },
  Query: {
    getUser: UserResolvers.getUser,
    getUsers: UserResolvers.getUsers,
    getCar: CarResolvers.getCar,
    getCars: CarResolvers.getCars
  },

  Mutation: {
    createUser: UserResolvers.createUser,
    createCar: CarResolvers.createCar,
  }
}
</code>```

src/graphql/schema.js

```<code>export default`
  type Status {
    message: String!
  }

  type User {
    _id: ID!
    firstName: String
    lastName: String
    email: String
    cars: [Car]
  }

  type Car {
    _id: ID
    make: String
    model: String
    year: String
    seller: User
  }

  type Query {
    getUser(_id: ID!): User
    getUsers: [User]
    getCar(_id: ID!): Car
    getCars: [Car]
  }

  type Mutation {
    createUser(firstName: String, lastName: String, email: String): User
    // change from _id to seller, due to base on logic _id conflict with CarId
    createCar(seller: ID!, make: String, model: String, year: String): Car
  }

  schema {
    query: Query
    mutation: Mutation
  }
`
</code>```

src/middlewares.js

```<code>import bodyParser from 'body-parser'
import { graphqlExpress, graphiqlExpress } from 'apollo-server-express'
import { makeExecutableSchema } from 'graphql-tools'

import typeDefs from '../graphql/schema'
import resolvers from '../graphql/resolvers'
import constants from './constants'

export const schema = makeExecutableSchema({
  typeDefs,
  resolvers
})

export default app => {

  app.use('/graphiql', graphiqlExpress({
    endpointURL: constants.GRAPHQL_PATH
  }))

  app.use(
    constants.GRAPHQL_PATH,
    bodyParser.json(),
    graphqlExpress(req => ({
      schema,
      context: {
        event: req.event
      }
    }))
  )
}
</code>```

Title: Relationships GraphQL

Body:
I have cloned your project and implemented some code and here what I changed to make relationship works. Note, I just did a basic code without validation or advance dataloader just to make sure non-complexity. Hope it can help.

src/graphql/resolvers/car-resolvers.js

import Car from '../../models/Car'
import User from '../../models/User'

export default {
  getCar: (_, { _id }) => Car.findById(_id),
  getCars: () => Car.find({}),
  getCarsByUser: (user, {}) =>  Car.find({seller: user._id }), // for relationship
  createCar: async (_, args) => {
    // Create new car
    return await Car.create(args)
  }
}

src/graphql/resolvers/user-resolvers.js

import User from '../../models/User'

export default {
  getUser: (_, { _id }) => User.findById(_id),
  getUsers: () => User.find({}),
  getUserByCar: (car, args) => User.findById(car.seller), // for relationship
  createUser: (_, args) => {
    return User.create(args)
  }
}

src/graphql/resolvers/index.js

import UserResolvers from './user-resolvers'
import CarResolvers from './car-resolvers'

export default {
  User:{
    cars: CarResolvers.getCarsByUser  // tricky part to link query relation ship between User and Car
  },
  Car:{
    seller: UserResolvers.getUserByCar  // tricky part to link query relation ship between User and Car
  },
  Query: {
    getUser: UserResolvers.getUser,
    getUsers: UserResolvers.getUsers,
    getCar: CarResolvers.getCar,
    getCars: CarResolvers.getCars
  },

  Mutation: {
    createUser: UserResolvers.createUser,
    createCar: CarResolvers.createCar,
  }
}

src/graphql/schema.js

export default`
  type Status {
    message: String!
  }

  type User {
    _id: ID!
    firstName: String
    lastName: String
    email: String
    cars: [Car]
  }

  type Car {
    _id: ID
    make: String
    model: String
    year: String
    seller: User
  }

  type Query {
    getUser(_id: ID!): User
    getUsers: [User]
    getCar(_id: ID!): Car
    getCars: [Car]
  }

  type Mutation {
    createUser(firstName: String, lastName: String, email: String): User
    // change from _id to seller, due to base on logic _id conflict with CarId
    createCar(seller: ID!, make: String, model: String, year: String): Car
  }

  schema {
    query: Query
    mutation: Mutation
  }
`

src/middlewares.js

import bodyParser from 'body-parser'
import { graphqlExpress, graphiqlExpress } from 'apollo-server-express'
import { makeExecutableSchema } from 'graphql-tools'

import typeDefs from '../graphql/schema'
import resolvers from '../graphql/resolvers'
import constants from './constants'

export const schema = makeExecutableSchema({
  typeDefs,
  resolvers
})

export default app => {

  app.use('/graphiql', graphiqlExpress({
    endpointURL: constants.GRAPHQL_PATH
  }))

  app.use(
    constants.GRAPHQL_PATH,
    bodyParser.json(),
    graphqlExpress(req => ({
      schema,
      context: {
        event: req.event
      }
    }))
  )
}


来源: stackexchange

问:
Make Voice Call and Video Call in android
I want to create an app used to make Voice Call and Video Call, but I don't know if this service will be free? and I am from Egypt
Any lesson will be appreciated,
Thanks in Advance.</p>

答: Alternate solution, A Complete SDK's & API for voice & video call. Visit this link</p>

ContentLicense: CC BY-SA 3.0


问:
building multiple project in visual studio
I have projects A,B in visual studio under the solution AB.
B is a static library with a simple method named "add" which is already declared with __declspec(dllexport)

and A is an application depending on B.

the build order is configured B -> A

B.lib is getting created properly but i am getting "error LNK2019: unresolved external symbol _add referenced in function _main"

I also referenced the B.lib's directory in Additional dependencies in A's Project settings page

Please let me know where i am making the mistake....

答:
sry got the solution to my problem...

C:\Documents and Settings\absasdf\My Documents\Visual Studio 2010\Projects\AB\Debug; added to Linker>General>Additional Library Directories

and

B.lib added to Linker>Input>Additional Dependencies

Now its working fine..

ContentLicense: CC BY-SA 2.5


问:
Laravel monthly count record
I want to create monthly statistics using Chartjs by Laravel.

```<code>$monthly_uploaded_product = DB::table('author_product')
         ->select(DB::raw('count(id) as total'), DB::raw('MONTH(created_at) as month'))
         ->groupBy('month')
         ->get();
</code>```

the result of query is:

```<code>[{"total":1,"month":10},{"total":17,"month":11}]
</code>```

the output of code should be like this to be represented in Javascript (Chartjs):

```<code>[0,0,0,0,0,0,0,0,0,1,17,0]
</code>```

I have wrote code to generate the array, but error Undefined offset: 1 :

```<code>$statistics_monthly_product = array();
foreach (range(1, 12) as $month) {
    foreach ($monthly_uploaded_product as $key) {
        if ($statistics_monthly_product[$month] == $key->month){
            $statistics_monthly_product[$month] = $key->total;
        }else{
            $statistics_monthly_product[$month] = 0;
        }
    }
}
</code>```

答:
The line $statistics_monthly_product = array(); creates a new array. Meaning that when you loop later on and try to do $statistics_monthly_product[$month] you are trying to access the index $month of an empty array. This will always give you the error of undefined index, since there is nothing in the array at all.

Perhaps you can initialize the array first with some default values:

$statistics_monthly_product = [0,0,0,0,0,0,0,0,0,0,0,0];

Title: Laravel monthly count record

Body:
I want to create monthly statistics using Chartjs by Laravel.

$monthly_uploaded_product = DB::table('author_product')
         ->select(DB::raw('count(id) as total'), DB::raw('MONTH(created_at) as month'))
         ->groupBy('month')
         ->get();

the result of query is:

[{"total":1,"month":10},{"total":17,"month":11}]

the output of code should be like this to be represented in Javascript (Chartjs):

[0,0,0,0,0,0,0,0,0,1,17,0]

I have wrote code to generate the array, but error Undefined offset: 1 :

$statistics_monthly_product = array();
foreach (range(1, 12) as $month) {
    foreach ($monthly_uploaded_product as $key) {
        if ($statistics_monthly_product[$month] == $key->month){
            $statistics_monthly_product[$month] = $key->total;
        }else{
            $statistics_monthly_product[$month] = 0;
        }
    }
}


问:
Print qr code in Java
I would really appreciate if you can help me with this little problem I`ve had for a while now.

The thing is that when i print a pdf wich contains a qr code, the qr code is not shown in the printed document, it just shows a blank space.
Please, I hope you can help me...Here is the code I`m using:

```<code>package utilities;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.print.Book;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;

import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;
import com.sun.pdfview.PDFRenderer;
import static java.awt.print.Printable.NO_SUCH_PAGE;
import static java.awt.print.Printable.PAGE_EXISTS;

/**
 * Converts the PDF content into printable format
 */
public class PrintPdf2 {

    private PrinterJob pjob = null;

    public static void main(String[] args) throws IOException, PrinterException {
                String ruta="C:\\examplePDF.pdf";
        System.out.println("Printing: " + ruta);
        // Create a PDFFile from a File reference
        FileInputStream fis = new FileInputStream(ruta);
        PrintPdf2 printPDFFile = new PrintPdf2(fis, "Test Print PDF");
        printPDFFile.print();
    }

    public PrintPdf2(InputStream inputStream, String jobName) throws IOException, PrinterException {
        byte[] pdfContent = new byte[inputStream.available()];
        inputStream.read(pdfContent, 0, inputStream.available());
        initialize(pdfContent, jobName);
    }

    public PrintPdf2(byte[] content, String jobName) throws IOException, PrinterException {
        initialize(content, jobName);
    }

    private void initialize(byte[] pdfContent, String jobName) throws IOException, PrinterException {
        ByteBuffer bb = ByteBuffer.wrap(pdfContent);
        // Create PDF Print Page
        PDFFile pdfFile = new PDFFile(bb);
        PDFPrintPage pages = new PDFPrintPage(pdfFile);

        // Create Print Job
        pjob = PrinterJob.getPrinterJob();
        PageFormat pf = PrinterJob.getPrinterJob().defaultPage();
        pjob.setJobName(jobName);
        Book book = new Book();
        book.append(pages, pf, pdfFile.getNumPages());
        pjob.setPageable(book);

        // to remove margins
        Paper paper = new Paper();
        paper.setImageableArea(0, 0, paper.getWidth(), paper.getHeight());
        pf.setPaper(paper);
    }

    public void print() throws PrinterException {
        // Send print job to default printer
        pjob.print();
    }
}

/**
 * Class that actually converts the PDF file into Printable format
 */
class PDFPrintPage implements Printable {

    private PDFFile file;

    PDFPrintPage(PDFFile file) {
        this.file = file;
    }

    public int print(Graphics g, PageFormat format, int index) throws PrinterException {
        int pagenum = index + 1;
        if ((pagenum >= 1) && (pagenum <= file.getNumPages())) {
            Graphics2D g2 = (Graphics2D) g;
            PDFPage page = file.getPage(pagenum);

            // fit the PDFPage into the printing area
            Rectangle imageArea = new Rectangle((int) format.getImageableX(), (int) format.getImageableY(),
                    (int) format.getImageableWidth(), (int) format.getImageableHeight());
            g2.translate(0, 0);
            PDFRenderer pgs = new PDFRenderer(page, g2, imageArea, null, null);
            try {
                page.waitForFinish();
                pgs.run();
            } catch (InterruptedException ie) {
                // nothing to do
            }
            return PAGE_EXISTS;
        } else {
            return NO_SUCH_PAGE;
        }
    }
}
</code>```

Thanks in advance :)

答:
It's very simple also with the "itextpdf" library:</p>

```<code>private void print() throws DocumentException, IOException {
    com.itextpdf.text.Document pdfDocument = new com.itextpdf.text.Document(PageSize.A4);
    java.io.File pdfFile = new java.io.File("d:/qrCode.pdf");
    com.itextpdf.text.pdf.PdfWriter.getInstance(pdfDocument, new java.io.FileOutputStream(pdfFile));
    pdfDocument.open();

    com.itextpdf.text.pdf.PdfPTable qrCodeTable = new com.itextpdf.text.pdf.PdfPTable(new float[] { 1.0f });

    java.util.Map<com.itextpdf.text.pdf.qrcode.EncodeHintType, Object> hints = new java.util.HashMap<com.itextpdf.text.pdf.qrcode.EncodeHintType, Object>();
    hints.put(com.itextpdf.text.pdf.qrcode.EncodeHintType.CHARACTER_SET, "ISO-8859-1");
    com.itextpdf.text.pdf.BarcodeQRCode qrCode = new com.itextpdf.text.pdf.BarcodeQRCode("TEST CODE", 200, 200, hints);
    com.itextpdf.text.Image qrCodeImage = qrCode.getImage();

    qrCodeTable.addCell(qrCodeImage);
    pdfDocument.add(qrCodeTable);

    pdfDocument.close();
}
</code>```

Title: Print qr code in Java

Body:
I would really appreciate if you can help me with this little problem I`ve had for a while now.

The thing is that when i print a pdf wich contains a qr code, the qr code is not shown in the printed document, it just shows a blank space.
Please, I hope you can help me...Here is the code I`m using:

package utilities;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.print.Book;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;

import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;
import com.sun.pdfview.PDFRenderer;
import static java.awt.print.Printable.NO_SUCH_PAGE;
import static java.awt.print.Printable.PAGE_EXISTS;

/**
 * Converts the PDF content into printable format
 */
public class PrintPdf2 {

    private PrinterJob pjob = null;

    public static void main(String[] args) throws IOException, PrinterException {
                String ruta="C:\\examplePDF.pdf";
        System.out.println("Printing: " + ruta);
        // Create a PDFFile from a File reference
        FileInputStream fis = new FileInputStream(ruta);
        PrintPdf2 printPDFFile = new PrintPdf2(fis, "Test Print PDF");
        printPDFFile.print();
    }

    public PrintPdf2(InputStream inputStream, String jobName) throws IOException, PrinterException {
        byte[] pdfContent = new byte[inputStream.available()];
        inputStream.read(pdfContent, 0, inputStream.available());
        initialize(pdfContent, jobName);
    }

    public PrintPdf2(byte[] content, String jobName) throws IOException, PrinterException {
        initialize(content, jobName);
    }

    private void initialize(byte[] pdfContent, String jobName) throws IOException, PrinterException {
        ByteBuffer bb = ByteBuffer.wrap(pdfContent);
        // Create PDF Print Page
        PDFFile pdfFile = new PDFFile(bb);
        PDFPrintPage pages = new PDFPrintPage(pdfFile);

        // Create Print Job
        pjob = PrinterJob.getPrinterJob();
        PageFormat pf = PrinterJob.getPrinterJob().defaultPage();
        pjob.setJobName(jobName);
        Book book = new Book();
        book.append(pages, pf, pdfFile.getNumPages());
        pjob.setPageable(book);

        // to remove margins
        Paper paper = new Paper();
        paper.setImageableArea(0, 0, paper.getWidth(), paper.getHeight());
        pf.setPaper(paper);
    }

    public void print() throws PrinterException {
        // Send print job to default printer
        pjob.print();
    }
}

/**
 * Class that actually converts the PDF file into Printable format
 */
class PDFPrintPage implements Printable {

    private PDFFile file;

    PDFPrintPage(PDFFile file) {
        this.file = file;
    }

    public int print(Graphics g, PageFormat format, int index) throws PrinterException {
        int pagenum = index + 1;
        if ((pagenum >= 1) && (pagenum <= file.getNumPages())) {
            Graphics2D g2 = (Graphics2D) g;
            PDFPage page = file.getPage(pagenum);

            // fit the PDFPage into the printing area
            Rectangle imageArea = new Rectangle((int) format.getImageableX(), (int) format.getImageableY(),
                    (int) format.getImageableWidth(), (int) format.getImageableHeight());
            g2.translate(0, 0);
            PDFRenderer pgs = new PDFRenderer(page, g2, imageArea, null, null);
            try {
                page.waitForFinish();
                pgs.run();
            } catch (InterruptedException ie) {
                // nothing to do
            }
            return PAGE_EXISTS;
        } else {
            return NO_SUCH_PAGE;
        }
    }
}

Thanks in advance :)

Body:
It's very simple also with the "itextpdf" library:

private void print() throws DocumentException, IOException {
    com.itextpdf.text.Document pdfDocument = new com.itextpdf.text.Document(PageSize.A4);
    java.io.File pdfFile = new java.io.File("d:/qrCode.pdf");
    com.itextpdf.text.pdf.PdfWriter.getInstance(pdfDocument, new java.io.FileOutputStream(pdfFile));
    pdfDocument.open();

    com.itextpdf.text.pdf.PdfPTable qrCodeTable = new com.itextpdf.text.pdf.PdfPTable(new float[] { 1.0f });

    java.util.Map<com.itextpdf.text.pdf.qrcode.EncodeHintType, Object> hints = new java.util.HashMap<com.itextpdf.text.pdf.qrcode.EncodeHintType, Object>();
    hints.put(com.itextpdf.text.pdf.qrcode.EncodeHintType.CHARACTER_SET, "ISO-8859-1");
    com.itextpdf.text.pdf.BarcodeQRCode qrCode = new com.itextpdf.text.pdf.BarcodeQRCode("TEST CODE", 200, 200, hints);
    com.itextpdf.text.Image qrCodeImage = qrCode.getImage();

    qrCodeTable.addCell(qrCodeImage);
    pdfDocument.add(qrCodeTable);

    pdfDocument.close();
}


问:
Android client - Java Server and Tor traffic
I am trying to set up a java server and an Android client whose communication is via Tor. Using this pages instructions I have managed to do so, using a Java client. But when I am trying to use the client side code to Android project the app crashes. My android-client code is below.

MainActivity.java

```<code>public class MainActivity extends Activity {

private BootStrapper bootstrapper;

@SuppressWarnings("unchecked")
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
    bootstrapper = new BootStrapper();
    bootstrapper.execute();

}

 @Override

     public boolean onCreateOptionsMenu(Menu menu) {

             getMenuInflater().inflate(R.menu.main, menu);
             return true;
 }

 private class BootStrapper extends AsyncTask<Object, Object, Object> {

    @Override
    protected Object doInBackground(Object... params) {

    TcpipNetAddress remoteAddress = new TcpipNetAddress("localhost", 3000);
    NetLayer netLayer = NetFactory.getInstance().getNetLayerById(NetLayerIDs.TCPIP);
    netLayer.waitUntilReady();

    try {
        NetSocket netSocket = netLayer.createNetSocket(null, null, remoteAddress);
    } catch (IOException e) {

        e.printStackTrace();
    }
    return null;}

        }

    }
</code>```

I am having not errors in the server side but on the client side this is the output of the logCat

```<code>06-07 22:07:26.981: W/dalvikvm(2364): VFY: unable to resolve new-instance 2065 (Lorg/silvertunnel_ng/netlib/api/util/TcpipNetAddress;) in Lcom/example/hellotor/MainActivity$BootStrapper;
</code>```

答: Hello try not to use this library on android because it has overall problems with the memory. Consider to take a look at this library for android. it is new, functional and fully updated</p>

Body:
I am trying to set up a java server and an Android client whose communication is via Tor. Using this pages instructions I have managed to do so, using a Java client. But when I am trying to use the client side code to Android project the app crashes. My android-client code is below.

MainActivity.java

public class MainActivity extends Activity {

private BootStrapper bootstrapper;

@SuppressWarnings("unchecked")
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
    bootstrapper = new BootStrapper();
    bootstrapper.execute();

}

 @Override

     public boolean onCreateOptionsMenu(Menu menu) {

             getMenuInflater().inflate(R.menu.main, menu);
             return true;
 }

 private class BootStrapper extends AsyncTask<Object, Object, Object> {

    @Override
    protected Object doInBackground(Object... params) {

    TcpipNetAddress remoteAddress = new TcpipNetAddress("localhost", 3000);
    NetLayer netLayer = NetFactory.getInstance().getNetLayerById(NetLayerIDs.TCPIP);
    netLayer.waitUntilReady();

    try {
        NetSocket netSocket = netLayer.createNetSocket(null, null, remoteAddress);
    } catch (IOException e) {

        e.printStackTrace();
    }
    return null;}

        }

    }

I am having not errors in the server side but on the client side this is the output of the logCat

06-07 22:07:26.981: W/dalvikvm(2364): VFY: unable to resolve new-instance 2065 (Lorg/silvertunnel_ng/netlib/api/util/TcpipNetAddress;) in Lcom/example/hellotor/MainActivity$BootStrapper;


问:
how to pass id from url to post_save_redirect in urls.py
I have several objects in the database. Url to edit an object using the generic view looks like site.com/cases/edit/123/ where 123 is an id of the particular object. Consider the cases/url.py contents:

```<code>url(r'edit/(?P<object_id>\d{1,5})/$', update_object, { ... 'post_save_redirect': ???}, name = 'cases_edit'),
</code>```

where update_object is a generic view. How to construct the post_save_redirect to point to site.com/cases/edit/123/. My problem is, that I don't know how to pass the id of the object to redirect function. I tried something like:

```<code>'post_save_redirect': 'edit/(?P<object_id>\d{1,5})/'
'post_save_redirect': 'edit/' + str(object_id) + '/'
</code>```

but obviously none of these work. reverse function was suggested, but how to pass the particular id?

```<code>'post_save_redirect': reverse('cases_edit', kwargs = {'object_id': ???})
</code>```

{% url %} in the temple also requires passing the id of the particular object. The id can be passed via extra_context:

```<code>extra_context = {'object_id': ???}
</code>```

In all the cases the problem is to get object_id from the url.

regards

chriss

答:
In short what you need to do is wrap the update_object function.</p>

```<code>def update_object_wrapper(request, object_id, *args, **kwargs):
    redirect_to = reverse('your object edit url name', object_id)
    return update_object(request, object_id, post_save_redirect=redirect_to, *args, **kwargs)
</code>```

OwnerDisplayName: chriss

Body:
I have several objects in the database. Url to edit an object using the generic view looks like site.com/cases/edit/123/ where 123 is an id of the particular object. Consider the cases/url.py contents:

url(r'edit/(?P<object_id>\d{1,5})/$', update_object, { ... 'post_save_redirect': ???}, name = 'cases_edit'),

where update_object is a generic view. How to construct the post_save_redirect to point to site.com/cases/edit/123/. My problem is, that I don't know how to pass the id of the object to redirect function. I tried something like:

'post_save_redirect': 'edit/(?P<object_id>\d{1,5})/'
'post_save_redirect': 'edit/' + str(object_id) + '/'

but obviously none of these work. reverse function was suggested, but how to pass the particular id?

'post_save_redirect': reverse('cases_edit', kwargs = {'object_id': ???})

{% url %} in the temple also requires passing the id of the particular object. The id can be passed via extra_context:

extra_context = {'object_id': ???}

In all the cases the problem is to get object_id from the url.

regards

chriss

LastEditorDisplayName: chriss

Body:
In short what you need to do is wrap the update_object function.

def update_object_wrapper(request, object_id, *args, **kwargs):
    redirect_to = reverse('your object edit url name', object_id)
    return update_object(request, object_id, post_save_redirect=redirect_to, *args, **kwargs)


问:
.remove does not work out - jQuery
I am trying to remove an id, and .live is necessary, the code is below

```<code>$('.TS').live('click',function() {
    ("#"+$(this).attr('id')).remove();
});
</code>```

The error got from chrome

Uncaught TypeError: Object #first has no method 'remove'

I tried removeId, but the above error message.

Appreciate all help

Thanks
Jean

答:
You are calling the remove method on a string.  You should make a jQuery selection using this:

```<code>$('.TS').live('click',function() {
    $(this).remove();
});
</code>```

Title: .remove does not work out - jQuery

Body:
I am trying to remove an id, and .live is necessary, the code is below

$('.TS').live('click',function() {
    ("#"+$(this).attr('id')).remove();
});

The error got from chrome

Uncaught TypeError: Object #first has no method 'remove'

I tried removeId, but the above error message.

Appreciate all help

Thanks
Jean

Body:
You are calling the remove method on a string.  You should make a jQuery selection using this:

$('.TS').live('click',function() {
    $(this).remove();
});


问:
Install app via usb: The device is temporarily restricted
When I toggle on the install via USB in developer mode:

it will pop the toast message said that the device is temporarily restricted

then toggle off the settings.

Is there any solution for this?

I searched through all the way like turning off MIUI optimization but still does not work. I cannot debug my application by Android Studio in this way......

答: The Best what I found devices without mobile data in device is to SIGN_OUT from MI_Account in the device and Login Again -> Try to enable USB_Debugging(Security Setting)-> enable INSTALL_VIA_USB


问:
Why i cant join string with first value of dictionary?
I would like to ask that why cant i join the string with the first value of the dictionary?

```<code>Dictionary<string, int> d = new Dictionary<string, int>()
{
    {"cat", 0},
    {"dog", 1},
    {"llama", 2},
    {"iguana", 3}
};

string z = string.Join("Test_", d.Select(x => x.Value + "\n"));
</code>```

These are the value of Z now

```<code>0
Test_1
Test_2
Test_3
</code>```

答:
If you are in a clever mood, you can stream out all the characters using SelectMany (a string is also an IEnumerable<char>) and construct the concatenated string that way.

```<code>var z = new string( d.SelectMany( x => x.Value.ToString("Test_0\n")).ToArray());
</code>```

Body:
I would like to ask that why cant i join the string with the first value of the dictionary?

Dictionary<string, int> d = new Dictionary<string, int>()
{
    {"cat", 0},
    {"dog", 1},
    {"llama", 2},
    {"iguana", 3}
};

string z = string.Join("Test_", d.Select(x => x.Value + "\n"));

These are the value of Z now

0
Test_1
Test_2
Test_3

Body:
If you are in a clever mood, you can stream out all the characters using SelectMany (a string is also an IEnumerable<char>) and construct the concatenated string that way.

var z = new string( d.SelectMany( x => x.Value.ToString("Test_0\n")).ToArray());


问:
Hdfs to s3 Distcp - Access Keys
For copying the file from HDFS to S3 bucket I used the command

```<code>hadoop distcp -Dfs.s3a.access.key=ACCESS_KEY_HERE\
-Dfs.s3a.secret.key=SECRET_KEY_HERE /path/in/hdfs s3a:/BUCKET NAME
</code>```

But the access key and sectet key are visible here which are not secure .
Is there any method to provide credentials from file .
I dont want to edit config file ,which is one of the method I came across .

答:
Recent (2.8+) versions let you hide your credentials in a jceks file; there's some documentation on the Hadoop s3 page there. That way: no need to put any secrets on the command line at all; you just share them across the cluster and then, in the distcp command, set hadoop.security.credential.provider.path to the path, like jceks://hdfs@nn1.example.com:9001/user/backup/s3.jceks

Fan: if you are running in EC2, the IAM role credentials should be automatically picked up from the default chain of credential providers: after looking for the config options & env vars, it tries a GET of the EC2 http endpoint which serves up the session credentials. If that's not happening, make sure that com.amazonaws.auth.InstanceProfileCredentialsProvider is on the list of credential providers. It's a bit slower than the others (and can get throttled), so best to put near the end.

Title: Hdfs to s3 Distcp - Access Keys

Body:
For copying the file from HDFS to S3 bucket I used the command

hadoop distcp -Dfs.s3a.access.key=ACCESS_KEY_HERE\
-Dfs.s3a.secret.key=SECRET_KEY_HERE /path/in/hdfs s3a:/BUCKET NAME

But the access key and sectet key are visible here which are not secure .
Is there any method to provide credentials from file .
I dont want to edit config file ,which is one of the method I came across .


问:
Can I catch the value by using bourne shell script?
When I type some command in openwrt, the result is like this.

```<code>Security  Signal(%)     Mode
WPA2      86            on
WPA2      42            on
</code>```

In this result, I want to catch the signal value(86) in first column.
How can i catch the value by using bourne shell script?

Plus, luci.sys.call function is only used in cbi file for making Luci, isn't it?

答:
```<code>cat test|tail +2|tr -s '\s\t' ' '|cut -d' ' -f2
</code>```

tail +2 skips first line, then I am replacing spaces or tabs with single space and cut get second field.

output:

```<code>4
5
8
</code>```

input:

```<code>x   y   z
1   4   7
2   5   7
4   8   0
</code>```

Body:
When I type some command in openwrt, the result is like this.

Security  Signal(%)     Mode
WPA2      86            on
WPA2      42            on

In this result, I want to catch the signal value(86) in first column.
How can i catch the value by using bourne shell script?

Plus, luci.sys.call function is only used in cbi file for making Luci, isn't it?

Body:
cat test|tail +2|tr -s '\s\t' ' '|cut -d' ' -f2

tail +2 skips first line, then I am replacing spaces or tabs with single space and cut get second field.

output:

4
5
8

input:

x   y   z
1   4   7
2   5   7
4   8   0


问:
Unable to run commands in docker container using docker-compose
EDITED - Added folder structure

I'm trying to run a node.js app in a docker container using docker-compose, however, the container fails to run the specified command and exits.

I'm running docker-for-mac, version 17.09.0-ce-mac35 (19611)

This is my folder structure:

```<code>.
├── docker-compose.yml
├── backend/
│  ├── Dockerfile
│  ├── package.json
│  ├── (source files)
├── frontend/
│  ├── Dockerfile
│  ├── package.json
│  ├── (source files)
</code>```

This is my docker-compose file:

```<code>version: "3"
services:
  ihm-backend:
    environment:
      - NODE_ENV=development
    build: ./backend
    volumes:
      - ./backend:/src
    ports:
      - "3000:3000"
      - "9222:9222"
    working_dir: /src
    command:
      - "./node_modules/.bin/nodemon --watch ./ --inspect=0.0.0.0:9222 --nolazy ./app.js"
</code>```

And this is my Dockerfile:

```<code>FROM node:6-alpine

COPY ./package.json src/
COPY ./npm-shrinkwrap.json src/

RUN cd /src && npm install

COPY . /src

WORKDIR /src

CMD ["./bin/www"]
</code>```

Notice that the docker-compose file overrides the command.

When I run it, I get the following error:

```<code>Cannot start service ihm-backend: oci runtime error: container_linux.go:265:
starting container process caused "exec: \"./node_modules/.bin/nodemon --watch
./ --inspect=0.0.0.0:9222 --nolazy ./app.js\": stat ./node_modules/.bin/nodemon
--watch ./ --inspect=0.0.0.0:9222 --nolazy ./app.js: no such file or directory"
</code>```

I tried to play with the command a bit - when changing it to ls or pwd I got the expected output. However, once I try to use npm or anything from the file-system like ls ./node_modules, I get the same error. Also, if I just start the container into a shell, I'm able to run any command I want, including npm scripts

答:
I found the problem. Seems like there's an issue with having spaces in the command attribute of the docker-compose file. The solution was to split it down to an array like this:

```<code>version: "3"
services:
  ihm-backend:
    environment:
      - NODE_ENV=development
    build: ./backend
    volumes:
      - ./backend:/src
    ports:
      - "3000:3000"
      - "9222:9222"
    working_dir: /src
    command:
      - /src/node_modules/.bin/nodemon
      - --watch
      - ./
      - --inspect=0.0.0.0:9222
      - --nolazy
      - ./app.js
</code>```

Body:
EDITED - Added folder structure

I'm trying to run a node.js app in a docker container using docker-compose, however, the container fails to run the specified command and exits.

I'm running docker-for-mac, version 17.09.0-ce-mac35 (19611)

This is my folder structure:

.
├── docker-compose.yml
├── backend/
│  ├── Dockerfile
│  ├── package.json
│  ├── (source files)
├── frontend/
│  ├── Dockerfile
│  ├── package.json
│  ├── (source files)

This is my docker-compose file:

version: "3"
services:
  ihm-backend:
    environment:
      - NODE_ENV=development
    build: ./backend
    volumes:
      - ./backend:/src
    ports:
      - "3000:3000"
      - "9222:9222"
    working_dir: /src
    command:
      - "./node_modules/.bin/nodemon --watch ./ --inspect=0.0.0.0:9222 --nolazy ./app.js"

And this is my Dockerfile:

FROM node:6-alpine

COPY ./package.json src/
COPY ./npm-shrinkwrap.json src/

RUN cd /src && npm install

COPY . /src

WORKDIR /src

CMD ["./bin/www"]

Notice that the docker-compose file overrides the command.

When I run it, I get the following error:

Cannot start service ihm-backend: oci runtime error: container_linux.go:265:
starting container process caused "exec: \"./node_modules/.bin/nodemon --watch
./ --inspect=0.0.0.0:9222 --nolazy ./app.js\": stat ./node_modules/.bin/nodemon
--watch ./ --inspect=0.0.0.0:9222 --nolazy ./app.js: no such file or directory"

I tried to play with the command a bit - when changing it to ls or pwd I got the expected output. However, once I try to use npm or anything from the file-system like ls ./node_modules, I get the same error. Also, if I just start the container into a shell, I'm able to run any command I want, including npm scripts

Body:
I found the problem. Seems like there's an issue with having spaces in the command attribute of the docker-compose file. The solution was to split it down to an array like this:

version: "3"
services:
  ihm-backend:
    environment:
      - NODE_ENV=development
    build: ./backend
    volumes:
      - ./backend:/src
    ports:
      - "3000:3000"
      - "9222:9222"
    working_dir: /src
    command:
      - /src/node_modules/.bin/nodemon
      - --watch
      - ./
      - --inspect=0.0.0.0:9222
      - --nolazy
      - ./app.js


问:
Javascript property exist and scope
I try to create a few objects like this:

```<code>Object_level_1 = Ext.extend ( Ext.util.Observable, {
  PropA: null,
  ProbB: null,
  initComponent: function () {
    Object_level_1.superclass.initComponent.call ();
  },
  setValue: function ( name, value ) { // it will come as 'PropA', 45
    if ( this.hasOwnProperty ( name ) ) { // ' fixed base on dtan answer
       // here is a problem 1
       // how I can access correct property and set it up
       // problem 2
       // How I set up property value of right property by having variable name
       this.fireEvent ( 'Update_on_level_1' );
    }
  }
}

Object_level_2 = Ext.extend ( Object_level_1, {
  PropC: null,
  ProbD: null,
  initComponent: function () {
    Object_level_1.superclass.initComponent.call ();
  },
  setValue: function ( name, value ) { // it will come as 'PropA', 45 or 'PropC', 100
    Object_level_2.superclass.setValue ( name, value );
    if ( this.hasOwnProperty ( name ) ) { // ' fixed base on dtan answer
       // here is a problem 1 again
       // how I can access correct property and set it up
       // problem 2 again
       // How I set up property value of right property by having variable name
       this.fireEvent ( 'Update_on_level_2' );
    }
  }
}
</code>```

Does someone know the solution?

答:
Actually, I spotted errors in the code:

Always declare var when creating variables

When calling parent's method, use ClassName.superclass.methodName.call(this, arg1, arg2..). It's important to pass the this because it will change the scope of the called parent's method to the scope of current object. (You can remove the this in my following testing code to see the different outputs).

Normally I declare this.addEvents in initComponent before using the events. Not sure if it's necessary.

Here is my full testing codes with outputs:

```<code>var Obj1 = Ext.extend(Ext.util.Observable, {
    propA: null,
    propB: null,
    initComponent: function() {
        Obj1.superclass.initComponent.call(this);
    },
    setValue: function(name, value) {
        if (name in this) { //Used dtan suggestion
            this[name] = value;
            console.log(this.propA, this.propB, this.propC, this.propD);
        }else{
            console.log(name+" is not in Obj1");
        }
    }
});

var Obj2 = Ext.extend(Obj1, {
    propC: null,
    propD: null,
    initComponent: function() {
        Obj2.superclass.initComponent.call(this);
    },
    setValue: function(name, value) {
        Obj2.superclass.setValue.call(this, name, value);
    }
});

var obj1 = new Obj1();
var obj2 = new Obj2();
obj1.setValue('propA', '1a'); //1a null undefined undefined
obj1.setValue('propB', '1b'); //1a 1b undefined undefined
obj2.setValue('propC', '2c'); //null null 2c null
obj2.setValue('propD', '2d'); //null null 2c 2d
obj1.setValue('propA', '1a'); //1a 1b undefined undefined
obj1.setValue('propB', '1b'); //1a 1b undefined undefined
obj1.setValue('propC', '1c'); //propC is not in Obj1
obj1.setValue('propD', '1d'); //propD is not in Obj1
obj2.setValue('propA', '2a'); //2a null 2c 2d
obj2.setValue('propB', '2b'); //2a 2b 2c 2d
obj2.setValue('propC', '2c'); //2a 2b 2c 2d
obj2.setValue('propD', '2d'); //2a 2b 2c 2d
</code>```

Try to read how ExtJS developers write their code in the src folders. You will see the correct usages of Ext.extend

Title: Javascript property exist and scope

Body:
I try to create a few objects like this:

Object_level_1 = Ext.extend ( Ext.util.Observable, {
  PropA: null,
  ProbB: null,
  initComponent: function () {
    Object_level_1.superclass.initComponent.call ();
  },
  setValue: function ( name, value ) { // it will come as 'PropA', 45
    if ( this.hasOwnProperty ( name ) ) { // ' fixed base on dtan answer
       // here is a problem 1
       // how I can access correct property and set it up
       // problem 2
       // How I set up property value of right property by having variable name
       this.fireEvent ( 'Update_on_level_1' );
    }
  }
}

Object_level_2 = Ext.extend ( Object_level_1, {
  PropC: null,
  ProbD: null,
  initComponent: function () {
    Object_level_1.superclass.initComponent.call ();
  },
  setValue: function ( name, value ) { // it will come as 'PropA', 45 or 'PropC', 100
    Object_level_2.superclass.setValue ( name, value );
    if ( this.hasOwnProperty ( name ) ) { // ' fixed base on dtan answer
       // here is a problem 1 again
       // how I can access correct property and set it up
       // problem 2 again
       // How I set up property value of right property by having variable name
       this.fireEvent ( 'Update_on_level_2' );
    }
  }
}

Does someone know the solution?

Body:
Actually, I spotted errors in the code:

Always declare var when creating variables

When calling parent's method, use ClassName.superclass.methodName.call(this, arg1, arg2..). It's important to pass the this because it will change the scope of the called parent's method to the scope of current object. (You can remove the this in my following testing code to see the different outputs).

Normally I declare this.addEvents in initComponent before using the events. Not sure if it's necessary.

Here is my full testing codes with outputs:

var Obj1 = Ext.extend(Ext.util.Observable, {
    propA: null,
    propB: null,
    initComponent: function() {
        Obj1.superclass.initComponent.call(this);
    },
    setValue: function(name, value) {
        if (name in this) { //Used dtan suggestion
            this[name] = value;
            console.log(this.propA, this.propB, this.propC, this.propD);
        }else{
            console.log(name+" is not in Obj1");
        }
    }
});

var Obj2 = Ext.extend(Obj1, {
    propC: null,
    propD: null,
    initComponent: function() {
        Obj2.superclass.initComponent.call(this);
    },
    setValue: function(name, value) {
        Obj2.superclass.setValue.call(this, name, value);
    }
});

var obj1 = new Obj1();
var obj2 = new Obj2();
obj1.setValue('propA', '1a'); //1a null undefined undefined
obj1.setValue('propB', '1b'); //1a 1b undefined undefined
obj2.setValue('propC', '2c'); //null null 2c null
obj2.setValue('propD', '2d'); //null null 2c 2d
obj1.setValue('propA', '1a'); //1a 1b undefined undefined
obj1.setValue('propB', '1b'); //1a 1b undefined undefined
obj1.setValue('propC', '1c'); //propC is not in Obj1
obj1.setValue('propD', '1d'); //propD is not in Obj1
obj2.setValue('propA', '2a'); //2a null 2c 2d
obj2.setValue('propB', '2b'); //2a 2b 2c 2d
obj2.setValue('propC', '2c'); //2a 2b 2c 2d
obj2.setValue('propD', '2d'); //2a 2b 2c 2d

Try to read how ExtJS developers write their code in the src folders. You will see the correct usages of Ext.extend


问:
End of File Exception on ObjectInputStream.readObject
My application streams twitter data and writes them to files.

```<code>while(true){
        Status status = queue.poll();

        if (status == null) {
            Thread.sleep(100);
        }

        if(status!=null){
            list.add(status);
        }

        if(list.size()==10){
            FileOutputStream fos = null;
            ObjectOutputStream out = null;
            try {
                String uuid = UUID.randomUUID().toString();
                String filename = "C:/path/"+topic+"-"+uuid+".ser";
                fos = new FileOutputStream(filename);
                out = new ObjectOutputStream(fos);
                out.writeObject(list);
                tweetsDownloaded += list.size();
                if(tweetsDownloaded % 100==0)
                    System.out.println(tweetsDownloaded+" tweets downloaded");
            //  System.out.println("File: "+filename+" written.");
                out.close();
            } catch (IOException e) {

                e.printStackTrace();
            }

            list.clear();
    }
</code>```

I have this code which gets data from files.

```<code>while(true){
    File[] files = folder.listFiles();

    if(files != null){
        Arrays.sort(//sorting...);

        //Here we manage each single file, from data-load until the deletion
        for(int i = 0; i<files.length; i++){
            loadTweets(files[i].getAbsolutePath());
            //TODO manageStatuses
            files[i].delete();
            statusList.clear();
        }

    }

}
</code>```

The method loadTweets() does the following operations:

```<code>private static void loadTweets(String filename) {

    FileInputStream fis = null;
    ObjectInputStream in = null;
    try{
        fis = new FileInputStream(filename);
        in = new ObjectInputStream(fis);
        statusList = (List<Status>) in.readObject();
        in.close();
    }
    catch(IOException | ClassNotFoundException ex){
        ex.printStackTrace();
    }

}
</code>```

Unfortunately, I don't know why sometimes it throws a

EOFException

when running this line

```<code>statusList = (List<Status>) in.readObject();
</code>```

Anybody knows how I can solve this? Thank you.

答:
Found out what was necessary to solve this. Thanks to @VGR's comment, I thought to pause the executing thread for 0.2 seconds if the file has been created less than a second ago.

```<code>if(System.currentTimeMillis()-files[i].lastModified()<1000){
        Thread.sleep(200);
</code>```

This prevents the exception and the application works now fine.

Body:
My application streams twitter data and writes them to files.

while(true){
        Status status = queue.poll();

        if (status == null) {
            Thread.sleep(100);
        }

        if(status!=null){
            list.add(status);
        }

        if(list.size()==10){
            FileOutputStream fos = null;
            ObjectOutputStream out = null;
            try {
                String uuid = UUID.randomUUID().toString();
                String filename = "C:/path/"+topic+"-"+uuid+".ser";
                fos = new FileOutputStream(filename);
                out = new ObjectOutputStream(fos);
                out.writeObject(list);
                tweetsDownloaded += list.size();
                if(tweetsDownloaded % 100==0)
                    System.out.println(tweetsDownloaded+" tweets downloaded");
            //  System.out.println("File: "+filename+" written.");
                out.close();
            } catch (IOException e) {

                e.printStackTrace();
            }

            list.clear();
    }

I have this code which gets data from files.

while(true){
    File[] files = folder.listFiles();

    if(files != null){
        Arrays.sort(//sorting...);

        //Here we manage each single file, from data-load until the deletion
        for(int i = 0; i<files.length; i++){
            loadTweets(files[i].getAbsolutePath());
            //TODO manageStatuses
            files[i].delete();
            statusList.clear();
        }

    }

}

The method loadTweets() does the following operations:

private static void loadTweets(String filename) {

    FileInputStream fis = null;
    ObjectInputStream in = null;
    try{
        fis = new FileInputStream(filename);
        in = new ObjectInputStream(fis);
        statusList = (List<Status>) in.readObject();
        in.close();
    }
    catch(IOException | ClassNotFoundException ex){
        ex.printStackTrace();
    }

}

Unfortunately, I don't know why sometimes it throws a

EOFException

when running this line

statusList = (List<Status>) in.readObject();

Anybody knows how I can solve this? Thank you.

Body:
Found out what was necessary to solve this. Thanks to @VGR's comment, I thought to pause the executing thread for 0.2 seconds if the file has been created less than a second ago.

if(System.currentTimeMillis()-files[i].lastModified()<1000){
        Thread.sleep(200);

This prevents the exception and the application works now fine.


问:
Android: force keyboard to appear and focus on EditText
Thanks in advance for the help.

I would like a keyboard to appear at the end or during the execution of the following code.

```<code>    // edit text
    EditText editText = new EditText(activity);
    editText.setBackgroundColor(Color.WHITE);
    editText.setGravity(Gravity.TOP);
    editText.setText("Type here...");

    RelativeLayout relativeLayoutEditText = new RelativeLayout(activity);
    RelativeLayout.LayoutParams paramRelativeLayoutEditText = new RelativeLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT, 43 * display.getHeight() / 80 );
    paramRelativeLayoutEditText.addRule(RelativeLayout.ALIGN_PARENT_TOP);
    relativeLayoutEditText.addView(editText,paramRelativeLayoutEditText);

    // add all created views to rootView
    rootView.addView(relativeLayoutEditText, paramEditText);

    // open keyboard
    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
</code>```

but the keyboard only appears after touching the editText field (ie with my finger).  Is there a way that I can make the board automatically appear without using a physical touch?

As an aside I know that how I am specifying the width and height isn't exactly the right way to do things.

答:
this will show the keypad

```<code>InputMethodManager imm = (InputMethodManager)
        OrderMainActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(txtCustomerId, InputMethodManager.SHOW_IMPLICIT);
</code>```

enter your activity name instead of this if you calling keypad from the listeners eg. button click

Body:
Thanks in advance for the help.

I would like a keyboard to appear at the end or during the execution of the following code.

    // edit text
    EditText editText = new EditText(activity);
    editText.setBackgroundColor(Color.WHITE);
    editText.setGravity(Gravity.TOP);
    editText.setText("Type here...");

    RelativeLayout relativeLayoutEditText = new RelativeLayout(activity);
    RelativeLayout.LayoutParams paramRelativeLayoutEditText = new RelativeLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT, 43 * display.getHeight() / 80 );
    paramRelativeLayoutEditText.addRule(RelativeLayout.ALIGN_PARENT_TOP);
    relativeLayoutEditText.addView(editText,paramRelativeLayoutEditText);

    // add all created views to rootView
    rootView.addView(relativeLayoutEditText, paramEditText);

    // open keyboard
    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);

but the keyboard only appears after touching the editText field (ie with my finger).  Is there a way that I can make the board automatically appear without using a physical touch?

As an aside I know that how I am specifying the width and height isn't exactly the right way to do things.

Body:
this will show the keypad

InputMethodManager imm = (InputMethodManager)
        OrderMainActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(txtCustomerId, InputMethodManager.SHOW_IMPLICIT);

enter your activity name instead of this if you calling keypad from the listeners eg. button click


问:
How to selectively enable and disable scroll button based on window size

I am trying to make a scroll viewer in which scroll button is visible only when window size is too small to show all the content. I have put some button into a stackpanel which is in the scrollviewer.

```<code><Grid>
           <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>

        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>

            <RowDefinition Height="20"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="20"/>

            <RowDefinition/>
        </Grid.RowDefinitions>

        <RepeatButton x:Name="LineLeftButton"
                Grid.Column="0"
                Grid.Row="0"

                Command="{x:Static ScrollBar.LineDownCommand}"
                Background="{StaticResource uparrow}"
                CommandTarget="{Binding ElementName=scrollViewer}"/>
        <RepeatButton x:Name="LineRightButton"
                Grid.Column="0"
                Grid.Row="2"
              Background="{StaticResource downarrow}"
                Command="{x:Static ScrollBar.LineUpCommand}"
                CommandTarget="{Binding ElementName=scrollViewer}"/>
        <ScrollViewer Grid.Column="1" Grid.Row="1"  x:Name="scrollViewer"
                  VerticalScrollBarVisibility="Hidden"
                  HorizontalScrollBarVisibility="Hidden">
            <StackPanel Orientation="Vertical">
            <Button Width="150" Height="20"/>
            <Button Width="150" Height="20"/>
            <Button Width="150" Height="20"/>
            <Button Width="150" Height="20"/>
            <Button Width="150" Height="20"/>
            <Button Width="150" Height="20"/>

            <Button Width="150" Height="20"/>
            </StackPanel>
        </ScrollViewer>
    </Grid>
</code>```

The scroll is working kk but how do you disable it when there are not enough element in the stack such that a scroll is not required?

答:
You can create a converter like the following

```<code>public class MyConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is double)
        {
            return ((double)value < 140) ? Visibility.Visible : Visibility.Collapsed;
        }
        return Visibility.Collapsed;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
</code>```

where 140 is the total height needed (you can make this parameter dynamic). Then you just need to bind the visibility of your button

```<code><RepeatButton x:Name="LineRightButton"
                Visibility="{Binding ActualHeight, Converter={StaticResource MyConv}, ElementName=scrollViewer, Mode=OneWay}"
                Grid.Column="0"
                Grid.Row="2"
                Background="{StaticResource downarrow}"
                Command="{x:Static ScrollBar.LineUpCommand}"
                CommandTarget="{Binding ElementName=scrollViewer}"/>
</code>```

You just need to define the converter mentioned above in your resources and it's done

EDIT Solution number 2 with Multibinding:

if you want to avoid to hardcode the total height of your button you can use a multivalueconverter and a multibinding

```<code>public class MyConverter : IMultiValueConverter
{
    public object Convert(object[] value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value[0] is double && value[1] is double)
        {
            return ((double)value[0] < (double)value[1]) ? Visibility.Visible : Visibility.Collapsed;
        }
        return Visibility.Collapsed;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
</code>```

and modify your button in this way

```<code><RepeatButton x:Name="LineRightButton"
            Grid.Column="0"
            Grid.Row="2"
          Background="Black"
            Command="{x:Static ScrollBar.LineUpCommand}"
            CommandTarget="{Binding ElementName=scrollViewer}">
        <RepeatButton.Visibility>
            <MultiBinding Converter="{StaticResource MyConv}">
                <Binding Path="ActualHeight"  ElementName="scrollViewer"/>
                <Binding Path="ActualHeight"  ElementName="test"/>
            </MultiBinding>
        </RepeatButton.Visibility>
    </RepeatButton>
</code>```

where "test is the name of the stackpanel containing the buttons

Body:
I am trying to make a scroll viewer in which scroll button is visible only when window size is too small to show all the content. I have put some button into a stackpanel which is in the scrollviewer.

<Grid>
           <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>

        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>

            <RowDefinition Height="20"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="20"/>

            <RowDefinition/>
        </Grid.RowDefinitions>

        <RepeatButton x:Name="LineLeftButton"
                Grid.Column="0"
                Grid.Row="0"

                Command="{x:Static ScrollBar.LineDownCommand}"
                Background="{StaticResource uparrow}"
                CommandTarget="{Binding ElementName=scrollViewer}"/>
        <RepeatButton x:Name="LineRightButton"
                Grid.Column="0"
                Grid.Row="2"
              Background="{StaticResource downarrow}"
                Command="{x:Static ScrollBar.LineUpCommand}"
                CommandTarget="{Binding ElementName=scrollViewer}"/>
        <ScrollViewer Grid.Column="1" Grid.Row="1"  x:Name="scrollViewer"
                  VerticalScrollBarVisibility="Hidden"
                  HorizontalScrollBarVisibility="Hidden">
            <StackPanel Orientation="Vertical">
            <Button Width="150" Height="20"/>
            <Button Width="150" Height="20"/>
            <Button Width="150" Height="20"/>
            <Button Width="150" Height="20"/>
            <Button Width="150" Height="20"/>
            <Button Width="150" Height="20"/>

            <Button Width="150" Height="20"/>
            </StackPanel>
        </ScrollViewer>
    </Grid>

The scroll is working kk but how do you disable it when there are not enough element in the stack such that a scroll is not required?

Body:
You can create a converter like the following

public class MyConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is double)
        {
            return ((double)value < 140) ? Visibility.Visible : Visibility.Collapsed;
        }
        return Visibility.Collapsed;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

where 140 is the total height needed (you can make this parameter dynamic). Then you just need to bind the visibility of your button

<RepeatButton x:Name="LineRightButton"
                Visibility="{Binding ActualHeight, Converter={StaticResource MyConv}, ElementName=scrollViewer, Mode=OneWay}"
                Grid.Column="0"
                Grid.Row="2"
                Background="{StaticResource downarrow}"
                Command="{x:Static ScrollBar.LineUpCommand}"
                CommandTarget="{Binding ElementName=scrollViewer}"/>

You just need to define the converter mentioned above in your resources and it's done

EDIT Solution number 2 with Multibinding:

if you want to avoid to hardcode the total height of your button you can use a multivalueconverter and a multibinding

public class MyConverter : IMultiValueConverter
{
    public object Convert(object[] value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value[0] is double && value[1] is double)
        {
            return ((double)value[0] < (double)value[1]) ? Visibility.Visible : Visibility.Collapsed;
        }
        return Visibility.Collapsed;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

and modify your button in this way

<RepeatButton x:Name="LineRightButton"
            Grid.Column="0"
            Grid.Row="2"
          Background="Black"
            Command="{x:Static ScrollBar.LineUpCommand}"
            CommandTarget="{Binding ElementName=scrollViewer}">
        <RepeatButton.Visibility>
            <MultiBinding Converter="{StaticResource MyConv}">
                <Binding Path="ActualHeight"  ElementName="scrollViewer"/>
                <Binding Path="ActualHeight"  ElementName="test"/>
            </MultiBinding>
        </RepeatButton.Visibility>
    </RepeatButton>

where "test is the name of the stackpanel containing the buttons


问:
how to show default selected option in select box
I have searched similar kind of links ,but no luck.

I have an array of objects which i need to show as a dropdown and i have to select one default option .My object contains value,selected properties.If value and selected properties are matched then it has to be the default selected option.My dropdown Array look like this...

```<code>[
    {
      "selected": "samsung",
      "resource_Attribute_ID": 486,
      "value": "hp",
      "type": "String"
    },
    {
      "selected": "samsung",
      "resource_Attribute_ID": 486,
      "value": "samsung",
      "type": "String"
    },
    {
      "selected": "samsung",
      "resource_Attribute_ID": 486,
      "value": "dell",
      "type": "String"
    }
  ]
</code>```

and HTML code like this..

```<code><select formControlName="controlFordropdwn" >
            <option value="" disabled  hidden>Select</option>
            <option *ngFor="let type of dropdown"   [value]="type.value" [selected]='type.value == type.selected'  >
              {{type.value}}
            </option>
          </select>
</code>```

Any response which is related to this will help me alot.
Thanks to you inAdvance

答:
With reactive forms, the selected attribute is completely ignored, so what you need to do, is to set the value to your form control instead, which can be found by use .find() and remove the selected from your template.

constructor(private fb: FormBuilder) {
  this.myForm = this.fb.group({
    controlFordropdwn: ['']
  });
  let item = this.dropdown.find(x => x.value === x.selected);
  this.myForm.controls.controlFordropdwn.setValue(item.value)
 }
```

Now your select will work correctly.

StackBlitz

Body:
I have searched similar kind of links ,but no luck.

I have an array of objects which i need to show as a dropdown and i have to select one default option .My object contains value,selected properties.If value and selected properties are matched then it has to be the default selected option.My dropdown Array look like this...

[
    {
      "selected": "samsung",
      "resource_Attribute_ID": 486,
      "value": "hp",
      "type": "String"
    },
    {
      "selected": "samsung",
      "resource_Attribute_ID": 486,
      "value": "samsung",
      "type": "String"
    },
    {
      "selected": "samsung",
      "resource_Attribute_ID": 486,
      "value": "dell",
      "type": "String"
    }
  ]

and HTML code like this..

<select formControlName="controlFordropdwn" >
            <option value="" disabled  hidden>Select</option>
            <option *ngFor="let type of dropdown"   [value]="type.value" [selected]='type.value == type.selected'  >
              {{type.value}}
            </option>
          </select>

Any response which is related to this will help me alot.
Thanks to you inAdvance

Body:
With reactive forms, the selected attribute is completely ignored, so what you need to do, is to set the value to your form control instead, which can be found by use .find() and remove the selected from your template.

constructor(private fb: FormBuilder) {
  this.myForm = this.fb.group({
    controlFordropdwn: ['']
  });
  let item = this.dropdown.find(x => x.value === x.selected);
  this.myForm.controls.controlFordropdwn.setValue(item.value)
 }

Now your select will work correctly.

StackBlitz


问:
Get user_metadata Roles in Auth0
I am trying to get user Roles when after logged in in Auth0, as per documentation, I created a rule

```<code>function (user, context, callback) {
    var namespace = 'https://myayth0.com/';
    context.idToken[namespace + 'app_metadata'] = user.app_metadata;
    context.idToken[namespace + 'user_metadata'] = user.user_metadata;
    context.idToken[namespace + 'roles'] = user.user_metadata.roles;
    context.accessToken[namespace + 'app_metadata'] = user.app_metadata;
    context.accessToken[namespace + 'user_metadata'] = user.user_metadata;
    context.accessToken[namespace + 'roles'] = user.user_metadata.roles;
    callback(null, user, context);
 }
</code>```

Now I have this data return

```<code>(...)
 email_verified
:
(...)
 https://ian:auth0:com/app_metadata
 :
(...)
https://ian:auth0:com/roles
:
https://ian:auth0:com/user_metadata
(...)
:
(...)
picture
:
(...)
sub
:
(...)
updated_at
:
(...)
</code>```

Now accessing picture or email  is easy

```<code>     this.user.email, this.user.picture
</code>```

But how about the role?

```<code>   https://ian:auth0:com/roles
     : Array(1)
     0: "admin"
   ..................
</code>```

答:
Please check this Auth0 Community Answer.

Once added to your token and returned to your Client application, it should simply be a case of validating and decoding the token to retrieve the value from the namespaced custom claim key.

You should also check whether it makes sense to have the ROLES information tagged to app_metadata rather than user_metadata (which is modifiable by end user) - and whether it is an ID Token (consumer app) or Access Token (receiving API) that should be responsible for holding the custom claim.

Title: Get user_metadata Roles in Auth0

Body:
I am trying to get user Roles when after logged in in Auth0, as per documentation, I created a rule

function (user, context, callback) {
    var namespace = 'https://myayth0.com/';
    context.idToken[namespace + 'app_metadata'] = user.app_metadata;
    context.idToken[namespace + 'user_metadata'] = user.user_metadata;
    context.idToken[namespace + 'roles'] = user.user_metadata.roles;
    context.accessToken[namespace + 'app_metadata'] = user.app_metadata;
    context.accessToken[namespace + 'user_metadata'] = user.user_metadata;
    context.accessToken[namespace + 'roles'] = user.user_metadata.roles;
    callback(null, user, context);
 }

Now I have this data return

(...)
 email_verified
:
(...)
 https://ian:auth0:com/app_metadata
 :
(...)
https://ian:auth0:com/roles
:
https://ian:auth0:com/user_metadata
(...)
:
(...)
picture
:
(...)
sub
:
(...)
updated_at
:
(...)

Now accessing picture or email  is easy

     this.user.email, this.user.picture

But how about the role?

   https://ian:auth0:com/roles
     : Array(1)
     0: "admin"
   ..................


问:
Inserting PHP html string into TinyMCE editor
Im trying to get HTML from my MySQL table inserted into my TinyMCE editor. But I have serious trouble setting up the PHP string into Javascript.

when I just try to insert it like this:

```<code>tinymce.activeEditor.setContent("'<? echo $description; ?>'", {format: 'raw'});
</code>```

It has trouble with the single quotes and the double quotes in the $description variable. I get unidentified id's in my string because the string gets cut off due to the single and double quotes that are located in the string.

How can I insert this into TinyMCE, which ultimately comes down to how to make a HTML string without cutting of early?

答:
You can simply replace those characters:</p>

```<code>tinymce.activeEditor.setContent("'<? echo str_replace(array('"', "'"), array('\"', "\'"), $description); ?>'", {format: 'raw'});
</code>```

Body:
Im trying to get HTML from my MySQL table inserted into my TinyMCE editor. But I have serious trouble setting up the PHP string into Javascript.

when I just try to insert it like this:

tinymce.activeEditor.setContent("'<? echo $description; ?>'", {format: 'raw'});

It has trouble with the single quotes and the double quotes in the $description variable. I get unidentified id's in my string because the string gets cut off due to the single and double quotes that are located in the string.

How can I insert this into TinyMCE, which ultimately comes down to how to make a HTML string without cutting of early?

Body:
You can simply replace those characters:

tinymce.activeEditor.setContent("'<? echo str_replace(array('"', "'"), array('\"', "\'"), $description); ?>'", {format: 'raw'});


问:
App developed in Xcode for native iOS
We have our native iOS app developed in Xcode and now software developer is saying that we should upgrade our code to Xcode 9 as we may face issue with the new release on the App Store if we continue using Xcode for development. I would like to know if this is a fact, since I am not from iOS development and I don't know if this is a fact.

Any help in this regarding or a pointer to documentation would be appreciated.

答:
Appstore won't reject your app because compiled with version 8 but as your developer says, It will be better approach to compile the project with latest version of Xcode.

In addition, with iPhone X release, Apple probably look into support for iPhone X so If you send a new version without iPhone X support, It may be rejected and for iPhone X support, you need to use Xcode version 9 or later.

Apple Xcode Support:

You should use the latest version of Xcode available on the Mac App Store to submit your apps, or when available, the latest GM seed release from the Downloads page. For more information, read the App Distribution Guide.

Note: If your source codes are written fully with Objective-C then compile won't be problem because with Xcode 9 nothing changed on Obj-C side. However, If you have a swift code It may needed to be updated to Swift 4.

Title: App developed in Xcode for native iOS


问:
Batch script: local variable from function1 to function2
Okay guys, let my try to explain my problem:

I start with a line from where I start 2 different functions

```<code>setlocal EnableDelayedExpansion
for %%i in ("C:\*.*") do (
call :function1 "%%~i"
call :function2 "%%~i"
)
goto :eof
</code>```

In function1, at a certain point I DO a SET in a local environment:

```<code>setlocal EnableDelayedExpansion
...
...
set name1=blabla
endlocal  & SET name=%name1%
echo %name%
goto :eof
</code>```

The echo does return my variable. Now onto my problem.
I quit function one and i go to function 2 (see first code-segment)
I can't call the variable form here. I tried in the function2, I tried before function2 is called, but both didn't resolve the issue.

My guess is a have set only a local variable for function1. I search the nets but i read that the line "endlocal  & SET name=%name1%" should have solved my issue.

I hope I have explained it well, all help appreciated!

答:
I'm not sure where your problem lies since this works perfectly:

```<code>@setlocal enableextensions enabledelayedexpansion
@echo off
set name=ORIGNAME
for %%i in (1 2) do (
    call :function1 %%i
    echo in main %name% !name!
)
endlocal
goto :eof

:function1:
    setlocal enableextensions enabledelayedexpansion
    set name1=%1_blabla
    endlocal  & SET name=%name1%
    echo in function %name%
    goto :eof
</code>```

outputting:

```<code>in function 1_blabla
in main ORIGNAME 1_blabla
in function 2_blabla
in main ORIGNAME 2_blabla
</code>```

Are you certain that, when you used name in the main areas, you used !name! instead of %name%?

If you used the %name% variant, that would be evaluated when the entire for loop was read, not at the time when you used it (in other words, it would be blank). You can see that in the output of ORIGNAME in the main line.

I'm not certain that's the case since you are using delayed expansion. But, just in case, I thought I'd mention it. I always use delayed expansion and I always used the ! variants of the environment variables since it more closely matches how I expect a shell to work.

In any case, the code I've given works fine so you may want to fiddle with that to see if you can incorporate it into your own.

Body:
Okay guys, let my try to explain my problem:

I start with a line from where I start 2 different functions

setlocal EnableDelayedExpansion
for %%i in ("C:\*.*") do (
call :function1 "%%~i"
call :function2 "%%~i"
)
goto :eof

In function1, at a certain point I DO a SET in a local environment:

setlocal EnableDelayedExpansion
...
...
set name1=blabla
endlocal  & SET name=%name1%
echo %name%
goto :eof

The echo does return my variable. Now onto my problem.
I quit function one and i go to function 2 (see first code-segment)
I can't call the variable form here. I tried in the function2, I tried before function2 is called, but both didn't resolve the issue.

My guess is a have set only a local variable for function1. I search the nets but i read that the line "endlocal  & SET name=%name1%" should have solved my issue.

I hope I have explained it well, all help appreciated!

Body:
I'm not sure where your problem lies since this works perfectly:

@setlocal enableextensions enabledelayedexpansion
@echo off
set name=ORIGNAME
for %%i in (1 2) do (
    call :function1 %%i
    echo in main %name% !name!
)
endlocal
goto :eof

:function1:
    setlocal enableextensions enabledelayedexpansion
    set name1=%1_blabla
    endlocal  & SET name=%name1%
    echo in function %name%
    goto :eof

outputting:

in function 1_blabla
in main ORIGNAME 1_blabla
in function 2_blabla
in main ORIGNAME 2_blabla

Are you certain that, when you used name in the main areas, you used !name! instead of %name%?

If you used the %name% variant, that would be evaluated when the entire for loop was read, not at the time when you used it (in other words, it would be blank). You can see that in the output of ORIGNAME in the main line.

I'm not certain that's the case since you are using delayed expansion. But, just in case, I thought I'd mention it. I always use delayed expansion and I always used the ! variants of the environment variables since it more closely matches how I expect a shell to work.

In any case, the code I've given works fine so you may want to fiddle with that to see if you can incorporate it into your own.


问:
Create video from images sorted in numerical order using ffmpeg
I have a bunch of images named pic1.png, pic2,png, pic24.png ,... etc. How can I use ffmpeg to create a video from them? I have tried

```<code>    ffmpeg -f image2 -r $FRAMERATE -pattern_type glob -i "*.png" output.mp4
</code>```

but it does not sort the images in the right order. Is it because of the naming convention I used? (pic2.png instead of pic002.png)

答:
You can use

```<code>ffmpeg -framerate $FRAMERATE -i "pic%d.png" output.mp4
</code>```

for the filename pattern you described.

If the names were like pic002.png, you would use "pic%03d.png" instead.

Body:
I have a bunch of images named pic1.png, pic2,png, pic24.png ,... etc. How can I use ffmpeg to create a video from them? I have tried

    ffmpeg -f image2 -r $FRAMERATE -pattern_type glob -i "*.png" output.mp4

but it does not sort the images in the right order. Is it because of the naming convention I used? (pic2.png instead of pic002.png)

Body:
You can use

ffmpeg -framerate $FRAMERATE -i "pic%d.png" output.mp4

for the filename pattern you described.

If the names were like pic002.png, you would use "pic%03d.png" instead.


问:
Calling PlaceAutocomplete Intent on EditText's OnClickListener
I'm trying to call a intent to launch the autocomplete activity inside a EditText's OnClickListener. When I Embed a PlaceAutocompleteFragment directly inside a onCreate, it is working fine. But I need to call this on EditText on Click event.

Here's my Code

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.softvision.gocartsapp.gocartz.CreateRide">

    <EditText
        android:id="@+id/editText_Source"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:ems="10"
        android:hint="Source"
        android:textSize="14sp"
        android:inputType="none"
        android:focusable="false"/>

    <EditText
        android:id="@+id/editText_Destination"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:ems="10"
        android:hint="Destination"
        android:textSize="14sp"
        android:inputType="none"
        android:focusable="false"/>
</LinearLayout>
</code>```

And java file

```<code>public class CreateRide extends AppCompatActivity {

    private int PLACE_AUTOCOMPLETE_REQUEST_CODE = 1;
    private EditText editTextSource, editTextDestination;
    private String TAG = "CreateRide";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_ride);

        // Handle editTextSource Click Handler
        editTextSource = (EditText)findViewById(R.id.editText_Source);
        editTextSource.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    Intent intent = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN).build(this);
                    startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST_CODE);
                } catch (GooglePlayServicesRepairableException e) {
                    // TODO: Handle the error.
                } catch (GooglePlayServicesNotAvailableException e) {
                    // TODO: Handle the error.
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == PLACE_AUTOCOMPLETE_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                Place place = PlaceAutocomplete.getPlace(this, data);
                Log.i(TAG, "Place: " + place.getName());
            } else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
                Status status = PlaceAutocomplete.getStatus(this, data);
                // TODO: Handle the error.
                Log.i(TAG, status.getStatusMessage());

            } else if (resultCode == RESULT_CANCELED) {
                // The user canceled the operation.
            }
        }
    }
}
</code>```

I'm getting an error as below:

```<code>Error:(33, 107) error: no suitable method found for build(<anonymous OnClickListener>)
method zzb.build(Activity) is not applicable
(argument mismatch; <anonymous OnClickListener> cannot be converted to Activity)
method IntentBuilder.build(Activity) is not applicable
(argument mismatch; <anonymous OnClickListener> cannot be converted to Activity)
</code>```

Please help me on this.

答:
Modify

```<code>Intent intent = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN)
    .build(this);
</code>```

to

```<code>Intent intent = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN)
    .build(CreateRide.this); // notice CrateRide.this
</code>```

this on your code refers to the anonymous OnClickListener, hence the error.

Body:
I'm trying to call a intent to launch the autocomplete activity inside a EditText's OnClickListener. When I Embed a PlaceAutocompleteFragment directly inside a onCreate, it is working fine. But I need to call this on EditText on Click event.

Here's my Code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.softvision.gocartsapp.gocartz.CreateRide">

    <EditText
        android:id="@+id/editText_Source"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:ems="10"
        android:hint="Source"
        android:textSize="14sp"
        android:inputType="none"
        android:focusable="false"/>

    <EditText
        android:id="@+id/editText_Destination"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:ems="10"
        android:hint="Destination"
        android:textSize="14sp"
        android:inputType="none"
        android:focusable="false"/>
</LinearLayout>

And java file

public class CreateRide extends AppCompatActivity {

    private int PLACE_AUTOCOMPLETE_REQUEST_CODE = 1;
    private EditText editTextSource, editTextDestination;
    private String TAG = "CreateRide";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_ride);

        // Handle editTextSource Click Handler
        editTextSource = (EditText)findViewById(R.id.editText_Source);
        editTextSource.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    Intent intent = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN).build(this);
                    startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST_CODE);
                } catch (GooglePlayServicesRepairableException e) {
                    // TODO: Handle the error.
                } catch (GooglePlayServicesNotAvailableException e) {
                    // TODO: Handle the error.
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == PLACE_AUTOCOMPLETE_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                Place place = PlaceAutocomplete.getPlace(this, data);
                Log.i(TAG, "Place: " + place.getName());
            } else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
                Status status = PlaceAutocomplete.getStatus(this, data);
                // TODO: Handle the error.
                Log.i(TAG, status.getStatusMessage());

            } else if (resultCode == RESULT_CANCELED) {
                // The user canceled the operation.
            }
        }
    }
}

I'm getting an error as below:

Error:(33, 107) error: no suitable method found for build(<anonymous OnClickListener>)
method zzb.build(Activity) is not applicable
(argument mismatch; <anonymous OnClickListener> cannot be converted to Activity)
method IntentBuilder.build(Activity) is not applicable
(argument mismatch; <anonymous OnClickListener> cannot be converted to Activity)

Please help me on this.

Body:
Modify

Intent intent = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN)
    .build(this);

to

Intent intent = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN)
    .build(CreateRide.this); // notice CrateRide.this

this on your code refers to the anonymous OnClickListener, hence the error.


问:
Opencart does not show coupon box
I have a site http://www.pentrim.com - when you click on the cart it takes you to a page where it asks you to enter a gift voucher - I want to replace this with a coupon box!

I have added a coupon to the opencart backend, but the box does not appear - which makes me think there may be something missing in my template or opencart configuration.

Can somebody help me determine what is missing?

答: You should go to extensions>order totals>copoun then change the status to be enabled</p>

Title: Opencart does not show coupon box


问:
Page Condition becomes false after the ajax call in wordpress
I am trying to avoid some code to get display on particular pages such as tags categories and other pages.

```<code>if( !is_front_page() && !is_search() && !is_page( 'article', 'preview' ) && !is_category() && !is_tax() && !is_tag() ){
//code goes here..
}
</code>```

The condition works fine when a user lands on the page. But these pages uses ajax to retrieve post and when this happens the condition becomes false and unnecessary code displayed on page.

Why is this happening? Do anyone has any idea about this. Any kind of help would be appreciated.

答:
You should get your Ajax response data with above condition .

Or you can pass one variable(argument) in your Ajax when you are in that page which you don't want to show that code, that time that will pass in your Ajax and when Ajax function get that variable(argument) that time you have to add your above condition if you not get(empty) argument then you perform for all page.

better way is get your response for Ajax in a way by which you can get above page condition.

Body:
I am trying to avoid some code to get display on particular pages such as tags categories and other pages.

if( !is_front_page() && !is_search() && !is_page( 'article', 'preview' ) && !is_category() && !is_tax() && !is_tag() ){
//code goes here..
}

The condition works fine when a user lands on the page. But these pages uses ajax to retrieve post and when this happens the condition becomes false and unnecessary code displayed on page.

Why is this happening? Do anyone has any idea about this. Any kind of help would be appreciated.


问:
curved div with transparent top
I'm trying to create transparent div full width and height around 500px using borders but i have trouble with creating this kind of curved shape.
It should look like on the example image, the yellow shape.

.transparent_bg {
    width: 100%;
    height: 485px;
    background: transparent;
    border:solid 5px #000;
    border-color:#000 transparent transparent transparent;
    border-radius: 50%/200px 200px 0 0;
    transform: rotate(180deg);
    position: relative;
    overflow:hidden;
}

.transparent_bg:after {
    content: "";
    width: 100%;
    height: 485px;
    position: absolute;
    top: 0;
    background: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="transparent_bg"></div></code>```

I have included a link to my work until this moment but without success.

答:
.transparent_bg {
    width: 100%;
    height: 485px;
    background: transparent;
    border-top-left-radius: 50% 50%;
    border-top-right-radius: 50% 50%;
    transform: rotate(180deg);
    position: relative;
    overflow:hidden;
}

.transparent_bg:after {
    content: "";
    width: 100%;
    height: 485px;
    position: absolute;
    top: 0;
    background: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="transparent_bg"></div></code>```

Title: curved div with transparent top

Body:
I'm trying to create transparent div full width and height around 500px using borders but i have trouble with creating this kind of curved shape.
It should look like on the example image, the yellow shape.

.transparent_bg {
    width: 100%;
    height: 485px;
    background: transparent;
    border:solid 5px #000;
    border-color:#000 transparent transparent transparent;
    border-radius: 50%/200px 200px 0 0;
    transform: rotate(180deg);
    position: relative;
    overflow:hidden;
}

.transparent_bg:after {
    content: "";
    width: 100%;
    height: 485px;
    position: absolute;
    top: 0;
    background: red;
}

I have included a link to my work until this moment but without success.

Body:
.transparent_bg {
    width: 100%;
    height: 485px;
    background: transparent;
    border-top-left-radius: 50% 50%;
    border-top-right-radius: 50% 50%;
    transform: rotate(180deg);
    position: relative;
    overflow:hidden;
}

.transparent_bg:after {
    content: "";
    width: 100%;
    height: 485px;
    position: absolute;
    top: 0;
    background: red;
}

<div class="transparent_bg"></div>


问:
How to monitor memory usage and build scalable java web server?
We are writing a web application with Java, which is served as chat room server powered by WebSocket. We design the server structure properly so that we can run multiple identical server instance to support massive connection and communication. The problem is that we can't scale the servers cluster dynamically. Ideally, any slave node should monitor its memory usage and notify the dedicated master node when it can't accept more connection. Now the web application simply crashes when too much connections come in rapidly. Are there any solution (or idea) to improve the situation?</p>

答:
In java its fairly easy to check up some information about the current cluster.

```<code>MemoryUsage heapMemoryUsage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
heapMemoryUsage.getUsed();
</code>```

If you want to check the JVM Runtime total memory for that cluster, here`s an example on how to do that.

```<code>public class TestMemory {

    public static void main(String [] args) {

        int mb = 1024*1024;

        //Getting the runtime reference from system
        Runtime runtime = Runtime.getRuntime();

        System.out.println("##### Heap utilization statistics [MB] #####");

        //Print used memory
        System.out.println("Used Memory:"
            + (runtime.totalMemory() - runtime.freeMemory()) / mb);

        //Print free memory
        System.out.println("Free Memory:"
            + runtime.freeMemory() / mb);

        //Print total available memory
        System.out.println("Total Memory:" + runtime.totalMemory() / mb);

        //Print Maximum available memory
        System.out.println("Max Memory:" + runtime.maxMemory() / mb);
    }
}
</code>```

So, now any child nodes know whey they are on theyr limit. If you have a open WebSocket comunication, you should have a ping on all child nodes and check theyr status, if they are heavily loaded you could instantiate a new node dynamically, for example, using Docker to make things easyer. (just deploy a new Docker container on a cloud based server, connect to the master node (you could use Node.js to connect via WebSocket to the master node eventually, so you could even connect before your JVM is actually on.) just telling "hey, new node here, gimme some stuff to do". Internally i would not know how far redirecting traffic from one node to other would be, but i hope this idea. If you want a more accurate connection (fewer crashes) dont only look at memory usage, but network usage and if any TCP packages are lost or websocket gets suddenly closed, the server should tell the master node right away to create a new instance of it.

Body:
In java its fairly easy to check up some information about the current cluster.

MemoryUsage heapMemoryUsage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
heapMemoryUsage.getUsed();

If you want to check the JVM Runtime total memory for that cluster, here`s an example on how to do that.

public class TestMemory {

    public static void main(String [] args) {

        int mb = 1024*1024;

        //Getting the runtime reference from system
        Runtime runtime = Runtime.getRuntime();

        System.out.println("##### Heap utilization statistics [MB] #####");

        //Print used memory
        System.out.println("Used Memory:"
            + (runtime.totalMemory() - runtime.freeMemory()) / mb);

        //Print free memory
        System.out.println("Free Memory:"
            + runtime.freeMemory() / mb);

        //Print total available memory
        System.out.println("Total Memory:" + runtime.totalMemory() / mb);

        //Print Maximum available memory
        System.out.println("Max Memory:" + runtime.maxMemory() / mb);
    }
}

So, now any child nodes know whey they are on theyr limit. If you have a open WebSocket comunication, you should have a ping on all child nodes and check theyr status, if they are heavily loaded you could instantiate a new node dynamically, for example, using Docker to make things easyer. (just deploy a new Docker container on a cloud based server, connect to the master node (you could use Node.js to connect via WebSocket to the master node eventually, so you could even connect before your JVM is actually on.) just telling "hey, new node here, gimme some stuff to do". Internally i would not know how far redirecting traffic from one node to other would be, but i hope this idea. If you want a more accurate connection (fewer crashes) dont only look at memory usage, but network usage and if any TCP packages are lost or websocket gets suddenly closed, the server should tell the master node right away to create a new instance of it.


问:
Swift - CollectionView Add Single Cell With Custom Animation
I have a UIViewController with a CollectionView inside of it, and a button that simply adds a new cell to the end of the CollectionView.
I add it by using this:

```<code>func addNewFolderCell {
    self.folder!.childFolders!.append(folder)
    let count = self.folder!.childFolders!.count
    let index = count > 0 ? count - 1 : count
    let indexPath = IndexPath(item: index, section: 0)
    collectionView?.performBatchUpdates({
        collectionView!.insertItems(at: [indexPath])
    })
}
</code>```

And that works, but I'd like to customize the default animation, so that I can perform a scale and fade in when the cell is added. I.E.:

```<code>UIView.animate(withDuration: 1.4, delay: 0.15 * Double(indexPath.row),  animations: {
    cell.alpha = 1.0
    cell.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
})
</code>```

I found this tutorial, but I can't figure out how to get it to work when you're in a UIViewController instead of a UICollectionViewController:

https://littlebitesofcocoa.com/306-customizing-collection-view-cell-insertion-animations

答:
You put the animation in collectionView:willDisplayCell:forItemAtIndexPath:

```<code>extension ViewController: UICollectionViewDelegate {
  func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    cell.alpha = 0
    cell.transform = CGAffineTransform(scaleX: 0.1, y: 0.1)
    UIView.animate(withDuration: 0.25) {
      cell.alpha = 1
      cell.transform = .identity
    }
  }
}
</code>```

EDIT UPDATE:

assuming you are using UICollectionViewFlowLayout you will need to subclass it and override initialLayoutAttributesForAppearingSupplementaryElement(ofKind:at:) which is defined on UICollectionViewLayout, the abstract parent of UICollectionViewFlowLayout.  If you return attributes from this method they are used as the initial attributes for the cell and the animation system will interpolate them to their final values.  You then set an instance of your custom UICollectionViewFlowLayout as your collection view's .collectionViewLayout

EDIT ADD CODE:

```<code>class MyFlowLayout: UICollectionViewFlowLayout {
  override func initialLayoutAttributesForAppearingItem(at itemIndexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
    let attributes = UICollectionViewLayoutAttributes()
    attributes.alpha = 0
    attributes.transform = CGAffineTransform(scaleX: 0.1, y: 0.1)
    return attributes
  }
}

class ViewController: UIViewController {
  var collectionView: UICollectionView!
  override func viewDidLoad() {
    collectionView.collectionViewLayout = MyFlowLayout()
  }
}
</code>```

Body:
I have a UIViewController with a CollectionView inside of it, and a button that simply adds a new cell to the end of the CollectionView.
I add it by using this:

func addNewFolderCell {
    self.folder!.childFolders!.append(folder)
    let count = self.folder!.childFolders!.count
    let index = count > 0 ? count - 1 : count
    let indexPath = IndexPath(item: index, section: 0)
    collectionView?.performBatchUpdates({
        collectionView!.insertItems(at: [indexPath])
    })
}

And that works, but I'd like to customize the default animation, so that I can perform a scale and fade in when the cell is added. I.E.:

UIView.animate(withDuration: 1.4, delay: 0.15 * Double(indexPath.row),  animations: {
    cell.alpha = 1.0
    cell.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
})

I found this tutorial, but I can't figure out how to get it to work when you're in a UIViewController instead of a UICollectionViewController:

https://littlebitesofcocoa.com/306-customizing-collection-view-cell-insertion-animations

Body:
You put the animation in collectionView:willDisplayCell:forItemAtIndexPath:

extension ViewController: UICollectionViewDelegate {
  func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    cell.alpha = 0
    cell.transform = CGAffineTransform(scaleX: 0.1, y: 0.1)
    UIView.animate(withDuration: 0.25) {
      cell.alpha = 1
      cell.transform = .identity
    }
  }
}

EDIT UPDATE:

assuming you are using UICollectionViewFlowLayout you will need to subclass it and override initialLayoutAttributesForAppearingSupplementaryElement(ofKind:at:) which is defined on UICollectionViewLayout, the abstract parent of UICollectionViewFlowLayout.  If you return attributes from this method they are used as the initial attributes for the cell and the animation system will interpolate them to their final values.  You then set an instance of your custom UICollectionViewFlowLayout as your collection view's .collectionViewLayout

EDIT ADD CODE:

class MyFlowLayout: UICollectionViewFlowLayout {
  override func initialLayoutAttributesForAppearingItem(at itemIndexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
    let attributes = UICollectionViewLayoutAttributes()
    attributes.alpha = 0
    attributes.transform = CGAffineTransform(scaleX: 0.1, y: 0.1)
    return attributes
  }
}

class ViewController: UIViewController {
  var collectionView: UICollectionView!
  override func viewDidLoad() {
    collectionView.collectionViewLayout = MyFlowLayout()
  }
}


问:
What archetype to choose for a simple java project
mvn archetype:generate provides way too many options and I am looking to create a simple java utility with junit test cases. I would like to know what archetype I should be using here?</p>

答:
the default archetype number now is 1092
1092: remote -> org.apache.maven.archetypes:maven-archetype-quickstart (An archetype which contains a sample Maven project.)</p>