text:
Q: how to send an object data that contains hashset of another object from jsp to controller in spring mvc; This is my jsp code
stuff contains list of stuffPacking
        var stuffPackingData;
        var kindOfStuffData;
        var array = [];
        var grid = $j("#kindOfStuffGrid").data("kendoGrid");
        var stuffPackingTempDS = stuffPackingDS.view();
        for (var i = 0; i < grid._data.length; i++) {
            var kindId = findKindOfStuffUnitIdByName(grid._data[i].kindOfStuffUnitName);
            kindOfStuffData = {
                'id': kindId,
                'name': grid._data[i].kindOfStuffUnitName
            }
            stuffPackingData = {
                'number': grid._data[i].number,
                'kindOfStuffUnit': kindOfStuffData,
            }
            array.push(stuffPackingData);
        }

        kindOfStuffData = {
            'id': $('#kindOfStuffUnitName').val(),
        }
        var data = {
            'id': lastSelectedStuffFullId,
            'name': $('#stuffNameInsertInput').val(),
            'kindOfStuffUnit': kindOfStuffData,
            'barcode': $('#stuffBarCodeInsert').val(),
            'irancode': $('#stuffIranCodeInsert').val(),
            'weight': $('#StuffWeightInsert').val(),
            'priceBuy': removeComma($("#stuffBuyPriceInsert").val()),
            'priceSell': removeComma($("#stuffSellPriceInsert").val()),
            'minimumStock': $("#stuffMinStockInsert").val(),
            'orderPoint': $("#stuffOrderPointInsert").val(),
            'percentAvarez': $("#stuffAvarezPercentInsert").val(),
            'percenrTax': $("#stuffTaxPercentInsert").val(),
            'stuffPackings': array,
            'year': "1395"
        };
        $.ajax({
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            type: "POST",
            url: contexPath + stuffUrl,
            data: JSON.stringify(data),
            dataType: "json",
            async: false,

and in controller im trying to add a new stuff that contains hashset of stuffPackings
@RequestMapping(method = RequestMethod.POST, value = "/Add")
public @ResponseBody
String Add(@Valid @RequestBody Stuff stuff, BindingResult result) {

in controller i cant access to my stuffpacking data
is ther another way to send and save this kind of values without these trubels?

A: Your jsp code is right,
You can do this by below code
just change your controller like this
HashSet<StuffPacking> SP = new HashSet<StuffPacking>();
        Object[] objArray = stuff.getStuffPackings().toArray();
        for (Object temp : objArray) {
            LinkedHashMap map = new LinkedHashMap(5);
            map = (LinkedHashMap) temp;

            StuffPacking stuffPacking = new StuffPacking();
            stuffPacking.setNumber(Double.valueOf(map.get("number").toString()));
            LinkedHashMap unitId= (LinkedHashMap)(map.get("kindOfStuffUnit"));

            KindOfStuffUnit kindunit = new KindOfStuffUnit();
            kindunit.setId(Byte.valueOf(unitId.get("id").toString()));
            stuffPacking.setKindOfStuffUnit(kindunit);
            stuffPacking.setStuff(stuff);
            SP.add(stuffPacking);
        }

        stuff.setStuffPackings(SP);


text:
Q: BroadcastReceiver within Service Can't Receive I register a BroadcastReceiver within MyService,
public class MyService extends Service {

final static String ACTION_ONE = "one";
final static String ACTION_TWO = "two";

 BroadcastReceiver receiver;

and a inner class
// use this as an inner class like here or as a top-level class
public class MyReceiver2 extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // do something
        Log.d("tag", "received! MyReceiver2");
    }

    // constructor
    public MyReceiver2(){

    }
}

onCreate method:
@Override
public void onCreate() {
   receiver = new MyReceiver2();

    IntentFilter filter = new IntentFilter();
    filter.addAction(MyService.ACTION_ONE);
    filter.addAction(MyService.ACTION_TWO);

    MyService.this.registerReceiver(receiver, filter);
}

And the code below is in MainActivity to send a broadcast:
    sendBroadcast.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

Intent intent = new Intent(v.getContext(), MyService.class);
            intent.setAction(MyService.ACTION_TWO);
            sendBroadcast(intent);
}
});

I can't understand why MyService(started, and is not yet destoryed) can not receive broadcast.
If I change the receiver variable to a MyReceiver class that extends BroadcastReceiver and has already been proved to work,
MyService is still not receiving broadcast.
myReceiver = new MyReceiver();

Here is MyReceiver(it is proved that it works well):
public class MyReceiver extends BroadcastReceiver{

public MyReceiver(){
    Log.d("tag", "MyReceiver Constructor");
}

@Override
public void onReceive(Context context, Intent intent) {
        Log.d("tag", "received");
}
}

============EDIT================
manifest
Both
    <service
        android:name=".MyService"
        android:enabled="true"
        android:exported="true" >
        <intent-filter >
            <action android:name="one" />
            <action android:name="two" />
        </intent-filter>
    </service>

and
    <service
        android:name=".MyService"
        android:enabled="true"
        android:exported="true" >
    </service>

do not work.

A: This looks like a manifest problem,
Please make sure you are declaring that receiver in the manifest!
for example:
<receiver android:name=".receivers.BackgroundTasksReceiver"/>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Remove subprocess buffer while reading a file I need to monitor a file in real time and extract certain information to inform users about the progress. Basically something similar to "tail -f" which outputs right away the lines added to the file. The problem is that it seems I have a buffering issues which delays getting the latest lines.
Here is my code:
f = subprocess.Popen(['tail','-F','/myfile'],stdout=subprocess.PIPE,stderr=subprocess.PIPE,bufsize=1, universal_newlines=True)
while True:
    line = f.stdout.readline()
    print (line)

I've also tried "sys.stdout.write" and "sys.stdout.flush" but that made no difference. I've tried to execute the Python script with "-u" but it changed nothing.
Could you please help?

A: You were on the right way, but using the wrong stream. Calling flush is the right idea. But sys.std* are the streams of your script, not the streams in the Popen object.
Use f.stdout.reconfigure(line_buffering=True). That sets the stream inside the Popen object to use flush automatically.
Instead of using tail, you could also just read from the file:
with open('/myfile', buffering=1) as f:
    for line in f:  # reads the file line-by line
        print(line)


text:
Q: Set path in /etc/crontab for php file Hello I have to run cron which I have written in core php.
Path of my php file in
/var/www/html/xplore/crons/examples/example.php
when I go to path of mu file and run script using php example.php it give me proper output.
But How to give path of file in crontab I have tried it by using
*/2 * * * * root  usr/bin/php xplore/crons/examples/example.php

Do you have any idea please help me in to that?

A: try like below,
*/2 * * * * /usr/bin/php -q /xplore/crons/examples/example.php

*/2 * * * *  It means that cron will run in every 2 min.

A: Seems like the file path that you are passing is wrong. You can try this
*/2 * * * * root  /usr/bin/php /xplore/crons/examples/example.php

if this path(xplore/crons/examples/example.php) is correct


text:
Q: Showing one marker at a time - Google Maps API v3 http://jsfiddle.net/michaelgruber/M84T7/
When the codeAddress function is run more than once (when multiple inputs are run) the old markers are saved on the map. Why is this? Shouldn't the MyMap.marker be overwritten?

A:
Shouldn't the MyMap.marker be overwritten?

Yes, but it is a reference to the marker not the marker itself.
To hide the marker:
 marker.setMap(null);

Before you overwrite it and lose the reference.
http://jsfiddle.net/zbZ8p/1/


text:
Q: How do I sort by distance from user, based on user's location? I have a Rails 7 app in which users can search, sort, and filter to find parks and nature reserves. I'm using the Ransack gem.
I have calculated the distance of each park from the user based on the user's IP address using Javascript.
Now I want to add a link on the Parks Index page for users to sort by distance. (Currently I have sort by rating and sort by name.)
Not sure how to go about this... I suspect I'll have to store the distance in the database somehow (on the user table?), so I can apply a server-side sort. Is that the right approach?
How do I store the distance from user in an efficient way, when the distance is recalculated every time the user visits the site?
app/javascript/controllers/geolocation_controller.js
import { Controller } from '@hotwired/stimulus';
import { getDistance, convertDistance } from 'geolib';

export default class extends Controller {
  static targets = ['park'];

  connect() {
    window.navigator.geolocation.getCurrentPosition((position) => {
      this.setUserCoordinates(position.coords);
      this.setDistanceText();
    })
  }

  setUserCoordinates(coordinates) {
    this.element.dataset.latitude = coordinates.latitude;
    this.element.dataset.longitude = coordinates.longitude;
  }

  getUserCoordinates() {
    return {
      latitude: this.element.dataset.latitude,
      longitude: this.element.dataset.longitude,
    };
  }

  setDistanceText() {
    this.parkTargets.forEach((parkTarget) => {
      let distanceFrom = getDistance(
        this.getUserCoordinates(),
        { latitude: parkTarget.dataset.latitude,
          longitude: parkTarget.dataset.longitude },
      );

      parkTarget.querySelector('[data-distance-away]').innerHTML =
            `${Math.round(convertDistance(distanceFrom, 'km'))} kilometers away`;
    });
  }
}

app/views/parks/_park_cards.erb
<% @parks.order('average_rating DESC NULLS LAST').each do |park| %>
  <li
    style="list-style-type: none;"
    data-geolocation-target="park"
    data-latitude="<%= park.latitude %>"
    data-longitude="<%= park.longitude %>"
  >

        <% if park.default_image && park.default_image.content_type.in?(%w[image/gif image/jpeg image/png]) %>
          ...
        <% else %>
          ...
        <% end %>

          <%= link_to park.name, park, class: "text-body" %>

            <% if park.average_rating? %>

                ...

              <%= park.average_rating.round(2) %>
            <% end %>

            ...

            ...

<% end %>

app/views/parks/index.html.erb
<% provide(:title, 'Parks') %>

    <%- if current_user && current_user.admin? %>
      <%= link_to "New park", new_park_path %>
    <% end %>

          <%= @parks.count %>
          <%= 'park'.pluralize(@parks.count) %>

          <%= link_to "Clear all filters", parks_path, class: "btn link-dark" %>

        <%= sort_link(@q, :average_rating, "Sort by rating", default_order: :desc, class: "btn") %>
        <% if I18n.locale.to_s.include?('he') %>
          <%= sort_link(@q, :name_he, "Sort by name (Hebrew)", default_order: :asc, class: "btn") %>
        <% else %>
          <%= sort_link(@q, :name_en, "Sort by name", default_order: :asc, class: "btn") %>
        <% end %>

          <%= render 'filters_button' %>

    <%= render 'park_cards', parks: @parks %>

    <%= will_paginate(@users) %>

<%= render 'filters_modal' %>

app/controllers/parks_controller.rb
class ParksController < ApplicationController
  before_action :set_park, only: %i[ show edit update destroy ]
  before_action :admin_user, only: %i[ new edit create update destroy ]

  # GET /parks or /parks.json
  def index
    @parks = @q.result(distinct: true).paginate(page:params[:page], :per_page => 48)
  end

  ...

app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  before_action :set_locale
  before_action :set_search

  def set_search
    @q = Park.ransack(params[:q])
  end

  ...


text:
Q: Interaction between neutrino and an anti-neutrino? What happens when a neutrino and an anti-neutrino interacts together? For example, what does a muon neutrino and anti-muon neutrino produce? it says in my book that it creates "muons and antimuons". But, how? Don't the particle and the antiparticle annihilate when they interact with each other?

A: If you are asking about an interaction between a $\nu_\mu$ and a $\bar{\nu}_\mu$, then they annihilate to a (generally off-shell) $Z^0$-boson and which then decays to some particle/anti-particle pair. The pair may be charged leptons, neutrinos or quarks (assuming there is enough energy to hadronize) so the final outcome could be a lot of different things.
$$ \nu_\mu + \bar{\nu}_\mu \to Z^{0*} \to \text{a pair of some kind}\,.$$
This is analogous to the process known as Drell-Yan when the intermediate boson is a photon, only the cross-section is much lower on account of being weak moderated.


text:
Q: GroupBy and OrderBy I'm trying to do a GroupBy and then OrderBy to a list I have. Here is my code so far:
reportList.GroupBy(x => x.Type).ToDictionary(y=>y.Key, z=>z.OrderBy(a=>a.Lost));

With the help of the last question I asked on linq I think the ToDictionary is probably unneeded, but without it I don't know how to access the inner value.
To be clear, I need to GroupBy the Type property and want the inner groups I get to be OrderBy the Lost property (an integer). I want to know if there is a better, more efficient way or at the least better then what I've done.
An explanation and not just an answer would be very much appreciated.

A: Yes, there is better approach. Do not use random names (x,y,z,a) for variables:
reportList.GroupBy(r => r.Type)
          .ToDictionary(g => g.Key, g => g.OrderBy(r => r.Lost));

You can even use long names to make code more descriptive (depends on context in which you are creating query)
reportList.GroupBy(report => report.Type)
          .ToDictionary(group => group.Key,
                        group => group.OrderBy(report => report.Lost));

A: Your code does basically the following things:

*

*Group elements by type

*Convert the GroupBy result into a dictionary where the values of the dictionary are IEnumerables coming from a call to OrderBy

As far as the code correctness it is perfectly fine IMO, but maybe can be improved in term of efficiency (even if depends on your needs).
In fact, with your code, the values of your dictionary are lazily evaluated each time you enumerate them, resulting in a call to OrderBy method.
Probably you could perform it once and store the result in this way:
var dict = reportList
           .GroupBy(x => x.Type)
           .ToDictionary(y => y.Key, z => z.OrderBy(a => a.Lost).ToList());
// note the ToList call

or in this way:
var dict = reportList.OrderBy(a => a.Lost)
                     .GroupBy(x => x.Type)
                     .ToDictionary(y => y.Key, z => z);
// here we order then we group,
// since GroupBy guarantees to preserve the original order

A: Looks fine to me. If you use an anonymous type instead of a Dictionary, you could probably improve the readability of the code that uses the results of this query.
reportList.GroupBy(r => r.Type)
    .Select(g => new { Type = g.Key, Reports = g.OrderBy(r => r.Lost) });


text:
Q: scheduling tasks in linux Can we schedule a program to execute every 5 ms or 10 ms etc?
I need to generate a pulse through the serial port for 1 khz and 15 khz.
But the program should only toggle the pins in the serial port , so the frequency has to be produced by a scheduler. is this possible in linux with a rt patch?

A: I believe a better solution is to put your "generate a pulse" function in a loop, for example:
for (;;) {
    generate_pulse(); /* generate a pulse */
    sleep(5ms);       /* or 10ms */
}

A: is this possible in linux with a rt patch?
I suggest to go for RT patch, if timing is critical.
Xenomai is a RT patch which I used on 2.6 kernel some days back.
Here is an example which runs every 1 second.
http://www.xenomai.org/documentation/trunk/html/api/trivial-periodic_8c-example.html

A: There is the PPS project that is now part ( at least a portion of it for the 2.6 branch, but in the latest 3.x kernel branch it looks like there is a full integration ) of the mainline linux kernel.
There is also an explicit reference to using this PPS implementation with a serial port in the linked txt file

A PPS source can be connected to a serial port (usually to the Data
  Carrier Detect pin) or to a parallel port (ACK-pin) or to a special
  CPU's GPIOs (this is the common case in embedded systems) but in each
  case when a new pulse arrives the system must apply to it a timestamp
  and record it for userland.

Apparently good examples / tutorials / guides, are not even that hard to find , I'm sure that you'll find a lot of good resources while just using search engine.
The header for the APIs is usually under /usr/include/linux/pps.h .

A: I have finally found a way to get it done.
The best way to do it is to first create a timer with the required amount of time. and then to call the task( which is the pulse generating program) every time the timer overflows. The program for the timer can be run in the background. the timer can be created and set using the timer_create() and timer_settime() respectively. A different program can be called from one program using fork() and execl(). The program can be run in the background using the daemon().
By using all these things we can create our own scheduler.


text:
Q: Which is the best technique that can be used for pdf compression in MVC4 application? I need to implement PDF compression so that it can be easily downloaded in MVC4 application.

A: It's simple for compressing file in MVC.

PDF document has been widely used by large enterprises and organizations to distribute and view documents. But in practical applications, the large size issue of PDF document (especially when the PDF document contains large number of images) causes a heavy burden on the bandwidth costs, network transmission time and digital storage. Thus, how to compress large-size existing PDF documents is quite useful for increasing the efficiency and productiveness of existing document management system.

Here is how to compress file.


text:
Q: Iterating search query through KnockoutJS Array How do I live-update-sort a KO observableArray() and perform one function on each object that gets sorted and another function on an object that remains?
So I've got an observableArray() of Google Maps Markers. 100+, so I'm trying to work out a sorting system that shows or hides the marker depending on if it matches a particular filter. I've used knockoutJS for the vast majority of the data bits in the app, so I'm trying to figure out how to best implement this. I can step through the array and get the titles via gMarkers()[i].title, but I'm not sure how to filter these items per another observable().
I've created userQuery() to accept an input, so I can use that to sort. I assume this has to be done via a ko.computed(), but I'm not sure how to best update this as it's going to be something changing on the fly as people type (changing userQuery()).
Is there a lightweight way to iterate through the array and perform a function on each result dependent on the sort, or should I be approaching this from a different way?

A: Use a (pure)Computed:
/// .... in your viewmodel ....
this.filteredData = ko.pureComputed(function() {
     // query all observables the outcome depends on
     var query = self.userQuery();
     var ...   = ...

     var fData = [];
     // iterate over your dataset or use ko.utils.map / ko.utils.filter
     for (...) {
         fData.push(...);
     }
     return fData;
});

The computed will recalculate whenever any observable you depend on changes. Be careful to not introduce cycles in your dependencies.


text:
Q: How do I ng-init a variable with nothing? This line currently triggers an error because probably there is nothing after the second =.
What value should return from php to tell filterSubject that is empty.
ng-init="filterSubject="
In some cases filterSubject= gets populated with an id from the query string like ?subject=11
but what do I have to pass from php when the query string is not present
Thank you

A: Since it looks like you're generating the string in PHP, put single quotes around the filter subject:
ng-init="filterSubject='$subject'"

A: you can use ternary operator something like this
ng-init="filterSubject = YOUR_EXPRESSION || ''"

A: You can do something like this :-
<div <?php if($_GET['subject']){ ?>ng-init="filterSubject='<?php echo $_GET['subject']; ?>'" <?php }?>>
.....
</div>

or
<?php
if($_GET['subject']){
$nginit = 'ng-init="filterSubject=\''.$_GET['subject'].'\'"';
}
?>

<div <?php echo $nginit;?>>
.....
</div>


text:
Q: Como obter valor do DB para uma variável? Tenho a seguinte dúvida:
Tenho um banco de dados no mongoDB, faço a busca dos dados pelo NodeJS ele me retorna tudo certo, porém gostaria de jogar esse valor da busca para uma variável, para fazer uma comparação. Tipo busco a data no DB e gostaria de comparar essa data com a data atual do sistema.
const CRUD = {
retrieve:function(query,mod){
    //console.log("Query",query);
    Model.findOne(query,mod, function(err,data){
        if(err) return console.log('ERRO: ',err);
        return console.log('Dado',data);
    });
};

Depois chamo esse CRUD em outro arquivo. Há uma forma de pegar o resultado dessa busca e jogar em uma variável para comparar com outra ? tipo assim:
var query3  = {data:'2016-12-04'};
var fields  = {data:1,_id:0};
CRUD.retrieve(query3,fields);

O resultado do CRUD é esse : Dado {data:'2016-12-04'}

A: Devias criar um novo argumento para esse método, para teres uma callback que seja corrida quando o resultado estiver disponivel.
const CRUD = {
    retrieve: function(query, mod, done){
        Model.findOne(query, mod, done);
    }
};

e depois chamares com esse argumento:
var query3  = {data:'2016-12-04'};
var fields  = {data:1, _id:0};
CRUD.retrieve(query3, fields, function(err, data) {
    if (err) return console.log('ERRO: ', err);
    // a partir daqui podes usar a variável "data"
    // e comparar o seu valor com outras variáveis
    console.log('Dado', data == 'algo a comparar');
});


text:
Q: Proof that the group of non-generators in a multiplicative group with a prime order is a sub-group I'm trying to solve the following problem - Let $\mathbb{Z}^{*}_p$ be a multiplicative group such that $p=2^k+1$ and is prime. I need to prove that the set of elements that are non-generators in $\mathbb{Z}^{*}_p$ is a sub-group.
My attempt was to take two elements which are non-generators and prove that their product modulu $p$ is also a part of the group of non-generators (In other words, to prove closure and thus convey that it's a sub-group), but I didn't have much success with this.
I'll appreciate any help on this issue.

A: Note that $|\mathbb{Z}_p^*| = 2^k$, so that every element has order a power of $2$. Now, if $a$ and $b$ are non-generators, then $|a| = 2^r$ and $|b|=2^s$ for $r, s < k$. But then $|ab| \le \textrm{lcm}(2^r, 2^s) = 2^{\max(r, s)} < 2^k$, so that $ab$ is also a non-generator. (Also, it's clear that $|a| = |a^{-1}|$, so the set of non-generators is also closed under inverses.)
EDIT: Adding discussion of orders.
Letting $d = \textrm{lcm}(2^r, 2^s)$, then we can write $d = 2^rm$ and $d = 2^sn$ for some integers $m, n$, and then
$$(ab)^d = a^db^d = a^{2^rm}b^{2^sn} = \left(a^{2^r}\right)^m\left(a^{2^s}\right)^n = e,$$
so that $|ab| \le d = \textrm{lcm}(2^r, 2^s)$.


text:
Q: TableAdapter wizard not generating INSERT method - UPDATE and DELETE fine I have inherited a project with an Access backend, using TableAdapters which I've not used before.
Most of the tables in the schema work fine, but a single one is not generating the INSERT statement and insert method.
I have checked everything mentioned here: http://msdn.microsoft.com/en-us/library/ms233812(vs.80).aspx
The adapter is using a simple query on a single table, the checkboxes for generating statements and methods are ticked and the table has a primary key. UPDATE and DELETE work fine.
Is there anything else that could be affecting this?

A: Go into the xsd file and look at the properties of the TableAdaptor, you should have an entry for InsertCommand. If this is missing you can add it manually.
This assumes you are using an xsd file obviously.
Edit:
Have you tried adding a new TableAdaptor using the wizard attached to the same table to see if it generates without the insert command?

A: I had the same problem, but I noticed something the table had no primary key, solve it by adding the primary key, now it works fine, have you tried that?

A: I had the same issue, and discovered that the INSERT command was not created if I had omitted fields from the dataset that were NOT NULL in the database.  Once I included the NOT NULL fields in the dataset, the INSERT command was created.

A: I had the same problem.  I went to my first tableadapter query and changed it from "Select fid1, fid2, fid3 from filename"  to  "Select * from tablename" and checked that I wanted the inserts, updates, etc generated.  It generated all new commands.  Worked great.


text:
Q: querying subscribers in rethinkdb I am quite new to RethinkDB (2 days) which I am considering it for a particular use case and at this stage I am trying to understand if it will be a viable solution. I have skimmed the documentation yet I have not been able to find a quick answer to that.
Having live/continuous queries is great and that solves the first half of my particular use case. My question is if I can query the subscribers of live queries that are running on a particular database (or table/query). And even better, subscribe to that meta-query.
My use case is: Subscribers randomly subscribe to a live topic and they use a key to indicate the slice of the data they are interested in getting live updates for. From the publisher's perspective, the publisher does not want to work on anything that subscribers are not interested in.
The publisher needs to be efficiently (without polling) made aware of

*

*if new subscribers came along

*if existing subscribers drop off or disconnect

Therefore, I am dreaming of a "system" query, to which my publisher can subscribe which notifies if any new subscribers come along or existing subscribers disappear. And on top of that, for each subscription, I can even dig in and find about the key they used when subscribing.
Any hope?

A: I think the following pretty much does what I am trying to achieve:
r.db("rethinkdb").table("jobs").filter({type: 'query'})


text:
Q: Cannot solve by hand:$ x + y = 2; 4x^2 + y^2 = 5(2x - y)(xy)^{\frac12}$ Firstly, this is not my homework. I am well past high school (finished graduate school several years ago) but I am mentoring a high schooler and I want to explain how to solve this by hand using just pen and paper.
A more presentable form + solution is here
My own attempts could only simplify it to a fourth degree polynomial in $x$ and equate it to $0$. There's gotta be a better way but it is beyond me and I feel embarrassed!

A: since $xy>0,x+y=2>0, \implies x>0,y>0$
let $x=a^2,y=b^2,a>0,b>0 \implies 4a^4+b^4=5(2a^2-b^2)ab \iff \\ 4a^4-10a^3b+5ab^3+b^4=0$
by observation, $a=b$ is a solution as $4-10+5+1=0$
so we get $(a-b)(4a^3-6a^2b-6ab^2-b^3)=0$
now to check  $4a^3-6a^2b-6ab^2-b^3=0$,a factor $b=-2a$ is existed. $\implies$
$(2a+b)(2a^2-4ab-b^2)=0 \implies 2a^2-4ab-b^2=0 $
with $a^2+b^2=2 $ we get $3a^2-4ab=2 \implies b=\dfrac{3a^2-2}{4a} \implies x+\dfrac{(3x-2)^2}{16x}=2$
$25x^2-44x+4=0$

A: Substituting $y=2-x$ in the second equation gives $16x^4+(2-x)^4+8x^2(2-x)^2 = 25(3x-2)^2(x(2-x))$ The solution is here. Then use the "by-hand"method of solving bi-quadratic equations. It's clumsy and laborious, but is "by-hand". Put back the values of $x$ and eliminate some of the solutions.


text:
Q: Is it possible to construct a regular expression that matches numbers with thousands and decimals delimiters exchanged such as 1,000.00 and 1,000.00? I am trying to build a regular expression in Javascript that matches numbers with , and . as delimiters of thousands and decimals and vice versa. It must match 1,000,000.00 and 1.000.000,00. So far I have this:
/^(\d{1,3}(?:([,\.])\d{3}){1}(?:\2\d{3})*|\d+)(?:(?!\2)[,\.](\d*))?$/

but it does not match when the number does not have thousands delimitir and have decimals delimitir such as 100.00 or 100,00 for example. I think it's because the capturing group of the thousands delimiter is null.
Is it possible to build  such regular expression?


text:
Q: Large JSON while exporting causing Memory Issues Problem:
I have an API, which fetches data from elastic multiple indexes and combine it into one single JSON record and return when the API is called. Also the result fetched from the API is generally huge.
So iam having a wrapper script which gets all the data from API for a day. But here in my code iam having an array named results, when the data for the day is less Iam not getting an issue. But when the data fetched for the day is huge the entire array is sitting in the RAM and causing the system to slow down.
My primary intention of creating this array is to export in a mongo which in another network, which i can directly copy from my network.
Code Snippet:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import division, print_function, absolute_import
import argparse
import sys
import logging
import MySQLdb
import requests
import json
import time

_logger = logging.getLogger(__name__)

def get_samples(date,end):
    """
    Get Samples hashes form Database

    :param date: date of sample arrival
    :return list_of_hashes
    """
    try:
        results = []
        cur_time = time.time()
        with open('config.json','r') as c:
            config = json.load(c)
        _logger.info('Entering into database {}'.format(date))
        connection = MySQLdb.connect(config['malware_mysql'],"root","root","meta")
        cursor = connection.cursor()
        cursor.execute("SELECT MD5 from some where `Last_Seen` BETWEEN '{} 00:00:00' AND '{} 23:59:59'".format(date,end))
        hashes = cursor.fetchall()
        for hash in hashes:
            _logger.info('Hash {}'.format(hash[0]))
            try:
                response = requests.get('http://{}:{}/some/{}'.format(config['a'],config['b'],hash[0]))
                _logger.info('Result from API {}'.format(response))
                if response.status_code == 200:
                    results.append(json.loads(response.text))
                else:
                    _logger.error('Error in Querying API {} for hash {}'.format(response.status_code,hash))
            except Exception as e:
                _logger.error('Error in querying database {} - {}'.format(hash,e))
        connection.close()
        with open('{}_{}.json'.format(date,end),'w') as f:
            f.write(json.dumps(results))
    except KeyboardInterrupt:
        print('Bye')
    except Exception as e:
        _logger.error('Error in querying database final {}'.format(e))
    return '{} completed'.format(date)

def parse_args(args):
    """
    Parse command line parameters

    :param args: command line parameters as list of strings
    :return: command line parameters as :obj:`airgparse.Namespace`
    """
    parser = argparse.ArgumentParser(
        description="Enter date to Export")
    parser.add_argument(
        dest="date",
        help="Date of Sample Arrival in format 2018-08-16",
        )
    parser.add_argument(
        dest="end",
        help="Date of Sample Arrival end",
        )
    return parser.parse_args(args)

def main(args):
    args = parse_args(args)
    print("{} Samples are quiered -- {}".format(args.date, get_samples(args.date,args.end)))
    _logger.info("Script ends here")

def run():
    logging.basicConfig(level=logging.INFO, stream=sys.stdout)
    main(sys.argv[1:])

if __name__ == "__main__":
    run()

Why iam doing this?
I want to export entire day's records from the API and transfer this JSON file to mongo using mongoimport.
What i needed?
Alternative solution to prevent this entire array sit in the RAM and cause system slow down. Other solution which makes the solution more efficient.

A: From what I gathered, you cannot connect directly to your Mongo DB, is that right? Could you spin up a MongoDB locally? This way you could use a Mongo Python library for saving results as you get them, use mongoexport to extract them as a JSON file, and then import them in your final DB?
Now to go back to your question, here are a couple of suggestions:

*

*Close your connection to MySQL connection.close() as soon as you get the info you need, so right after hashes = cursor.fetchall()

*json.loads(response.text) is also known under a nicer API response.json()

*Instead of appending to a results list in memory, you could write directly to the file

Putting it all together, without Keyboard interrupt handling, only changing the get_samples function:
def get_samples(date, end):
    with open('{}_{}.json'.format(date, end), 'w') as out_file:
        out_file.write('[\n')
        with open('config.json','r') as c:
            config = json.load(c)
        _logger.info('Entering into database {}'.format(date))
        connection = MySQLdb.connect(config['malware_mysql'],"root","root","meta")
        cursor = connection.cursor()
        cursor.execute(
            "SELECT MD5 from some where `Last_Seen` BETWEEN '{} 00:00:00' AND '{} 23:59:59'".format(date, end)
        )
        hashes = cursor.fetchall()
        connection.close()
        for hash in hashes:
            _logger.info('Hash {}'.format(hash[0]))
            try:
                response = requests.get('http://{}:{}/some/{}'.format(config['a'],config['b'],hash[0]))
                _logger.info('Result from API {}'.format(response))
                if response.status_code == 200:
                    out_file.write(response.json() + ',\n')
                else:
                    _logger.error('Error in Querying API {} for hash {}'.format(response.status_code,hash))
            except Exception as e:
                _logger.error('Error in querying database {} - {}'.format(hash,e))
        out_file.write(']\n')

I haven't tried this code, so there might be a syntax error somewhere. Hopefully, that should get you close enough.
If the memory usage is still high, note that the Requests library has a streaming mode, which could potentially help further.


text:
Q: Disabling shotwell duplicate detection I'm new to Ubuntu. Afaik shotwell is the best option to view photos in recursive/multiple folders. I want to see them even if they are duplicated, but I don't know how to disable the duplicate detection feature in shotwell.
This question and this question are similar but they don't have a proper answer and they are both outdated.
Second question: is there any software that can list all images in given folders other than shotwell?

A: Regarding your second question, there are many other options, such as gthumb, feh (try feh -ZXrF ./), digikam.
I suppose that you don't need to be taught how to install software.
For your first question, if there is no mention of any such option, then maybe you'll have to modify the source code and recompile. I know that this is a task that is out of reach for most.


text:
Q: How to perform a WHERE NOT in Laravel with query build Laravel query build has many where options, but I could not found a way to describe fields type timestamp that are not null but have an invalid value. e.g: 0000-00-00 00:00:00
whereNull() are not working since it is not null
whereNot() is treated as a invalid field not
I want to use the native MySQL query NOT field since it match with "empty" values like 0000-00-00 00:00:00

A: Then, you will have to query it with IS NULL option. Check the ex :
SELECT * FROM `tablename` WHERE `columnname` IS NULL LIMIT 0 , 30

See if the following helps
$table->date('colname')->nullable();

$table->date('colname')->notnullable();


text:
Q: Issues With Cascading Dropdowns Using MVC4 and Jquery I've researched this problem extensively and cannot figure out what is wrong.  I am trying to implement cascading dropdowns using MVC4 and Jquery for a page that I have, and no matter what solution I use online, my ActionResult parameter is always null.
Here's the Javascript which gets called just fine:
<script type="text/javascript">
$('.clientnames').on('change', function (e) {

    // Retrieve the filter url from the data-filter-url attribute
    var filterUrl = $(this).attr('data-filter-url');

    // Grab the id of the selected item
    var selectedId = $(this).val();
    window.alert("filterurl:" + filterUrl + "    selectedID:" + selectedId);

    // Grab the container that should be updated
    var updateContainer = $(this).attr('data-update-container');

    // Grab the id of new dropdown
    var dataUpdateId = $(this).attr('data-update-id');

    var completeUrl = filterUrl + selectedId;

    $.get(completeUrl, function (r) {

        // Load Partial View using the URL from the data-filter-url attribute
        $(updateContainer).html(r);

        // This would be used if you wanted to trigger the new dropdown to filter another
        if (dataUpdateId != null) {
            // Trigger the change event after it is loaded
            $(dataUpdateId).trigger('change');
        }
    });
});

Controller function, this is getting called but the value not successfully passed in:
 public ActionResult ImportList(string selectedId)
     {
         //DO COOL STUFF
     }

And the view:

 @Html.DropDownListFor(model => model.Clients.DropdownItems,
         new SelectList(Model.Clients.DropdownItems, "ItemID","ItemName"),
                        new
                        {
                            @class = "clientnames",
                            data_filter_url = Url.Content("~/import/importlist/"),
                            data_update_container = ".dropdown-container",
                            data_update_id = "#SecondItemID"
                        }
)

I am pretty much following the advice on this page here: http://www.sidecreative.com/Blog/Entry/Cascading-dropdown-lists-with-MVC4-and-jQuery
Although I've tried a few different solutions, and everytime the value is still null.  I'm pretty new to MVC and Jquery, so any advice would be appreciated.

A: Try passing the selected value like this:
$('.clientnames').on('change', function (e) {

    // Retrieve the filter url from the data-filter-url attribute
    var filterUrl = $(this).attr('data-filter-url');

    // Grab the id of the selected item
    var selectedId = $(this).val();
    window.alert("filterurl:" + filterUrl + "    selectedID:" + selectedId);

    // Grab the container that should be updated
    var updateContainer = $(this).attr('data-update-container');

    // Grab the id of new dropdown
    var dataUpdateId = $(this).attr('data-update-id');

    $.get(filterUrl, { selectedId: selectedId }, function (r) {

        // Load Partial View using the URL from the data-filter-url attribute
        $(updateContainer).html(r);

        // This would be used if you wanted to trigger the new dropdown to filter another
        if (dataUpdateId != null) {
            // Trigger the change event after it is loaded
            $(dataUpdateId).trigger('change');
        }
    });
});

Your controller action takes a parameter called selectedId, and notice how this is passed in the $.get function:
$.get(filterUrl, { selectedId: selectedId }, function (r) {
    ...
});

You might also checkout the following post for other examples of implementing cascading droipdowns in ASP.NET MVC.


text:
Q: PhsyicalMemory condition always fails on bundle/bootstrapper installation for WiX 3.6 The condition for PhysicalMemory always fails when using the bal extensions. I can try PhysicalMemory >= 3500 and PhysicalMemory < 3500 and PhysicalMemory >= 0. No matter what, the condition fails.
I want to verify the computer has 4GB of RAM before starting the bundle installation and give them a custom message.
If I add the condition to the Bundle tag, it works but always says "the specified program requires a newer version of windows". I do not know how to customize this message.
(As a side note: VersionNT > 6.0 condition works properly)
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi"
     xmlns:netfx="http://schemas.microsoft.com/wix/NetFxExtension"
     xmlns:bal="http://schemas.microsoft.com/wix/BalExtension">
  <Bundle Version="1.0.0" UpgradeCode="XXXXXXXX-XXXX-XXXX-XXXX-AFD8530214A6" Name="My Bundle Name" DisableModify="yes">
    <BootstrapperApplicationRef Id="WixStandardBootstrapperApplication.RtfLicense">
      <bal:WixStandardBootstrapperApplication ThemeFile="RtfTheme.xml" LocalizationFile="RtfTheme.wxl" SuppressOptionsUI="yes" LicenseFile="license.rtf" LogoFile="logo.png"/>
    </BootstrapperApplicationRef>
    <bal:Condition Message="My Custom Message">
      PhysicalMemory >= 3500
    </bal:Condition>

Thanks for any help.

A: PhysicalMemory isn't a built-in Burn variable. Burn duplicates many, but not all, of the built-in MSI properties. Here's a complete list.


text:
Q: web servers - How to specify server being used I am writing a simple web server. This is the Python code I have:
import http.server

from os import curdir, sep

class RequestHandler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path.endswith(".php"):
            f = open(curdir + sep + self.path)

            self.send_response(200);
            self.send_header("Content-type", "text/php")
            self.end_headers()

            self.wfile.write(f.read())
            f.close()

        else:
            self.send_error(404, "Cannot open non-html file")

httpd = http.server.HTTPServer(("", 8000), RequestHandler)
httpd.serve_forever()

And this is the HTML code:
<!doctype html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Hello</title>

        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    </head>

    <body>
        <input type="button" value="Click me" id="button">

        <script>

            var buttonOnClick =
                function() {

                    var updateButton =
                        function(result) {
                            $("#button").replaceWith("<p>" + result + "<p>");
                          };

                    $.get("text.php", updateButton);
                };

            $("#button").click(buttonOnClick);

        </script>
    </body>
</html>

text.php
<?php
        echo "Hello!";
?>

When I run this with Apache on, I get the expected results. The button changes to "Hello!" when you click it. When I run it with Apache off, however, the page shows an ERR_CONNECTION_REFUSED error. This tells me that my webpage is using Apache as its server and not my Python code. I cannot figure out how to make my HTML and jQuery code use my custom web server instead of Apache. This might be a really simple question, but I am stumped.
And if there is anything that I can improve in my code, please let me know.

A: The port number goes after the hostname in the URL, not at the end.
And since your HTTP server doesn't have SSL enabled, you have to use http: as the protocol, not https:.
So the URL should be http://localhost:8000/webprograms/testwebserver/index.html


text:
Q: Is there a algorithm to extract the minimum number of Cartesian products from a set of formulas? For example, we have a set of formulas as below:
B*2*j
B*3*i
B*3*j
C*2*j
C*3*i
C*3*j
D*2*i
D*2*j
D*3*i
D*3*j

And we could have three Cartesian products to represent the formulas above:
D*(2+3)*(i+j)
(B+c)*3*(i+j)
(B+C)*2*j

So the total number is 3. And we could also have:
3*(B+C+D)*(i+j)
2*(B+C)*D
2*D*(i+j)

which is also 3.
I wanna ask that is there a algorithm to determine the minimum number of Cartesian products from a set of formulas? And also come up with these products?


text:
Q: Combo headphone/microphone splitter does not work on Ubuntu 18.04, individually plugging in headphone or microphone does So I can plug either my external lavalier microphone or my headphones directly into my Lenovo T450s laptop's single 3.5mm jack, and they both work using the Built-in Audio = Stereo Analog Duplex setting in pavucontrol:

When I unplug the microphone after having it directly in the jack, the input device port correctly changes to "Built-in microphone" under the Input Devices tab. And it correctly changes back when I plug it back in.
I purchased this microphone and headset combo jack which splits the single 3.5mm jack on my computer into a headset output and a microphone input, but I cannot get the microphone to work through it. The audio out of the splitter works just fine, and the microphone even shows up under pavucontrol when it's plugged into the mic input of the splitter, but it does not seem to register any sound when I use the exact same gnome-alsamixer settings as the ones that worked when the microphone was plugged in directly.
Based on research I've tried adding the following lines to /etc/modprobe.d/alsa-base.conf but neither makes a difference:
options snd-hda-intel model=,dell-headset-multi

and separately,
options snd-hda-intel model=laptop-dmic

Is there anything else I should be looking at? Thanks.


text:
Q: ASP.Net Post not working I have a Problem with my Edit method in my Controller. The answer parameter always stays null when submitting the edit form.
What can I do to get the SmallTalkAnswer in the edit method to write it back to the database?
The Controller contains the edit method as found in ms documentation:
  [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(SmallTalkAnswer answer)
    {
        var a = ModelState.IsValid;
        _smallTalkAnswerRepository.Update(answer);
        return RedirectToAction("Index");

    }

The View is generated by visual studio:
@model ChatBotAdminCenter.Models.SmallTalkAnswer

@{
    ViewBag.Title = "Edit";
}

Edit

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

SmallTalkAnswer

        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.PartitionKey, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.PartitionKey, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.PartitionKey, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.RowKey, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.RowKey, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.RowKey, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.Timestamp, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.Timestamp, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Timestamp, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.ETag, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.ETag, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.ETag, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.Answer, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.Answer, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Answer, "", new { @class = "text-danger" })

                <input type="submit" value="Save" class="btn btn-default" />

}

    @Html.ActionLink("Back to List", "Index")

Model:
public class SmallTalkAnswer : TableEntity
    {
        public SmallTalkAnswer() { }
        public SmallTalkAnswer(string hash, string categoryId)
        {
            this.PartitionKey = hash;
            this.RowKey = categoryId;
        }

        public string Hash => PartitionKey;
        public string CategoryId => RowKey;
        public string Answer { get; set; }
    }

A: Seems that you've a property named Answer on your model:
public string Answer { get; set; }

And the action method argument name has similar name of property name defined above:
public ActionResult Edit(SmallTalkAnswer answer)

AFAIK, this setup may cause confusion on default model binder side when referred the model in POST action method, hence it contains null value.
Try changing argument name of viewmodel in POST action method into another name by your choice (e.g. model or smallTalkAnswer, just avoid reusing property name as viewmodel argument):
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(SmallTalkAnswer model)
{
    // other stuff
    _smallTalkAnswerRepository.Update(model);
    // other stuff
}

Similar issue: viewmodel returns null on postback mvc 5


text:
Q: Actualizar una variable PHP tipo array mediante JQuery Tengo un plugin en wordpress que ejecuta unos contadores:

Mi pregunta es si es posible actualizar esa variable con JQuery mediante algún evento por ejemplo al dar click en el ícono del corazón.
No pretendo que me hagan el trabajo, solamente que me digan si es posible y más o menos un ejemplo de cómo hacerlo, no soy experto en PHP y menos en JQuery.
De antemano muchas gracias.
Archivo PHP:

if(isset($count_options['font-color']) && $count_options['font-color'] != ''){
    $dynamic_css[] = "color: {$count_options['font-color']};";
}

if(isset($count_options['animation']['enable'])){
    $data_animation = "data-enable='on'";
}else{
    $data_animation = "data-enable='off'";
}

if(isset($count_options['animation']['enable'])){
    if(isset( $count_options['animation']['delay'] ) && $count_options['animation']['delay'] !='' ){
        $data_delay = "data-delay='{$count_options['animation']['delay']}'";
    }else{
        $data_delay = '';
    }

    if(isset( $count_options['animation']['duration'] ) && $count_options['animation']['duration'] !='' ){
        $data_duration = "data-duration='{$count_options['animation']['duration']}'";
    }else{
        $data_duration = '';
    }
}else{
    $data_delay = '';
    $data_duration ='';
}
if ($counter == 2) {
    $count_options['content'] = $count_prayer * 3;
}
?>

<span class="ec-count-number" <?php echo $data_animation; echo $data_delay; echo $data_duration; ?> ><?php echo esc_attr($count_options['content']); ?><?php if($template == 'template12'){ ?>+<?php } ?>

<?php
if(isset($count_options['font-family']) && $count_options['font-family'] !=''){
    if(!in_array( $count_options['font-family'], $google_fonts_used_array) ){
        array_push($google_fonts_used_array, preg_replace('/\s/', '+', $count_options['font-family']) );
    }
    $dynamic_css[] = "font-family: {$count_options['font-family']};";
}

if(!empty($dynamic_css)){
    $dynamic_css = implode(' ', $dynamic_css);
}else{
    $dynamic_css ='';
}

ob_start();
?>
.ec-<?php echo $template; ?> .ec-counter-item-<?php echo $counter; ?> .ec-count-content .ec-count-number { <?php echo esc_attr($dynamic_css); ?> }

<?php
$ec_dynamic_css_at_end[] = ob_get_contents();
ob_end_clean();

}

A: Al hacer click en el boton, en vias la informacion que quiras con ajax:
Ejemplo:
$('#idDeMiBoton').click(function(){
    var data = {nombre: nombre, tel: tel, email: email, text: texto};//datos que capturas del html si lo necesitas
    $.ajax({
                type: "POST",
                url: "ruta hasta tu fichero php",
                data: data,
                success: function (response) {
                   //esta funcion se ejecuta cuando la consulta devuel status: 200 "Correcto"
                }
            })
            ;

});

luego en tu codigo php obtienes los datos de la peticion:
$request->get('nombre');
$request->get('tel');


text:
Q: Report viewer no añade un conjunto de datos Estoy intentando añadir un nuevo conjunto de datos (dataset) en el report viewer. Adjunto capturas de pantalla de los pasos que estoy siguiendo.
En esa imagen le doy a Nuevo, en la siguiente pantalla, presiono Objeto, selecciono los objetos que necesito así:

A continuación le doy a finalizar, pero estos objetos no se añaden a los conjuntos de datos disponibles.

También he probado a añadirlos de uno en uno, pero sigue sin pasar nada, ¿estoy haciendo algo mal?


text:
Q: How to submit html to Solr not over http I am using SOLR 4.6 for indexing and now i have large amount of stored html files.
I tried  to add these files to SOLR over http or curl but it's taking much time.
Anyone knows how to submit files for indexing directly to SOLR? I have these files on server where I have my SOLR running.

A: You can use the DIH to index all the files. There is also a HTMLStripTransformer if you want the content cleaned up,

A: Though answer provided by Okke Klein is good but its much complex.
I found the simplest solution for the problem i am submitting the file over http but with the option stream.file=local_file_path
Example :-
curl http://localhost:8080/solr/update/extract?stream.file="+file.getPath()+"&literal.id="+id+"&commit=true


text:
Q: How can i select a datetime as ddMMyy, so a two-digit year? I'm replacing my C# code for performance reasons with a sql query:
CreatedAt.ToString("ddMMyy", System.Globalization.CultureInfo.InvariantCulture)

returns the creation-date as 140115(for today). Simple enough in C#, but how do i get this in T-SQL?
I have tried:
REPLACE(CONVERT(CHAR(10), ChargeArrival.CreatedAt, 103), '/', '')

which is  almost correctly, but the year  has four digits instead of two, so 14012015 instead of 140115.

A: As the docs for CONVERT state, use 103 if you want the century and 3 if you dont:
REPLACE(CONVERT(CHAR(10), ChargeArrival.CreatedAt, 3), '/', '')

A: You can use this also
SELECT REPLACE(CONVERT(CHAR(10), ChargeArrival.CreatedAt, 5), '-', '')


text:
Q: Conway games and Induction Principle for games First of all, about the Notation:
Conwaygame: Let x,y be sets containing Conwaygames, then the ordered tuple G:=(x,y) is a Conway game. Call the elements of x (the elements of y) the left options of $G$ (the right options of $G$).
Game: By game I mean a specific type of game, namely one with: two players L and R, taking alternating turns $t\in T$, $T$ being the set of turns for the game, beginning with a first turn $t_0$; two relations $\rightarrow_R$ and $\rightarrow_L$, such that a turn can be written as $t\rightarrow_R t'$ for $t,t'\in T$ in the case of player R making a turn for example. The player who cannot make a turn loses the game. Finally, require every game to be of finite length, meaning that there are only finite many turns.
$\underline{Question~1}$:
I want to show:

Every Conwaygame is a game.

Let $G=(x,y)$ be a Conwaygame and set $t_0 = G$. Set T equal to the set containing $t_0$ and all the left and right options of $G$. Let $t\rightarrow_R t' ~iff~$ $t'$ right option of $G$, $t\rightarrow_L t' ~iff~$ $t'$ left option of $G$.
My question is about the requirement of finiteness: I've read that if there exists an infinite sequence of turns $t_0 \rightarrow t_1 \rightarrow \dots$, then the axiom of regularity would be contradicted. What is the connection between the existence of such an infinite sequence and the axiom, which says that every nonempty set contains an element which is disjoint to the set itself? (Is it possible to construct the infinite sequence in a way, such that it would be equal to the set $T$?)

A: This is a good question that is mainly about set theory.
Instead of $G=(x,y)$, I will write things like $G=(G^L,G^R)$. Suppose, for sake of contradiction, that we had a Conwaygame with an infinite sequence of play like $G_0\to_LG_1\to_RG_2\to_L\cdots$. You didn't define how the ordered pair is formed as a set, but whether we use Kuratowski's definition or not, grant me that it's some set with the two components as (possibly layers-deep) elements, possibly several layers deep. This leads to a descending sequence of sets (each one an element of the previous) like $G_0,?,G_0^L,G_1,?,G_1^R,G_2,?,G_2^L,\ldots$. But the axiom of regularity/foundation proves no infinite descending sequence of sets exists.
However, instead of relying on regularity/foundation, the graduate textbook "Combinatorial Game Theory" by Aaron N. Siegel just defines the class of long games inductively using ordinals, so that it doesn't matter if regularity/foundation holds.
Unlike what you have called Conwaygames, "loopy games" are games where play can go on forever. They are defined differently, usually in terms of a version of graphs with two kinds of directed edges for $\to_L$ and $\to_R$. These sorts of games are discussed in Coping with cycles by Aaron N. Siegel.


text:
Q: How do I override a Mojolicious::Controller->new method Let's assume I have a Mojo controller with a virtual-esque method init in it.
package App::Controller
use Mojo::Base 'Mojolicious::Controller';

sub init {
  my $self = shift;
  # Do things with $self->param('myparam');
}
...

And I would like to extend it and make changes to the init method.
In this example, I make a subclass App::Controller::Person and I want to pull a value out of params and do something different with it.
package App::Controller::Person;
use parent 'App::Controller';

sub init {
  my $self = shift;
  # Do different things with $self->param('myparam');
}
...

I want to be able to inject or call the init method when the Controller is instantiated, but can't seem to figure out how to go about doing that.
Initially, I wanted to just override the new method in App::Controller by doing something like this:
package App::Controller
use Mojo::Base 'Mojolicious::Controller';

sub new {
  my ($class, @args) = @_;
  my $self = $class->SUPER::new(@args);
  $self->init();
  return $self;
}

I but didn't have any luck with that.  I'm guessing that I am not passing things correctly to SUPER, but can't seem to figure out what I would need to do in order to get this to work.
How do I go about implementing something like this?


text:
Q: Output file for each key in Reducer in new MapReduce API I am working on a single machine Cloudera Sandbox instance and I am trying to produce a output file for each Reducer output. I know that it was possible to do that in old API using MultipleTextOutputFormat class, however it does not work anymore. I also do not want to have drop Reduce phase.
I attach an image displaying my issue

A: Use this one MultipleOutputs.


text:
Q: Grouping created_at by date only? I have the following in my Product model.
def grouped_created_at
  @created_ats = @products.group_by { |c| c.created_at }
end

Works fine, but I want to group by the date only. As this is a timestamp, i'm not getting the results I need. Can anyone advise how to modify this?
Many thanks!

A: Read this if you want to group records by your CLIENT'S timezone!
I've spent about a day on this, so I hope this post helps someone. I was trying to count my users activities for each of the last 10 days. Easy enough right? This is what I tried that didn't work:
Not working
Activity.select("user_id", "id", "created_at")
  .where(user_id: @user.id)
  .where("created_at >= ?", DateTime.now.beginning_of_day - 10.days)
  .group("user_id", "DATE(created_at)") # <- POSTGRES' DATE FUNCTION
  .count("id")

The problem above is that this query would group the activities by UTC time. For example, In Toronto (UTC - 4 hours) if I create an activity after 8PM at night on April 1st, Postgres would think it was created the next day (April 2nd) instead of "today" (April 1st). This was no good, since I wanted to group these activities by the user's timezone.
Using the handy browser_timezone_rails gem (that uses javascript to attach user's timezones to requests), and switching my .group line to this was what ultimately worked:
Working
.group("user_id", "DATE(created_at AT TIME ZONE 'UTC' AT TIME ZONE '#{Time.zone.name}')")

You'll see there were actually two AT TIME ZONEs required. The first confirms that our timestamp is in UTC, and the second converts the timestamp to the Time.zone set by the gem (for example: 'America/New_York').
Hopefully this helps someone. This answer on the postgres group was super help for me, as well.

A: def grouped_created_at
  @created_ats = @products.group_by { |c| c.created_at.to_date }
end

A:
FOR MY FELLAS WHO LAND ON THIS PAGE - ALTERNATE SOLUTION

BASED ON WHAT DATABASE YOU USE
For MySql
Model.group("date(table_name.created_at)")
For SQLite
Model.group("strftime('%Y-%m-%d', table_name.created_at)")
PostgreSQL:
Model.group("table_name.created_at::date")
WILL RESULT YOU
ActiveSupport::OrderedHash like
{Sun, 13 Sep 2015=>2,
 Fri, 11 Sep 2015=>1,
 Tue, 01 Sep 2015=>1,
 Mon, 31 Aug 2015=>2,
 Wed, 26 Aug 2015=>1,
 Tue, 11 Aug 2015=>2,
 Sun, 09 Aug 2015=>2,
 Thu, 30 Jul 2015=>3,
 Tue, 07 Jul 2015=>3,
 Mon, 06 Jul 2015=>1,
 Sun, 05 Jul 2015=>2,
 Thu, 02 Jul 2015=>5}


text:
Q: WebAPI as a front end for Orleans Service does not receive requests I am trying to make a WebAPI front end for Orleans service, but my WebAPI does not receive any requests
I following the tutorial as described at https://dotnet.github.io/orleans/Tutorials/Front-Ends-for-Orleans-Services.html.
Also tried to run Orleans GPSTracker sample, but I have the same issue.
I'm using Orleans version 1.3.0 on VisualStudio 2015 4.5.2, and got the same results using Orleans 1.3.1.
If I use console application as an orleans client it works Ok.
recently I tried VisualStudio2017RC 4.6.2 and my WebApi client works.
What am I missing?


text:
Q: Convert digit to words in SQL Server For one of my SSRS report, I need to show the numbers in letters:
e.g.
1 - ONE
23 - TWENTY THREE
6001233 - SIX MILLION ONE THOUSAND TWO HUNDRED THIRTY THREE

Is there any existing function in SQL Server which does that?
I have gone through the other answers and it talks about same old method of writing a big code foe that.
Thanks in advance.


text:
Q: Bulk copy files from CD, and rename disallowed filenames along the way I have an old CD with Amiga files on that I want to copy to my modern Windows 7 PC.
Most files are read fine, but when Windows finds a file with a problematic filename, it only allows you to skip that file. It won't automatically copy the file and remove the forbidden characters (such as '?' or '|') in it at the same time.
I want those supposedly "forbidden" files. How do I get Windows to automatically rename them as it copies and continue with the rest?
I've tried the following file manager programs, all without success. I even tried to dip into the options for each program to hopefully use its own custom copy method:

*

*FreeCommander XE (has its own copy routine, but still fails)

*XYplorer (has its own copy routine, but still fails)

*Double Commander

*Directory Opus 11 64-bit. (Pro edition)

*xplorer²

*Q-Dir

*Unreal Commander

*NexusFile

*Total Commander

*My Commander

*Nomad.NET

*Just Manager

A: The solutions you mentioned are all generic file managers. I suggest to take a look at tools that are specifically made to image and copy optical media.
I'm not a fan of promoting commercial software here, but I used IsoBuster multiple times for very similar issues quite successfully. The good news: they have a (limited functionality) free version so you can try it out before you buy it.

A: Try the cp utility I supply with my Hamilton C shell.  (Full disclosure:  I'm the author.)  Internally, I used Microsoft's new long UNC format (using the \\?\ prefix) intended to allow access to files and directories with names containing arbitrary characters.  I doubt many other vendors are using this yet.  You can try this with the free demo version.
cp doesn't include an auto-renaming feature, so this part you'll have to do in one of a couple ways.

*

*You may be able to cp the entire directory onto your hard disk with the odd names, then mv things around to your liking.  Create a directory first, then cp everything into the directory.  If the experiment fails and you're stuck with some names you can't specify on the command line, you can rm -x the whole directory and start over.

*You could write a script that copies all the odd-named pieces individually, specifying how each piece is to be renamed on the the command line to cp.  This script could be little more than a long list of cp commands you've edited, perhaps starting with a list of filenames generated by ls -r1.

Please let me know how it works out.  You're welcome to contact me offline if I can be helpful.

A: You should be able to do this from the command line in Windows fairly easily. Specifically renaming WHILE copying I am not sure. But, I have been able to move 'forbidden' files by changing or removing the file extention.Then copying them and adding the file extension back.
Open Command prompt.
Navigate to the folder where your files are.

cd C:\File\Directory\With\Your\Files
ren *.txt *.doc

Better yet.Here is a link to something previously written:
http://www.windows-commandline.com/rename-file-extensions-bulk/
Maybe this will help.

A: Check out the answer to:
How can I mass rename files?
Bulk Rename Utility is the top answer, which has copy options, and regex match/replace options.
Checking the manual, they also have a 'Remove Symbols' option:

Note that the "Remove Symbols" option removes the following symbols (some of which are not valid
in filenames anyway):
! £ $ % ^ & * ( ) - _ = + [ ] { } ; : ' @ # ~ , .  / ? \ | ` ¬ ¦


text:
Q: Show date like 30-04-2020 instead of 2020-04-30 from mysql database using javascript I'am building a small webapplication for personal business purpose. I have come far from looking around and looking how to program a webapplication. So I can added reservations and edit them and also delete them.  The last days I have been looking how to save a date into Mysql database and how to show it in the webapplication. For so far its working but its not showing in the right format. If you see the attachment Date sample I want the date like this "30-04-2020" and not like "2020-04-30". For some reason I just cant configure it. Can someone help me with that. I will put some code. The code below
database connection;
const db = mysql.createConnection ({
host: 'localhost',
user: 'root',
password: '',
database: '',
dateStrings: true,

});
My insert query
let query = "INSERT INTO `players` (achternaam, telefoonnummer, adres, email, typetaart, aantalpersonen, smaak, vulling, opmerking, prijs, reedsVoldaan, nogTeVoldoen, date, image, user_name) VALUES ('" +
                                achternaam + "', '" + telefoonnummer + "', '" + adres + "', '" + email + "', '" + typetaart + "', '" + aantalpersonen + "', '" + smaak + "','" + vulling + "', '" + opmerking + "', '" + prijs + "', '" + reedsVoldaan + "', '" + nogTeVoldoen + "',STR_TO_DATE ('" + date + "', '%d-%m-%Y'), '" + image_name + "', '" + username + "')";

homepage
    exports.homepageMTaartenAdmin = function(req, res, next){

   var user =  req.session.user,
   userId = req.session.userId;
   console.log('ddd='+userId);
   if(userId == null){
      res.redirect("login");
      return;
   }

   var sql="SELECT * FROM `players` ORDER BY id ASC"; // query database to get all the players

   db.query(sql, function(err, result){
      res.render('homepageMTaartenAdmin', {players:result});

   });
}

Date sample

If you need any further information please tell me. I appreciate your help.
Kind regards,
William Ashoti

A: In MySQL, you can use date function date_format() to display your date in the desired string format:
SELECT
    achternaam,
    telefoonnummer,
    adres,
    email,
    typetaart,
    aantalpersonen,
    smaak,
    vulling,
    opmerking,
    prijs,
    reedsVoldaan,
    nogTeVoldoen,
    DATE_FORMAT(date, '%d-%m-%Y') date,  --> here
    image,
    user_name
FROM `players`
ORDER BY id ASC

If you want to avoid enumerating all the columns, you can add a new column in the result set with a different identifier, like:
SELECT p.*, DATE_FORMAT(date, '%d-%m-%Y') formatted_date
FROM `players` p
ORDER BY id ASC


text:
Q: I need the year needs to be passed as a variable in the link so it can be grabbed via a get statement My html page.
I have this line.
2011

My php page.
I have this line of code.
<?php
$inputyr = $_GET[inputyr];
$query = "SELECT * FROM players
WHERE playeryear = $inputyr;
ORDER BY number";
$players = mysql_query($query);
?>

I want my php page to do a query using the year 2011.
After I click on the link it opens the page.  It does show...
but the players don't fill in the table.  The query does work if I manually type in the 2011.

A: You had a extra semicolon in your query after $inputyr. Try the following.
$query = "SELECT * FROM players
    WHERE playeryear = $inputyr
    ORDER BY number";

You should also be escaping anything you put into sql strings. In theory someone could do very bad things to your database right now with a properly crafted $inputyr value
//protect against sql injection
$inputyr = mysql_real_escape_string($inputyr)

$query = "SELECT * FROM players
    WHERE playeryear = $inputyr
    ORDER BY number";

A: You need single quotes around $inputyr.
<?php
$inputyr = $_GET[inputyr];
$query = "SELECT * FROM players
WHERE playeryear = '$inputyr'
ORDER BY number";
$players = mysql_query($query);
?>


text:
Q: Explicit Description of the map from Adam's $E_2$ term to Continuous Group Cohomology I am currently working through the paper ''The Homotopy of $L_2V(1)$ for the Prime $3$" by Goerss, Henn, Mahowald which can be found in the book Categorical Decomposition Technique in Algebraic Topology.
On page 136 they make reference to the map
$$\lambda_X \colon \text{Ext}^{s,t}_{BP_*BP}(BP_*, BP_*X) \to H_{\text{cont.}}^s(\mathbb G_2;E_t(X))$$
where $X$ is a finite spectrum and $\mathbb G_2$ is $\mathbb S_2 \rtimes C_2$ with $\mathbb S_2$ the second Morava stablizer group at the prime $3$ and $C_2$ the cyclic group of order 2 acting on $\mathbb S_2$ via a (the?) lift of the Galois action. Furthermore, $E$ is the spectrum coming from lifts of the Honda formal group law (see page 127-128 for more details).
I am thinking we could write out an explicit description of this map in terms of the cobar complex and the usual resolution which computes continuous group cohomology. Indeed I think this should be straightforward to write down but I'm finding the literature rather impenetrable and the papers by Devinatz, Hopkins etc. to be rather abstract.


text:
Q: EXC_BAD_INSTRUCTION when instantiating a Realm Object I have a Realm object called Dog:
import RealmSwift

class Dog: Object {
    @objc dynamic var name = ""
    @objc dynamic var age = 0
}

However, when I try to instantiate it
let myDog = Dog()

I'm getting this error:

Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

I also get this in the All Output window but I'm not sure if it's causing the crash:

SampleApp[25047:274257] *** NSForwarding: warning: object 0x10ba06d20 of class 'SDK.Dog' does not implement methodSignatureForSelector: -- did you forget to declare the superclass of 'SDK.Dog'?
2018-12-06 14:02:06.243187-0600 SampleApp[25047:274257] *** NSForwarding: warning: object 0x10ba06d20 of class 'SDK.Dog' does not implement doesNotRecognizeSelector: -- abort

Here's the SDK's linked frameworks and libraries, I needed to make them optional to get the SampleApp to build.

A: You are using RealmSwift, you need to be using Realm for Objective-C as well if you want to declare @objc dynamic var. The Object you're declaring needs to inherit from NSObject in order for that to work and the error you're seeing indicates that your object fails to implement certain required methods that are implemented by that super class.
Try adding both RealmSwift.framework and Realm.framework to your project.


text:
Q: Not working the modal window of gallery (JS files) I have a trouble with fancyBox LightBox Alternative. I do everything like in the manual, but gallery just not working.
1. Connecting all files.

<link rel="stylesheet" href="fancybox/source/jquery.fancybox.css" type="text/css" media="screen" />

<link rel="stylesheet" href="fancybox/source/helpers/jquery.fancybox-buttons.css" type="text/css" media="screen" />

<link rel="stylesheet" href="fancybox/source/helpers/jquery.fancybox-thumbs.css" type="text/css" media="screen" />

2. Nothing works. =(
I found a bug in the console.

Uncaught TypeError: $(...).fancybox is not a function

in line:

$(".fancybox").fancybox({

How to fix it?


text:
Q: Rdlc export to pdf break table I am using RDLC report which consists of table and looks like this:

After exporting to Pdf table jumps to second page and makes first page almost empty.

It occurs when table fits right in second page. In situation when there is more data, table starts directly after header.
Is it possible to force table to stay in first page no matter on it size ?
This topic also didnt help
Page break on a RDLC Report Table

A: Here is solutions:
Had to select on Report menu "Grouping"
Choose Advanced mode.
Then on Row Groups panel select on table and in property window set "KeepTogether" to false.


text:
Q: how to rewrite a single URL to add .html in wordpress I ported an old static HTML site to wordpress. All posts and pages now have permalinks /%postname%/
I need a single post URL to include the .html extension (it needs to match the original canonical URL which included the .html)
EXAMPLE:
www.domain.com/thispageonly/
-TO-
www.domain.com/thispageonly.html
This is needed for a single post only nothing more.
Thank you!

A: It's best to use 301 redirect for this (SEO reasons):
RewriteEngine on
Redirect 301 /thispageonly /thispageonly.html


text:
Q: Joining attributes from points to polygon I am working with two shapefile, polygons and points. These shapefiles do not overlap and have different attribute values.
The point layer contains data that I want to join to the beginning and end of the polygon layer. Is it possible? (Example below)


text:
Q: how to create buttons for webservice apis? Lets say we have some webservice API which we want to expose in form of a button (something like facebook's like/ twitter's tweet buttons). I am not sure what goes behind these buttons.
I would like the button to first authenticate with my service
If authenticated the user should click the button which should be able to call a webservice.
Would love to get insights in this. Thanks.

A: Actualy from client side of view, webservice can provide you only with data.
Usuall scenario can work as following:

*

*there is a button on page

*user clicks the button

*ajax call to webservice is made

*webservice returns some data (f.e. current time)´

*javascript have to display this data to user now

Hope this helps


text:
Q: Changing the Window Focus c# user32.dll (SetForegroundWindow) oh i have been trying to make a program which looks to see if a program in this case chrome is running then switching to it, i have been trying to follow a similar thread (thread one, thread two) unfortunately I'm having issues with the handle as it seems to like switching to windows explorer (file manager)
[DllImport("User32.dll")]
static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("User32.dll")]
static extern int SetForegroundWindow(IntPtr hWnd);

IntPtr ptrFF = FindWindow(null, "chrome");
SetForegroundWindow(ptrFF);

Process proc = Process.GetProcessesByName("firefox")[0];
IntPtr ptrFF = proc.Handle;
SetForegroundWindow(ptrFF);

these are the two bits of code i have been playing with, however i only got the second one to actuly do somthing, using a basic console aplication i tested weather it was actuly finding the right prosess when i uses "chrome" as the name and this appeared to be the case
test code:
   var proc = Process.GetProcessesByName("chrome")[0];
   Console.WriteLine(proc.ToString());

The Output of the Writeline is "System.Diagnostics.Prosess (chrome)"
if i printed Process.GetProcessesByName("chrome")[0].Handle;
it comes out as 572
but using:
var proc = Process.GetProcessesByName("chrome")[0].Handle;
Console.WriteLine(proc.ToString());
SetForegroundWindow(proc);

doesn't set the current window to chrome nor give me any errors


text:
Q: How to query between two MSSQL databases with the same schema and combine results in Entity framework I have a database that currently holds all the transactions data. It is growing exponentially in size because of the growth of the business. [More business, More Transactions, More space needed for the database]. Because of the large sums of data, my database queries have been slowed down. So I have planned to have another database to store the legacy [Historical] data.
However, when I am picking specific transaction details or number of transactions, I want it in such a way that if the transaction(s) is not found in the transactions database, I want Entity framework to automatically look it up in the Legacy information.  The transactions database has information for a specified period of time. So if the time [in the select query] is past the specified period, I want Entity framework to query the legacy information database and not the transactions database.
If the query has results from both databases, I want Entity framework to be able to combine the results and give me one result set. I would not want to start sending individual queries to the various databases and start combining the results manually! Is there a way Entity framework can do this for me automatically?
Both the transactions and legacy information databases have the same schema.
How do I achieve the above objective? Thank you

A: you can make result in Store procedure or view and added this objects to Entity Framework.
Entity Framework is an Object Relational Mapper(ORM) which is a type of tool that simplifies mapping between objects in your software to the tables and columns of a relational database
You must support this capability in your query result that can run as job in specific times .


text:
Q: Print using a button from window.open I have the following button which opens a new window
Run Report

In my js file, I have this function which creates the window:-
function PrintElem(elem, h1)
{
      Popup($(elem).html(), h1);
}

function Popup(data, h1)
{
    var mywindow = window.open('', 'my div', 'height=768,width=1024');
    mywindow.document.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">');
    mywindow.document.write('');
    mywindow.document.write('<title></title>');
    mywindow.document.write('<link rel="stylesheet" href="'+base_url+'/css/print1.css'+'" type="text/css" />');
    mywindow.document.write('<link rel="stylesheet" href="'+base_url+'/assets/global/plugins/font-awesome/css/font-awesome.min.css'+'" type="text/css" />');
    mywindow.document.write('');
    mywindow.document.write('');
    mywindow.document.write('
'+h1+'
');
    mywindow.document.write($('#window_print').html());
    mywindow.document.write('
');
    mywindow.document.write(data);
    mywindow.document.write('
');
    mywindow.document.write('');
    mywindow.document.close();
    mywindow.focus();
    return true;
}

function print(){
    window.print();
}

I have the following button in the new window which I created there I have a button I want to print the table which is in the window. please see the HTML below:-

   Print

I want to print the table which is in the new window. Can anyone help me to achieve this?? Any help will be appreciated.

A: Add window.print() in your print function, It will push it to print forcefully.

A: You need to add: mywindow.print(). Because window refers to the current window, you need to print the new window. So, make mywindow variable global and call print method.
var mywindow;
function Popup(data, h1)
{
    mywindow = window.open('', 'my div', 'height=768,width=1024');
   //rest of your code
}
function print(){
    mywindow.print();
}

Demo

A: try to use "innerHTML" rather than "document.write" with `` back-ticks like this example :
<!DOCTYPE html>

<button onclick="myFunction()">click here to open the new window</button>


text:
Q: C# Typewriter - How to reuse chunks of the template I've been trying to figure out is there is a way to reuse parts of the template so that I do not have repeat the same stuff all over the place. Here is the template:
$Classes(MyProject.Model.*)[
$NestedEnums[
export enum $Parent_$Name { $Values[$Name = $Value][,] }]

export class $Name {
    $Properties[
    public $Name: $Type = $Type[$Default];]
}

$NestedClasses[
$NestedEnums[
export enum $Parent_$Name { $Values[$Name = $Value][,] }]

export class $Name {
    $Properties[
    public $Name: $Type = $Type[$Default];]
}
]
]

EDIT: So, I was able to figure out how to include different Namespaces, you can just use a lambda expression to accomplish it like so:
$Classes(c => c.Namespace == "MyProject.Model" || c.Namespace == "MyProject.Comms")

So, all I need to figure out now is if it possible to reuse parts of the template. This section in the $Classes part:
$NestedEnums[
export enum $Parent_$Name { $Values[$Name = $Value][,] }]

export class $Name {
    $Properties[
    public $Name: $Type = $Type[$Default];]
}

Is exactly the same as the one inside the $NestedClasses part, and it would be great if I can just reuse it somehow! Any help would be greatly appreciated.

A: If there is functionality that you want to reuse in multiple places in your template, I would place it in its own C# function (outside the $Classes part of the template, but within the ${} outermost brackets in the .tst file) and then call that function wherever you need it in your template. This function would take in an Enumeration and return a string.
Take a look at how the rendering of Knockout Observables is handled by the "KnockoutInitializer" function in this example from the Typewriter website: http://frhagn.github.io/Typewriter/pages/examples.html. There is also some documentation under the "Custom methods" heading here: http://frhagn.github.io/Typewriter/pages/getting-started.html
Hope this helps!


text:
Q: Selecting multiple table columns and alias conditions in laravel I would like to achieve this query in laravel..
select sum(reading * multiplier) as consumption, reading_date, count(id) as num, (sum(reading * multiplier) / count(id)) as average
from electricities where meter_name != '' ;

so far i have this
electricities = Electricity::select(DB::raw('sum(reading * multiplier) as consumption', 'reading_date', 'count(id) as num', '(sum(reading * multiplier) / count(id)) as average'))
                                        ->where('factory_code', '=', $request->$factory_code)
                                        ->whereYear('reading_date', $request->$year)
                                        ->groupBy(DB::raw('month(reading_date)'))
                                        ->orderBy('reading_date', 'asc')
                                        ->get();

but it would not return the desired output..
can anyone help me with this? thanks

A: Based on your Query:
electricities = Electricity::select(DB::raw('sum(reading * multiplier) as consumption', 'reading_date', 'count(id) as num', '(sum(reading * multiplier) / count(id)) as average'))
                                        ->where('meter_name', '!=', '')
                                        ->get();

A: Electricity::where('id', '=', $user->id)->get(['product_name as name','product_price as price']);


text:
Q: grpc: failed to create grpc gateway due to unknown fields I want to start a simple grpc gateway:
import (
    "context"
    "github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
    "google.golang.org/grpc"
    "log"
    "net/http"
    authpb "seekCar/auth/api/gen/v1" // the auth code generated by protobuf
)

func main() {
    c := context.Background()
    c, cancel := context.WithCancel(c)
    defer cancel()

    mux := runtime.NewServeMux(runtime.WithMarshalerOption(runtime.MIMEWildcard, &runtime.JSONPb{
        EnumsAsInts: true, // Unknown field 'EnumsAsInts' in struct literal
        OrigName:    true, // Unknown field 'OrigName' in struct literal
    }))

    err := authpb.RegisterAuthServiceHandlerFromEndpoint(
        c,
        mux,
        "localhost:8081",
        []grpc.DialOption{grpc.WithInsecure()},
    )

    if err != nil {
        log.Fatalf("cannot register auth service: %v", err)
    }

    log.Fatal(http.ListenAndServe(":8080", mux))
}

But EnumsAsInts and OrigName are marked red by the compiler and an error is reported:
Unknown field 'EnumsAsInts' in struct literal
Unknown field 'OrigName' in struct literal

The go.mod is:
module learnGo

go 1.18

require (
    github.com/grpc-ecosystem/grpc-gateway/v2 v2.11.3
    go.uber.org/zap v1.16.0
    google.golang.org/grpc v1.49.0
    google.golang.org/protobuf v1.28.1
)

require (
    github.com/golang/protobuf v1.5.2 // indirect
    github.com/pkg/errors v0.9.1 // indirect
    go.uber.org/atomic v1.6.0 // indirect
    go.uber.org/multierr v1.5.0 // indirect
    golang.org/x/net v0.0.0-20220909164309-bea034e7d591 // indirect
    golang.org/x/sys v0.0.0-20220728004956-3c1f35247d10 // indirect
    golang.org/x/text v0.3.7 // indirect
    google.golang.org/genproto v0.0.0-20220930163606-c98284e70a91 // indirect
    gopkg.in/yaml.v2 v2.4.0 // indirect
)

But jsonp/encode.go do have these two fields.

What's wrong with my code?


text:
Q: Cómo mostrar con Value Objects los campos de dos tablas Por ejemplo tengo dos tablas: Trabajador y Planilla
Y cada tabla tiene su respectivo Value Object con setters y getters.
class TrabajadorVO {
    private $_id;
    private $_nom;
    private $_ape;
    private $_fecnac;
(...)

class PlanillaVO {
private $_id;
private $_area;
private $_sueldo;
private $_fecing;
(...)

Y en una consulta quiero mostrar los registros de ambas tablas relacionados por el id que es común.
$sql = "SELECT  a.id, a.nom, a.ape, a.fecnac, b.area, b.sueldo, b.fecing
        FROM    trabajador a,
                planilla b
        WHERE   a.id = b.id";

Pero cómo los asigno a un Value Object?
Tengo que crear otro VO consolidado para cada consulta que necesite?
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $registroVO = new TrabajadorVO();  // Aquí instancio el VO de Trabajador pero no de Planilla
    $registroVO->set_id( $row['id'] );
    $registroVO->set_nom( $row['nom'] );
    $registroVO->set_ape( $row['ape'] );
    $registroVO->set_fecnac( $row['fecnac'] );

    $registros[] = $registroVO;
}

A: No sé a qué te refieres con esto: ¿Tengo que crear otro VO consolidado para cada consulta que necesite?
Si quieres llenar tu clase PlanillaVO con sus respectivos datos, tienes que crear una instancia de esa clase y llenarla con los setter, como haces con TrabajadorVO y luego meter esa instancia en registros.
Por ejemplo:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    /*Simplificamos el nombrado para este contexto*/
    $t = new TrabajadorVO();
    $t->set_id( $row['id'] );
    $t->set_nom( $row['nom'] );
    $t->set_ape( $row['ape'] );
    $t->set_fecnac( $row['fecnac'] );

    $p=new PlanillaVO();
    $p->set_id( $row['id'] );
    /*Doy por supuesto que los setter se llaman así ...*/
    $p->set_area( $row['area'] );
    $p->set_sueldo( $row['sueldo'] );
    $p->set_fecing( $row['fecing'] );
    $registros[] = array('trabajador'=>$t, 'planilla'=>$p);
}

#Test
var_dump($registros);

Post-Data
PDO te permite mapear los resultados de una consulta a una clase1, lo cual es bastante útil para clases simples. Pero ese mapeo no escala entre clases, para casos como la herencia por ejemplo. Usando un ORM podrías fácilmente mapear resultados como estos, llenando cada instancia respectiva, pero refinando el modelo de datos.

*

*Ver la pregunta: ¿Como se mapea el resultado de una consulta SQL a una clase en PHP usando PDO y cómo se usa?


text:
Q: How to override the side-menu in bootstrap - Yii I've configure blackboot (i.e. bootstrap) on yii and I've been using it for the past couple of weeks to develop my website. However, at this point I'm running into a slight problem. Generally, the pages that are generated have a top menu, a side menu (on the left side that says something like "Create XXXX" "Manage XXXXX"_ and the content displayed in the center. I'd like to be able to delete the current menu and instead use that space to display my own form/field. The current code in the index view is
<?php
/* @var $this RecipientController */
/* @var $dataProvider CActiveDataProvider */

$this->breadcrumbs=array(
    'Recipients',
);
$this->menu=array(
    array('label'=>'List Recipient', 'url'=>array('index')),
    array('label'=>'Create Recipient', 'url'=>Yii::app()->createUrl('recipient/create', array('id'=>$id))),

);
?>

 Recipients

        <a class="btn btn-primary" href=
            "<?php echo Yii::app()->createUrl('recipient/processpayment', array('id'=>$id)); ?>"> Pay All
        <a class="btn btn-inverse" href="<?php echo Yii::app()->createUrl('recipient/create', array('id'=>$id)); ?>" >Add User

<?php $this->widget('zii.widgets.grid.CGridView', array(
    'id'=>'recipient-grid',
    'dataProvider'=>$dataProvider,
    'filter'=>$model,
    'columns'=>array(
        'name',
        'position',
        'msisdn',
        'balance',
        /*
        * this is to implement the checklist
        array(
            'id'=>'autoId',
            'class'=>'CCheckBoxColumn',
            'selectableRows' => '50',
        ),
        */
    ),
)); ?>

<?
/*
php $this->widget('zii.widgets.CListView', array(
    'dataProvider'=>$dataProvider,
    'itemView'=>'_view',
));
*/
 ?>

In which $this->menu() defines the area that I would like to be using. In its place I would like to put this html.

    <form action="<?php echo Yii::app()->createUrl('recipient/processpayment', array('id'=>$id)) ?>" method="post" >

  List Summary

              <?php echo $numpeople; ?> Recipients

              Total Due:  <?php echo $totaldue ?> rwf

            <?php
                $accounts= CHtml::listData(Account::model()->findAll(array("condition"=>"user_id = $user_id")),'id', 'name');
                echo CHtml::dropDownList("listF",'id', $accounts);
            ?>

            <button class="btn btn-block btn-primary " type="submit">Pay Now</button>

    </form>

But, whenever I try to place this small box inside of my web page - I am forced to place it inside of the main blank page in the center. How can I override this menu/html so that I can place my own form on the left side of the page?


text:
Q: Popped a power supply fuse - What did I do wrong? I recently purchased a 5V 40A power supply that looks similar to this:

It didn't come with a power cable, so I found one that I wasn't using and stripped the side opposite the three-pronged side (the other side was a female connector that looks like what you'd plug into a computer power supply).
After stripping it, I noticed that there were three wires, each a different color:

*

*Green (I assumed this to be ground)

*White (I assumed this to be neutral)

*Black (I assumed this to be live)

I screwed the stripped black wire into the L (AC) position, the stripped white wire into the stripped N (AC) position, and the stripped green wire into the position beneath the ground symbol to the right of N (AC).
I plugged the power supply into the wall, and there was a bright, blue light for a fraction of a second, and then nothing. I unplugged it immediately, waited a bit, and tried it again; however, the positions beneath +V were not supplying any voltage, so I assumed it was dead at that point.
After waiting a bit, I opened the power supply cover and noticed that the fuse looked like it wasn't there anymore. I also noticed that the copper for the neutral and ground wires were very close to one-another, but didn't seem to be touching.
What exactly did I do wrong to cause the fuse to burn up?
Did the copper of both the neutral and ground wires being close together cause it to arc, resulting in a short?

A: I would think that most likely the power supply was simply faulty when you got it. Second most likely is that you dropped some conductive detritus into the power supply while you were working on it.

that looks similar to this

The words "looked similar to" are setting off alarm bells here, if you bought a power supply from a reputable vendor you should be able to give us a link or a part number or something! So I would guess you bought this from a less than reputable source.

After stripping it, I noticed that there were three wires, each a different color:
Green (I assumed this to be ground)
     White (I assumed this to be neutral)
     Black (I assumed this to be live)

That would be the normal american color code. Even if the colors were somehow wrong it would not have resulted in blowing the fuse in an otherwise disconnected power supply (it may have resulted in you getting an electric shock but that is another story).

Did the copper of both the neutral and ground wires being close together cause it to arc, resulting in a short?

A short between neutral and ground is likely to trip a GFCI, but if the installation is otherwise normal it's unlikely to do much beyond that. Even if by some stroke of bad luck live and neutral connections were reversed the fault current would have flowed OUTSIDE the power supply, so it would have had no affect on a fuse INSIDE the power supply.
P.S. I usually use insulated ring crimps on power supplies like these. I find they give a secure result and make the connections more touch-resistant than they would be if bare wires are used (though still far from touch-proof, a power supply like this should be inside an enclosure).


text:
Q: Complexity of btrfs-send / btrfs-receive I considered incremental btrfs send/receive as a fast possibility for incremental backups. However, btrfs-receive seems to take forever in my case, which is a small change in a singe HUGE (1.5TB) file, while btrfs-send seems to retrieve and send a small differential pretty quickly.
Is this expected, since e.g. btrfs-receive needs to read a big part of the older snapshot the differential is based on, or is there a problem that could be fixed to speed it up?

A: Try mounting the receiver with nodatasum I would expect btrfs-receive to be faster than rsync because like git the receiver is in a guaranteed state. But it's probably double checking the file.


text:
Q: BigQuery very slow CSV upload BigQuery suddenly slowed 2019-02-26 16:00 UTC by about 10x for CSV upload to replace an existing table through API.
What would cause this sudden uptick in upload time? What once took 30min is now taking 6 hours.

A: Since your question is a general one let me give you some guidelines on how to continue.
You can find the execution plan in the webUI near the results or from the Job history on the top left panel, See an image below on how to open the execution plan of a query.
Important notes:

*

*You see 4 colours phases which show the execution lifetime, If the Wait phase is coloured and not greyed out it means you are waiting for a resource

*output of a phase is the input of the 2nd phase, So if your output is big it might mean the next step is working hard to finish, There are few best practice around this which can be described per a specific issue

*You can also expand the step and see more interesting details such as: Shuffeling, Broadcast, Sort etc which can help you get more information on what's going on under the hood

*This is BigQuery URL with more details on execution plan (Check to Job.get API to get this the execution plan via API)

*This is BigQuery Limit information


text:
Q: How to test whether a GDI+ GraphicsPath intersects with a Rectangle on Mono? I am trying to make a Windows.Forms code base (i.e. it uses GDI+ to draw) work on Mono.
Mono's GDI+ support only leaves a few issues to resolve.
One of them: I need to test whether a given fragment of the drawing intersects with a given Rectangle.
The existing code looks like this:
[...]
GraphicsPath gp = new GraphicsPath();
[...]  // draw something to the GraphicsPath
Pen penToUse = new Pen(Color.Black, 10);  // 1 would probably do as well
gp.Widen(penToUse); //TODO: find a better way
Region reg = new Region(gp);
return reg.IsVisible(rect);

Mono doesn't support Widen, and when I omit it, the path has no area, causing IsVisible to always fail.
How can I fix this in a way Mono will support?