问:
Play only one SWF file at a time
How can I stop one SWF file playing when playing another in a HTML page?

I currently have a carousel that displays multiple SWF files and I don't want any overlapping of video or audio. I've been looking into LocalConnection and JavaScript options but with no luck.
My SWF files are currently ActionScript 3 and Flash Player 10.
I have a large play button on them, with the ActionScript code:

```<code>import fl.video.VideoEvent;
import fl.video.VideoState;

video.addEventListener(VideoEvent.STATE_CHANGE,showButton);
playVideoButton.addEventListener(MouseEvent.MOUSE_UP,playVideo);

function playVideo(event:MouseEvent):void {
    video.play();
    playVideoButton.visible=false;
}

function showButton(event:VideoEvent):void {
    switch (event.target.state) {
        case "stopped" :
            playVideoButton.visible=true;
            break;
        case "playing" :
            playVideoButton.visible=false;
            break;
        case "paused" :
            playVideoButton.visible=true;
            break;
    }
}
</code>```

Is there a way to incoporate a "stop the other SWF files playing" in this somehow?

答:
What you'll want to do is set up an ExternalInterface callback method in each SWF file. That will allow JavaScript to call a function within your SWF file.

So for instance, you could set up a function called stopPlaying() and that's that.

Then, you set up a JavaScript function called playVideo(string:String) that calls stopPlaying() on every SWF file except the one that is associated with the string that you pass in.

Whenever someone hits play in one of your SWF files, do ExternalInterface.call("playVideo", "myString") and your JavaScript function should work.

Title: Play only one SWF file at a time

Body:
How can I stop one SWF file playing when playing another in a HTML page?

I currently have a carousel that displays multiple SWF files and I don't want any overlapping of video or audio. I've been looking into LocalConnection and JavaScript options but with no luck.
My SWF files are currently ActionScript 3 and Flash Player 10.
I have a large play button on them, with the ActionScript code:

import fl.video.VideoEvent;
import fl.video.VideoState;

video.addEventListener(VideoEvent.STATE_CHANGE,showButton);
playVideoButton.addEventListener(MouseEvent.MOUSE_UP,playVideo);

function playVideo(event:MouseEvent):void {
    video.play();
    playVideoButton.visible=false;
}

function showButton(event:VideoEvent):void {
    switch (event.target.state) {
        case "stopped" :
            playVideoButton.visible=true;
            break;
        case "playing" :
            playVideoButton.visible=false;
            break;
        case "paused" :
            playVideoButton.visible=true;
            break;
    }
}

Is there a way to incoporate a "stop the other SWF files playing" in this somehow?


来源: stackexchange

问:
UIBezierPath not equally fat everywhere and cut off
I am trying to draw a line with a smooth quadratic curve attached to its end. Therefore, I am using this code:

```<code>import Foundation
import UIKit

class IndicatingView: UIView {
    var path: UIBezierPath!

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    func createLineWithCurve() {
        path = UIBezierPath()

        path.move(to: CGPoint(x: 0, y: 0))

        path.addLine(to: CGPoint(x: 0, y: self.frame.height - self.frame.width))

        path.addQuadCurve(to: CGPoint(x: self.frame.width, y: self.frame.height), controlPoint: CGPoint(x: 0, y: self.frame.height))
    }

    override func draw(_ rect: CGRect) {
        self.createLineWithCurve()

        path.lineWidth = 3
        // Specify a border (stroke) color.
        UIColor.purple.setStroke()
        path.stroke()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
</code>```

And the output I get looks quite good already:

However, as you can see, the quad-curve is fatter than the normal line. Also, the quad-curve seems to be cut off at the bottom. How can I fix that? I want the path to be completely smooth without looking fatter at some points or being cut-off somehow.

Thanks in advance for your help :)

答:
here you see my "result" -> i made the linewidth a bit bigger that you can see, it paints perfect ;)

Apple draws always exactly on point, so if you paint a line of width 3 on point 0,0, one point is -1,0, one on 0,0 and one on 1,0

ContentLicense: CC BY-SA 4.0

Body:
I am trying to draw a line with a smooth quadratic curve attached to its end. Therefore, I am using this code:

import Foundation
import UIKit

class IndicatingView: UIView {
    var path: UIBezierPath!

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    func createLineWithCurve() {
        path = UIBezierPath()

        path.move(to: CGPoint(x: 0, y: 0))

        path.addLine(to: CGPoint(x: 0, y: self.frame.height - self.frame.width))

        path.addQuadCurve(to: CGPoint(x: self.frame.width, y: self.frame.height), controlPoint: CGPoint(x: 0, y: self.frame.height))
    }

    override func draw(_ rect: CGRect) {
        self.createLineWithCurve()

        path.lineWidth = 3
        // Specify a border (stroke) color.
        UIColor.purple.setStroke()
        path.stroke()
    }

    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

And the output I get looks quite good already:

However, as you can see, the quad-curve is fatter than the normal line. Also, the quad-curve seems to be cut off at the bottom. How can I fix that? I want the path to be completely smooth without looking fatter at some points or being cut-off somehow.

Thanks in advance for your help :)


问:
Hibernate: add existing child entity to new entity with OneToMany bidirectional relationship and persist it ('detached entity passed to persist')
In order to understand why I have persisted child entities, here is the mapping.

I have Author (id, name, books) and Book (id, title, authors) entities. Their relationship is ManyToMany since any Author may have more than one Book, and any Book may have more than one Author. Also I have BookClient (id, name, rentDate, books) - relationship with Book entity is OneToMany since any Client may rent zero to many books.

Author.java

```<code>@Table
public class Author {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String name;

    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "books_authors",
            joinColumns = { @JoinColumn(name = "author_id") },
            inverseJoinColumns = { @JoinColumn(name = "book_id") }
    )
    private Set<Book> books = new HashSet<>();
</code>```

Book.java

```<code>@Entity
@Table
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(nullable = false, unique = true)
    private Long id;

    @Column(nullable = false)
    private String title;

    @ManyToMany(mappedBy = "books", fetch = FetchType.EAGER)
    private Set<Author> authors = new HashSet<>();

    @ManyToOne
    @JoinColumn(name = "client_id")
    private BookClient bookClient;
</code>```

BookClient.java

```<code>@Entity
@Table
public class BookClient {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "client_id")
    private Long id;

    @Column(nullable = false)
    private String name;

    @OneToMany(mappedBy = "bookClient", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    private Set<Book> books = new HashSet<>();

    private LocalDate rentDate;
</code>```

Some business logic behind the scenes: there're a lot of books written by different authors which are persisted in DB of some, let's say, library. And this library gives books to clients. Any new client may register in the library when he/she takes a book.

Book clients are persisted using Entity Manager:

```<code>@Transactional
@Repository("bookClientDao")
public class BookClientDaoImpl implements BookClientDao {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public void save(BookClient bookClient) {
        entityManager.persist(bookClient);
    }

    @Override
    public void saveOrUpdate(BookClient bookClient) {
        if(bookClient.getId() == null) {
            save(bookClient);
        } else {
            entityManager.merge(bookClient);
        }
    }
}
</code>```

Here is an example of how it may look like in code:

```<code>    public static void main(String[] args) {
        ApplicationContext appContext = new ClassPathXmlApplicationContext("META-INF/context.xml");
        AuthorDao authorDao = (AuthorDao) appContext.getBean("authorDao");
        BookClientDao bookClientDao = (BookClientDao) appContext.getBean("bookClientDao");

        //Create a book and its author
        Book book = new Book();
        book.setTitle("John Doe Book the 1st");

        Author author = new Author();
        author.setName("John Doe");
        author.getBooks().add(book);
        authorDao.save(author);

        //Registering new Book Client
        BookClient bookClient = new BookClient();
        bookClient.setName("First Client");
        bookClient.getBooks().add(book);
        bookClient.setRentDate(LocalDate.now());

        book.setBookClient(bookClient);

        //book is expected to be updated by cascade
        bookClientDao.saveOrUpdate(bookClient); //'detached entity passed to persist' occurs here
    }
</code>```

After running this code I get detached entity passed to persist exception since Book instance has already been persisted earlier.

```<code>Exception in thread "main" javax.persistence.PersistenceException:
org.hibernate.PersistentObjectException: detached entity passed to persist: entity.manager.example.entity.Book
...
Caused by: org.hibernate.PersistentObjectException:
detached entity passed to persist: entity.manager.example.entity.Book
</code>```

If I persist BookClient berforehand, then connection between BookClient and Book is set correctly since both entities are existed in DB. But it seems to me as some workaround.

Is it possible to create new object, connect already persisted entity to it and persist this object with cascade update of all its children?

答:
In your example, save operation for the author and the bookClient executes in different persistence contexts. So as for the main method, first you should merge books (into saveOrUpdate method) that were detached during saving the author.

Is it possible to create new object, connect already persisted entity to it and persist this object with cascade update of all its children?

It may depend on your application requirements and functionality. In this main() example, it looks like you want to save all these entities transactionally.

Body:
In order to understand why I have persisted child entities, here is the mapping.

I have Author (id, name, books) and Book (id, title, authors) entities. Their relationship is ManyToMany since any Author may have more than one Book, and any Book may have more than one Author. Also I have BookClient (id, name, rentDate, books) - relationship with Book entity is OneToMany since any Client may rent zero to many books.

Author.java

@Table
public class Author {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String name;

    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "books_authors",
            joinColumns = { @JoinColumn(name = "author_id") },
            inverseJoinColumns = { @JoinColumn(name = "book_id") }
    )
    private Set<Book> books = new HashSet<>();

Book.java

@Entity
@Table
public class Book {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(nullable = false, unique = true)
    private Long id;

    @Column(nullable = false)
    private String title;

    @ManyToMany(mappedBy = "books", fetch = FetchType.EAGER)
    private Set<Author> authors = new HashSet<>();

    @ManyToOne
    @JoinColumn(name = "client_id")
    private BookClient bookClient;

BookClient.java

@Entity
@Table
public class BookClient {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "client_id")
    private Long id;

    @Column(nullable = false)
    private String name;

    @OneToMany(mappedBy = "bookClient", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    private Set<Book> books = new HashSet<>();

    private LocalDate rentDate;

Some business logic behind the scenes: there're a lot of books written by different authors which are persisted in DB of some, let's say, library. And this library gives books to clients. Any new client may register in the library when he/she takes a book.

Book clients are persisted using Entity Manager:

@Transactional
@Repository("bookClientDao")
public class BookClientDaoImpl implements BookClientDao {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public void save(BookClient bookClient) {
        entityManager.persist(bookClient);
    }

    @Override
    public void saveOrUpdate(BookClient bookClient) {
        if(bookClient.getId() == null) {
            save(bookClient);
        } else {
            entityManager.merge(bookClient);
        }
    }
}

Here is an example of how it may look like in code:

    public static void main(String[] args) {
        ApplicationContext appContext = new ClassPathXmlApplicationContext("META-INF/context.xml");
        AuthorDao authorDao = (AuthorDao) appContext.getBean("authorDao");
        BookClientDao bookClientDao = (BookClientDao) appContext.getBean("bookClientDao");

        //Create a book and its author
        Book book = new Book();
        book.setTitle("John Doe Book the 1st");

        Author author = new Author();
        author.setName("John Doe");
        author.getBooks().add(book);
        authorDao.save(author);

        //Registering new Book Client
        BookClient bookClient = new BookClient();
        bookClient.setName("First Client");
        bookClient.getBooks().add(book);
        bookClient.setRentDate(LocalDate.now());

        book.setBookClient(bookClient);

        //book is expected to be updated by cascade
        bookClientDao.saveOrUpdate(bookClient); //'detached entity passed to persist' occurs here
    }

After running this code I get detached entity passed to persist exception since Book instance has already been persisted earlier.

Exception in thread "main" javax.persistence.PersistenceException:
org.hibernate.PersistentObjectException: detached entity passed to persist: entity.manager.example.entity.Book
...
Caused by: org.hibernate.PersistentObjectException:
detached entity passed to persist: entity.manager.example.entity.Book

If I persist BookClient berforehand, then connection between BookClient and Book is set correctly since both entities are existed in DB. But it seems to me as some workaround.

Is it possible to create new object, connect already persisted entity to it and persist this object with cascade update of all its children?


问:
jQuery variable scope within each
I am trying to build an array containing all the values of every form element. The alert works just find, but on console.log data is empty, am I failing to understand how scoping in javascript works?

```<code>  var data = new Array();
  $("#page2 input").each(function(index) {
      alert($(this).attr('id'));
      data[$(this).attr('id')] = $(this).val();
  });
</code>```

Many thanks for your time,

答:
One thing to know is that an Array in JavaScript can only ever have positive integer indexes (which are really treated as strings).

When you assign a string to the key, you are assigning properties to an Object.

You probably want something like this...

```<code>var data = {};
$("#page2 input").each(function() {
   data[this.id] = this.value;
});
</code>```

jsFiddle.

If you wanted just the id attributes.

```<code>var data = $("#page2 input").map(function() {
               return this.id;
           }).get();
</code>```

jsFiddle.

ContentLicense: CC BY-SA 3.0

Title: jQuery variable scope within each

Body:
I am trying to build an array containing all the values of every form element. The alert works just find, but on console.log data is empty, am I failing to understand how scoping in javascript works?

  var data = new Array();
  $("#page2 input").each(function(index) {
      alert($(this).attr('id'));
      data[$(this).attr('id')] = $(this).val();
  });

Many thanks for your time,

Body:
One thing to know is that an Array in JavaScript can only ever have positive integer indexes (which are really treated as strings).

When you assign a string to the key, you are assigning properties to an Object.

You probably want something like this...

var data = {};
$("#page2 input").each(function() {
   data[this.id] = this.value;
});

jsFiddle.

If you wanted just the id attributes.

var data = $("#page2 input").map(function() {
               return this.id;
           }).get();

jsFiddle.


问:
How to get autocomplete in jupyter notebook without using tab?
I would like to get an autocompletion feature in notebooks i.e. when I type something, a dropdown menu appears, with all the possible things I might type, without having to press the tab button. Is there such a thing?

I tried :

%config IPCompleter.greedy=True

but this requires the tab button to be pressed

答:
Add the below to your keyboard user preferences on jupyter lab (Settings->Advanced system editor)</p>

```<code>{
    "shortcuts":[
        {
            "command": "completer:invoke-file",
            "keys": [
                "Ctrl Space"
            ],
            "selector": ".jp-FileEditor .jp-mod-completer-enabled"
        },
        {
            "command": "completer:invoke-file",
            "keys": [
                "Ctrl Space"
            ],
            "selector": ".jp-FileEditor .jp-mod-completer-enabled"
        },
        {
            "command": "completer:invoke-notebook",
            "keys": [
                "Ctrl Space"
            ],
            "selector": ".jp-Notebook.jp-mod-editMode .jp-mod-completer-enabled"
        }

    ]
}
</code>```

Body:
Add the below to your keyboard user preferences on jupyter lab (Settings->Advanced system editor)

{
    "shortcuts":[
        {
            "command": "completer:invoke-file",
            "keys": [
                "Ctrl Space"
            ],
            "selector": ".jp-FileEditor .jp-mod-completer-enabled"
        },
        {
            "command": "completer:invoke-file",
            "keys": [
                "Ctrl Space"
            ],
            "selector": ".jp-FileEditor .jp-mod-completer-enabled"
        },
        {
            "command": "completer:invoke-notebook",
            "keys": [
                "Ctrl Space"
            ],
            "selector": ".jp-Notebook.jp-mod-editMode .jp-mod-completer-enabled"
        }

    ]
}


问:
How to show exactly 4 numbers after decimal point without rounding in Python?
I want to calculate square root of numbers and print them with exactly 4 numbers after decimal point without rounding.
This code rounds the numbers

```<code>num="%.4f" % num
</code>```

and this one doesn't show 1.0000 or numbers like this.

```<code>num=math.floor(num * 10000)/10000
</code>```

答:
You could convert the number to a string, then use string manipulation:</p>

```<code>def numberWithoutRounding(num, precision=4):
    [beforeDecimal, afterDecimal] = str(num).split('.')
    return beforeDecimal + '.' + afterDecimal[0:precision]
</code>```

```<code>>>> numberWithoutRounding(1.43219)
'1.4321'
</code>```

Body:
I want to calculate square root of numbers and print them with exactly 4 numbers after decimal point without rounding.
This code rounds the numbers

num="%.4f" % num

and this one doesn't show 1.0000 or numbers like this.

num=math.floor(num * 10000)/10000

Body:
You could convert the number to a string, then use string manipulation:

def numberWithoutRounding(num, precision=4):
    [beforeDecimal, afterDecimal] = str(num).split('.')
    return beforeDecimal + '.' + afterDecimal[0:precision]

>>> numberWithoutRounding(1.43219)
'1.4321'


问:
How do you declare a value constrained type?
Ada

```<code>type Year_type is range 1800 .. 2100;
</code>```

Raku

```<code>subset Natural of Int where * ≥ 0;
</code>```

Kavorka

```<code>Int $even where { $_ % 2 == 0 }
</code>```

TS

```<code>type Natural = BigInteger /* hypothetical → */ where (n) => { return n >= 0 };
</code>```

答:
You can't, at least as of TS3.8.

There is an open suggestion, microsoft/TypeScript#15480 to support a ranged numeric type; if you want to see that happen you might want to go to that issue, give it a , and maybe describe your use case if you think it's particularly compelling and not already accounted for.

For the "even number" type in one of your examples, you'd need something else entirely; probably as a prerequisite you'd need the compiler to be able to perform arithmetic at the type level, which it currently does not do.  As usual, there's an existing open issue for that, microsoft/TypeScript#26382, but I don't know if that will ever seriously happen.  Dependent types are great but I don't know if they will happen anytime soon in the language.

Until then the best you can do is make a nominal-like type and a user-defined type guard to allow values to be of the proper type.  But all that's doing is forcing developers to perform a bunch of runtime tests every time they want to use your constrained type, since the compiler can't enforce or check it:

```<code>type EvenNumber = number & { ___isEven: true };

function isEven(x: number): x is EvenNumber {
  return x % 2 == 0;
}

function divideByTwoEvenly(x: EvenNumber): number {
  return x / 2;
}

const a = divideByTwoEvenly(100); // error! 100 is not an EvenNumber
const hundred = 100;
if (isEven(hundred)) {
  const a = divideByTwoEvenly(hundred);
} else {
  throw new Error("I'm SAD");
}
</code>```

Not so great.  Oh well, hope that helps; good luck!

Playground link to code

Body:
Ada

type Year_type is range 1800 .. 2100;

Raku

subset Natural of Int where * ≥ 0;

Kavorka

Int $even where { $_ % 2 == 0 }

TS

type Natural = BigInteger /* hypothetical → */ where (n) => { return n >= 0 };

Body:
You can't, at least as of TS3.8.

There is an open suggestion, microsoft/TypeScript#15480 to support a ranged numeric type; if you want to see that happen you might want to go to that issue, give it a , and maybe describe your use case if you think it's particularly compelling and not already accounted for.

For the "even number" type in one of your examples, you'd need something else entirely; probably as a prerequisite you'd need the compiler to be able to perform arithmetic at the type level, which it currently does not do.  As usual, there's an existing open issue for that, microsoft/TypeScript#26382, but I don't know if that will ever seriously happen.  Dependent types are great but I don't know if they will happen anytime soon in the language.

Until then the best you can do is make a nominal-like type and a user-defined type guard to allow values to be of the proper type.  But all that's doing is forcing developers to perform a bunch of runtime tests every time they want to use your constrained type, since the compiler can't enforce or check it:

type EvenNumber = number & { ___isEven: true };

function isEven(x: number): x is EvenNumber {
  return x % 2 == 0;
}

function divideByTwoEvenly(x: EvenNumber): number {
  return x / 2;
}

const a = divideByTwoEvenly(100); // error! 100 is not an EvenNumber
const hundred = 100;
if (isEven(hundred)) {
  const a = divideByTwoEvenly(hundred);
} else {
  throw new Error("I'm SAD");
}

Not so great.  Oh well, hope that helps; good luck!

Playground link to code


问:
Could not attach to pid: "1839"

Hello there, I've got this issue in Xcode. I've googled it, but was unsuccessfully, nothing helps me. Can someone help, please?

答:
You can try running this in the terminal.</p>

```<code>sudo DevToolsSecurity -enable
</code>```

Title: Could not attach to pid: "1839"

Body:
You can try running this in the terminal.

sudo DevToolsSecurity -enable


问:
Python git package get tag and commit
I would like to print a git commit and the tag in my Python code.
How can I do this using git package?

When I am going to my Bitbucket I see

```<code>tag: 73-2-g46b9856

commit checksum: 46b9856
</code>```

How can I retrieve this info from git package?

I have done the following:

```<code>import git
repo = git.Repo(search_parent_directories=True)
sha = repo.head.object.hexsha
</code>```

答:
Here is what solved my issue:</p>

```<code>repo = git.Repo(search_parent_directories = True)
sha = repo.head.object.hexsha

commit_chksum = repo.git.rev_parse(sha, short = 7)
tag = subprocess.check_output(["git", "describe", "--always"]).strip().decode()
</code>```

Title: Python git package get tag and commit

Body:
I would like to print a git commit and the tag in my Python code.
How can I do this using git package?

When I am going to my Bitbucket I see

tag: 73-2-g46b9856

commit checksum: 46b9856

How can I retrieve this info from git package?

I have done the following:

import git
repo = git.Repo(search_parent_directories=True)
sha = repo.head.object.hexsha

Body:
Here is what solved my issue:

repo = git.Repo(search_parent_directories = True)
sha = repo.head.object.hexsha

commit_chksum = repo.git.rev_parse(sha, short = 7)
tag = subprocess.check_output(["git", "describe", "--always"]).strip().decode()


问:
Make a play pause switch with html audio
I'm looking for a way to do a play / pause action on click of an element.

Basically when you click and the track is not playing it plays and when it's playing and you click it stops.

So far I was looking for a solution like this but it seems to make a conflict between the play / pause action.

```<code>$('#feli').click(function() {
  feli.currentTime = 0;
  if (feli.play()) {
    feli.pause();
  } else {
    feli.play();;
  }
})
</code>```

Any tips on how to do this simple action ?

Thanks !!

答:
Found my solution I put it here :</p>

```<code>$('#feli').click(function() {
  if (feli.paused) {
    feli.currentTime = 0;
    feli.play();
  } else {
    feli.pause();
  }
})
</code>```

Body:
I'm looking for a way to do a play / pause action on click of an element.

Basically when you click and the track is not playing it plays and when it's playing and you click it stops.

So far I was looking for a solution like this but it seems to make a conflict between the play / pause action.

$('#feli').click(function() {
  feli.currentTime = 0;
  if (feli.play()) {
    feli.pause();
  } else {
    feli.play();;
  }
})

Any tips on how to do this simple action ?

Thanks !!

Body:
Found my solution I put it here :

$('#feli').click(function() {
  if (feli.paused) {
    feli.currentTime = 0;
    feli.play();
  } else {
    feli.pause();
  }
})


答:
If you're using the input id as a key what you're creating is an Object, not an Array.</p>

```<code>var data = new Object();
</code>```

Title: jQuery variable scope within each

Body:
If you're using the input id as a key what you're creating is an Object, not an Array.

var data = new Object();


问:
OnClickListener in RecyclerView Adapter not initialized
I am trying to add an OnClickListener to a recycler view item i however keep getting this error

```<code>lateinit property listener has not been initialized
</code>```

Here is how my adapter looks like

```<code>class CartAdapter(private val cartItems: List<CartItemEntity>? = null) : RecyclerView.Adapter<CartAdapter.CartViewHolder>() {

    private lateinit var listener: OnItemClickListener

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CartViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.cart_item, parent, false)
        return CartViewHolder(view, cartItems!!, listener)
    }

    override fun getItemCount() = cartItems!!.size

    override fun onBindViewHolder(holder: CartViewHolder, position: Int) {
        val cartItem = cartItems?.get(position)
        holder.productPrice.text = cartItem.productPrice.toInt().toString()
        holder.cart = listOf(cartItem)
    }

    class CartViewHolder(val view: View, var cart: List<CartItemEntity>, listener: OnItemClickListener) : RecyclerView.ViewHolder(view) {
        private val cartRemove: TextView = view.findViewById(R.id.cartRemove)

        init {
            cartRemove.setOnClickListener {
                listener.onItemClick(cart)
            }

        }
    }

    interface OnItemClickListener{
        fun onItemClick(cartItems: List<CartItemEntity>?)
    }

    fun setOnItemClickListener(listener: OnItemClickListener){
        this.listener = listener
    }

}
</code>```

This is how i am implementing it in my Fragment

```<code>adapter!!.setOnItemClickListener(object : CartAdapter.OnItemClickListener{
            override fun onItemClick(cartItems: List<CartItemEntity>?) {
                Log.e("Cart Item", ""+ cartItems!![0].id)
            }
        })
</code>```

Not sure what am doing wrong

答:
You can add the listener as part of your CartAdapter constructor

```<code>class CartAdapter(private val cartItems: List<CartItemEntity>? = null, itemListener: OnItemClickListener) : RecyclerView.Adapter<CartAdapter.CartViewHolder>() {

    private val listener: OnItemClickListener = itemListener

    ...

    interface OnItemClickListener{
        fun onItemClick(cartItems: List<CartItemEntity>?)
    }
}
</code>```

Then from your activity, pass the listener when you initialize the adapter

```<code>    val adapter = CartAdapter(itemList, object: CartAdapter.OnItemClickListener {
        override fun onItemClick(cartItems: List<CartItemEntity>?) {
            Log.e("Cart Item", ""+ cartItems!![0].id)
        }
    })
</code>```

Body:
I am trying to add an OnClickListener to a recycler view item i however keep getting this error

lateinit property listener has not been initialized

Here is how my adapter looks like

class CartAdapter(private val cartItems: List<CartItemEntity>? = null) : RecyclerView.Adapter<CartAdapter.CartViewHolder>() {

    private lateinit var listener: OnItemClickListener

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CartViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.cart_item, parent, false)
        return CartViewHolder(view, cartItems!!, listener)
    }

    override fun getItemCount() = cartItems!!.size

    override fun onBindViewHolder(holder: CartViewHolder, position: Int) {
        val cartItem = cartItems?.get(position)
        holder.productPrice.text = cartItem.productPrice.toInt().toString()
        holder.cart = listOf(cartItem)
    }

    class CartViewHolder(val view: View, var cart: List<CartItemEntity>, listener: OnItemClickListener) : RecyclerView.ViewHolder(view) {
        private val cartRemove: TextView = view.findViewById(R.id.cartRemove)

        init {
            cartRemove.setOnClickListener {
                listener.onItemClick(cart)
            }

        }
    }

    interface OnItemClickListener{
        fun onItemClick(cartItems: List<CartItemEntity>?)
    }

    fun setOnItemClickListener(listener: OnItemClickListener){
        this.listener = listener
    }

}

This is how i am implementing it in my Fragment

adapter!!.setOnItemClickListener(object : CartAdapter.OnItemClickListener{
            override fun onItemClick(cartItems: List<CartItemEntity>?) {
                Log.e("Cart Item", ""+ cartItems!![0].id)
            }
        })

Not sure what am doing wrong

Body:
You can add the listener as part of your CartAdapter constructor

class CartAdapter(private val cartItems: List<CartItemEntity>? = null, itemListener: OnItemClickListener) : RecyclerView.Adapter<CartAdapter.CartViewHolder>() {

    private val listener: OnItemClickListener = itemListener

    ...

    interface OnItemClickListener{
        fun onItemClick(cartItems: List<CartItemEntity>?)
    }
}

Then from your activity, pass the listener when you initialize the adapter

    val adapter = CartAdapter(itemList, object: CartAdapter.OnItemClickListener {
        override fun onItemClick(cartItems: List<CartItemEntity>?) {
            Log.e("Cart Item", ""+ cartItems!![0].id)
        }
    })


问:
Using Selenium in Python to click all buttons in a webpage
I am trying to click on all the buttons on a webpage. I'd like to be able to click them all.
webpage
i can click on one of them by using css selector

```<code>browser.find_element_by_css_selector('li.clickable_area:nth-child(1) > div:nth-child(3)').click()
</code>```

these are the css selector for the 5 buttons

the 5 buttons follow this pattern:

Button 1: li.clickable_area: nth - child(1) > div:nth - child(3)

Button 2: li.clickable_area: nth - child(2) > div:nth - child(3)

Button 3: li.clickable_area: nth - child(3) > div:nth - child(3)

Button 4: li.clickable_area: nth - child(4) > div:nth - child(3)

Button 5: li.clickable_area: nth - child(5) > div:nth - child(3)

How i can i click them all using css selector without writing a code for each one?

答:
Make a list of all buttons and iterate it. Please try below code:

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

    buttons=WebDriverWait(browser,30).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "li.clickable_area > div:nth-child(3)")))
        for x in range(0,len(buttons)):
            if buttons[x].is_displayed():
                buttons[x].click()
</code>```

OR

```<code>buttons=WebDriverWait(browser,30).until(EC.visibility_of_all_elements_located((By.XPATH, "//div[contains(text(), 'Button ')]")))
        for x in range(0,len(buttons)):
           button = WebDriverWait(driver, 50).until(EC.presence_of_element_located((By.XPATH, "//div[contains(text(), 'Button ')]")))
                   button.click()
</code>```

Body:
I am trying to click on all the buttons on a webpage. I'd like to be able to click them all.
webpage
i can click on one of them by using css selector

browser.find_element_by_css_selector('li.clickable_area:nth-child(1) > div:nth-child(3)').click()

these are the css selector for the 5 buttons

the 5 buttons follow this pattern:

Button 1: li.clickable_area: nth - child(1) > div:nth - child(3)

Button 2: li.clickable_area: nth - child(2) > div:nth - child(3)

Button 3: li.clickable_area: nth - child(3) > div:nth - child(3)

Button 4: li.clickable_area: nth - child(4) > div:nth - child(3)

Button 5: li.clickable_area: nth - child(5) > div:nth - child(3)

How i can i click them all using css selector without writing a code for each one?

Body:
Make a list of all buttons and iterate it. Please try below code:

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

    buttons=WebDriverWait(browser,30).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "li.clickable_area > div:nth-child(3)")))
        for x in range(0,len(buttons)):
            if buttons[x].is_displayed():
                buttons[x].click()

OR

buttons=WebDriverWait(browser,30).until(EC.visibility_of_all_elements_located((By.XPATH, "//div[contains(text(), 'Button ')]")))
        for x in range(0,len(buttons)):
           button = WebDriverWait(driver, 50).until(EC.presence_of_element_located((By.XPATH, "//div[contains(text(), 'Button ')]")))
                   button.click()


问:
jQuery html() function with javascript
It appears that the .html function doesn't return javascript.  Is there a function that returns both javascript and html?

EDIT:

Example:

Main Page

```<code>$.ajax({
  url: 'ajaxpage.php',
  type: 'post',
  data: postvars,
  cache: false,
  dataType: 'html',
  success: function (html) {
    $('#content').html($(html).find('#content').html());
  }
});
</code>```

ajaxpage.php

```<code><html>
<body>
<div id="content">
   //SOME HTML
   <script type="text/javascript">
      //SOME JAVASCRIPT
   </script>
</div>
</body>
</html>
</code>```

$(html).find('#content').html() returns

```<code>   //SOME HTML
</code>```

while I want

```<code>   //SOME HTML
   <script type="text/javascript">
      //SOME JAVASCRIPT
   </script>
</code>```

答: Looks like some of jQuery's insertion methods (like html or append) process the code for possible injections, removing script tags along the way. You can take a look at the answers to this question, or see the relevant comment in the jQuery API docs.</p>

Title: jQuery html() function with javascript

Body:
It appears that the .html function doesn't return javascript.  Is there a function that returns both javascript and html?

EDIT:

Example:

Main Page

$.ajax({
  url: 'ajaxpage.php',
  type: 'post',
  data: postvars,
  cache: false,
  dataType: 'html',
  success: function (html) {
    $('#content').html($(html).find('#content').html());
  }
});

ajaxpage.php

   //SOME HTML

$(html).find('#content').html() returns

   //SOME HTML

while I want

   //SOME HTML


问:
How to get all the strings after a specific index?
Suppose I have this string: /ban 1d hello world which is essentially a command sended to a bot, meaning:

/ban specify to ban the user

1d represents the time

hello world is the reason

I need to get the reason, so I did:

let c = '/ban 1d hello world';
let arr = c.split(' ');
let result = c.replace(arr[0], '');
result = result.replace(arr[1], '')
alert(result);```

this is working, but I would like to ask if there is a better way to achieve this.

Kind regards.

答:
If you know the concrete format of the command parts, you could use a regex to get each individual part this way:

let c = '/ban 1d hello world';

var regex = /\/([a-z]+)\ ([0-9]+[a-z])\ (.*)/g;
var resultArray = regex.exec(c);

console.log(resultArray);

let command = resultArray[1] //ban
let time = resultArray[2]; //1d
let result = resultArray[3]; //hello world

console.log(result);```

Body:
Suppose I have this string: /ban 1d hello world which is essentially a command sended to a bot, meaning:

/ban specify to ban the user

1d represents the time

hello world is the reason

I need to get the reason, so I did:

let c = '/ban 1d hello world';
let arr = c.split(' ');
let result = c.replace(arr[0], '');
result = result.replace(arr[1], '')
alert(result);

this is working, but I would like to ask if there is a better way to achieve this.

Kind regards.


问:
Twilio. Set Fax Webhook programmatically using the API
My application wants to dynamically purchase new FAX numbers when the pool of serviced users exceeds a certain amount.  I am able to do this programmatically from API like this (C#):

```<code>using Twilio;
using Twilio.Rest.Fax.V1;
using Twilio.Rest.Api.V2010.Account;

var incomingPhoneNumber = IncomingPhoneNumberResource.Create(
  statusCallback: new Uri("https://myapp.co/api/v1/fax/twiliostatus"),
  statusCallbackMethod:Twilio.Http.HttpMethod.Post,
  pathAccountSid:"xxx",
  phoneNumber: new Twilio.Types.PhoneNumber(numbers[i].PhoneNumber)
  );
</code>```

...but I don't see any mechanism for setting the value corresponding to the "A Fax Comes In" webhook (where I set method and URI) in the portal.  Is there a way I can set this from the API?

thanks in advance!

答:
It looks like the attribute you need to set is voiceReceiveMode.

IncomingPhoneNumber resource

The configuration parameter for the new phone number to receive incoming voice calls or faxes. Can be: fax or voice and defaults to voice.

Body:
My application wants to dynamically purchase new FAX numbers when the pool of serviced users exceeds a certain amount.  I am able to do this programmatically from API like this (C#):

using Twilio;
using Twilio.Rest.Fax.V1;
using Twilio.Rest.Api.V2010.Account;

var incomingPhoneNumber = IncomingPhoneNumberResource.Create(
  statusCallback: new Uri("https://myapp.co/api/v1/fax/twiliostatus"),
  statusCallbackMethod:Twilio.Http.HttpMethod.Post,
  pathAccountSid:"xxx",
  phoneNumber: new Twilio.Types.PhoneNumber(numbers[i].PhoneNumber)
  );

...but I don't see any mechanism for setting the value corresponding to the "A Fax Comes In" webhook (where I set method and URI) in the portal.  Is there a way I can set this from the API?

thanks in advance!


问:
Counting elements in a list that only occur once: how do I optimise my performance? It's very slow
I have a large list that contains usernames (about 60,000 strings). Each username represents a submission. Some users have made only one submission i.e. they are "one-time users", so their username appears only once in this list. Others have made multiple submission (returning users) so their username can appear many times in this list. I want to count how many of these one-time users there are and get some stats based on that. Here are the variables I'm currently grabbing:

import time

start_time = time.time()

users = ["UserA", "UserB", "UserC", "UserA", "UserA", "UserA", "UserB", "UserB", "UserD"] # ...just a sample, this goes up to ~60,000 elements
print(f"1: got users list. Time elapsed: {time.time() - start_time}")

one_time_users = [user for user in users if users.count(user) == 1]
print(f"2: got one-time users list. Time elapsed: {time.time() - start_time}")

returning_users = [user for user in users if users.count(user) != 1]
print(f"3: got returning users list. Time elapsed: {time.time() - start_time}")

frequencies = [users.count(user) for user in set(users)]
print(f"4: calculated frequencies list. Time elapsed: {time.time() - start_time}")

sorted_frequencies = sorted(frequencies, reverse=True) # Descending order, largest first
print(f"5: got sorted frequencies list. Time elapsed: {time.time() - start_time}")

top_ten_frequencies_sum = sum(sorted_frequencies[:10])
print(f"6: got top 10 frequencies sum. Time elapsed: {time.time() - start_time}")

top_ten_frequencies_percentage = round(((top_ten_frequencies_sum / len(users)) * 100), 2)
print(f"7: got top 10 frequencies percentage. Time elapsed: {time.time() - start_time}")

average_submissions_per_user = round(len(users) / len(set(users)), 2)
print(f"8: got average submissions per user. Time elapsed: {time.time() - start_time}")
```

<p>This operation is <strong>very slow.</strong> Here is my output:</p>

```1: got users list. Time elapsed: 0.41695237159729004
2: got one-time users list. Time elapsed: 48.26731848716736
3: got returning users list. Time elapsed: 101.88410639762878
4: calculated frequencies list. Time elapsed: 104.39784860610962
5: got sorted frequencies list. Time elapsed: 104.39850783348083
6: got top 10 frequencies sum. Time elapsed: 104.39853930473328
7: got top 10 frequencies percentage. Time elapsed: 104.39856457710266
8: got average submissions per user. Time elapsed: 104.4005241394043
```

As you can see the list comprehensions are taking the most time. Can someone explain to me:

Why it's so slow in terms of time complexity.

Whether collections.Counter() will be a better choice and how best to apply it here.

Thank you!

答:
As mentioned in your own comment, Counter is significantly faster here. You can see from your own timing that creating a set of the results takes around 10ms to complete (#8->#9), which is roughly the time Counter will take as well.

With counter you look at at each of the N elements once, and then at each unique element (at most N) once.

When you use .count() you iterate through the entire list (a fast implementation, but still the entire list).  You do this for every element, so you look at each of N elements N times.

Every time your list gets 1000x bigger you require 1000x the time for the Counter method, but 1000000x for .count versions.

Body:
I have a large list that contains usernames (about 60,000 strings). Each username represents a submission. Some users have made only one submission i.e. they are "one-time users", so their username appears only once in this list. Others have made multiple submission (returning users) so their username can appear many times in this list. I want to count how many of these one-time users there are and get some stats based on that. Here are the variables I'm currently grabbing:

import time

start_time = time.time()

users = ["UserA", "UserB", "UserC", "UserA", "UserA", "UserA", "UserB", "UserB", "UserD"] # ...just a sample, this goes up to ~60,000 elements
print(f"1: got users list. Time elapsed: {time.time() - start_time}")

one_time_users = [user for user in users if users.count(user) == 1]
print(f"2: got one-time users list. Time elapsed: {time.time() - start_time}")

returning_users = [user for user in users if users.count(user) != 1]
print(f"3: got returning users list. Time elapsed: {time.time() - start_time}")

frequencies = [users.count(user) for user in set(users)]
print(f"4: calculated frequencies list. Time elapsed: {time.time() - start_time}")

sorted_frequencies = sorted(frequencies, reverse=True) # Descending order, largest first
print(f"5: got sorted frequencies list. Time elapsed: {time.time() - start_time}")

top_ten_frequencies_sum = sum(sorted_frequencies[:10])
print(f"6: got top 10 frequencies sum. Time elapsed: {time.time() - start_time}")

top_ten_frequencies_percentage = round(((top_ten_frequencies_sum / len(users)) * 100), 2)
print(f"7: got top 10 frequencies percentage. Time elapsed: {time.time() - start_time}")

average_submissions_per_user = round(len(users) / len(set(users)), 2)
print(f"8: got average submissions per user. Time elapsed: {time.time() - start_time}")

This operation is very slow. Here is my output:

1: got users list. Time elapsed: 0.41695237159729004
2: got one-time users list. Time elapsed: 48.26731848716736
3: got returning users list. Time elapsed: 101.88410639762878
4: calculated frequencies list. Time elapsed: 104.39784860610962
5: got sorted frequencies list. Time elapsed: 104.39850783348083
6: got top 10 frequencies sum. Time elapsed: 104.39853930473328
7: got top 10 frequencies percentage. Time elapsed: 104.39856457710266
8: got average submissions per user. Time elapsed: 104.4005241394043

As you can see the list comprehensions are taking the most time. Can someone explain to me:

Why it's so slow in terms of time complexity.

Whether collections.Counter() will be a better choice and how best to apply it here.

Thank you!


问:
Create a dictionary inside nested lists
Can someone explain how can I construct a dictionary inside lists? For example, I have this dictionary:

```<code>A = {'typeA': [12], 'typeB': [12, 13]}
</code>```

and I want to get this:

```<code>A = {'typeA': [{12: []}], 'typeB': [{12: []}, {13: []}]}
</code>```

I have tried something like this:

```<code>listFinal = []
for key in A.keys
---- newDict = {}
---- for value in A[key]:
--------- newDict[value] = []
newDict[key].append(value)
</code>```

But this isn't right...
This can be a little confusing and I believe it isn't that elegant. I'm sorry if this isn't a relevant question.

答:
If you just want to "transform" each item in each value to a single-element dict with an empty list, you can do:

A = {'typeA': [12], 'typeB': [12, 13]}

for lst in A.values():
    for i, val in enumerate(lst):
        lst[i] = {val: []}

print(A)
```

<p>Gives:</p>

<pre class="lang-none prettyprint-override"><code>{'typeA': [{12: []}], 'typeB': [{12: []}, {13: []}]}
</code>```

Going with your initial line-of-thought you probably meant for something similar to:

for key in A.keys():
    listFinal = []
    for value in A[key]:
        newDict = {value: []}
        listFinal.append(newDict)
    A[key] = listFinal
```

Which gives the same output

Title: Create a dictionary inside nested lists

Body:
Can someone explain how can I construct a dictionary inside lists? For example, I have this dictionary:

A = {'typeA': [12], 'typeB': [12, 13]}

and I want to get this:

A = {'typeA': [{12: []}], 'typeB': [{12: []}, {13: []}]}

I have tried something like this:

listFinal = []
for key in A.keys
---- newDict = {}
---- for value in A[key]:
--------- newDict[value] = []
newDict[key].append(value)

But this isn't right...
This can be a little confusing and I believe it isn't that elegant. I'm sorry if this isn't a relevant question.

Body:
If you just want to "transform" each item in each value to a single-element dict with an empty list, you can do:

A = {'typeA': [12], 'typeB': [12, 13]}

for lst in A.values():
    for i, val in enumerate(lst):
        lst[i] = {val: []}

print(A)

Gives:

{'typeA': [{12: []}], 'typeB': [{12: []}, {13: []}]}

Going with your initial line-of-thought you probably meant for something similar to:

for key in A.keys():
    listFinal = []
    for value in A[key]:
        newDict = {value: []}
        listFinal.append(newDict)
    A[key] = listFinal

Which gives the same output


问:
Redshift Query CPU time
I am trying to fetch the query_cpu_time value from SVL_QUERY_METRICS table in Redshift. But I want the date and time also for all the queries. Is there any system table or solution for this?

答:
you can use SVL_QLOG table and create a join with SVL_QUERY_METRICS on column query.

```<code>SELECT t.starttime,
       t.endtime,
       m.query_cpu_time
FROM   svl_qlog AS t
       JOIN svl_query_metrics AS m
         ON t.query = m.query
</code>```

Title: Redshift Query CPU time

Body:
you can use SVL_QLOG table and create a join with SVL_QUERY_METRICS on column query.

SELECT t.starttime,
       t.endtime,
       m.query_cpu_time
FROM   svl_qlog AS t
       JOIN svl_query_metrics AS m
         ON t.query = m.query


问:
<Lists> emptying themselves
Good evening,

I am having a weird issue with a method I am trying to implement on Java.
I will try and describe it as well as possible:

Basically what it does is checks for the next states an Epsilon-Non Deterministic State Machine would reach, given a state and an array of possible transitions.
The method "loadEpsilon(List)" loads up the possible epsilon transitions for the given list of states.

```<code>      if (transitionList.isEmpty()){
          return new HashSet<State>(stateEntryList);
      }
      else{
          for (int i=0; i <= transitionList.size()-1; i++){
              for (int j=0; j <= stateEntryList.size()-1; j++){
                  for (Transition tr : this.transitions()){
                      if ((tr.fromState() == stateEntryList.get(j)) && (tr.label() == transitionList.get(i))){
                          if (!stateExitList.contains(tr.toState())){
                              stateExitList.add(tr.toState());
                          }
                      }
                  }
              }
              stateEntryList.clear();
              stateEntryList = loadEpsilon(stateExitList);
              stateExitList.clear();
          }
          return new HashSet<State>(stateEntryList);
              }
</code>```

So, filling up the whole code with tracing "System.out.print"s right to the very end, just before the

```<code>    stateExitList.clear();
</code>```

everything is OK. However, past that line, I print BOTH lists RIGHT after that sentence (StateExitList and StateEntryList) and they are both GONE.

I just can't figure out why they are emptying themselves.

Any chance for help?

Thanks a lot in advanced.

EDIT: This here would be the code for loadEpsilon:

```<code>  public List<State> loadEpsilon(List<State> states) throws NoInitialStateException{
      State stateRead;
      if (states.isEmpty()){
          if (this.getInitialState() == null){
              throw new NoInitialStateException();
          }
          states.add(this.getInitialState());
          return loadEpsilon(states);
      }
      else{
          for (int i=0; i <= states.size()-1;i++){
              stateRead = states.get(i);
              for (Transition tr : this.transitions()){
                  if ((tr.fromState() == stateRead) && (tr.label().isEpsilon()) && (!states.contains(tr.toState()))){
                      states.add(tr.toState());
                      System.out.print(states.size());
                  }
              }
          }
      }
      return states;
  }
</code>```

The declaration of the lists are the following:

```<code>      List<State> stateEntryList = new ArrayList<State>();
      stateEntryList = loadEpsilon(stateEntryList);
      List<State> stateExitList = new ArrayList<State>();
      List<Label> listaLabels = new ArrayList<Label>();
      listaLabels.addAll(Arrays.asList(labels));
</code>```

答: Is loadEpsilon using deferred execution?  That would explain why emptying the list passed to it would result in the list it returns being empty.

Title: <Lists> emptying themselves

Body:
Good evening,

I am having a weird issue with a method I am trying to implement on Java.
I will try and describe it as well as possible:

Basically what it does is checks for the next states an Epsilon-Non Deterministic State Machine would reach, given a state and an array of possible transitions.
The method "loadEpsilon(List)" loads up the possible epsilon transitions for the given list of states.

      if (transitionList.isEmpty()){
          return new HashSet<State>(stateEntryList);
      }
      else{
          for (int i=0; i <= transitionList.size()-1; i++){
              for (int j=0; j <= stateEntryList.size()-1; j++){
                  for (Transition tr : this.transitions()){
                      if ((tr.fromState() == stateEntryList.get(j)) && (tr.label() == transitionList.get(i))){
                          if (!stateExitList.contains(tr.toState())){
                              stateExitList.add(tr.toState());
                          }
                      }
                  }
              }
              stateEntryList.clear();
              stateEntryList = loadEpsilon(stateExitList);
              stateExitList.clear();
          }
          return new HashSet<State>(stateEntryList);
              }

So, filling up the whole code with tracing "System.out.print"s right to the very end, just before the

    stateExitList.clear();

everything is OK. However, past that line, I print BOTH lists RIGHT after that sentence (StateExitList and StateEntryList) and they are both GONE.

I just can't figure out why they are emptying themselves.

Any chance for help?

Thanks a lot in advanced.

EDIT: This here would be the code for loadEpsilon:

  public List<State> loadEpsilon(List<State> states) throws NoInitialStateException{
      State stateRead;
      if (states.isEmpty()){
          if (this.getInitialState() == null){
              throw new NoInitialStateException();
          }
          states.add(this.getInitialState());
          return loadEpsilon(states);
      }
      else{
          for (int i=0; i <= states.size()-1;i++){
              stateRead = states.get(i);
              for (Transition tr : this.transitions()){
                  if ((tr.fromState() == stateRead) && (tr.label().isEpsilon()) && (!states.contains(tr.toState()))){
                      states.add(tr.toState());
                      System.out.print(states.size());
                  }
              }
          }
      }
      return states;
  }

The declaration of the lists are the following:

      List<State> stateEntryList = new ArrayList<State>();
      stateEntryList = loadEpsilon(stateEntryList);
      List<State> stateExitList = new ArrayList<State>();
      List listaLabels = new ArrayList();
      listaLabels.addAll(Arrays.asList(labels));


问:
VBA Access Transfertext Import Errors
I would like to import a spreadsheet to an access database, on column has ages 1-89 plus another that's says 90+ which in turn create a Import Error. Using the DoCmd.TransferText, is it possible to import everything as it is including 90+ in the column of all other numbers? </p>

答:
If you import data into a table that doesn't already exist, Access will create one for you. It automatically determines the data type of each column based on the first few rows that are imported. If your source data contains a mixture of data types in one column, then you may experience this error.

There are 2 solutions:

Build the import table to be of the correct data type for your data (i.e. specify that the age column is Short Text). Then import to the pre-defined import table.

Ensure that the CSV or Excel file stores each age as a string i.e. "20" instead of 20 (in Excel, format the cell as Text, so it is left aligned or start cell contents with an apostrophe '20 or use formulaic notation ="20").

You could do either of those things, but it would be better to do both of them if possible.

Title: VBA Access Transfertext Import Errors


问:
Delphi - ActionToolBar how to get Submenu property on Action execute event
In Delphi on ActionToolBar how to get "Tag" property of Submenu Item on Action->onExecute event.

So not Action Tag, I need TActionClientItem ("Open") tag property on submenu trigger that action OR Main Button (Action2) Tag or even Main Button ("Action2") index (position) on ActionToolBar … all on Submenu Action-> onExecute event

答:
AFAIK, that is not possible.

Usually the triggering component can be retrieved via the action's ActionComponent property, but doesn't work in this case because TActionClientItem is not derived from TComponent.


问:
Why am I getting "Invalid input syntax for type integer" in postgresql when importing a CSV?
I'm trying to import a .csv file to my postgresql DB.
I created a table as follows:

```<code>CREATE TABLE accounts
(
    acc_id integer,
    acc_name text,
    website text,
    lat numeric,
    longe numeric,
    primary_poc text,
    sales_rep_id integer
)
</code>```

Then I used the following command to import the .csv file

```<code>COPY accounts(acc_id,acc_name,website,lat,longe,primary_poc,sales_rep_id)
FROM 'D:\accounts.csv' DELIMITER ';' CSV ;
</code>```

And my .csv file contains the following:

```<code>1;Walmart;www.walmart.com;40.23849561;-75.10329704;Tamara Tuma;321500
2;Exxon Mobil;www.exxonmobil.com;41.16915630;-73.84937379;Sung Shields;321510
3;Apple;www.apple.com;42.29049481;-76.08400942;Jodee Lupo;321520
</code>```

However, this doesn't work and the following message appear:

```<code>ERROR:  invalid input syntax for type integer: "1"
CONTEXT:  COPY accounts, line 1, column acc_id: "1"
SQL state: 22P02
</code>```

答:
Maybe there is a BOM in the CSV?

hexdump the file, and inspect the first three characters

(and) use an editor to remove the BOM

(or) export again, without the BOM (there should be a checkmark, even in the Microsoft "software")

Body:
I'm trying to import a .csv file to my postgresql DB.
I created a table as follows:

CREATE TABLE accounts
(
    acc_id integer,
    acc_name text,
    website text,
    lat numeric,
    longe numeric,
    primary_poc text,
    sales_rep_id integer
)

Then I used the following command to import the .csv file

COPY accounts(acc_id,acc_name,website,lat,longe,primary_poc,sales_rep_id)
FROM 'D:\accounts.csv' DELIMITER ';' CSV ;

And my .csv file contains the following:

1;Walmart;www.walmart.com;40.23849561;-75.10329704;Tamara Tuma;321500
2;Exxon Mobil;www.exxonmobil.com;41.16915630;-73.84937379;Sung Shields;321510
3;Apple;www.apple.com;42.29049481;-76.08400942;Jodee Lupo;321520

However, this doesn't work and the following message appear:

ERROR:  invalid input syntax for type integer: "1"
CONTEXT:  COPY accounts, line 1, column acc_id: "1"
SQL state: 22P02


问:
Python Keras - Custom Labels in ImageDataGenerator
I am currently creating a CNN model that classifies whether the font is Arial, Verdana, Times New Roman and Georgia. All in all there are 16 classes since I considered also detecting whether the font is regular, bold, italics or bold italics. So 4 fonts * 4 styles = 16 classes.

The data that I have used in my training are the following:

```<code>Training data set : 800 image patches of 256 * 256 dimension (50 for each class)
Validation data set : 320 image patches of 256 * 256 dimension (20 for each class)
Testing data set : 160 image patches of 256 * 256 dimension (10 for each class)
</code>```

Below is my initial code:

```<code>import numpy as np
import keras
from keras import backend as K
from keras.models import Sequential
from keras.layers import Activation
from keras.layers.core import Dense, Flatten
from keras.optimizers import Adam
from keras.metrics import categorical_crossentropy
from keras.preprocessing.image import ImageDataGenerator
from keras.layers.normalization import BatchNormalization
from keras.layers.convolutional import *
from matplotlib import pyplot as plt
import itertools
import matplotlib.pyplot as plt
import pickle

 image_width = 256
 image_height = 256

 train_path = 'font_model_data/train'
 valid_path =  'font_model_data/valid'
 test_path = 'font_model_data/test'

  train_batches = ImageDataGenerator().flow_from_directory(train_path, target_size=(image_width, image_height), classes=['1','2','3','4', '5', '6', '7', '8', '9', '10', '11', '12','13', '14', '15', '16'], batch_size = 16)
 valid_batches = ImageDataGenerator().flow_from_directory(valid_path, target_size=(image_width, image_height), classes=['1','2','3','4', '5', '6', '7', '8', '9', '10', '11', '12','13', '14', '15', '16'], batch_size = 16)
 test_batches = ImageDataGenerator().flow_from_directory(test_path, target_size=(image_width,
 image_height), classes=['1','2','3','4', '5', '6', '7', '8', '9', '10', '11', '12','13', '14', '15', '16'], batch_size = 160)

 imgs, labels = next(train_batches)
 print(labels)

#CNN model
model = Sequential([
    Conv2D(32, (3,3), activation='relu', input_shape=(image_width, image_height, 3)),
    Flatten(),
    Dense(**16**, activation='softmax'), # I want to make it 4
])
</code>```

I'm planning to have 4 output nodes in the network:

```<code>4 Output Nodes (4 bits):
Class 01 - 0000
Class 02 - 0001
Class 03 - 0010
Class 04 - 0011
Class 05 - 0100
Class 06 - 0101
Class 07 - 0110
Class 08 - 0111
Class 09 - 1000
Class 10 - 1001
Class 11 - 1010
Class 12 - 1011
Class 13 - 1100
Class 14 - 1101
Class 15 - 1110
Class 16 - 1111
</code>```

But the labels generated by ImageDataGenerator is a 16 bits label

```<code>[[0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]]
</code>```

How will I assign a custom label for my classes? I want my labels to be :

```<code> labels = [[0,0,0,0],
 [0,0,0,1],
 [0,0,1,0],
 [0,0,1,1],
 [0,1,0,0],
 [0,1,0,1],
 [0,1,1,0],
 [0,1,1,1],
 [1,0,0,0],
 [1,0,0,1],
 [1,0,1,0],
 [1,0,1,1],
 [1,1,0,0],
 [1,1,0,1],
 [1,1,1,0],
 [1,1,1,1]]
</code>```

The purpose of it is to make the output nodes of my network/ last dense layer from 16 to 4 nodes, thus, less complicated architecture.

Body:
I am currently creating a CNN model that classifies whether the font is Arial, Verdana, Times New Roman and Georgia. All in all there are 16 classes since I considered also detecting whether the font is regular, bold, italics or bold italics. So 4 fonts * 4 styles = 16 classes.

The data that I have used in my training are the following:

Training data set : 800 image patches of 256 * 256 dimension (50 for each class)
Validation data set : 320 image patches of 256 * 256 dimension (20 for each class)
Testing data set : 160 image patches of 256 * 256 dimension (10 for each class)

Below is my initial code:

import numpy as np
import keras
from keras import backend as K
from keras.models import Sequential
from keras.layers import Activation
from keras.layers.core import Dense, Flatten
from keras.optimizers import Adam
from keras.metrics import categorical_crossentropy
from keras.preprocessing.image import ImageDataGenerator
from keras.layers.normalization import BatchNormalization
from keras.layers.convolutional import *
from matplotlib import pyplot as plt
import itertools
import matplotlib.pyplot as plt
import pickle

 image_width = 256
 image_height = 256

 train_path = 'font_model_data/train'
 valid_path =  'font_model_data/valid'
 test_path = 'font_model_data/test'

  train_batches = ImageDataGenerator().flow_from_directory(train_path, target_size=(image_width, image_height), classes=['1','2','3','4', '5', '6', '7', '8', '9', '10', '11', '12','13', '14', '15', '16'], batch_size = 16)
 valid_batches = ImageDataGenerator().flow_from_directory(valid_path, target_size=(image_width, image_height), classes=['1','2','3','4', '5', '6', '7', '8', '9', '10', '11', '12','13', '14', '15', '16'], batch_size = 16)
 test_batches = ImageDataGenerator().flow_from_directory(test_path, target_size=(image_width,
 image_height), classes=['1','2','3','4', '5', '6', '7', '8', '9', '10', '11', '12','13', '14', '15', '16'], batch_size = 160)

 imgs, labels = next(train_batches)
 print(labels)

#CNN model
model = Sequential([
    Conv2D(32, (3,3), activation='relu', input_shape=(image_width, image_height, 3)),
    Flatten(),
    Dense(**16**, activation='softmax'), # I want to make it 4
])

I'm planning to have 4 output nodes in the network:

4 Output Nodes (4 bits):
Class 01 - 0000
Class 02 - 0001
Class 03 - 0010
Class 04 - 0011
Class 05 - 0100
Class 06 - 0101
Class 07 - 0110
Class 08 - 0111
Class 09 - 1000
Class 10 - 1001
Class 11 - 1010
Class 12 - 1011
Class 13 - 1100
Class 14 - 1101
Class 15 - 1110
Class 16 - 1111

But the labels generated by ImageDataGenerator is a 16 bits label

[[0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]]

How will I assign a custom label for my classes? I want my labels to be :

 labels = [[0,0,0,0],
 [0,0,0,1],
 [0,0,1,0],
 [0,0,1,1],
 [0,1,0,0],
 [0,1,0,1],
 [0,1,1,0],
 [0,1,1,1],
 [1,0,0,0],
 [1,0,0,1],
 [1,0,1,0],
 [1,0,1,1],
 [1,1,0,0],
 [1,1,0,1],
 [1,1,1,0],
 [1,1,1,1]]

The purpose of it is to make the output nodes of my network/ last dense layer from 16 to 4 nodes, thus, less complicated architecture.

Body:
This is what you already have:

custom_labels = ['0000',  '0001', '0010', '0011', '0100', '0101', '0110', '0111',
                 '1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111']

output = [[0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
            [0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
            [0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
            [1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
            [0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
            [0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0.],
            [0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0.],
            [0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
            [0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
            [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1.]]

You'll need to get the index of the 1:

import numpy as np

column = np.argmax(output, axis=1)

Out[10]: array([ 1,  2,  3,  0,  2,  9,  7,  4,  2, 15], dtype=int64)

With this, you can select the corresponding custom label:

array(['0001', '0010', '0011', '0000', '0010', '1001', '0111', '0100',
       '0010', '1111'], dtype='<U4')

But what you want is a list of these, but as separate integers:

final_labels = np.array([list(i) for i in np.array(custom_labels)[column]]).astype(int)

array([[0, 0, 0, 1],
       [0, 0, 1, 0],
       [0, 0, 1, 1],
       [0, 0, 0, 0],
       [0, 0, 1, 0],
       [1, 0, 0, 1],
       [0, 1, 1, 1],
       [0, 1, 0, 0],
       [0, 0, 1, 0],
       [1, 1, 1, 1]])


问:
Display Many To Many Relationship from Entity Model in ASP.NET GridView Control
Lets say i have two tables: Cars and BodyStyle with a many to many relationship.

In Data Entity Model it would show the two tables but in Sql it has a helper table to link since its a many to many relationship.

I want to know how is it possible to display the all the Styles related to an instance of Car inside a gridview.

so basically the gridview should look like:

ID | Make | Model | Style |

 ----------------------------------'

1 | Acura | EL | Sedan, Luxury|

2 | Acura | MDX | SUV, Luxury|

I cant seem to access the helping table through c#

Sorry I am new to c# programming.

答:
You got couple of options to do that. Your Car class should have Models Navigation property and your Model class should have Cars navigation property.

First option: Write a stored procedure which will accept the particular (car/model) as a parameter and return back the resultset accordingly and then map that sp in the edm. You can then call the SP from you code-behind (if you are not using Reporsitoy/Separation of Concern) and bind to the gridview.

Second option: If you are having POCO car class, write a Navigation property named Models which will basically query your db (using LINQ to SQL) and get all the models and then You just need to call that property (as IEnumerable) in your UI and bind to gridview.

Hope this helps and hope I have understood your question appropriately


问:
Change Apache directory to show Wordpress homepage
I have Wordpress installed using an AWS EC2 instance. The public IP is as here. I used LetsEncrypt to get SSL, that worked fine. But after that, my homepage now shows the 'Apache2 Ubuntu Default Page'. It should be showing me the Wordpress homepage. I still have ssh access to the EC2 (Bitnami Wordpress), so my data is supposedly still there.

I've been doing some research at it seems that I need to change something with Apache so it direct to the Wordpress directory/page.

Any help in the matter would be most appreciated :)

答:
The fact that you're getting the Apache default page is a good sign, it means everything from a networking standpoint is working correctly. Now, you just need to show Apache where to serve your files.

Apache stores their default configuration typically in /etc/httpd/httpd.conf or /etc/apache2/sites-available/default and looks something like below.

```<code><VirtualHost *:80>
        ServerAdmin webmaster@localhost

        DocumentRoot /var/www
        <Directory />
                Options FollowSymLinks
                AllowOverride None
        </Directory>
        <Directory /var/www/>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride None
                Order allow,deny
                allow from all
        </Directory>
</code>```

Before making changes to this file (whenever you find it), you will also need to know where the DocumentRoot is. This is essentially the directory that your index.php is located. In the example above it's located in /var/www, and that's typically a good place to start looking.

If you're having a hard time finding your root directory, you can do something like find / -type f -name "index.php".

Assuming your index.php is in /var/www/wordpress your configuration could look as simple as this.

```<code><VirtualHost *:80>
        ServerAdmin admin@example.com
        ServerName example.com
        ServerAlias www.example.com
        DocumentRoot /var/www/wordpress
</VirtualHost>
</code>```

Body:
The fact that you're getting the Apache default page is a good sign, it means everything from a networking standpoint is working correctly. Now, you just need to show Apache where to serve your files.

Apache stores their default configuration typically in /etc/httpd/httpd.conf or /etc/apache2/sites-available/default and looks something like below.

<VirtualHost *:80>
        ServerAdmin webmaster@localhost

        DocumentRoot /var/www
        <Directory />
                Options FollowSymLinks
                AllowOverride None
        </Directory>
        <Directory /var/www/>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride None
                Order allow,deny
                allow from all
        </Directory>

Before making changes to this file (whenever you find it), you will also need to know where the DocumentRoot is. This is essentially the directory that your index.php is located. In the example above it's located in /var/www, and that's typically a good place to start looking.

If you're having a hard time finding your root directory, you can do something like find / -type f -name "index.php".

Assuming your index.php is in /var/www/wordpress your configuration could look as simple as this.

<VirtualHost *:80>
        ServerAdmin admin@example.com
        ServerName example.com
        ServerAlias www.example.com
        DocumentRoot /var/www/wordpress
</VirtualHost>


问:
How to insert a date in format "dd/mm/yyyy" in SQL?
I have the following table:

```<code>drop table if exists Activity;
create table Activity (

    id_activity serial,
    type varchar(255),
    day date
    primary key (id_activity)
);
</code>```

I have to insert different values to this table. The issue is that the date format accepts this format by default "yyyy/mm/dd" and I have to insert the date in format "dd/mm/yyyy".

This is what I'm trying:

```<code>insert into Activity (type, day) values ("football", [What should I type here?]);
</code>```

How can I solve this?

Thanks in advance.

答:
try this

insert into Activity (type, day) values ("football", CONVERT(date,
  YourDateValue, 103))

You can get the reference here

Body:
I have the following table:

drop table if exists Activity;
create table Activity (

    id_activity serial,
    type varchar(255),
    day date
    primary key (id_activity)
);

I have to insert different values to this table. The issue is that the date format accepts this format by default "yyyy/mm/dd" and I have to insert the date in format "dd/mm/yyyy".

This is what I'm trying:

insert into Activity (type, day) values ("football", [What should I type here?]);

How can I solve this?

Thanks in advance.


问:
Code keeps looping into max call stack error
I am trying to make tic tac toe on a website using javascript. That worked and now I'm trying to make a bot that, then you have 2 area's in a row. It needs to block you. But everytime it does block me, it won't do anything else afterwards, because it keeps looping into the error.

The t-numbers are the tile names, 0 means unoccupied,1 means for player 1, and 2 for player 2.
The t-numbers with a 1 behind it are just the tiles but they mustn't interfere with the functions (they are t-numbers too).

How do I fix this?

```<code>function tbot(){
  while (turn == "player 2") {
    if (t41 == 0 &&
      (t01 == 1 && t81 == 1) ||
      (t11 == 1 && t71 == 1) ||
      (t21 == 1 && t61 == 1) ||
      (t31 == 1 && t51 == 1)
    ) {t4()}

    else {
    var tiles = ['0', '1', '2', '3', '4', '5', '6', '7', '8'];
    var tile = tiles[Math.floor(Math.random()*tiles.length)];
         if (tile == '0' && t01 == 0) {t0()}
    else if (tile == '1' && t11 == 0) {t1()}
    else if (tile == '2' && t21 == 0) {t2()}
    else if (tile == '3' && t31 == 0) {t3()}
    else if (tile == '4' && t41 == 0) {t4()}
    else if (tile == '5' && t51 == 0) {t5()}
    else if (tile == '6' && t61 == 0) {t6()}
    else if (tile == '7' && t71 == 0) {t7()}
    else if (tile == '8' && t81 == 0) {t8()}
  }
  }
}
</code>```

```<code>function update() {
  if (t01 == 1 &&
    ((t11 == 1 && t21 == 1)||(t31 == 1 && t61 == 1))
    ||t41 == 1 &&
    ((t31 == 1 && t51 == 1)||(t11 == 1 && t71 == 1)||
    (t01 == 1 && t81 == 1)||(t21 == 1 && t61 == 1))
    ||t81 == 1 &&
    ((t61 == 1 && t71 == 1)||(t21 == 1 && t51 == 1))
) {
  twin = 1;
  document.getElementById('turnshow').innerHTML = "Player 1 is the winner!";
  document.getElementById('treset').style.backgroundColor = '#888';
  } else if (t01 == 2 &&
    ((t11 == 2 && t21 == 2)||(t31 == 2 && t61 == 2))
    ||t41 == 2 &&
    ((t31 == 2 && t51 == 2)||(t11 == 2 && t71 == 2)||
    (t01 == 2 && t81 == 2)||(t21 == 2 && t61 == 2))
    ||t81 == 2 &&
    ((t61 == 2 && t71 == 2)||(t21 == 2 && t51 == 2))
) {
  twin = 1;
  document.getElementById('turnshow').innerHTML = "Player 2 is the winner!";
  document.getElementById('treset').style.backgroundColor = '#888';
  } else {
  if (bot == 1) {tbot();}
  document.getElementById('turnshow').innerHTML = "It is " + turn + "'s turn!";
  }
}
</code>```

```<code>function t4() {
  if (t41 == 0 && twin == 0) {
  if (turn == "player 1") {
    document.getElementById('t4').style.backgroundColor = p1;
    turn = "player 2";
    t41 = 1;
  } else {
    document.getElementById('t4').style.backgroundColor = p2;
    turn = "player 1";
    t41 = 2;
  }
}
update();
}
</code>```

答:
The program never exit the while loop because condition (turn == "player 2") is always true.

If you're expecting t4() to change turn then I guess it doesn't do the job right. Check for (t41 == 0 && twin == 0), turn will never change if this condition is never been true.

Body:
I am trying to make tic tac toe on a website using javascript. That worked and now I'm trying to make a bot that, then you have 2 area's in a row. It needs to block you. But everytime it does block me, it won't do anything else afterwards, because it keeps looping into the error.

The t-numbers are the tile names, 0 means unoccupied,1 means for player 1, and 2 for player 2.
The t-numbers with a 1 behind it are just the tiles but they mustn't interfere with the functions (they are t-numbers too).

How do I fix this?

function tbot(){
  while (turn == "player 2") {
    if (t41 == 0 &&
      (t01 == 1 && t81 == 1) ||
      (t11 == 1 && t71 == 1) ||
      (t21 == 1 && t61 == 1) ||
      (t31 == 1 && t51 == 1)
    ) {t4()}

    else {
    var tiles = ['0', '1', '2', '3', '4', '5', '6', '7', '8'];
    var tile = tiles[Math.floor(Math.random()*tiles.length)];
         if (tile == '0' && t01 == 0) {t0()}
    else if (tile == '1' && t11 == 0) {t1()}
    else if (tile == '2' && t21 == 0) {t2()}
    else if (tile == '3' && t31 == 0) {t3()}
    else if (tile == '4' && t41 == 0) {t4()}
    else if (tile == '5' && t51 == 0) {t5()}
    else if (tile == '6' && t61 == 0) {t6()}
    else if (tile == '7' && t71 == 0) {t7()}
    else if (tile == '8' && t81 == 0) {t8()}
  }
  }
}

function update() {
  if (t01 == 1 &&
    ((t11 == 1 && t21 == 1)||(t31 == 1 && t61 == 1))
    ||t41 == 1 &&
    ((t31 == 1 && t51 == 1)||(t11 == 1 && t71 == 1)||
    (t01 == 1 && t81 == 1)||(t21 == 1 && t61 == 1))
    ||t81 == 1 &&
    ((t61 == 1 && t71 == 1)||(t21 == 1 && t51 == 1))
) {
  twin = 1;
  document.getElementById('turnshow').innerHTML = "Player 1 is the winner!";
  document.getElementById('treset').style.backgroundColor = '#888';
  } else if (t01 == 2 &&
    ((t11 == 2 && t21 == 2)||(t31 == 2 && t61 == 2))
    ||t41 == 2 &&
    ((t31 == 2 && t51 == 2)||(t11 == 2 && t71 == 2)||
    (t01 == 2 && t81 == 2)||(t21 == 2 && t61 == 2))
    ||t81 == 2 &&
    ((t61 == 2 && t71 == 2)||(t21 == 2 && t51 == 2))
) {
  twin = 1;
  document.getElementById('turnshow').innerHTML = "Player 2 is the winner!";
  document.getElementById('treset').style.backgroundColor = '#888';
  } else {
  if (bot == 1) {tbot();}
  document.getElementById('turnshow').innerHTML = "It is " + turn + "'s turn!";
  }
}

function t4() {
  if (t41 == 0 && twin == 0) {
  if (turn == "player 1") {
    document.getElementById('t4').style.backgroundColor = p1;
    turn = "player 2";
    t41 = 1;
  } else {
    document.getElementById('t4').style.backgroundColor = p2;
    turn = "player 1";
    t41 = 2;
  }
}
update();
}


问:
Getting the name of a link from a html web site using Python
```<code><a class="inst" href="http://www.tsetmc.com/loader.aspx?ParTree=151311&i=9987529074833218" target="9987529074833218">كشت و صنعت آبشيرين</a>
</code>```

I need to fetch the name of the link("كشت و صنعت آبشيرين"). I can fetch the href and the target, but I don't know how to get the name.

Below you will find a piece of code that I used to get the link and target to write on a text file. Can you please help me extract the name also.

```<code>for link in soup.find_all('a'):
    Href_q.write(link.get('href')+ '\t' + link.get('target') + '\n')
Href_q.close()
</code>```

答:
Here after is the code to your solution

```<code>from bs4 import BeautifulSoup

source = '<a class="inst" href="http://www.tsetmc.com/loader.aspx?ParTree=151311&i=9987529074833218" target="9987529074833218">كشت و صنعت آبشيرين</a>'

soup = BeautifulSoup(source,features="lxml")

print(soup.find('a').text)
</code>```

output:

```<code>                                                                     كشت و صنعت آبشيرين
</code>```

Body:
كشت و صنعت آبشيرين

I need to fetch the name of the link("كشت و صنعت آبشيرين"). I can fetch the href and the target, but I don't know how to get the name.

Below you will find a piece of code that I used to get the link and target to write on a text file. Can you please help me extract the name also.

for link in soup.find_all('a'):
    Href_q.write(link.get('href')+ '\t' + link.get('target') + '\n')
Href_q.close()

Body:
Here after is the code to your solution

from bs4 import BeautifulSoup

source = '<a class="inst" href="http://www.tsetmc.com/loader.aspx?ParTree=151311&amp;i=9987529074833218" target="9987529074833218">كشت و صنعت آبشيرين</a>'

soup = BeautifulSoup(source,features="lxml")

print(soup.find('a').text)

output:

                                                                     كشت و صنعت آبشيرين


问:
C Program Printing Wrong Message | Logical Operator Problem?
I am new to coding in C and trying to write a program that prints the message 'You may enter' if your age is 15 or over, and your gender is equal to male. Kindly see what I've got below. When you enter your age as 15 or over and your gender as male, the program prints the wrong message. I think it could be a problem with my logical operators but I can't quite figure out why. Could you assist?</p>

```<code>#include <stdio.h>
#include <unistd.h>

int main(void)
{
    int age;
    char gen;

    printf("How old are you?\n");
    scanf("%d", &age);

    printf("What is your gender? (m/f) \n");
    scanf("%s", &gen);

    if(age >= 15 && gen == 'm')
    {
         write(1, "You man enter\n", 15);
    }

    if(age < 14 || gen == 'f')
    {
        write(1, "No entry\n", 9);
    }

    return 0;
}
</code>```

答:
Thanks @gsamaras!</p>

```<code>#include <stdio.h>
#include <unistd.h>

int main(void)
{
    int age;
    char gen;

    printf("How old are you?\n");
    scanf("%d", &age);

    printf("What is your gender? (m/f) \n");
    scanf(" %c", &gen);

    if(age >= 15 && gen == 'm')
    {
         write(1, "You may enter\n", 15);
    }

    if(age <= 14 || gen == 'f')
    {
        write(1, "No entry\n", 9);
    }

    return 0;
}
</code>```

Body:
I am new to coding in C and trying to write a program that prints the message 'You may enter' if your age is 15 or over, and your gender is equal to male. Kindly see what I've got below. When you enter your age as 15 or over and your gender as male, the program prints the wrong message. I think it could be a problem with my logical operators but I can't quite figure out why. Could you assist?

#include <stdio.h>
#include <unistd.h>

int main(void)
{
    int age;
    char gen;

    printf("How old are you?\n");
    scanf("%d", &age);

    printf("What is your gender? (m/f) \n");
    scanf("%s", &gen);

    if(age >= 15 && gen == 'm')
    {
         write(1, "You man enter\n", 15);
    }

    if(age < 14 || gen == 'f')
    {
        write(1, "No entry\n", 9);
    }

    return 0;
}

Body:
Thanks @gsamaras!

#include <stdio.h>
#include <unistd.h>

int main(void)
{
    int age;
    char gen;

    printf("How old are you?\n");
    scanf("%d", &age);

    printf("What is your gender? (m/f) \n");
    scanf(" %c", &gen);

    if(age >= 15 && gen == 'm')
    {
         write(1, "You may enter\n", 15);
    }

    if(age <= 14 || gen == 'f')
    {
        write(1, "No entry\n", 9);
    }

    return 0;
}


问:
Why isn't the "gets()" function declared when I include stdio.h?
```<code>#include <stdio.h>

int main() {
   char str[50];

   printf("Enter a string : ");
   gets(str);

   printf("You entered: %s", str);

   return (0);
}
</code>```

In my code, why isn't the gets() function declared? It shows me a bunch of errors such as:

```<code>In function ‘int main()’:
 error: ‘gets’ was not declared in this scope
gets(str);
    ^~~~
[Finished in 0.2s with exit code 1]
</code>```

I want to know why this kind of problem occurs?

答:
gets() has been removed from the C language. This function cannot be used safely because the size of the destination array is not provided, hence a long enough input line will cause undefined behavior as gets() will write beyond the end of the array.

Here is a replacement function that takes an extra argument:

#include <stdio.h>

// read a line from stdin, ignore bytes beyond size-1, strip the newline.
char *safe_gets(char *dest, size_t size) {
    int c;
    size_t i = 0;
    while ((c = getc(stdin)) != EOF && c != '\n') {
        if (i + 1 < size)
            dest[i++] = c;
    }
    if (size > 0)
        dest[i] = '\0';
    return (i == 0 && c == EOF) ? NULL : dest;
}
```

Body:
#include <stdio.h>

int main() {
   char str[50];

   printf("Enter a string : ");
   gets(str);

   printf("You entered: %s", str);

   return (0);
}

In my code, why isn't the gets() function declared? It shows me a bunch of errors such as:

In function ‘int main()’:
 error: ‘gets’ was not declared in this scope
gets(str);
    ^~~~
[Finished in 0.2s with exit code 1]

I want to know why this kind of problem occurs?


问:
Yocto: overriding kernel configuration
Related to this question.
In order to customize the kernel configuration I created in my custom layer this structure:

```<code>$ tree recipes-kernel/
recipes-kernel/
└── linux
    ├── files
    │   └── <image>-defconfig
    └── linux-stm32mp_4.19.bbappend
</code>```

Where the defconfig file is actually the .config used to manually compile the kernel (see the other question). The bbappend file contains the following code:

```<code>SRC_URI += "file://<full-path>/meta-custom-layer/recipes-kernel/linux/files/<image>-defconfig"
KERNEL_DEFCONFIG_stm32mp1_<variant> = "{WORKDIR}/<image>-defconfig"
</code>```

I'm sure the file is processed because if I change the name of the defconfig bitbake raises a file not found error.

The problem is the compiled kernel does not have my customization.
But if I copy my defconfig to the build directory (i.e. tmp/work/stm32mp1_<variant>-openstlinux_eglfs-linux-gnueabi/linux-stm32mp/4.19-r0/linux-stm32mp1-<variant>-standard-build/.config) and manually bitbake virtual/kernel) it does.

So it seems it searches and finds my defconfig but then it ignores it.
Where is my mistake?

答:
I don't know what is your mistake. But I know what I do.

Instead of trying to overload defconfig I let bitbake generate kernel fragments (diffs from the kernel supplied defconfig): https://edison-fw.github.io/meta-intel-edison/5.1-Bitbake-tricks#configuring-the-kernel-and-grab-the-kernel-fragment

Then I add the fragments to my recipe: https://github.com/edison-fw/meta-intel-edison/blob/warrior/meta-intel-edison-bsp/recipes-kernel/linux/linux-yocto_5.4.0.bb

Title: Yocto: overriding kernel configuration

Body:
Related to this question.
In order to customize the kernel configuration I created in my custom layer this structure:

$ tree recipes-kernel/
recipes-kernel/
└── linux
    ├── files
    │   └── <image>-defconfig
    └── linux-stm32mp_4.19.bbappend

Where the defconfig file is actually the .config used to manually compile the kernel (see the other question). The bbappend file contains the following code:

SRC_URI += "file://<full-path>/meta-custom-layer/recipes-kernel/linux/files/<image>-defconfig"
KERNEL_DEFCONFIG_stm32mp1_<variant> = "{WORKDIR}/<image>-defconfig"

I'm sure the file is processed because if I change the name of the defconfig bitbake raises a file not found error.

The problem is the compiled kernel does not have my customization.
But if I copy my defconfig to the build directory (i.e. tmp/work/stm32mp1_<variant>-openstlinux_eglfs-linux-gnueabi/linux-stm32mp/4.19-r0/linux-stm32mp1-<variant>-standard-build/.config) and manually bitbake virtual/kernel) it does.

So it seems it searches and finds my defconfig but then it ignores it.
Where is my mistake?


问:
Deleting an element from dictionary array in javascript
$scope.couponMatches = {};

I have a function which adds elements to a dictionary:
$scope.couponMatches[$scope.currentMatch] = { firstElemet: "a", secondElement: "b" };

Every time I call this function it adds an elemet to my dictionary

EX:
-MND3sdaDFFls2s : { firstElemet: "a", secondElement: "b" }
-MGHuwenSN3mndb : { firstElemet: "a", secondElement: "b" }

In firebase I save it .

I need to delete one element with an index before save it to firebase.

答:
You have a reserved word delete specially for this case.

Lets say you want to delete property a from object obj, use:

```<code>delete obj.a
</code>```

Body:
You have a reserved word delete specially for this case.

Lets say you want to delete property a from object obj, use:

delete obj.a


问:
How to deal with JSON message with spring-rabbit in spring boot application?
Here are my code snippets.

MQConfiguration class for configuration

```<code>@Configuration
public class MQConfiguration {
    @Bean
    public Receiver receiver() {
        return new Receiver();
    }
}
</code>```

Receiver class for dealing with receiving messages

```<code>@RabbitListener(queues = "testMQ")
public class Receiver {

    @RabbitHandler
    public void receive(Message msg){
        System.out.println(msg.toString());
    }
}
</code>```

And here is the JSON message I sent to the RabbitMQ

```<code>{
    "id": 1,
    "name": "My Name",
    "description": "This is description about me"
}
</code>```

However I got following error message when I ran my application.

```<code>2017-02-28 17:16:35.931  WARN 11828 --- [cTaskExecutor-1] s.a.r.l.ConditionalRejectingErrorHandler : Execution of Rabbit message listener failed.

org.springframework.amqp.rabbit.listener.exception.ListenerExecutionFailedException: Listener threw exception
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.wrapToListenerExecutionFailedExceptionIfNeeded(AbstractMessageListenerContainer.java:872) ~[spring-rabbit-1.7.0.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:782) ~[spring-rabbit-1.7.0.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.invokeListener(AbstractMessageListenerContainer.java:702) ~[spring-rabbit-1.7.0.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.access$001(SimpleMessageListenerContainer.java:95) [spring-rabbit-1.7.0.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$1.invokeListener(SimpleMessageListenerContainer.java:186) ~[spring-rabbit-1.7.0.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.invokeListener(SimpleMessageListenerContainer.java:1227) [spring-rabbit-1.7.0.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.executeListener(AbstractMessageListenerContainer.java:683) ~[spring-rabbit-1.7.0.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.doReceiveAndExecute(SimpleMessageListenerContainer.java:1181) [spring-rabbit-1.7.0.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.receiveAndExecute(SimpleMessageListenerContainer.java:1165) [spring-rabbit-1.7.0.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.access$1500(SimpleMessageListenerContainer.java:95) [spring-rabbit-1.7.0.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$AsyncMessageProcessingConsumer.run(SimpleMessageListenerContainer.java:1367) [spring-rabbit-1.7.0.RELEASE.jar:na]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_60]
Caused by: org.springframework.amqp.AmqpException: No method found for class [B
    at org.springframework.amqp.rabbit.listener.adapter.DelegatingInvocableHandler.getHandlerForPayload(DelegatingInvocableHandler.java:127) ~[spring-rabbit-1.7.0.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.adapter.DelegatingInvocableHandler.getMethodNameFor(DelegatingInvocableHandler.java:224) ~[spring-rabbit-1.7.0.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.adapter.HandlerAdapter.getMethodAsString(HandlerAdapter.java:61) ~[spring-rabbit-1.7.0.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.adapter.MessagingMessageListenerAdapter.invokeHandler(MessagingMessageListenerAdapter.java:140) ~[spring-rabbit-1.7.0.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.adapter.MessagingMessageListenerAdapter.onMessage(MessagingMessageListenerAdapter.java:106) ~[spring-rabbit-1.7.0.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:779) ~[spring-rabbit-1.7.0.RELEASE.jar:na]
    ... 10 common frames omitted
</code>```

So what should I do if all I want is to print the JSON message in receive() method? I'd really appreciate that anyone can shed a light on this. :)

答:
in Simple way you can use this function new String(Messages)

```<code>@RabbitListener(queues = "testMQ")
public class Receiver {

    @RabbitHandler
    public void receive(Message msg){
String MQMessage = new String(msg.getBody());
        System.out.println(MQMessage);
    }
}
</code>```

Body:
Here are my code snippets.

MQConfiguration class for configuration

@Configuration
public class MQConfiguration {
    @Bean
    public Receiver receiver() {
        return new Receiver();
    }
}

Receiver class for dealing with receiving messages

@RabbitListener(queues = "testMQ")
public class Receiver {

    @RabbitHandler
    public void receive(Message msg){
        System.out.println(msg.toString());
    }
}

And here is the JSON message I sent to the RabbitMQ

{
    "id": 1,
    "name": "My Name",
    "description": "This is description about me"
}

However I got following error message when I ran my application.

2017-02-28 17:16:35.931  WARN 11828 --- [cTaskExecutor-1] s.a.r.l.ConditionalRejectingErrorHandler : Execution of Rabbit message listener failed.

org.springframework.amqp.rabbit.listener.exception.ListenerExecutionFailedException: Listener threw exception
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.wrapToListenerExecutionFailedExceptionIfNeeded(AbstractMessageListenerContainer.java:872) ~[spring-rabbit-1.7.0.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:782) ~[spring-rabbit-1.7.0.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.invokeListener(AbstractMessageListenerContainer.java:702) ~[spring-rabbit-1.7.0.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.access$001(SimpleMessageListenerContainer.java:95) [spring-rabbit-1.7.0.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$1.invokeListener(SimpleMessageListenerContainer.java:186) ~[spring-rabbit-1.7.0.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.invokeListener(SimpleMessageListenerContainer.java:1227) [spring-rabbit-1.7.0.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.executeListener(AbstractMessageListenerContainer.java:683) ~[spring-rabbit-1.7.0.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.doReceiveAndExecute(SimpleMessageListenerContainer.java:1181) [spring-rabbit-1.7.0.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.receiveAndExecute(SimpleMessageListenerContainer.java:1165) [spring-rabbit-1.7.0.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer.access$1500(SimpleMessageListenerContainer.java:95) [spring-rabbit-1.7.0.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer$AsyncMessageProcessingConsumer.run(SimpleMessageListenerContainer.java:1367) [spring-rabbit-1.7.0.RELEASE.jar:na]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_60]
Caused by: org.springframework.amqp.AmqpException: No method found for class [B
    at org.springframework.amqp.rabbit.listener.adapter.DelegatingInvocableHandler.getHandlerForPayload(DelegatingInvocableHandler.java:127) ~[spring-rabbit-1.7.0.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.adapter.DelegatingInvocableHandler.getMethodNameFor(DelegatingInvocableHandler.java:224) ~[spring-rabbit-1.7.0.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.adapter.HandlerAdapter.getMethodAsString(HandlerAdapter.java:61) ~[spring-rabbit-1.7.0.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.adapter.MessagingMessageListenerAdapter.invokeHandler(MessagingMessageListenerAdapter.java:140) ~[spring-rabbit-1.7.0.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.adapter.MessagingMessageListenerAdapter.onMessage(MessagingMessageListenerAdapter.java:106) ~[spring-rabbit-1.7.0.RELEASE.jar:na]
    at org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer.doInvokeListener(AbstractMessageListenerContainer.java:779) ~[spring-rabbit-1.7.0.RELEASE.jar:na]
    ... 10 common frames omitted

So what should I do if all I want is to print the JSON message in receive() method? I'd really appreciate that anyone can shed a light on this. :)

Body:
in Simple way you can use this function new String(Messages)

@RabbitListener(queues = "testMQ")
public class Receiver {

    @RabbitHandler
    public void receive(Message msg){
String MQMessage = new String(msg.getBody());
        System.out.println(MQMessage);
    }
}