text:
Q: Expressing setup time with cumulatives There are many families of scheduling problems. I'm looking into a problem where
I have families of jobs/tasks where the transition from one family to another family
require reconfiguring the machine (setup time).
I'm using cumulatives[2/3] to solve this problem, but I feel unsure how the setup time
could be expressed.
In this small example I have 10 tasks belonging to 3 different families. Any task can run on any machine, but a switch from one task in one family to another task in another family require a setup-time to be added.
:- use_module(library(clpfd)).
:- use_module(library(lists)).

go( Ss, Es, Ms, Tm, Lab ) :-

    Ss = [S1, S2, S3, S4,S5,S6,S7,S8,S9,S10], %Starttimes
    Es = [E1, E2, E3, E4,E5,E6,E7,E8,E9,E10], %Endtimeds
    Ms = [M1, M2, M3, M4,M5,M6,M7,M8,M9,M10], %MachineIds

    domain(Ss, 1, 30),
    domain(Es, 1, 30),
    domain(Ms, 1, 3 ),

    Tasks = [
        %Family 1: Setuptime, Su1 = 4,
        task(  S1, 6,  E1,  1, M1 ),  %Task T1
        task(  S2, 6,  E2,  1, M2 ),  %Task T2
        task(  S3, 3,  E3,  1, M3 ),  %Task T3
        task(  S4, 7,  E4,  1, M4 ),  %Task T4
        %Family 2: Setuptime, Su2 = 3
        task(  S5, 5,  E5,  1, M5 ),  %Task T5
        task(  S6, 8,  E6,  1, M6 ),  %Task T6
        task(  S7, 4,  E7,  1, M7 ),  %Task T7
        %Family 3: Setuptime, Su3 = 5
        task(  S8, 4,  E8,  1, M8 ),  %Task T8
        task(  S9, 4,  E9,  1, M9 ),  %Task T9
        task( S10, 5,  E10, 1, M10 )  %Task T10
    ],

    %All machines has resource capacity = 1
    Machines = [
        machine(  1, 1 ), %M1
        machine(  2, 1 ), %M2
        machine(  3, 1 )  %M3
    ],

    cumulatives(Tasks, Machines, [bound(upper),task_intervals(true)] ),

    maximum( MaxEndTime, Es ),

    %Make the list of options to pass to the labeling predicate
    append( [ [minimize(MaxEndTime)], [time_out( Tm, _)], Lab ], LabOpt ),
    Vars=[S1,M1,S2,M2,S3,M3,S4,M4,S5,M5,S6,M6,S7,M7,S8,M8,S9,M9,S10,M10],
    labeling( LabOpt, Vars).

One valid schedule ( but not optimal ) could be:
M1: Su1,T1,T2,Su3,T10
M2: Su2,T5,T6,Su3,T8
M3: Su1,T3,T4,Su2,T7,Su3,T9

How is the best way to express this together with use of cumulatives[2/3]? By making the duration of each task a domain variable and adding extra constraints to it?

A: First, cumulatives/[2,3] doesn't have an option for expression setup times, so one has to post explicit constraints expressing "if two tasks of different families run on the same machine, then there must be a gap between the end of the predecessor task and the start of the successor task".
This can be encoded by calling:
setups(Ss, Ms, [6,6,3,7,5,8,4,4,4,5], [1,1,1,1,2,2,2,3,3,3], [4,4,4,4,3,3,3,5,5,5]),

defined as:
% post setup constraints for start times Ss, machines Ms, durations
% Ds, task families Fs, and setup times Ts
setups(Ss, Ms, Ds, Fs, Ts) :-
    (   fromto(Ss,[S1|Ss2],Ss2,[]),
        fromto(Ms,[M1|Ms2],Ms2,[]),
        fromto(Ds,[D1|Ds2],Ds2,[]),
        fromto(Fs,[F1|Fs2],Fs2,[]),
        fromto(Ts,[T1|Ts2],Ts2,[])
    do  (   foreach(S2,Ss2),
            foreach(M2,Ms2),
            foreach(D2,Ds2),
            foreach(F2,Fs2),
            foreach(T2,Ts2),
            param(S1,M1,D1,F1,T1)
        do  (   F1 = F2 -> true
            ;   % find forbidden interval for S2-S1 if on same machine
                L is 1-(T1+D2),
                U is (T2+D1)-1,
                StartToStart in \(L..U),
                (M1#\=M2 #\/ S2 - S1 #= StartToStart)
            )
        )
    ).

Secondly, if the machines are interchangeable as in your example, you can break symmetries by imposing that 1 should occur before 2 and 2 should occur before 3 in Ms:
value_order(Ms),

defined as:
value_order(Ms) :-
    automaton(Ms, [source(q0),sink(q0),sink(q1),sink(q2)],
              [arc(q0,1,q1),
               arc(q1,1,q1), arc(q1,2,q2),
               arc(q2,1,q2), arc(q2,2,q2), arc(q2,3,q2)]).

Thirdly, fixing all machines before all start times is a much better search strategy.  Yet another refinement is to (a) fix the machines, (b) narrow the intervals of the tasks enough to impose an order per machine, (c) fix the start times:
    Q1 #= S1/6,
    Q2 #= S2/6,
    Q3 #= S3/3,
    Q4 #= S4/7,
    Q5 #= S5/5,
    Q6 #= S6/8,
    Q7 #= S7/4,
    Q8 #= S8/4,
    Q9 #= S9/4,
    Q10 #= S10/5,
    labeling([minimize(MaxEndTime)/*,time_out( Tm, _)*/|Lab],
             [M1,M2,M3,M4,M5,M6,M7,M8,M9,M10,
              Q1,Q2,Q3,Q4,Q5,Q6,Q7,Q8,Q9,Q10,
              S1,S2,S3,S4,S5,S6,S7,S8,S9,S10]).

With these changes, the optimal solution with proof of optimality is obtained in some 550ms:
| ?- statistics(runtime,_), go(Ss,Es,Ms,_,[step]), statistics(runtime,R).
Ss = [1,7,1,13,7,12,17,1,5,9],
Es = [7,13,4,20,12,20,21,5,9,14],
Ms = [1,1,2,1,2,2,3,3,3,3],
R = [1621540,550] ?
yes


text:
Q: Counting Results With IdiORM When An Array Is Returned Currently my db stores emails and the date collected.  I want to build an chart that shows how many emails were collected each day.  I found a tutorial using idiORM but this graphs values that are returned from the db and not counting how many are returned.
Any ideas on how to count for each result?
if (isset($_GET['start']) AND isset($_GET['end'])) {

$start = $_GET['start'];
$end = $_GET['end'];
$data = array();

// Select the results with Idiorm
$results = ORM::for_table('tbl_data')
        ->where_gte('date', $start)
        ->where_lte('date', $end)
        ->order_by_desc('date')
        ->find_array();

// Build a new array with the data
foreach ($results as $key => $value) {
    $data[$key]['label'] = $value['date'];
    $data[$key]['value'] = $value['email'];
}

echo json_encode($data);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why doesn't the combined area of the two small squares equal the bigger square? So, I was trying to solve this problem from a textbook. The Problem is: "A piece of wire 60 inches long is cut into two pieces and then each piece is bent into the shape of a square. If the sum of the areas of the two squares is 117 square inches, find the length of each piece of wire."
And this is the solution.
"A piece of wire 60 inches is cut into two pieces and then each piece was bent into the shape of a square"
$4x + 4y = 60$
$x + y = 15$
$y = (15-x)$:
"the sum of the areas of the two square is 117 square inches"
$x^2 + (15-x)^2 = 117$
$(15-x)(15-x)+x^2=
x^2 + 225 - 15x - 15x + x^2 = 117$
combine like terms
$2x^2 - 30x + 225 - 117 = 0$
$2x^2 - 30x + 108 = 0$
simplify divide by 2
$x^2 - 15x + 54 = 0$.
Factors to
$x = 6$ and
$x = 9$
therefore
4(6) = 24" is one piece of wire
and
4(9)= 36" is the other
But something doesn't make sense here, If we bend the original 60-inch wire into a square. Then it's area would be 400 square inches.
So why do the two smaller squares area equal, 117 square inches and not 400?

A: If you bend the $60$-inch wire into a square, the area should be $\left( \frac{60}4\right)^2=225$
In general, we have
$$\left( p+q\right)^2 \ne p^2+q^2$$
Hence $p=\frac{24}4$ and $q=\frac{36}{4}$
We have $(p+q)^2 = p^2+2pq+2^2$. Hence there should be a difference of $2pq=2\left( \frac{24}{4}\right)\left(\frac{36}{4} \right)=108.$
Geometrically: Don't forget the rectangle region.

A: The area of a square formed by the full piece of wire would be $(60/4)^2=15^2=225$ square inches, not $400$. As for why the total area of two squares isn't $225$ square inches, let's consider what happens when we cut an arbitrary length off the wire, say $x$ inches, where $0<x<60.$ Now we have two lengths of wire--one is $x$ inches, and the other is $60-x$ inches. Bending both into squares gives us one area of $$\left(\frac{x}{4}\right)^2=\frac{x^2}{16}$$ and another of $$\left(\frac{60-x}{4}\right)^2=\frac{(60-x)^2}{16}=\frac{3600-120x+x^2}{16},$$ for a total area of $$\frac{3600-120x+2x^2}{16}=\frac{3600}{16}+\frac{2x^2-120x}{16}=225+\frac{x(x-60)}8.$$ But remember that $0<x<60,$ so $x(x-60)<0,$ and so the total area is less than $225.$


text:
Q: SWIFT: Prototype Cells not being loaded after performSegueWithIdentifier I have a ViewController that calls (clicking on a button) another View using this function
@IBAction func btnSeeContact(sender: AnyObject) {
        self.performSegueWithIdentifier("segueSeeContact", sender: self)
    }

and my prototype cell is "linked" to a custom View Controller named ContactsTableViewCell that I have created and it implements:
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! ContactsTableViewCell

        cell.txtName.text = "test"
        cell.txtPhone.text = "1234567890"

        return cell

    }

When I run the project, the button calls the table, but there is no Cell on it, and I put a breakpoint on those tableView functions and they are not being reached.
What am I missing here that those functions are never being called?

A: I am adding a new answer since my previous answer was up voted, so I don't want to make massive edits that one, and is still a valid way to fix your issue.
The issue is you have your custom classes confused.  In your screen shot you can see that the the Table View Controller is not set to a custom class, it just says Table View Controller.  That is the object that needs to get a custom implementation of the UITableViewController class.
Instead you seem to be setting the cell's class to a custom class, and implementing the delegate methods there.  You still need a custom class for the table view cell, but it should be a custom class of UITableViewCell.
So your cell class should look something like this:
import UIKit
class YourCustomTableViewCell: UITableViewCell {
  @IBOutlet weak var yourLabel1: UILabel!
  @IBOutlet weak var yourLabel2: UILabel!
}

You will be given an instance of this cell to configure in cellForIndexPath.
So your Table view controller class should be set to a class that looks like below.  The YourTableViewController is were you want to implement all the delegate methods.
Note:  if you are using a UITableViewController dragged out from the storyboard, it will already have the tableView, and delegate / data source stuff already wired up for you.  You will also notice that you are overriding the delegate methods as the UITableViewController class has default implementations of these.  If you are just using a normal view controller, then see my previous answer for more details on how to set that up.
import UIKit

class YourTableViewController: UITableViewController {

  override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
  }

  override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return 1
  }

  override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
    if let cell = cell as? YourCustomTableViewCell {
      cell.yourLabel1.text = "some text"
      cell.yourLabel2.text = "some other text"
    }
    return cell
  }
}

A: As others have commented, you really need to provide a little more context.
Here are a few things that might be going wrong,  providing more context would confirm or deny this guesses.
First you don't show the numberOfSectionsInTableView method.
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
          return 0
  }

I think you would need to provide a value other than 0
Secondly, since I don't see override in front of what I am sure you are intending to be UITableViewDelegate methods function calls, that means your view controller is not a UITableViewController. This makes me wonder if you defined this view controller as conforming to the UITableViewDelegate protocol and if you set the table view outlet delegate to self. (or even wired up the UITableView to an outlet)
If you use a plain UIViewController to host a table view you need to do the following:

*

*Wire up your UITableView to an outlet in your view controller

*Declare the view controller as conforming to the UITableViewDeleagate (and maybe UITableViewDataSource) protocol

*set the table view's outlet delegate (and maybe dataSource) properties to self (the view controller implementing the protocols)

*Implement the required methods

So something like this:
class MyTableViewController: UIViewController, UITableViewDelegate {

  @IBOutlet weak var tableView: UITableView!

  override func viewDidLoad() {
    super.viewDidLoad()
    tableView.delegate = self
  }

  func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
  }

  func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return 1
  }

  func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("your PrototypeCell", forIndexPath: indexPath)
    // Configure the cell...
    return cell
  }
}


text:
Q: How to make 's height of position:fixed column follow its content's height? Currently, I have a table in my page and I am trying to make the first column freeze. The freeze column works fine using position: fixed for that particular column.
However there is another problem. When the content has more than one row, the
 doesn't extend its height based on its content. Therefore, is there any solution for this?
Here is my demo:
https://jsfiddle.net/yusrilmaulidanraji/ckfdubsf/121/

#table-wrapper {
  width: 95%;
  float: left;
  overflow-x: scroll;
  background: #ddd;
}

table {
  background: #fff;
  width: 1200px;
  text-align: center;
  overflow: hidden;
  position: relative;
}

table thead tr th {
  width: 15em;
}

table thead tr th:first-child,
table tbody tr td:first-child {
  top: auto;
  left: 0.5;
  position: fixed;
  width: 6em;
}

table thead tr th:nth-child(2),
table tbody tr td:nth-child(2) {
  padding-left: 7em;
  /*to show second column behind the first*/
}
<button id="left">←</button>
<button id="right">→</button>

        Heading1
        Heading2
        Heading3
        Heading4
        Heading5

        1
asdasdada
        12
        13
        14
        15

        2
asdasdada
asdasdada
        22
        23
        24
        25

        3
asdasdada
        32
        33
        34
        35

        4
asdasdada
asdasdada
asdasdada
asdasdada
asdasdada
        42
        43
        44
        45

        5
asdasdada
        52
        53
        54
        55

A: You can go through all td fixed elements and then set those heights to default td elements.
  $('table tbody tr td:first-child').each(function(){
      var height = $(this).height();
      $(this).parent().find('td').height(height);
  });

Working example https://jsfiddle.net/ckfdubsf/122/

A: I ended up by using @feesar answer, however I had another issue regarding performance. Therefore, Here is the final result for my case:
https://jsfiddle.net/yusrilmaulidanraji/ckfdubsf/124/
  // Adjust the th and td's height.
  // Improve the performance by using native js + for loop.
  var firstHeader = $('#table-wrapper th:first-child');
  firstHeader[0].style.height = firstHeader[0].parentNode.offsetHeight + "px";
  var firstColumn = $('#table-wrapper td:first-child');
  for (var i = 0; i < firstColumn.length; i++) {
    firstColumn[i].parentNode.style.height = firstColumn[i].offsetHeight + "px";
  }

The logic and the result are the same, but it has a better performance. Hopefully, it can help.

A: In terms of performance, I think you will be best off simply cloning the first table column and painting it above the "real" one, like this:

var $overlayTable = $("#table-wrapper table").clone().addClass("overlay");
$overlayTable.find("tr > *:not(:first-child)").remove();
$overlayTable.appendTo("#table-wrapper");

$(window).on("scroll", function () {
    $overlayTable.css("left", $(window).scrollLeft() + "px");
});
#table-wrapper {
  position: relative;
}
#table-wrapper table {
  text-align: center;
  table-layout: fixed;
  overflow-x: scroll;
  width: 1200px;
  border-collapse: collapse;
}
#table-wrapper table tr > * {
  margin-left: 150px;
  width: auto;
}
#table-wrapper table tr > *:first-child {
  width: 6em;
}
#table-wrapper table.overlay {
  position: absolute;
  top: 0;
  color: red;
  background-color: white;
  width: 6em;
}

  <button id="left">←</button>
  <button id="right">→</button>

        Heading1
        Heading2
        Heading3
        Heading4
        Heading5

        1
asdasdada
        12
        13
        14
        15

        2
asdasdada
asdasdada
        22
        23
        24
        25

        3
asdasdada
        32
        33
        34
        35

        4
asdasdada
asdasdada
asdasdada
asdasdada
asdasdada
        42
        43
        44
        45

        5
asdasdada
        52
        53
        54
        55


text:
Q: How to implement Actor based HTTP Routing in Akka I'm new to Akka. While learning I've created a sample project on Github. Here this project uses Akka, Akka-HTTP, Slick, Flyway and Macwire. I wanted to implement Akka Actors for HTTP routing. I tried to implement this on redis/ but not working as expected.
Currently the Controller is working as:
class AuthController(userService: UserService[Future]) extends Controller {

  import de.heikoseeberger.akkahttpjson4s.Json4sSupport._
  implicit val serialization: Serialization.type = jackson.Serialization // or native.Serialization
  implicit val formats: DefaultFormats.type = DefaultFormats

  override def route: Route = pathPrefix("users") {
    pathEndOrSingleSlash {
      register
    }
  }

  private def register = {
    (post & entity(as[RegistrationData])) { registrationData =>
      complete(userService.registerUser(registrationData))
    }
  }

}

But I'm trying to implement something like this with some changes in existing code:
class AuthController(userhandler: ActorRef) extends Controller {

  import de.heikoseeberger.akkahttpjson4s.Json4sSupport._
  implicit val serialization: Serialization.type = jackson.Serialization // or native.Serialization
  implicit val formats: DefaultFormats.type = DefaultFormats

  override def route: Route = pathPrefix("users") {
    pathEndOrSingleSlash {
      register
    }
  }

  private def register = {
    (post & entity(as[RegistrationData])) { registrationData =>
      complete(
        (userHandler ? UserHandler.Register(registrationData)).map {
          case true => OK -> s"Thank you ${registrationData.username}"
          case _ => InternalServerError -> "Failed to complete your request. please try later"
        }
      )
    }
  }

}

Can anyone suggest me how can I implement the above? I appreciate your help.

A: When asking such questions please include the error you're seeing. Here I assume it's about the missing execution context (for the Future to run on) as well as the Timeout, read more about the ask (A.K.A. ?) pattern: https://doc.akka.io/docs/akka/2.5/actors.html#ask-send-and-receive-future
In general what you're missing MAY (since not sure what exactly your problem is) be resolved by:
import system.dispatcher // The ExecutionContext that will be used
system being an actor system, and:
implicit val timeout = Timeout(5 seconds) // needed for?below
You can extract an ActorSystem instance from routes as well btw:


text:
Q: IIS Worker process recycles soonner than the regular time interval set (Both 6.0 and 7.0) We've configured our application pool to recycle at a regular time interval of 180 minutes. But the worker processes are getting recycled every 60 minutes.
Is this a known issue, or do we need to configure something else?
Thanks

A: As stated in What causes an application pool in IIS to recycle?:
You might want to turn on full AppPool Recycle Event logs:
cscript adsutil.vbs Set w3svc/AppPools/DefaultAppPool/LogEventOnRecycle 255

You also might want to take a look at this Scott Guthrie blog article: [http://weblogs.asp.net/scottgu/archive/2005/12/14/433194.aspx][1] that shows how to write code in Global.ASAX to log the actual cause of an Application.End event.


text:
Q: Wordpress links https overwrite issue We're running WP woocommerce website, we got there problem with generating links.
Steam api is generating link in this format:
steam://rungame/730/76561202255233023/+csgo_econ_action_preview%20S76561198030116216A15860401386D2594883032411162261
but wordpress is changing link into this:
https://rungame/730/76561202255233023/+csgo_econ_action_preview%20S76561198030116216A15860401386D16457881814965865661
Its removing "Steam" and replacing with HTTPS.
Does anyone know where is problem? We're using Cloudflare and I tried disable feature "Automatic HTTPS Rewrites".
Thank you a lot for helpful replies. :)


text:
Q: JBoss hibernate error in inserting data I configured a data source and use it in persistence.xml:
<persistence-unit name="myds">
      <jta-data-source>java:jboss/datasources/BBDS</jta-data-source>
      <properties>
         <property name="hibernate.hbm2ddl.auto" value="create-drop" />
         <property name="hibernate.show_sql" value="false" />
      </properties>
   </persistence-unit>

I tested it and it shows the connection was successful:

http://localhost:9990/console

In my Web application, I have an import.sql for initial loading to database:
insert into Member (id, name, email, phone_number) values (0, 'John Smith', 'john.smith@mailinator.com', '2125551212')

I am using Wildfly server, and I tried to launch my application, but received this error message. It seems it can't load the initial Member record.
01:57:49,830 INFO  [org.jboss.as.connector.deployers.jdbc] (MSC service thread 1-8) JBAS010403: Deploying JDBC-compliant driver class org.hsqldb.jdbc.JDBCDriver (version 2.0)
01:57:49,831 INFO  [org.jboss.weld.deployer] (MSC service thread 1-8) JBAS016005: Starting Services for CDI deployment: bword.war
01:57:49,854 INFO  [org.jboss.weld.Version] (MSC service thread 1-8) WELD-000900: 2.2.6 (Final)
01:57:49,872 INFO  [org.jboss.as.connector.deployers.jdbc] (MSC service thread 1-15) JBAS010417: Started Driver service with driver-name = bword.war_org.hsqldb.jdbc.JDBCDriver_2_0
01:57:49,872 INFO  [org.jboss.weld.deployer] (MSC service thread 1-10) JBAS016008: Starting weld service for deployment bword.war
01:57:49,970 INFO  [org.jboss.as.jpa] (ServerService Thread Pool -- 50) JBAS011409: Starting Persistence Unit (phase 2 of 2) Service 'bword.war#myds'
01:57:50,022 INFO  [org.hibernate.annotations.common.Version] (ServerService Thread Pool -- 50) HCANN000001: Hibernate Commons Annotations {4.0.4.Final}
01:57:50,109 INFO  [org.hibernate.dialect.Dialect] (ServerService Thread Pool -- 50) HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
01:57:50,196 INFO  [org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory] (ServerService Thread Pool -- 50) HHH000397: Using ASTQueryTranslatorFactory
01:57:50,410 INFO  [org.hibernate.tool.hbm2ddl.SchemaExport] (ServerService Thread Pool -- 50) HHH000227: Running hbm2ddl schema export
01:57:50,416 ERROR [org.hibernate.tool.hbm2ddl.SchemaExport] (ServerService Thread Pool -- 50) HHH000389: Unsuccessful: drop table if exists Member
01:57:50,416 ERROR [org.hibernate.tool.hbm2ddl.SchemaExport] (ServerService Thread Pool -- 50) No database selected
01:57:50,417 ERROR [org.hibernate.tool.hbm2ddl.SchemaExport] (ServerService Thread Pool -- 50) HHH000389: Unsuccessful: drop table if exists hibernate_sequence
01:57:50,417 ERROR [org.hibernate.tool.hbm2ddl.SchemaExport] (ServerService Thread Pool -- 50) No database selected
01:57:50,417 ERROR [org.hibernate.tool.hbm2ddl.SchemaExport] (ServerService Thread Pool -- 50) HHH000389: Unsuccessful: create table Member (id bigint not null, email varchar(255) not null, name varchar(25) not null, phone_number varchar(12) not null, primary key (id))
01:57:50,417 ERROR [org.hibernate.tool.hbm2ddl.SchemaExport] (ServerService Thread Pool -- 50) No database selected
01:57:50,418 ERROR [org.hibernate.tool.hbm2ddl.SchemaExport] (ServerService Thread Pool -- 50) HHH000389: Unsuccessful: alter table Member add constraint UK_9qv6yhjqm8iafto8qk452gx8h  unique (email)
01:57:50,418 ERROR [org.hibernate.tool.hbm2ddl.SchemaExport] (ServerService Thread Pool -- 50) No database selected
01:57:50,418 ERROR [org.hibernate.tool.hbm2ddl.SchemaExport] (ServerService Thread Pool -- 50) HHH000389: Unsuccessful: create table hibernate_sequence ( next_val bigint )
01:57:50,418 ERROR [org.hibernate.tool.hbm2ddl.SchemaExport] (ServerService Thread Pool -- 50) No database selected
01:57:50,418 ERROR [org.hibernate.tool.hbm2ddl.SchemaExport] (ServerService Thread Pool -- 50) HHH000389: Unsuccessful: insert into hibernate_sequence values ( 1 )
01:57:50,418 ERROR [org.hibernate.tool.hbm2ddl.SchemaExport] (ServerService Thread Pool -- 50) No database selected
01:57:50,419 ERROR [org.hibernate.tool.hbm2ddl.SchemaExport] (ServerService Thread Pool -- 50) HHH000388: Unsuccessful: insert into Member (id, name, email, phone_number) values (0, 'John Smith', 'john.smith@mailinator.com', '2125551212')
01:57:50,419 ERROR [org.hibernate.tool.hbm2ddl.SchemaExport] (ServerService Thread Pool -- 50) No database selected
01:57:50,419 INFO  [org.hibernate.tool.hbm2ddl.SchemaExport] (ServerService Thread Pool -- 50) HHH000230: Schema export complete

I have a specific question:
1) The data source name is "BBDS". Should I create the database name "BBDS" in my MySql (MariaDB) before I run the application? I thought the database and tables will be automatically created and destroyed due to
2) "No database selected", where to specify the database?
Edited:
<subsystem xmlns="urn:jboss:domain:datasources:2.0">
            <datasources>
                <datasource jndi-name="java:jboss/datasources/ExampleDS" pool-name="ExampleDS" enabled="true" use-java-context="true">
                    <connection-url>jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE</connection-url>
                    <driver>h2</driver>
                    <security>
                        <user-name>sa</user-name>
                        <password>sa</password>
                    </security>
                </datasource>
                <datasource jndi-name="java:/jboss/datasources/BBDS" pool-name="BBDS" enabled="true" use-java-context="true">
                    <connection-url>jdbc:mariadb://localhost:3306</connection-url>
                    <driver-class>org.mariadb.jdbc.Driver</driver-class>
                    <driver>mariadb-java-client-1.3.2.jar</driver>
                    <security>
                        <user-name>testUser</user-name>
                        <password>testPass</password>
                    </security>
                </datasource>
                <drivers>
                    <driver name="h2" module="com.h2database.h2">
                        <xa-datasource-class>org.h2.jdbcx.JdbcDataSource</xa-datasource-class>
                    </driver>
                </drivers>
            </datasources>
        </subsystem>

A: Database will not be created automatically for you with such configuration. The BombwordDS datasource has to be configured in wildfly before you deploy this application and it should reference an existing database.
If you don't care about persisting your data for now, and just want to test your application / schema, you could also use Wildfly included ExampleDS which uses H2 in-memory database.


text:
Q: Why can't I kill stealthily? I have 100 sneak with all perks excluding the left branch (however, I have tried it with all the left branch perks as well). I'm currently at Knifepoint Ridge, on a quest to stealthily kill all the bandits. Although it's not necessary to kill the bandits stealthily, I choose to do so because I'm a stealth character.
The problem is that whenever I sneak up behind a bandit and cut his/her throat stealthily with muffled boots, stealth rings and necklaces with 100 sneak the sleeping/awake bandits still manage to 'hear' something and say "What was that?" or something along those lines and follows up by detecting me. This has never seemed to happen before. Any advice?

A: Are you fighting Forsworn? They have heightened senses and are harder to sneak kill than other human characters.

A: *

*Non-dagger weapons are not silent. If you are using a sword, they are hearing you.

*Do you have a follower? They are notoriously loud.

*There's a chance that the victim dropped a large, metal item (weapon, shield, etc) that landed somewhere unfortunate and skidded along the ground noisily. I can't imagine this is the case every time, though.

A: Make sure you're wearing equipment that's been enchanted by muffle. Also be cognizant of the shadows. Walking onto any surface with light reduces your chance to successfully sneak on a NPC. Sometimes even the slightest inconsistencies can easily cause detection. Walking over pressure plates, weapons, or any miscellaneous objects are all ways of making noise. As a fellow Nightingale, walk with the shadows.

A: Silly question, but you should use Light Armor(5/5), Muffle Spell (but your boots already provide it), daggers to avoid making noise when hitting someone.
You can check if its a bug by using a invisibility potion or that spell you can get after completing the thiefs guild questline that makes you invisible while crouched.
If you are doing all these steps,i just can't figure out while you are getting caught. Probably a Bug.

A: Heavy armor:Makes a lot of noise on it own. If it is really heavy more noise such as Dragon Bone armor. Light armor: makes less noise and a lot lighter so (faster). Being able to kill quick is very good for someone like you. If you use a dagger UPGRADE ONE HANDED only straight up. Power attacks are good if you think a normal crouching attack will not kill this also enables a stealthy kill. UPGRADE SNEAK SKILL COMPLETELY! Dark Brother hood gloves and boots are very good as well, same with Astrids Blade of Woe. Hope this helps now go upgrade these two skills at the very being of the game with either person i became level 100 sneak and level 50 one handed in the first room in Helgan! P.S. you should try using two daggers at once also upgrade that on one handed!


text:
Q: Print Selected Area in Map in Arcgis javascript API I'm working on arcgis javascript api, and I'm trying to implement a selection print tool, I'm new to this api, and don't know how to select area of the map, and after that, print the selected drawn area. Any help?

A: As far as I can tell, you'll need to just zoom in on the selected area and print it, assuming you're using the Print Task found here: https://developers.arcgis.com/javascript/jsapi/printtask-amd.html. It doesn't look like there's an option to print only part of what's visible.
Note: The PrintTask requires an ArcGIS Server 10.1 Export Web Map Task. So make sure you've got that first.
Create a navigation toolbar and set it to ZOOM_IN: https://developers.arcgis.com/javascript/jsapi/navigation-amd.html. That will be your "select an area of the map".
Now, there is also an option that's just referred to as "export": http://resources.arcgis.com/en/help/arcgis-rest-api/index.html#/Export_Map/02r3000000v7000000/
1) This is not the same thing as the Export Web Map task.
2) It does not print the basemap, only the layers on your server.
3) It does allow you to specify a bounding box.
If export is available on your server and you choose this option you'll want to use the Draw toolbar instead of the navigation area: https://developers.arcgis.com/javascript/jsapi/draw-amd.html. Get the extent of the shape once it's drawn and pass the xmin, ymin, xmax, ymax to the export function.


text:
Q: For some reason the this in the code is underlined in red.How do I resolve this error? Here is code for Main6Activity.java. I am getting some of that code underlined. Please suggest me what to do in this case:
public class Main6Activity extends AppCompatActivity {
        private Button buttonChoose;
        private Button buttonUpload;
        private ImageView imageView;
        private EditText editTextName;
        private Bitmap bitmap;
        private int PICK_IMAGE_REQUEST = 1;
        private String UPLOAD_URL = "http://simplifiedcoding.16mb.com/VolleyUpload/upload.php";
        private String KEY_IMAGE = "image";
        private String KEY_NAME = "name";

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main6);
            buttonChoose = (Button) findViewById(R.id.buttonChoose);
            buttonUpload = (Button) findViewById(R.id.buttonUpload);
            editTextName = (EditText) findViewById(R.id.editText);
            imageView = (ImageView) findViewById(R.id.imageView);
            buttonChoose.setOnClickListener(this);
            buttonUpload.setOnClickListener(this);
        }

        public String getStringImage(Bitmap bmp) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            byte[] imageBytes = baos.toByteArray();
            String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
            return encodedImage;

        private void uploadImage() { //Showing the progress dialog
            final ProgressDialog loading = ProgressDialog.show(this, "Uploading...", "Please wait...", false, false);
            StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL, new Response.Listener<String>() {
                @Override
                public void onResponse(String s) { //Disimissing the progress dialog
                    loading.dismiss(); //Showing toast message of the response
                    Toast.makeText(Main6Activity.this, s, Toast.LENGTH_LONG).show();
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    //Dismissing the progress dialog
                    loading.dismiss(); //Showing toast
                    Toast.makeText(Main6Activity.this, volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
                }
            }) {
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    //Converting Bitmap to String
                    String image = getStringImage(bitmap); //Getting Image Name
                    String name = editTextName.getText().toString().trim(); //Creating parameters
                    Map<String, String> params = new Hashtable<String, String>(); //Adding parameters
                    params.put(KEY_IMAGE, image);
                    params.put(KEY_NAME, name); //returning parameters
                    return params;
                }
            };
            RequestQueue requestQueue = Volley.newRequestQueue(this);
            //Adding request to the queue
            requestQueue.add(stringRequest);
        }

        private void showFileChooser() {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
        }

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
                Uri filePath = data.getData();
                try {
                    //Getting the Bitmap from Gallery
                    bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                    //Setting the Bitmap to ImageView
                    imageView.setImageBitmap(bitmap);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        @Override
        public void onClick(View v) {
            if (v == buttonChoose) {
                showFileChooser();
            }
            if (v == buttonUpload) {
                uploadImage();
            }
        }
    }

Thank you and help would be appreciated. For some reason the this is underlined in red. How do I resolve this?

A: Change the this in nested classes (such as in new Response.ErrorListener()) to:
Main6Activity.this


text:
Q: SQL Update with Min and Sum and Group By I'm looking to write an update that will correct a flag that's gone astray.
I'd like to set the PRIMARY_FLAG = 1 for the min(TABLE_ID) grouped by ACCOUNT_NUMBER where the sum(PRIMARY_FLAG) <> 1 grouped by ACCOUNT_NUMBER.
Here is what the table looks like now:
TABLE_ID   ACCOUNT_NUMBER   PRIMARY_FLAG
--------   --------------   ------------
1          ABC123           0
2          ABC123           1
3          ABC123           0
4          987XYZ           0
5          987XYZ           0
6          987XYZ           0
7          5A5B5C           1
8          5A5B5C           1
9          5A5B5C           0
10         5A5B5C           0

Here's what I want it to look like after the update:
TABLE_ID   ACCOUNT_NUMBER   PRIMARY_FLAG
--------   --------------   ------------
1          ABC123           0
2          ABC123           1
3          ABC123           0
4          987XYZ           1
5          987XYZ           0
6          987XYZ           0
7          5A5B5C           1
8          5A5B5C           0
9          5A5B5C           0
10         5A5B5C           0

Scenario 1 - TABLE_ID 1, 2, 3 with ACCOUNT_NUMBER = ABC123 is already correct and I do not want the update to touch it.
Scenario 2 - ACCOUNT_NUMBER = 987XYZ, none of the TABLE_ID have a PRIMARY_FLAG = 1, so update will set PRIMARY_FLAG = 1 where TABLE_ID = 4
Scenario 3 - ACCOUNT_NUMBER = 5A5B5C has multiple TABLE_ID = 1, so update would leave TABLE_ID 7 but SET PRIMARY_FLAG = 0 where TABLE_ID = 8
Help is appreciate!

A: Here is a generic method:
update t
    set primary_flag = (case when t.id = (select min(t2.id)
                                          from t t2
                                          where t2.account_number = t.account_number
                                         )
                             then 1 else 0
                        end)
    where t.account_number in (select t2.acount_number
                               from t t2
                               group by t2.acount_number
                               having sum(t2.primary_flag) <> 1
                              );

This is standard SQL and will work in most databases.  However, specific databases might have more concise or efficient methods of doing the same thing.

A: Join the table to the query that returns the minimum table_id for each account_number that needs to be updated:
update t
set t.primary_flag = case when t.table_id = g.minid then 1 else 0 end
from tablename t inner join (
  select account_number, min(table_id) minid
  from tablename
  group by account_number
  having sum(primary_flag) <> 1
) g on g.account_number = t.account_number;

See the demo.
Or with a CTE:
with cte as (
  select *,
    row_number() over (partition by account_number order by table_id) rn,
    sum(primary_flag) over (partition by account_number) total
  from tablename
)
update cte
set primary_flag = case when rn = 1 then 1 else 0 end
where total <> 1

See the demo.
To avoid unnecessary updates for the rows that do not need to be updated:
with cte as (
  select *,
    row_number() over (partition by account_number order by table_id) rn,
    sum(primary_flag) over (partition by account_number) total
  from tablename
)
update cte
set primary_flag = abs(primary_flag - 1)
where (total <> 1) and ((rn = 1 and primary_flag = 0) or (rn > 1 and primary_flag = 1))

See the demo.
Results:
> TABLE_ID | ACCOUNT_NUMBER | PRIMARY_FLAG
> -------: | :------------- | -----------:
>        1 | ABC123         |            0
>        2 | ABC123         |            1
>        3 | ABC123         |            0
>        4 | 987XYZ         |            1
>        5 | 987XYZ         |            0
>        6 | 987XYZ         |            0
>        7 | 5A5B5C         |            1
>        8 | 5A5B5C         |            0
>        9 | 5A5B5C         |            0
>       10 | 5A5B5C         |            0


text:
Q: It is possible for sqlalchemy to add field level rule that two specific columns cannot be both None? I have a model that looks like this:
class Foo(db.Model):

    id = db.Column(db.Integer, primary_key=True)

    # omitted lengthy codes...

    spam = db.relationship('Spam')
    spam_id = db.Column(db.Integer, db.ForeignKey('spams.id'))

    bar = db.relationship('Bar')
    bar_id = db.Column(db.Integer, db.ForeignKey('bars.id'))

    created = db.Column(db.DateTime, server_default=db.func.now())

Is there any options available for Flask-SQLAlchemy to add a behaviour that the spam_id and bar_id cannot be both None during insert/update? But will accept if atleast one of these columns has a value.

A: You can use a table constraint here
from sqlalchemy import CheckConstraint

class Foo(db.Model):

    id = db.Column(db.Integer, primary_key=True)

    # omitted lengthy codes...

    spam = db.relationship('Spam')
    spam_id = db.Column(db.Integer, db.ForeignKey('spams.id'))

    bar = db.relationship('Bar')
    bar_id = db.Column(db.Integer, db.ForeignKey('bars.id'))

    created = db.Column(db.DateTime, server_default=db.func.now())

    __table_args__ = (
        CheckConstraint('NOT(spam_id IS NULL AND bar_id IS NULL)', name='both_null'),
    )

Trying to add a new Foo instance with spam_id with None ? Ok you can
foo=Foo(spam_id=None, bar_id=1)
sqlalchemy_session.add(foo)
sqlalchemy_session.commit()

Trying to add Foo with both spam_id and bar_id at None ? Nope Sir !
foo=Foo(spam_id=None, bar_id=None)
sqlalchemy_session.add(foo)
sqlalchemy_session.commit()  # Raises Exception

The raised exception comes from your DBMS, for exemple with PostgresQL and psycopg2 driver it is psycopg2.IntegrityError


text:
Q: CSV date and separator issue I have a CSV file, delimited by comma and I have some date values inside it, like "01/13/2010 05:00:00 AM", or "04/01/2010 05:00:00 AM". The issue is that when I open the CSV file with Microsoft Excel, it will show these days as 01/13/2010 05:00:00 AM and 04/01/2010  05:00, respectively. The value of the second one is 04/01/2010  05:00:00, but it still shows 04/01/2010  05:00. I've made a few tests and I've realized that Excel is not able to determine which is the day and which is the month in a few cases. In fact Excel gets a string like:
__/__/____ __:__:__ __

It deduces from the last two characters (AM/PM) the value of hour, it knows what the minute and second is, also, it determines the year when it sees the four-character long number sequence, so the question is about month and day. If the first and the second number from the string are both <= 12, then it can't determine which is the month and which is the year, so it messes up my date format.
I would like to have a date format such as
MM/dd/yyyy HH:mm:ss AM/PM

and I've found out that using the function called TEXT is able to do just that, like this:
=TEXT("04/13/2010 05:54:00 AM", "MM/dd/yyyy HH:mm:ss AM/PM")

It works like a charm, but it still guesses which is the day and which is the month. However, assuming that the clients will have the same default date format as the data in the CSV, the month and the day won't be inverted. However, I don't want to open Excel and type the formula in, because I need to give this file to clients and it should show the right value whenever they open the file. So, I need to write the formula inside the comma-separated file, but... TEXT is two-dimensional and there is a comma separating my date from my format.
If I type:
= ABS(-5),=TEXT("04/13/2010 05:54:00 AM", "MM/dd/yyyy HH:mm:ss AM/PM")

into my file, I will see 3 cells, the first being 5, the second is =TEXT("04/13/2010 05:54:00 AM" and the third is  "MM/dd/yyyy HH:mm:ss AM/PM").
How can I prevent this behavior? Can I use something else instead of the comma inside my function call? Or can I change the separator? Or is there a better solution?
Can you enlighten me, to learn how can I enter function calls inside a CSV file?
Thanks in advance to everybody who tries to help,
Lajos Árpád.

A:
If I type:
= ABS(-5),=TEXT("04/13/2010 05:54:00 AM", "MM/dd/yyyy HH:mm:ss AM/PM")

into my file, I will see 3 cells, the first being 5, the second is
  =TEXT("04/13/2010 05:54:00 AM" and the third is "MM/dd/yyyy HH:mm:ss AM/PM").

To make this example work, you need to surround your second data item with double-quotes to escape the comma. As a consequence, you need to use double double-quotes to have them interpreted as double-quotes inside the double-quotes -- I hope this is a readable sentence.
So the example you give should work if you use this in your file:
=ABS(-5),"=TEXT(""04/13/2010 05:54:00 AM"", ""MM/dd/yyyy HH:mm:ss AM/PM"")"


text:
Q: How to combine two batch scripts, put them into one batch file and run them in descending order Hi I would like to take two batch scripts and combine them into " one ". I would also like the now " One " batch file to run in descending order.
I am able to use the CALL function however, I then have three batch files.
I am trying to combine them and achieve the same result as I would if I had to run batchA.bat and batchB.bat from the callbatchA+batchB.bat file

e.g  callbatchA+B.batch, batchA.bat, batchB.bat

I tried a simple concat of the files by running concatfile.bat included below
copy callbatchA+B.bat+batchA.bat+batchB.bat combined_.bat

This did not work example of concatenated file below
    ::CallScript
    CALL C:\Users\Myname\Desktop\batchA.bat
    CALL C:\Users\Myname\Desktop\BatchB.bat
    ::ScriptA
    @echo off
    setlocal EnableDelayedExpansion
    CD "C:\deviceno\"

    ::only change these three lines
    set "start=295"  ::starts from this number
    set "amount=10" ::amount of files created
    set "length=5" ::

    set /a "last=%start%+%amount%"
    for /l %%i in (%start%,1,%last%) do (
    set "folderName=0000000000%%i"
    set "folderName=!folderName:~-%length%!"
    md "!folderName!"
    )
    pausefor
    ::ScriptB
    /D  %%a  in ("C:\deviceno\*.*") do xcopy  /y  /d  C:\Source\*.*"%%a\"

I tried to edit the code with goto :eof such as below but I have had no luck so far.
::ScriptA
@echo off
setlocal EnableDelayedExpansion
CD "C:\device_numbers\"

::only change these three lines
set "start=295"  ::starts from this number
set "amount=10" ::amount of files created
set "length=5" ::

set /a "last=%start%+%amount%"
for /l %%i in (%start%,1,%last%) do (
set "folderName=0000000000%%i"
set "folderName=!folderName:~-%length%!"
md "!folderName!"
) DO CALL ::ScriptB

::ScriptB
p /D  %%a  in ("C:\device_numbers\*.*") do xcopy  /y  /d   C:\Source\*.*"%%a\"
goto :eof

A: I think you're trying to do this:
::CallScript
@echo off
CALL :ScriptA
CALL :ScriptB
pause
goto :eof

:ScriptA
setlocal EnableDelayedExpansion
CD "C:\deviceno\"

::only change these three lines
set "start=295"  ::starts from this number
set "amount=10" ::amount of files created
set "length=5" ::length of fileNames

set /a "last=%start%+%amount%"
for /l %%i in (%start%,1,%last%) do (
set "folderName=0000000000%%i"
set "folderName=!folderName:~-%length%!"
md "!folderName!"
)
goto :eof

:ScriptB
for /D %%a in ("C:\deviceno\*.*") do xcopy /y /d "C:\Source\*.*" "%%a\"
goto :eof

This would be one file, using subroutines for the file creation and the copying.
I would suggest looking at this for a better understanding of how calling labels works

A: Something like this, perhaps?
@ECHO off
SETLOCAL

:: set up some data items for demo

SET /a fred=3
SET /a joe=8
SET /a charlie=10

CALL external add result %fred% %charlie%
ECHO %result%
CALL external add result %fred% %charlie% %joe%
ECHO %result%
CALL external subtract result %fred% %charlie%
ECHO %result%
CALL external concatenate result %fred% xyz %charlie%
ECHO %result%

GOTO :EOF

external.bat
:: @echo off
setlocal enabledelayedexpansion
goto %*

:add
shift
set $=%1&shift
set /a $t=0
:addloop
set /a $t+=%1
shift
if "%1" neq "" goto addloop
:commonexit
endlocal&set %$%=%$t%
goto :eof

:subtract
shift
set $=%1&shift
set /a $t=%1-%2
goto commonexit

:concatenate
shift
set $=%1&shift
set "$t="
:concatloop
set "$t=%$t%%1"
shift
if "%1" neq "" goto concatloop
goto commonexit

A: Did you mean this?
Run batchA.bat and pipe batchA.bat output to batchB.bat and then run batchB.bat
batchA | batchB

or run batchA.bat and then run batchB.bat
batchA & batchB


text:
Q: Soundcloud API - What is the status of user-playback-count? I tried to make use of the user-playback-count property of the /tracks resource (well actually users/{id}/tracks). It never returned anything over 1. After some searching I came across this 2 years old post which explains. I did not find any other information though, which led me to the question:
What is the status and prospect of the user-playback-count property?
The Soundcloud team encourages people to address them through SO.

A: This property was deprecated. Sorry for the lack of documentation on this one.


text:
Q: Using Burnside's Lemma; understanding the intuition and theory I am presented with the following task:

Find the number of distinguishable ways the edges of a square of cardboard can be painted if six colors of paint are available and
a) no color is used more than once
b) the same color can be used on any number of edges (A first course in Abstract Algebra, Fraleigh, 17.7)

Now, using elementary knowledge from probability in high school, I know that there are $6 \cdot 5 \cdot 4 \cdot 3 = 360$ ways of painting the edges given 6 colors. Other than this observation, I am having a hard time calculating the task. Given the chapter of the task, I assume I am to use Burnside's formula, given by $$r \cdot |G| = \sum_{g \in G}|X_g|$$
I assume that I am to let $X$ be the set of $360$ possible ways to paint the square. Now, I am having a hard time seeing the intuition behind it, in particular: I am to include rotations? Should I use $G = S_4$ or $G = D_4$? When do I know when I am to use one or the other?

A: Since we are painting the edges of squares, we assume that these four colorings are all considered the same, and should not be counted separately:

(It should be clear that painting triangular wedges is the same as painting edges, since there is a natural bijection between wedges and edges.)
It's not completely clear in the question, but we should probably also assume that the squares can be flipped over, so that these two colorings should also be considered the same:

That is the crucial question that decides whether to use $C_4$ or $D_4$: Are those two different colorings, or are they the same coloring?  If they are the same coloring, then we say we are allowed to flip over the square, and flipping becomes part of the group we consider in applying the theorem.  If they are different colorings, then reflections are not part of the group.
To apply the Cauchy-Frobenius-Burnside-Redfield-Pólya lemma, we begin by observing that our squares have the symmetry group $D_4$, which includes the four reflections.  Then we count the number of colorings that are fixed points of a coloring under action by each element of $D_4$. Let $x$ be such an element, and suppose that $x$'s action on the square partitions the set of edges into $o(x)$ orbits.  Then for a coloring to be fixed by $x$, all the edges in each orbit must be the same color.  If there are $N$ different colors, then $N^{o(x)}$ are left fixed by the action of $x$.
The 8 elements of $D_4$ can be classified as follows:

*

*2 orthogonal reflections, which divide the edges into 3 orbits ($2N^3$)
(For example, reflecting the square horizontally puts the left and right edges in one orbit, the top edge in a second orbit, and the bottom edge in a third orbit)

*2 diagonal reflections, which divide the edges into 2 orbits ($2N^2$)
(For example, reflecting the square on the topleft-bottomright axis puts the top and left edges in one orbit, the bottom and right edges in the other)

*2 quarter-turns, which put all the edges in a single orbit ($2N$)

*the half-turn, which divides the edges into 2 orbits ($N^2$)

*the identity, which leaves each edge in its own orbits ($N^4$)

The number of colorings with $N$ colors is the sum of the terms for each of these,  divided by 8, the order of the symmetry group.  Adding up the contributions from these we get $$\chi_{D_4}(N) = \frac18(N^4+2N^3+3N^2+2N).$$
This formula gives $\chi_{D_4}(0)=0, \chi_{D_4}(1)=1$ as we would hope.  Hand enumeration of the $N=2$ case quickly gives 6 different colorings (four red edges; three red edges; two opposite red edges; two adjacent red edges; one red edge; no red edges)  which agrees with the formula.
If reflections are not permitted, we delete the corresponding terms ($2N^3 + 2N^2$) from the enumeration, and divide by 4 instead of 8, as the symmetry group now has 4 elements instead of 8, obtaining instead $$\chi_{C_4}(N) = \frac14(N^4+N^2+2N).$$
This happens to have the same value as $\chi_{D_4}$ for $N<3$; this is because every coloring of the square with fewer than 3 colors has a reflection symmetry.  The simplest coloring that has no reflection symmetry requires 3 colors:
You asked "I am to include rotations?"  The answer is probably yes, or the question would not have specified the edges of a square, which has a natural rotational symmetry.  But suppose you wanted to consider   to be different colorings.  Then rotations of a coloring are not allowed, and the group you consider should be one that omits the rotation elements.  In the extreme case, we can consider every coloring different, and then the group is the trivial group, and the same analysis says to omit all the terms except the $N^4$ contributed by the identity element, and we get $$\chi_{C_1}(N) = N^4$$ which is indeed the correct number of colorings.

A: For the sake of brevity and by way of an incentive to learn more about this wonderful theory, here is a solution using the Polya Enumeration Theorem. All we need here is to calculate the cycle index $Z(G)$ of the symmetry group $G$ of the edges of a square, substitute our $N$ colors into the cycle index and extract coefficients. We get for the first question that the answer is
$${N\choose 4}[C_1 C_2 C_3 C_4]Z(G)(C_1+C_2+C_3+C_4)$$
and for the second question,
$$Z(G)(C_1+C_2+\cdots+C_N)_{C_1=1, C_2=1, \ldots C_N=1}.$$
Let us now compute the cycle index by enumerating the permutations of $G$. There is the identity, which contributes $$a_1^4.$$ There are the rotations by $90$ degrees and $270$ degrees which together contribute $$2 a_4.$$ The rotation by $180$ degrees contributes $$a_2^2.$$ The two reflections about a diagonal contribute $$2 a_2^2$$ and the reflections about horizontal / vertical axes passing through the center of the square contribute $$2 a_1^2 a_2.$$ Summing these contributions we obtain that
$$Z(G) = \frac{1}{8}
\left(a_1^4 + 2a_4 + 3 a_2^2 + 2 a_1^2 a_2\right).$$
Hence the substituted cycle index becomes
$$Z(G)(C_1+C_2+\cdots+C_N)
=  \frac{1}{8}
\left((C_1+\cdots+C_N)^4 +
2(C_1^4+\cdots+C_N^4) \\+
3 (C_1^2+\cdots+C_N^2)^2 +
2 (C_1+\cdots+C_N)^2 (C_1^2+\cdots+C_N^2)\right).$$
In answering the first question (no repeated colors) we see that all terms in the sum except the first use a color at least twice (a phenomenon that generalizes to generic permutation groups), so we have
$${N\choose 4}[C_1 C_2 C_3 C_4] Z(G) =
{N\choose 4}[C_1 C_2 C_3 C_4] \frac{1}{8} (C_1+C_2+C_3+C_4)^4.$$
Expanding the power we get
$$(C_1+C_2+C_3+C_4) \times (C_1+C_2+C_3+C_4)
\\ \times (C_1+C_2+C_3+C_4) \times (C_1+C_2+C_3+C_4).$$
It now becomes evident that there are $24$ ways to obtain the product $C_1 C_2 C_3 C_4,$ for a final answer of
$${N\choose 4} \frac{1}{8} \times 24 = 3{N\choose 4}.$$
We obtain the answer to the second question by setting $C_1=C_2=\cdots=C_N=1$ in the substituted cycle index, for a result of
$$\frac{1}{8}
\left(N^4+2N+3N^2+2N^3\right)
= \frac{1}{8}
\left(N^4+2N^3+3N^2+2N\right).$$
This is sequence A002817 from the OEIS.
This MSE link points to a chain of similar calculations.


text:
Q: How can I transfer eth from an account wallet to a smart contract I'm creating a smart contract that allows people to pay for a monthly subscription
I got stacked in this :
how to transfer plan.amount from the user wallet to the smart contract?
function subscribe(uint planId) external {
    Plan storage plan = plans[planId];
    require(plan.merchant != address(0), 'address not valid');

    bool sent = payable(address(this)).send(plan.amount);
        require(sent, "tx failed");

    emit PaymentSent(
      msg.sender,
      plan.merchant,
      plan.amount, // the monthly amount for Subscription
      planId,
      block.timestamp
    );

    subscriptions[msg.sender][planId] = Subscription(
      msg.sender,
      block.timestamp,
      block.timestamp + 4 weeks // next payement
    );
    emit SubscriptionCreated(msg.sender, planId, block.timestamp);
  }

A: The subscribe() function needs to use the payable modifier in order to accept ETH. Then you can validate how much the user has sent while invoking your function with the msg.value global variable.
It's not possible to request a specific amount from the contract, as the contract code is executed after the user has sent the transaction. You always need to validate how much has the user sent along with the transaction invoking the function.
function subscribe(uint planId) external payable {
    // revert if the sent value is not expected
    require(msg.value == 1 ether, "You need to send 1 ETH");
}

However you can control the predefined value on the UI, while creating the transaction request to their MetaMask or other wallet.
await window.ethereum.request(
    method: 'eth_sendTransaction',
    [
        from: userAddress,
        to: yourContract,
        data: <invoking the subscribe() function>,
        value: <1 ETH in wei, in hex>
    ]
);

Docs: https://docs.metamask.io/guide/ethereum-provider.html#ethereum-request-args


text:
Q: Calling an app from another app In this app I'm developing I need to load/call another app that is already installed on the phone. It's an application for my own personal use only, so no need to check if the other app is installed - I know it is.
I've googled this problem for hours, but I can't find anything that works. Mostly because the guidelines for finding package name and class name are really bad.
Via cmd and adb I was able to find that the info regarding the application I'd like to call is:
package:/data/app/com.soundcloud.android-1.apk=com.soundcloud.android
(that's exactly what it said in the cmd window.)
I tried something like this:
Intent i = new Intent();
i.setClassName("/data/app/com.soundcloud.android-1.apk", "com.soundcloud.android");
startActivity(i);

But my app just crashes instead. I used the above code because someone said that this could call an app:
Intent i = new Intent();
i.setClassName("<package_name>","<Class Name(with package name)>");
startActivity(i);

Does anyone know what to really write?
P.S.: my own app does not need any information about what's happening in the called app.

A: Use the PackageManager to get an Intent for the package:
PackageManager pm = getPackageManager();
Intent intent = pm.getLaunchIntentForPackage("com.example.package");
startActivity(intent);

A: The documentation is
here.
I think in your example, com.soundcloud.android is in fact the package name, so that should be the first argument. For the second one, you still need to figure out the class to use.
If you don't have the code, you can check how to find out the class from the apk with this.


text:
Q: git move unpushed committed changes to a remote branch, work on master, then go back to the branch I am new to git.
I have 10 commits (git status shows I am ahead of origin/master by 10) with lots of code. I have not pushed yet.
After committing changes I did a git pull, resolved all conflicts and then git add and then git commit again which was a big commit.
I now want:
1) other people to view and git pull my work from a new branch and not from master.
2) to start working on another feature from the latest "master" code that does not have my committed changes and be able to push them to master
3) I then later want come back to my current committed unpushed changes and be able to make modifications and eventually push them to master.
Move the most recent commit(s) to a new branch with Git does not answer my question as it does not show how other people can git pull my changes plus looks like it has some complications related to --rebase.


text:
Q: WPF ComboBox selection change after switching tabs I made a project based on nested tabs.
the nested tabs are different instance of the same viemModel and the same UI.
when I switch between the tabs he comboboxes present in the tabs chenge thei selection depending on the tab that is loosing focus.
I add both the viewmodels and the view of my test project.
thank you in advance for your help
main window
<Window.Resources>

    <DataTemplate DataType="{x:Type local:IntermediateViewModel}">
        <local:IntermediateView />
    </DataTemplate>

    <DataTemplate x:Key="HeaderedTabItemTemplate">
        <Grid>
            <ContentPresenter
                        Content="{Binding Path=Header, UpdateSourceTrigger=PropertyChanged}"
                        VerticalAlignment="Center" >
            </ContentPresenter>
        </Grid>
    </DataTemplate>

    <Style x:Key="SimpleTabItemStyle" TargetType="TabItem">
        <Setter Property="Foreground" Value="White"/>
        <Setter Property="FontWeight" Value="Bold"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type TabItem}">
                    <Grid>
                        <Border Name="Border" BorderThickness="1" BorderBrush="#555959">
                            <ContentPresenter x:Name="ContentSite" VerticalAlignment="Center" HorizontalAlignment="Center"
                                 ContentSource="Header" Margin="12,2,12,2" RecognizesAccessKey="True" Height ="40" MinWidth ="90"/>
                        </Border>
                    </Grid>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsSelected" Value="True">
                            <Setter TargetName="Border" Property="Background" Value="#555959" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

    <DataTemplate x:Key="DefaultTabControlTemplate">
        <TabControl IsSynchronizedWithCurrentItem="True"
                        BorderThickness="0"
                        ItemsSource="{Binding}"
                        ItemTemplate="{StaticResource HeaderedTabItemTemplate}"
                        ItemContainerStyle="{StaticResource SimpleTabItemStyle}"
                        SelectionChanged="TabControl_SelectionChanged"
                        />
    </DataTemplate>

    <!---->

</Window.Resources>

<Grid MinHeight="200" MinWidth="300">
    <Grid.RowDefinitions>
        <RowDefinition Height="260*" />
        <RowDefinition Height="51*" />
    </Grid.RowDefinitions>
    <Border >
        <ContentControl
            Content="{Binding Path=Workspaces}"
            ContentTemplate="{DynamicResource DefaultTabControlTemplate}"
             />
    </Border>
    <Button Grid.Row="1" Content="Add" Command="{Binding AddCommand}"/>
</Grid>

view model (create a different istance each time)
class MainWindowViewModel : WorkspacesViewModel<IntermediateViewModel>
{
    public MainWindowViewModel()
    {
        this.WorkspacesView.CurrentChanged += new EventHandler(WorkspacesView_CurrentChanged);
    }

    void WorkspacesView_CurrentChanged(object sender, EventArgs e)
    {
    }

    RelayCommand myVar = null;
    public ICommand AddCommand
    {
        get
        {
            return myVar ?? (myVar = new RelayCommand(param =>
            {
                SetWindow(new IntermediateViewModel("AA" + this.Workspaces.Count) );
            }));
        }
    }

first level tab
    <UserControl.Resources>

    <DataTemplate DataType="{x:Type local:ClassViewModel}">
        <local:ClassView />
    </DataTemplate>
</UserControl.Resources>

<Border>
    <ContentControl Content="{Binding Path=CurrentWorkspace, Mode=OneWay}" Loaded="ContentControl_Loaded" DataContextChanged="ContentControl_DataContextChanged" IsVisibleChanged="ContentControl_IsVisibleChanged" LayoutUpdated="ContentControl_LayoutUpdated" TargetUpdated="ContentControl_TargetUpdated" Unloaded="ContentControl_Unloaded" />
</Border>

first level viewmodel
class IntermediateViewModel : WorkspacesViewModel
    {
        public string Header { get; set; }
    public IntermediateViewModel(string header)
    {
        Header = header;
        SetWindow(new ClassViewModel(header));
    }
}

nested tab
    <UserControl.Resources>
    <CollectionViewSource x:Key="StatusView" Source="{Binding Path=StatusList}"/>
</UserControl.Resources>
<Grid>
    <ComboBox Name="_spl2Status" ItemsSource="{Binding Source={StaticResource StatusView}}"
      SelectedValue="{Binding Path=MyProperty, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
      SelectedValuePath="FL_TYPE"
      DisplayMemberPath="ID_TYPE" Margin="76,12,0,0" Height="40" VerticalAlignment="Top" HorizontalAlignment="Left" Width="146"
               DataContextChanged="_spl2Status_DataContextChanged"
               IsVisibleChanged="_spl2Status_IsVisibleChanged"
               Loaded="_spl2Status_Loaded"
                SelectionChanged="_spl2Status_SelectionChanged"
               >
    </ComboBox>
</Grid>

nested tab view model
public enum myTypes
{
    tipo0 = 0,
    tipo1 = 1,
    tipo2 = 2,
}

class ClassViewModel : WorkspaceViewModel
{
    public ClassViewModel(string name)
    {
        Name = name;
    }

    public string Name { get; set; }

    private List<IntEnumType> _statusList = null;
    public List<IntEnumType> StatusList
    {
        get
        {
            if (_statusList == null)
                _statusList = new List<IntEnumType>()
                {
                    new IntEnumType((int)myTypes.tipo0, myTypes.tipo0.ToString()),
                    new IntEnumType((int)myTypes.tipo1, myTypes.tipo1.ToString()),
                    new IntEnumType((int)myTypes.tipo2, myTypes.tipo2.ToString()),
                };
            return _statusList;
        }
    }

    private int myVar = 1;
    public int MyProperty
    {
        get
        {
            return myVar;
        }
        set
        {
            if (myVar != value)
            {
                myVar = value;
                OnPropertyChanged(() => MyProperty);
            }
        }
    }
}

public class TabItemStyleSelector : StyleSelector
{
    public Style MainTabItem { get; set; }
    public Style ChildrenTabItem { get; set; }
    public Style SpecificationTabItem { get; set; }

    public override Style SelectStyle(object item, DependencyObject container)
    {
        //if (item is IHome)
        //    return MainTabItem;
        //else if (item is SpecificationItemViewModel)
        //    return SpecificationTabItem;
        //else
            return ChildrenTabItem;
    }
}

A: The code is a little hard to completely follow, but I'm guessing that the issue is that there is only one instance of your ClassViewModel and it is where the selection for the combo box is stored {Binding Path=MyProperty, so whatever is stored in MyProperty will be reflected in all instances of the combo box regardless of where they live.

A: Well this is a bit late, but as I'm facing the same issue, I want to share my analysis.
When you change your tabs, you change the DataContext of the current Tab to your other ViewModel and hence also the ItemsSource of your ComboBox.
In case your previously selected Item (SelectedItem) is not contained within the new ItemsSource, the ComboBox fires a SelectionChanged-Event and therefore sets the SelectedIndex to -1.
Altough this default behaviour of the ComboBox might make sense, it's very annoying in many cases.
We've derived an own class from ComboBox, handling that. But it's not very satisfying as you loose some default behaviour you most probably need.

A: The problem is in your loaded event handlers.
When you switch tabs your unloading one tab and loading a new one.
I suspect your changing MyComboBox.SelectedIndex in _spl2Status_Loaded.


text:
Q: rtree is indexable assertion Here is the piece of my code. I am trying to create a rtree tree for the vertex class objects RTreeVertex.
class Entity {

public:
  int num;
public:
  Entity(int nr): num(nr){ }
  virtual ~Entity(){}
   bool operator==(const Entity& b)
   {
     return num == b.num;
   }
};

class Vertex : public Entity {

public :
  struct Coord{
  double X, Y, Z;
  }Pos;

  Vertex(int num=0, double X=0., double Y=0., double Z=0.): Entity (num)
  {
    Pos.X = X;
    Pos.Y = Y;
    Pos.Z = Z;
  }
};

here is how I declare the rtree:
#include <boost/geometry/index/rtree.hpp>
namespace bgi = boost::geometry::index;
bgi::rtree< Vertex, bgi::linear<32> > RTreeVertex;

but I get an error saying that vertec is not Indexable.
and one more general question: Is it a good idea to use rtree for storing data related to a mesh?

A: You have to register your point class with boost geometry. It creates a slew of traits for your class. I tested this, it works.
    class Vertex : public Entity {

    public :
            double X, Y, Z;

        Vertex(int num=0, double x=0., double y=0., double z=0.): Entity (num)
        {
            X = x;
            Y = y;
            Z = z;
        }
    };

BOOST_GEOMETRY_REGISTER_POINT_3D( Vertex, double, bg::cs::cartesian, X, X, X );
#include <boost/geometry/index/rtree.hpp>
namespace bgi = boost::geometry::index;
bgi::rtree< Vertex, bgi::linear<32> > RTreeVertex;

I could not get it to work with X,Y,Z in a structure with Pos::X..., there may be a way. You could join the geometry group on boost.org. They are the geometry experts.
Addendum:
I was curious, so I looked at how REGISTER.. works. With:
BOOST_GEOMETRY_REGISTER_POINT_3D( Vertex, double, bg::cs::cartesian, Pos.X, Pos.Y, Pos.Z );

You can use your structure for your x,y,z.
And namespace bg = boost::geometry;
is the name space I used above


text:
Q: When using Spring, When is the Form class property stored in the value that's sent from the html form tag? I should implement like execute(@ModelAttribute RegisterForm registerForm, Model model) in Controller class below.
I forgot put the @ModelAttribute.
However it works. When is name in RegisterForm class stored in the value that's sent from html?
Part of Controller class
@Controller
public class RegisterController {

  @RequestMapping(value = "/register/")
  public String register() {
      return "register";
  }

  @RequestMapping(value="/register/execute", method=RequestMethod.POST)
  //(@ModelAttribute RegisterForm registerForm, Model model) is better
  public String execute(RegisterForm registerForm, Model model) {
      model.addAttribute("registered_name", registerForm.getName());
      return "index";
  }
}

Form class
public class RegisterForm {

  private String name; //when is this property stored in the value??

  public String getName() {
    return name;
  }
}

Part of HTML file

Enter your name

    <input type="text" name="name" />

Please let me know if you need more information to solve this.Thanks.

A: add setter name to your class RegisterForm  it's important
you should lik this  :
<form action="register/execute">

Enter your name

    <input type="text" name="name" />

<form>

or usign tag form spring  :
add this in  your controller
@RequestMapping(value="/index", method=RequestMethod.POST)
public String executet(Model model) {
    model.addAttribute("registerForm ", new RegisterForm ());
    return "index";
}

include this code in your jsp
   <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>

<form:form method="POST" modelAttribute="registerForm ">
  <form:input path="name" />
 <input type="submit" value="Register">
</form:form>


text:
Q: nodejs + sequelize :: include where required false i have the following hierarchy of objects:

*

*user

*parent (hasOne)

*children (hasMany)

once i have a user object, im attempting to load the associated parent object along with some of its children. the following works:
user.getParent({
  include: [{
    model: Child
  }]
}).then(function(parent) {
  var children = parent.children;
});

but if i want to selectively load some of the parent's children, like so:
user.getParent({
  include: [{
    model: Child,
    where: { gender: 'FEMALE' }
  }]
}).then(function(parent) {
  var daughters = parent.daughters;
});

if the parent has one or more daughters, the query works and i get the parent data along with all daughters' data. however, if the parent has only sons, the parent object returned is null..
i want that if the parent has no daughters, the parent object should still be resolved with children = null or children = []..
also, if i wanted to simply load a count of children while loading the parent, how can i go about doing that?
thanks

A: it turned out to be an issue with my own code.. sequelize fails to load a model if a nested include has a where clause that returns no models.. to ensure it doesnt fail completely, you can set a required: false clause along with the where clause.. this makes sequelize return a blank array instead of failing the load completely..
more info at https://github.com/sequelize/sequelize/issues/4019

A: required: false + where is inconsistent/buggy in sequelize 6.5.1 SQLite vs PostgreSQL
Edit: it was working fine as of sequelize v6.13.0, so it got fixed somewhere along the way.
This is one of the many many many Sequelize association bugs/inconsistencies that make me want to try and find another ORM at some point. Reported at: https://github.com/sequelize/sequelize/issues/13809
Consider the following example where we want to:

*

*list all tags

*in addition, determine if each tag has been assigned to a selected animal
Our where condition on the animal then is a simple "check if the animal is a specific animal", and can only return 0 or 1 entries therefore. But the same would be valid with any other more complex condition.
main.js
#!/usr/bin/env node
const assert = require('assert')
const path = require('path')
const { DataTypes, Sequelize } = require('sequelize')
let sequelize
if (process.argv[2] === 'p') {
  sequelize = new Sequelize('tmp', undefined, undefined, {
    dialect: 'postgres',
    host: '/var/run/postgresql',
  })
} else {
  sequelize = new Sequelize({
    dialect: 'sqlite',
    storage: 'tmp.sqlite'
  })
}
;(async () => {
const Animal = sequelize.define('Animal', {
  species: { type: DataTypes.STRING },
})
const Tag = sequelize.define('Tag', {
  name: { type: DataTypes.STRING },
})
Animal.belongsToMany(Tag, { through: 'AnimalTag' })
Tag.belongsToMany(Animal, { through: 'AnimalTag' })
await sequelize.sync({force: true})
const animal0 = await Animal.create({ species: 'bat' })
const animal1 = await Animal.create({ species: 'ant' })
const animal2 = await Animal.create({ species: 'dog' })
const tag0 = await Tag.create({ name: 'mammal' })
const tag1 = await Tag.create({ name: 'flying' })
const tag2 = await Tag.create({ name: 'aquatic' })
await animal0.addTag(tag0)
await animal0.addTag(tag1)
await animal2.addTag(tag1)
const animals = [animal0, animal1, animal2]
for (let animal of animals) {
  let rows
  rows = await Tag.findAll({
    include: [{
      model: Animal,
      where: { id: animal.id },
      // No effect.
      //on: { id: animal.id },
      through: {
        // Same as putting the where outside of through.
        //where: { AnimalId: animal.id },
      },
      required: false,
    }],
    order: [['name', 'ASC']],
  })
  console.error(animal.species);
  console.error(rows.map(row => { return {
    name: row.name,
    animals: row.Animals.map(animal => animal.species),
  } }))
}
})().finally(() => { return sequelize.close() })

package.json
{
  "name": "tmp",
  "private": true,
  "version": "1.0.0",
  "dependencies": {
    "pg": "8.5.1",
    "pg-hstore": "2.3.3",
    "sequelize": "6.5.1",
    "sqlite3": "5.0.2"
  }
}

Run:
npm install
./main.js p
./main.js

The PotsgreSQL results are as expected:
bat
[
  { name: 'aquatic', animals: [] },
  { name: 'flying', animals: [ 'bat' ] },
  { name: 'mammal', animals: [ 'bat' ] }
]

ant
[
  { name: 'aquatic', animals: [] },
  { name: 'flying', animals: [] },
  { name: 'mammal', animals: [] }
]

dog
[
  { name: 'aquatic', animals: [] },
  { name: 'flying', animals: [] },
  { name: 'mammal', animals: [ 'dog' ] }
]

But the SQLite results are just plain wrong:
bat
[
  { name: 'aquatic', animals: [] },
  { name: 'flying', animals: [ 'bat' ] },
  { name: 'mammal', animals: [ 'bat', null ] }
]

ant
[
  { name: 'aquatic', animals: [] },
  { name: 'flying', animals: [] },
  { name: 'mammal', animals: [] }
]

dog
[
  { name: 'aquatic', animals: [] },
  { name: 'flying', animals: [] },
  { name: 'mammal', animals: [] }
]

I don't mind the null that much, I can work around that.
But dog not being a mammal, that I cannot work around.
Underlying queries
We can look at the underlying queries to guess what is going on.
PostgreSQL has queries of type:
SELECT
  "Tag"."name",
  "Animals"."species" AS "Animals.species",
FROM
  "Tags" AS "Tag"
  LEFT OUTER JOIN (
    "AnimalTag" AS "Animals->AnimalTag"
    INNER JOIN "Animals" AS "Animals" ON "Animals"."id" = "Animals->AnimalTag"."AnimalId"
  ) ON "Tag"."id" = "Animals->AnimalTag"."TagId"
  AND "Animals"."id" = 1
ORDER BY
  "Tag"."name" ASC;

SQLite has queries of type:
SELECT
 `Tag`.`name`,
 `Animals`.`species` AS `Animals.species`
FROM `Tags` AS `Tag`
LEFT OUTER JOIN `AnimalTag` AS `Animals->AnimalTag`
  ON `Tag`.`id` = `Animals->AnimalTag`.`TagId`
LEFT OUTER JOIN `Animals` AS `Animals`
  ON `Animals`.`id` = `Animals->AnimalTag`.`AnimalId`
  AND `Animals`.`id`= 3
ORDER BY
 `Tag`.`name` ASC;

So only the PostgreSQL query is the desired one because of the way it uses the subquery so that the:
ON "Tag"."id" = "Animals->AnimalTag"."TagId"
  AND "Animals"."id" = 1

gets applied only to the outer LEFT OUTER JOIN.
The SQLite query produces undesired results, running it manually for each animal we get outputs:
bat

aquatic|
flying|bat
mammal|bat
mammal|

ant

aquatic|
flying|
mammal|
mammal|

dot

aquatic|
flying|
mammal|
mammal|dog

so what seems to happen is that the animal first result is null, then sequelize ignores it on the return, which would explain why we saw:
  { name: 'mammal', animals: [ 'bat', null ] }

for bat but:
  { name: 'mammal', animals: [] }

for dog.
The desired statement would have the AND on the first LEFT OUTER JOIN:
SELECT
 `Tag`.`name`,
 `Animals`.`species` AS `Animals.species`
FROM `Tags` AS `Tag`
LEFT OUTER JOIN `AnimalTag` AS `Animals->AnimalTag`
  ON `Tag`.`id` = `Animals->AnimalTag`.`TagId`
  AND `Animals->AnimalTag`.`AnimalId`= 1
LEFT OUTER JOIN `Animals` AS `Animals`
  ON `Animals`.`id` = `Animals->AnimalTag`.`AnimalId`
ORDER BY
 `Tag`.`name` ASC;

Workaround: super many to many
The best workaround I could come up so far is to use super many to many, this is often a good bet when the problem is that we need greater control about ON conditions:
#!/usr/bin/env node
const assert = require('assert')
const path = require('path')
const { DataTypes, Sequelize } = require('sequelize')
let sequelize
let logging = process.argv[3] === '1'
if (process.argv[2] === 'p') {
  sequelize = new Sequelize('tmp', undefined, undefined, {
    dialect: 'postgres',
    host: '/var/run/postgresql',
    logging,
  })
} else {
  sequelize = new Sequelize({
    dialect: 'sqlite',
    storage: 'tmp.sqlite',
    logging,
  })
}
;(async () => {
const AnimalTag = sequelize.define('AnimalTag')
const Animal = sequelize.define('Animal', {
  species: { type: DataTypes.STRING },
})
const Tag = sequelize.define('Tag', {
  name: { type: DataTypes.STRING },
})
AnimalTag.belongsTo(Animal)
Animal.hasMany(AnimalTag)
AnimalTag.belongsTo(Tag)
Tag.hasMany(AnimalTag)
Animal.belongsToMany(Tag, { through: AnimalTag })
Tag.belongsToMany(Animal, { through: AnimalTag })

await sequelize.sync({force: true})
const animal0 = await Animal.create({ species: 'bat' })
const animal1 = await Animal.create({ species: 'ant' })
const animal2 = await Animal.create({ species: 'dog' })
const tag0 = await Tag.create({ name: 'flying' })
const tag1 = await Tag.create({ name: 'mammal' })
const tag2 = await Tag.create({ name: 'aquatic' })
await animal0.addTag(tag0)
await animal0.addTag(tag1)
await animal2.addTag(tag1)
const animals = [animal0, animal1, animal2]
for (let animal of animals) {
  let rows
  rows = await Tag.findAll({
    include: [{
      model: AnimalTag,
      where: { AnimalId: animal.id },
      required: false,
      include: [{
        model: Animal,
      }]
    }],
    order: [['name', 'ASC']],
  })
  console.error(rows.map(row => { return {
    name: row.name,
    animals: row.AnimalTags.map(animalTag => animalTag.Animal.species)
  } }))
  console.error();
}
})().finally(() => { return sequelize.close() })

produces the correct output for both PostgreSQL and Sequelize. The produced query is exactly what we wanted:
SELECT
  "Tag"."id",
  "Tag"."name",
  "Tag"."createdAt",
  "Tag"."updatedAt",
  "AnimalTags"."createdAt" AS "AnimalTags.createdAt",
  "AnimalTags"."updatedAt" AS "AnimalTags.updatedAt",
  "AnimalTags"."AnimalId" AS "AnimalTags.AnimalId",
  "AnimalTags"."TagId" AS "AnimalTags.TagId",
  "AnimalTags->Animal"."id" AS "AnimalTags.Animal.id",
  "AnimalTags->Animal"."species" AS "AnimalTags.Animal.species",
  "AnimalTags->Animal"."createdAt" AS "AnimalTags.Animal.createdAt",
  "AnimalTags->Animal"."updatedAt" AS "AnimalTags.Animal.updatedAt"
FROM
  "Tags" AS "Tag"
  LEFT OUTER JOIN "AnimalTags" AS "AnimalTags" ON "Tag"."id" = "AnimalTags"."TagId"
  AND "AnimalTags"."AnimalId" = 3
  LEFT OUTER JOIN "Animals" AS "AnimalTags->Animal" ON "AnimalTags"."AnimalId" = "AnimalTags->Animal"."id"
ORDER BY
  "Tag"."name" ASC;

Tested on Ubuntu 21.10, PostgreSQL 13.5.


text:
Q: How do I split an convolutional autoencoder? I have compiled an autoencoder (full code is below), and after training it I would like to split it into two separate models: encoder (layers e1...encoded) and decoder (all other layers) in which to feed manually modified images that had been encoded by the decoder. I have succeeded in creating an encoder as a separate model with:
encoder = Model(input_img, autoencoder.layers[6].output)

But the same approach fails when I try to make a decoder:
encoded_input = Input(shape=(4,4,8))
decoder = Model(input_img, decoded)

This is my full code:
from keras.layers import Input, Dense, Conv2D, MaxPooling2D, UpSampling2D
from keras.models import Model
from keras import backend as K
from keras.models import load_model

input_img = Input(shape=(28, 28, 1))  # adapt this if using channels_first` image data format

e1 = Conv2D(16, (3, 3), activation='relu', padding='same')(input_img)
e2 = MaxPooling2D((2, 2), padding='same')(e1)
e3 = Conv2D(8, (3, 3), activation='relu', padding='same')(e2)
e4 = MaxPooling2D((2, 2), padding='same')(e3)
e5 = Conv2D(8, (3, 3), activation='relu', padding='same')(e4)
encoded = MaxPooling2D((2, 2), padding='same')(e5)

# at this point the representation is (4, 4, 8) i.e. 128-dimensional

d1 = Conv2D(8, (3, 3), activation='relu', padding='same')(encoded)
d2 = UpSampling2D((2, 2))(d1)
d3 = Conv2D(8, (3, 3), activation='relu', padding='same')(d2)
d4 = UpSampling2D((2, 2))(d3)
d5 = Conv2D(16, (3, 3), activation='relu')(d4)
d6 = UpSampling2D((2, 2))(d5)
decoded = Conv2D(1, (3, 3), activation='sigmoid', padding='same')(d6)

autoencoder = Model(input_img, decoded)
autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')

Plese help.
EDIT
By the way, I was able to do this with an autoencoder consisting of dense layers:
from keras.layers import Input, Dense
from keras.models import Model

# this is the size of our encoded representations
encoding_dim = 32  # 32 floats -> compression of factor 24.5, assuming     the input is 784 floats

# this is our input placeholder
input_img = Input(shape=(784,))

# "encoded" is the encoded representation of the input
encoded = Dense(encoding_dim, activation='relu')(input_img)

# "decoded" is the lossy reconstruction of the input
decoded = Dense(784, activation='sigmoid')(encoded)

# this model maps an input to its reconstruction
autoencoder = Model(input_img, decoded)

# this model maps an input to its encoded representation
encoder = Model(input_img, encoded)

# create a placeholder for an encoded (32-dimensional) input
encoded_input = Input(shape=(encoding_dim,))

# retrieve the last layer of the autoencoder model
decoder_layer = autoencoder.layers[-1]

# create the decoder model
decoder = Model(encoded_input, decoder_layer(encoded_input))

A: Ok, I figured this out after a few hours. What worked for me was to:
1. Create a separate model for the encoder
2. Create a separate model for teh decoder
3. Create a general model for the autoencoder:
autoencoder = Model(input, Decoder()(Encoder(input))

The full working code is below:
def Encoder():
    input_img = Input(shape=(28, 28, 1))  # adapt this if using `channels_first` image data format
    e1 = Conv2D(16, (3, 3), activation='relu', padding='same')(input_img)
    e2 = MaxPooling2D((2, 2), padding='same')(e1)
    e3 = Conv2D(8, (3, 3), activation='relu', padding='same')(e2)
    e4 = MaxPooling2D((2, 2), padding='same')(e3)
    e5 = Conv2D(8, (3, 3), activation='relu', padding='same')(e4)
    e6 = MaxPooling2D((2, 2), padding='same')(e5)
    return Model(input_img, e6)

def Decoder():
    input_img = Input(shape=(4, 4, 8))  # adapt this if using `channels_first` image data format
    d1 = Conv2D(8, (3, 3), activation='relu', padding='same')(input_img)
    d2 = UpSampling2D((2, 2))(d1)
    d3 = Conv2D(8, (3, 3), activation='relu', padding='same')(d2)
    d4 = UpSampling2D((2, 2))(d3)
    d5 = Conv2D(16, (3, 3), activation='relu')(d4)
    d6 = UpSampling2D((2, 2))(d5)
    d7 = Conv2D(1, (3, 3), activation='sigmoid', padding='same')(d6)
    return Model(input_img, d7)

# define input to the model:
x = Input(shape=(28, 28, 1))

# make the model:
autoencoder = Model(x, Decoder()(Encoder()(x)))

# compile the model:
autoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')


text:
Q: Retrieve specific dictionary of a larger one in Python I'm new to Python so I apologize is I confuse the terminology a bit...
I'm given the following dictionary:
[
   {
      "responseData":true,
      "requestClass":"MessageService",
      "requestMethod":"newMessage",
      "requestId":1,
      "__class__":"ServerResponse"
   },
   {
      "responseData":{
         "time":1590429080,
         "__class__":"Time"
      },
      "requestClass":"TimeService",
      "requestMethod":"updateTime",
      "requestId":1,
      "__class__":"ServerResponse"
   },
   {
      "responseData":[
         {
            "value":16,
            "type":"recruitment_acceleration",
            "__class__":"RecruitmentAccelerationBonus"
         },
         {
            "value":3,
            "type":"daily_strategypoint",
            "__class__":"DailyStrategyPointBonus"
         }
      ],
      "requestClass":"BonusService",
      "requestMethod":"getBonuses",
      "requestId":1,
      "__class__":"ServerResponse"
   },
   {
      "responseData":{
         "resources":{
            "diplomacy":372,
            "brush":0,
            "marble":559
         },
         "__class__":"Resources"
      },
      "requestClass":"ResourceService",
      "requestMethod":"getPlayerResources",
      "requestId":1,
      "__class__":"ServerResponse"
   },
   { # added missing bracket
      "responseData":[
         {
            "gridId":"main",
            "type":"antiquesExchange",
            "time":1590481057,
            "__class__":"Timer"
         }
      ],
      "requestClass":"TimerService",
      "requestMethod":"getTimers",
      "requestId":1,
      "__class__":"ServerResponse"
   }
]

And need to extract the part contained in the same array as the requestMethod named getPlayerResources, in the current case:
{
   "diplomacy":372,
   "brush":0,
   "marble":559
  }

I have tried multiple things with find or the sample below but never managed to get what I want.
The position of the getPlayerResources may not always be the same, which complicate things.
    def search(values, searchFor):
        for k in values:
            print (values)
            print (k)
            for v in values[k]:
                if searchFor in v:
                    return k
        return None

if '/game/json' in request.path:
            responsestring = request.response.body
            response_json_object = json.loads(responsestring)

            for object in response_json_object:
                for attribute, value in object.items():
                    if value != True and value != False:
                        result = search(value, 'getPlayerResources')

A: Try the below, pay attention that your json is not valid.
d = [
   {
      "responseData":True,
      "requestClass":"MessageService",
      "requestMethod":"newMessage",
      "requestId":1,
      "__class__":"ServerResponse"
   },
   {
      "responseData":{
         "time":1590429080,
         "__class__":"Time"
      },
      "requestClass":"TimeService",
      "requestMethod":"updateTime",
      "requestId":1,
      "__class__":"ServerResponse"
   },
   {
      "responseData":[
         {
            "value":16,
            "type":"recruitment_acceleration",
            "__class__":"RecruitmentAccelerationBonus"
         },
         {
            "value":3,
            "type":"daily_strategypoint",
            "__class__":"DailyStrategyPointBonus"
         }
      ],
      "requestClass":"BonusService",
      "requestMethod":"getBonuses",
      "requestId":1,
      "__class__":"ServerResponse"
   },
   {
      "responseData":{
         "resources":{
            "diplomacy":372,
            "brush":0,
            "marble":559
         },
         "__class__":"Resources"
      },
      "requestClass":"ResourceService",
      "requestMethod":"getPlayerResources",
      "requestId":1,
      "__class__":"ServerResponse"
   },
    {"responseData":[
         {
            "gridId":"main",
            "type":"antiquesExchange",
            "time":1590481057,
            "__class__":"Timer"
         }
      ],
      "requestClass":"TimerService",
      "requestMethod":"getTimers",
      "requestId":1,
      "__class__":"ServerResponse"
   }
]

for inner_d in d:
    if "requestMethod" in inner_d and inner_d["requestMethod"] == "getPlayerResources":
        print(inner_d["responseData"]['resources'])

The above code uses the fixed json and prints:
{'diplomacy': 372, 'brush': 0, 'marble': 559}

A: The outermost character in that json is a square bracket, so this is a list of dicts.
# loop over all the dicts
for d in response_json_object:

    # is this the one we're looking for?
    if d.get("requestMethod") == "getPlayerResources":
        print("Found the data!")
        print(d["responseData"]["resources"]

A: You don't have a dictionnary but a list of dictionnaries. Also, be aware that you must put a capital T to True in Python, otherwise your code won't work.
The following function will return the part you want to extract if you give it your list in argument:
def findResource(l):
    for d in l:
        if "requestMethod" in d and d["requestMethod"] == "getPlayerResources":
            return d["responseData"]["resources"]
    return None

A: You have not been given a dictionnary, but a list of dict, json file.
First there is a '{' missing in line 51 of your file.
Once you have imported the json file, you can find the position of the dict you're looking for using a loop, and then get what you want:
import json
with open('p.json') as f:
    response_json_object = json.load(f)

position = []
for pos, elt in enumerate(response_json_object):
    if elt['requestMethod'] == 'getPlayerResources':
        position.append(pos)

response_json_object[position[0]]['requestMethod']

Should give you 'getPlayerResources'. position is a list so the [0] is there to get the number inside.

A: Here you go:
res_dict = json.loads(responsestring)
for section in res_dict:
    if section['requestMethod'] == 'getPlayerResources':
        resources = section['responseData']['resources']
        print(resources)
        break

Output
{'diplomacy': 372, 'brush': 0, 'marble': 559}


text:
Q: If I set up DHCP and static IP simultaneously, Google nameserver becomes unreachable
Currently I have two network interfaces, ens160(DHCP) and ens192(static).
However, if these two NICs alive together, ping 8.8.8.8 is blocked so I can't update any packages. If I shut down ens192, Google DNS becomes reachable.
What is the problem? How can I set up two interfaces without blocking access to nameserver 8.8.8.8?
This is my gateway information.


text:
Q: How to random only on 10 first recents posts? I am facing of a client request, he has 100 products with pagination ( 10 per page), he wants only random on the first 10 products and for the rest of the pages no random ( for others paginations other than 1 )
I have this query :
$args = array(
    'post_type' => array('products'),
    'paged'=> ( get_query_var('paged') ? get_query_var('paged') : 1 ),
);
$products = new Wp_Query($argss);
... Loop here ...
... End loop ...
... Pagination ...

Products displays well, pagination works, only i ask myself how to achieve this goal. If i use :
if( $paged == 1 ) $args['orderby'] = 'rand';

It will random on the first page but he will pick other products other than the first 10 product, the goal is to only random the first 10 products on home search page without picking up the others.
Thanks for your help.

A: Try this.
if page is 1 then set 'order' => 'rand'
     $args = array(
            'post_type' => array('products'),
            'paged'=> ( get_query_var('paged') ? get_query_var('paged') : 1 ),
            'order_by' => 'ID',
            'post_status'=> 'publish',
            'posts_per_page' => -1,
        );

        if($args['paged'] == 1){
            $args['order'] = 'rand';
        } else{
          $args['order'] = 'DESC';
        }
        $products = new Wp_Query($args);

A: Try the following
if(get_query_var( 'paged', 1 )==1)
{
    shuffle($products->posts);
}

after $products = new Wp_Query($argss);


text:
Q: Git command to push the files without cloning I have a requirement,

*

*I need to clone a remote branch to Local.

*Add some files the local folder

*Push the changes to some other existing  remote branch.

But, when I do got push, it is actually cloning the remote branch details in to my local, and then pushing it.
Because of that, I am losing the newly added files in my local (those will be overwrite) and those files will not push to the other branch.
The command I am using to push is as below:
git init
cd git_test
git fetch
git checkout repobranchB
git add -A
git commit -m "test"
git push

Is there any option in git push, where it will not clone the existing files in the remote branch to local? I just need to add all the files in my local to the specified remote branch.

A: It sounds like you want to:

*

*Checkout the branch

*Pull remote changes (temporarily)

*Make YOUR changes to the files

*Commit and push to remote

*Checkout your old branch again locally

You can even delete the local branch if you no longer need it:
git branch -d repobranchB

Commits on one branch should not effect another unless you 'git add...' the changes while on that branch. When you switch back to the original branch your changes won't be there
https://git-scm.com/book/id/v2/Git-Branching-Remote-Branches


text:
Q: Combining zsh's tab completion with case insensitivity I have zsh 5.0.7 configured to use case-insensitive tab completion with
zstyle ':completion:*' matcher-list 'm:{a-zA-Z}={A-Za-z}'

The problem I'm having is that this case insensitivity often leads to my needing to press Tab an extra time. For example, my home directory contains the folders "Desktop", "Documents", and "Downloads". If I'm in my home folder and I type
cd D

and then press Tab, I see the three possibilities listed for me. On the other hand, if I type
cd d

and then press Tab then the "d" changes to "D" but I don't see the completion menu; I need to press Tab again for that to happen. Is there a way to get the completion menu at the same time that the "d" is changed to a "D"?

A: Another useful setting could be
setopt no_list_ambiguous

It will correct "c" to "C" and show the completion menu.

A: Enabling the option MENU_COMPLETE will skip the correction and immediately insert the first possible match.