text:
Q: jquery clone object issue I am cloning following div and I want to create newids on every clone. and it is doing like that but it is creating div as separate and inputs as separate out side div and all design messup. I want following div_ clone withall inputs should appear in other div container.
HTML

    Label :    <input type="text"  id="txtlabel" name="txtlabel" />
    value :    <input type="text"  id="txtvalue" name="txtvalue" />
    Selected : <input type="checkbox" name="chk_sel" value="chk_sel" />
    Required : <input type="checkbox" name="chk_isreq" value="chk_isreq" />

jQuery
var = question_cnt=1;
$("#div_").clone().find("input,label").andSelf().each(function() {
    $(this).show();
    $(this).attr('id', this.id +question_cnt );
    $(this).attr('name', this.name +question_cnt );
}).appendTo("#container").end();
question_cnt++;

A: I think this is probably what you're trying to do, although I'm puzzled by looping through the labels too? They don't have id's or name's, or even for's, which would make sense. Why loop over those?
$(document).ready(function(){
    var $underscore = $("#div_"),
        question_cnt = 0;

    function clone() {
        var $clone = $underscore.clone();

        $clone
            .find("input, label")
            .each(function() {
                $(this)
                    .attr({
                        id: this.id + question_cnt,
                        name: this.name + question_cnt
                    });
            });

        $clone
            .appendTo("#container")
            .show();

        question_cnt++;
    }

    $('#cloneit').click(clone);
});

http://jsfiddle.net/userdude/M2xjp/


text:
Q: When using onValue to listen to a Firebase realtime database for updates, is it possible to retrieve the event type of child_added or child_changed? I am using the following to query a Firebase realtime database for updates in a React application:
onValue(query(ref(db, 'users')), (snapshot) => {

  if(snapshot.exists()) {
   // do stuff with snapshot.val()
  }

}, (cancelCallback) => {
  console.log(cancelCallback);
});

As expected, this returns all the data that exists under the users node when instantiated and will execute again every time data at this node is changed, added or removed.
Is it possible to retrieve the event type of child_added, child_changed or child_removed from the snapshot?
I have checked the documentation at Firebase and could not find a solution.

A:
Is it possible to retrieve the event type of child_added,
child_changed or child_removed from the snapshot?

It's not possible with onValue() but you can use onChildAdded(), onChildChanged() and onChildRemoved() respectively.

redpajama_set_name: RedPajamaStackExchange


text:
Q: zf3 - calling custom plugin from Module.php I'm new to Zend Framework 3. And migrating my Zend Framework 2 application to Zend Framework 3.
Currently I'm trying to call userPlugin from Application Module's Module.php file.
Here is my code,
public function onRoute(MvcEvent $e)
{
    $sm = $e->getApplication()->getServiceManager();
    $userPlugin = $sm->get('ControllerPluginManager')->get('userPlugin');
    $userPlugin->setServiceManager($e->getApplication()->getServiceManager());
    $checkLogin = $userPlugin->isLoggedIn();
}

And in my module.config.php,
'controller_plugins' => array(
    //This is also not working
    //'invokables' => array(
    //    'userPlugin' => 'User\Controller\Plugin\UserPlugin',
    //),
    'factories' => [
        Controller\Plugin\UserPlugin::class => InvokableFactory::class,
    ],
    'aliases' => [
        'userPlugin' => Controller\Plugin\UserPlugin::class,
    ]
)

But getting this error

Uncaught Zend\ServiceManager\Exception\ServiceNotFoundException: A plugin by the name "UserPlugin" was not found in the plugin manager Zend\Mvc\Controller\PluginManager

Where am I wrong?

A: Use below code
 $sm = $e->getApplication()->getServiceManager();
 $checkLogin = $sm->get('ControllerPluginManager')
                  ->get(Controller\Plugin\UserPlugin::class)
                  ->isLoggedIn();


text:
Q: Manage Azure SAS HTML URL Route with its key I have static website in azure blocked blob storage. I secure that HTML content with azure Shared Access Storage, but whenever I access one of them page that link to another page that can not be served because that need URL token is there any way to cache that and manage that key with static html content.

A: I know this is generally frown upon in SO, but this question needs an answer beyond what's asked.
In general we do not recommend Azure BLOB storage to host web sites directly from blob storage. Some scenarios call for "direct" blob usage, but those are usually concerned with CDN or similar. Shared Access Signatures (SAS) are there to provide security to the objects stored in blob storageю
Shared Access Signatures, Part 1: Understanding the SAS Model
https://azure.microsoft.com/en-us/documentation/articles/storage-dotnet-shared-access-signature-part-1/
For the simple static web site hosting scenario we usually recommend to consider Azure Web Apps. Web Apps provide simple and scalable infrastructure to host your static web sites in PaaS model. Sometimes I call it "IIS for hire":
Web Apps overview
https://azure.microsoft.com/en-us/documentation/articles/app-service-web-overview/


text:
Q: Iterating over 12 items specify markup up on nth items Hi I am using Bootstrap 2 with a PHP content management system.
I am rendering 12 items from the database, each 3 items needs to be wrapped in a row. However I am unable to achieve this my last attempt is below (with simplified markup):
$i = 1;
                echo "
";
                foreach($posts as $p) {
                    if ($i % 3 == 0) {
                        echo "
";
                    }
                    if ($i % 4 == 0) {
                        echo "
";
                    }
                    echo "

$p->title

";

                    $i++;

                }

In affect what I am looking for is something like this:

</item>
           <div class="item"</item>

</item>

</item>
           <div class="item"</item>

</item>

</item>
           <div class="item"</item>

</item>

</item>
           <div class="item"</item>

</item>

I have tried everything I can think of any help would be great thanks.

A: I think this will work
                $i = 0;
                echo "
";
                foreach($posts as $p) {

                    echo "

$p->title

";
                    if ($i % 3 == 0) {
                        echo "

";
                    }

                    $i++;

               }
               echo "
";

A: Try if there are 12 rows :
         echo "
";
            foreach($posts as $p) {
                echo "

$p->title

";
                if ($i % 3 == 0) {
                    echo "
";
                    echo ( $i< 12 )? "
" : "";
                }
                $i++;
            }


text:
Q: Adding images/subtexts to listbox control wpf How do you add images(from resources) beside a listbox item?
Pseudocode:

1. Set image of Listbox1.items.item(0) = My.Resources.image0
2. Set image of Listbox1.items.item(1) = My.Resources.image1


text:
Q: Как удалить ключ и его значение из словаря? Суть такая,  я могу добавлять в словарь много ключей и значений, но если такой ключ и такое значение уже есть в словаре, мне нужно их удалять.
Kак такое можно сделать?

A: Безопасный способ удаления ключа и значения - даже если такой ключ отсутствует , не будет исключительной ситуации (exception):
_ = dict_.pop(key, None)

Пример:
d = dict(a=1, b=2, c=3)
print(d)
_ = d.pop("b")
print(d)
_ = d.pop("blah", None)
print(d)

Вывод:
{'a': 1, 'b': 2, 'c': 3}
{'a': 1, 'c': 3}
{'a': 1, 'c': 3}

A: Вариантов есть несколько. Про pop уже написали. Но традиционный всё-таки вариант через del. Приведу варианты с проверкой наличия ключа и значения:
d = {'a': 1, 'b': 2, 'c': 3}
if 'a' in d and d['a'] == 1:
    del d['a']

Или:
if d.get('a') == 1:
    del d['a']


text:
Q: DAX measure for Sum of values on the first and last day of a cycle I have a table 'fact WorkItems', where changes made to items are saved on the day of the change ([ChangedDate]).

WorkItemId
AreaPath
ChangedDate
State
StoryPoints
IterationPath
1day
14day
Commitment
Delivered

1
A
04/01/2022
New
4
24.1
4

1
A
06/01/2022
Ready
6
24.1
6

1
A
10/01/2022
Active
6
24.1
6

1
A
12/01/2022
Testing
8
24.1
8

8

1
A
18/01/2022
Testing
2
24.1

1
A
19/01/2022
Testing
2
24.1

1
A
28/01/2022
Closed
2
24.1

2

1
A
01/02/2022
Closed
2
24.1

2

2

1
A
03/02/2022
Closed
2
24.1

I also have a table called 'dim Itrations', where cycles' start and end dates are kept.

IterationPath
StartDate
EndDate

24.1
13/01/2022
02/02/2022

24.2
03/02/2022
17/02/2022

24.3
18/02/2022
04/03/2022

I have created a measure [1day] which tells me how many [StoryPoints] had an Item on or before a cycle started
1day =
CALCULATE (
    SUM( 'fact WorkItems'[StoryPoints] ),
    FILTER (
        'dim Iterations',
            MAX('fact Workitems'[ChangedDate]) <= 'dim Iterations'[StartDate]
    )
)

I have also created a measure [14day] which tells me how many [StoryPoints] had an Item by the end of the cycle once it's in "Closed" [State].
14day =
CALCULATE (
    SUM( 'fact WorkItems'[StoryPoints] ),
    FILTER ('fact WorkItems',
        AND(
            'fact Workitems'[State]="Closed",
            'fact Workitems'[ChangedDate] <= MIN('dim Iterations'[EndDate])
            )
))

My objective is to create two measures: [Commitment] and [Delivered] which will sum all the StoryPoints each team ([AreaPath]) had for each of  the cycles exactly on the the day the cycle started and ended (the latter with status closed). I know how to "tell" Power BI to only look at the rows, where Change date = [StartDate] or [ClosedDate].
The problem is when changes to items are made before the start/end date. I'm trying to "fill in those gaps" in the table by telling Power BI to look at the last record which was changed before or on the Start/End Date and to use those values. What I'm trying to achieve is presented in the table. Any ideas?


text:
Q: App structure for roles-based RESTful resources Is there a consensus best approach to implementing user roles when using RESTful resource routes?
Say I have the following resources:
User has_many Tickets
Event has_many Tickets
Ticket belongs_to Person, Event

And then further say I have two types of Users: customers and agents.  Both will log into the system, but with different resource access and functionality based on their roles.  For example:
Customers can access:

*

*Event index, show

*Ticket index (scoped by user), show, buy/create, return/delete

*Person create, show, update

Agents can access:

*

*Event index, show, create, update, delete

*Ticket index, show, sell/create, update, refund/delete

*Person index, show, create, update, delete

Which of the 4 general approaches below will be cleaner and more flexible?
Separate controllers within role folders and resources in namespaces, eg:
namespace "agent" do
  resources :events, :tickets, :people
end
namespace "customer" do
  resources :events, :tickets, :people
end

Separate controllers by role, eg:
AgentController
  def sell_ticket, etc

CustomerController
  def buy_ticket, etc

Shared controllers with separate actions where needed, eg:
TicketController
  before_filter :customer_access, :only => :buy
  before_filter :agent_access, :except => :buy

  def buy  #accessed by customer to create ticket

  def sell   #accessed by agent to create ticket

Shared actions with conditional statements, eg:
TicketController
  def create
    if @role == :customer
      #buy ticket
    elsif @role == :customer
      #sell ticket
    end
  end

A: I would suggest using a combination of the last two proposed implementations. They adhere to RESTful representation, they put authorization at the appropriate level (controllers), and it is a scalable implementation.
REST is, essentially, about accessing nouns with verbs. So you want Agents and Customers to perform actions (verbs) in relation to Tickets, Users, and Events (nouns). In order to accurately represent these nouns you should have a controller for each. Customers can then identify the resource they are looking for by the URL, http://example.com/events/22. From here you can use Rails' routing to represent context for various resources, ie http://example.com/events/22/tickets by doing something like:
resource :events do
  resource :tickets
end

By adhering to a RESTful architecture, you are buying into the end to end principle. The paradigm for representing objects needs to be only responsible for that. It shouldn't try to authenticate. That isn't its job. Authorization should happen in the controllers. I would highly recommend looking into gems like CanCan or Declarative Authorization that set all of this up for you.
Finally, this model scalable. By keeping authorization separate from the representation of your resources you only have to use it if you need it. This keeps your application light, flexible, and simple.

A: While they both deal with creating Tickets, the Agent / Ticket selling vs. the Customer / Ticket purchasing seem different enough to me that they should be separated. Eventually they could further diverge since they are being used so differently from the beginning.
It is possible to have shared controller functionality either with modules or by inheriting from a common parent controller:
module TicketsControllersCommom
  # common helper methods
end

class TicketsController < ApplicationController
  include TicketsControllersCommom
  # actions
end

class AgentTicketsController < ApplicationController
  include TicketsControllersCommom
  # actions
end

I might treat the agent parts as a sort of admin section, with the customer parts being the default:
/events/xx/tickets # collection
/events/xx/tickets/xx # member
# etc.
/events/xx/agent/tickets # collection
/events/xx/agent/tickets/xx # member
# etc.

Or, if you have a lot of admin-type stuff, like if the agents manage the events as well, you can namespace a whole section:
/agent/events/xx/tickets
/agent/events/xx/edit
# etc.

A: If you use the same model for customer and agent tickets, there should be no major difference between how they are handled in controller. So, create action will be always like this:
@ticket = Ticket.new(params[:ticket])

if @ticket.save
  redirect_to @ticket
else
  render :action => "new"
end

But your views can be simply customized:
<% if customer? %>
  Customer area.
<% else %>
  Agent area.
<% end %>


text:
Q: How to to Convert PSObject to Stream output or DataTable using C# Powershell System.Management.Automation I need to convert PowerShell PSObject to stream in a sameway the way PowerShell does. PowerShell also provides the output on standard stream in generic way.
e.g. $PSVersionTable only outputs 2 column ( Name, Value ) and not the whole Hashtable.
So, I want each PSObject to process in a same standard way the way PowerShell does under the hood. Furthermore, I want to convert that to DataTable.
I know, there are other links illustrating this problem, but they are operating on all properties of PSObject. Somehow, PowerShell doing this stuff out of the box.
Do I need to convert PSObject to other type?
Examples
PowerShell script outputs $PSVersionTable as

PSVersion      5.1.17134.228
PSEdition      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}

$host or Get-Host outputs as

Get-WebApplication outputs

Name             Application pool   Protocols    Physical Path
----             ----------------   ---------    -------------
IisHostedServer  DefaultAppPool     http        C:\TestDirectory\Src\IisHostedServer

Get-ChildItem -Path "C:\TestDirectory\TestSubDir\Studio":

Mode                LastWriteTime         Length Name
----                -------------         ------ ----
d-----       29.06.2018     11:54                TestFileDir
d-----       24.07.2018     16:37                TestSites
-a----       13.08.2018     11:53            343 TestXml.xml

Similarly there could be other reference or custom types.
I want to get these outputs in a same way in C# and need to show them either as String or DataTable. Is there any conversion available from PSObject to stream or something which returns above output in completely generic way?
while I am dealing with following method in C#:
var outputCollection = new PSDataCollection<PSObject>();

outputCollection.DataAdded += OnOutputDataAdded;
powerShell.Invoke(null, outputCollection);

private void OnOutputDataAdded(object sender, DataAddedEventArgs e)
{
    var records = (PSDataCollection<PSObject>) sender;
    var data = records[e.Index];
    var outputTable = ConverToLogableDataStream(data);
}
private void ConverToLogableDataStream(PSObject)
{
    ...
    ...
}

A: This question is quite old but have a look at ConvertTo-Json and work it into a data table or class of your choice from there (worked for me)
eg.
Powershell:
Get-Host | ConvertTo-Json
C#:
JsonConvert.DeserializeObject< List < classname > > (PSObject)


text:
Q: How to use soap API in Magento2? In Magento1, we use a username/ password in the SOAP call for authentication, what is the difference in Magento2?
For example, When i want to get an order info, I use
http://example.com/soap/en?services=salesOrderRepositoryV1
I got the WSDL request sample like this:
<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:en="http://k11.dev.cleargo.com/soap/en?services=salesOrderRepositoryV1">
   <soap:Header/>
   <soap:Body>
      <en:salesOrderRepositoryV1GetRequest>
         <id>1</id>
      </en:salesOrderRepositoryV1GetRequest>
   </soap:Body>
</soap:Envelope>

Where should I put the authentication information?

A: If you want to see how many soap services are enabled in your website, you can run below url,
http://localhost/magentoce27/index.php/soap/default?wsdl_list=1
Change your host entry accordingly. Now to get specific orders details, below is the script which will work for you,
Try to add this script in your projects root folder. Script.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

require('vendor/zendframework/zend-server/src/Client.php');
require('vendor/zendframework/zend-soap/src/Client.php');
require('vendor/zendframework/zend-soap/src/Client/Common.php');

$wsdlurl = 'http://10.16.16.190/magentoce27/index.php/soap/default?wsdl&services=salesOrderRepositoryV1';

$token = 'dx2x7pl5mxq9hp8jr8efcl5crv2pk699';

$opts = ['http' => ['header' => "Authorization: Bearer ".$token]];
$context = stream_context_create($opts);
//$arguments =
$serviceArgs = array('searchCriteria'=>
        array('filterGroups' =>
            array ('filters' =>
                array('field' =>'increment_id',
                      'value' => '000000002' ,
                      'condition_type' => 'eq')
                )
         )
);
$soapClient = new \Zend\Soap\Client($wsdlurl);
$soapClient->setSoapVersion(SOAP_1_2);
$soapClient->setStreamContext($context);
$result = $soapClient->salesOrderRepositoryV1GetList($serviceArgs);//array('searchCriteria' => $serviceArgs));
//$result = $soapClient->customerCustomerRepositoryV1GetById(array('customerId' => 1));
/*'search_criteria'=>
        array('filter_groups' =>
            array ('filters' =>
                array('field' =>'firstname',
                      'value' => 'Veronica' ,
                      'condition_type' => 'eq')
                )
         )
);*/
echo "<pre>"; print_r($result);
?>

Here, salesOrderRepositoryV1 will call soap services for sales and it will find increment_id as "000000002" as I have used in search criteria.
I have used, $token = 'dx2x7pl5mxq9hp8jr8efcl5crv2pk699' which you need to create from admin panel using below steps,
System->Integration->Add New Integration. Once integration is created, activate it and put token in your script file.
Now hit URL, http://10.16.16.190/magentoce27/Script.php and it will give you output as shown in the screen shot.

A: The search criteria is not actually correct. Use this instead
$serviceArgs = array('searchCriteria'=>
    array('filterGroups' =>
        [
            array ('filters' =>
                [
                    array('field' =>'increment_id',
                          'value' => '000000002' ,
                          'condition_type' => 'eq')
                ]
            )
        ]
    )
);


text:
Q: input from a file into an array of class objects c++ I am not sure how to input my data. Sorry I am a noob and the only examples I've found for something like this are way too complicated and I can't understand what is going on. I know this is not even close to being right but I have no idea how to set up the input from the file. My file data looks like this:
986  8
432  24
132  100
123  89
329  50
503  30
783  78
822  32
233  56
322  74

And my program so far looks like this:
#include <iostream>
#include <fstream>
using namespace std;

// This program defines a class called Inventory that has itemnumber (which
// contains the id number of a product) and numofitem (which contains the
// quantity on hand of the corresponding product)as private data members.
// The program will read these values from a file and store them in an
// array of objects (of type Inventory).  It will then print these values
// to the screen.

// Example: Given the following data file:
//     986 8
//     432 24
// This program reads these values into an array of objects and prints the
// following:
//     Item number 986 has 8 items in stock
//     Item number 432 has 24 items in stock

const int NUMOFPROD = 10;   // This holds the number of products a store sells

class Inventory
{
public:

   void getId(int item);      // This puts item in the private data member
                              // itemnumber of the object that calls it.
   void getAmount(int num);   // This puts num in the private data member
                              // numofitem of the object that calls it.
   void display();            // This prints to the screen
                              // the value of itemnumber and numofitem of the
                              // object that calls it.

private:

   int  itemNumber;         // This is an id number of the product
   int  numOfItem;          // This is the number of items in stock

};

int main()
{

   ifstream infile;       // Input file to read values into array
   infile.open("inventory.dat");

   // Fill in the code that declares an array of objects of class Inventory
   // called products. The array should be of size NUMOFPROD
   Inventory products[NUMOFPROD];

   int pos;                   // loop counter
   int id;                    // variable holding the id number
   int total;                 // variable holding the total for each id number

   // Fill in the code that will read inventory numbers and number of items
   // from a file into the array of objects. There should be calls to both
   // getId and getAmount member functions somewhere in this code.
   // Example: products[pos].getId(id); will be somewhere in this code
   pos = 0;
   while(NUMOFPROD > pos++ && infile >> products[pos])
   {
        id = products[pos];
        products[pos].getId(id);

       //products[pos].getAmount(total);
   }
    infile.close();
   // Fill in the code to print out the values (itemNumber and numOfItem) for
   // each object in the array products.
   // This should be done by calling the member function display within a loop
   pos = 0;
   while(NUMOFPROD > pos++)
   {
       products[pos].display();
   }

   return 0;

}

// Write the implementations for all the member functions of the class.

void getId(int item)
{
    itemNumber = item;

}
void getAmount(int num)
{
    numOfItem = num;
}
void display()
{
    cout << itemNumber << " ";
}

A: to input and from a file, do this:
#include <fstream>
#include <iostream>
using namespace std;

int main()
{
    ifstream fin("YourTxtFile.txt");
    fin >> something //Fin acts just like your standard cin

    fin.close() //Don't forget to close the stream when you're done!
}

if you want to output to a file, do this:
#include <fstream>
#include <iostream>
using namespace std;

int main()
{
    ofstream fout("YourTxtFile.txt");
    fout >> something //Fout acts just like your standard cout

    fout.close() //Don't forget to close the stream when you're done!
}

you can also do both at the same time!
#include <fstream>
#include <iostream>
using namespace std;

int main()
{
    ifstream fin("YourTxtFile1.txt");
    fin >> something //Fin acts just like your standard cin

    fin.close() //Don't forget to close the stream when you're done!

    ofstream fout("YourTxtFile2.txt");
    fout >> something //Fout acts just like your standard cout

    fout.close() //Don't forget to close the stream when you're done!
}

Just to let you know, fin and fout can be called whatever you want.
If this post answers your question, please mark it as the answer.
Thanks


text:
Q: Error -Ionic InAppBrowser on iOS Loading White Blank Screen I am getting the white blank screen in ios cordova application after injecting inAppBrowser dependency in one of the components.
I couldnt resolve the issue. Kindly help

A: Instead of injecting InAppbrowser in constructor,
use
cordova.InAppBrowser.open in ur calling method.
This solves the problem.
Please find the url for the same,
https://forum.ionicframework.com/t/how-to-open-link-externally/83880/20


text:
Q: Calling sql with subroutines embeded I'm having a problem whilst trying to execute an SQL line of code:
sql1 = "select ",(variable.get())," FROM ProductTable WHERE", Queryby.get()
 cursor.execute(sql1)
When I go to execute these lines of code in the program, it says
ValueError: operation parameter must be str
I presume this is because of the fact I am trying to use .get() inside the sql line of code. The reason I assume this is because if I change the code from cursor.execute(sql) to print(sql1) it says:
('select ', 'OrderNo', ' FROM ProductTable WHERE', 'This is a test')
I think the problem is that this isn't all considered a string, but I'm unsure of the resolution on how to call the .get() parts of the code without interfering the SQL. Any suggestions?

A: Instead of using commas, join the strings using +:
sql1 = "select " + variable.get() + " FROM ProductTable WHERE" + Queryby.get()

This will return a string, but note that in general this is an insecure way to build your query. Instead of simply sticking strings to each other please read up on parameterized queries to protect yourself from SQL injection, one of the most common security vulnerabilities there is.
I'm not sure precisely what library you are using for your database access, but most support parameterization out of the box.


text:
Q: joining html header, body and trailer using Python I'm trying to join htm header with the body and trailer like this
    message1 = """

"""
message2 = 'Hello World!'
message3 = """

"""

html_message = join(message1,message2,message3)

but when I print "html_message" the result is "\Hello World!\", why themthe backslashes appear , how could I remove

A: I suppose that you are using a (wrong) imported method, but you can use the percent operand with strings
template = """

%(text)s

"""
html_message = template % {"text":"Hello World!"}

Don't forget, the variable name format is: percent sign + name in parentheses + format (s for string)

A: Here is how I would join the string:
message1 = """

"""
message2 = 'Hello World!'
message3 = """

"""

html_message = "".join([message1,message2,message3])

The join you are referring to merges files together, which are usually in the form Something/another/thing, hence the back slashes. No need for from os.path import basename, join

A: To join strings, use the + symbol
html_message = message1 + message2 + message3

os.path.join is used to create file path like os.path.join('my', 'script.py') => my/script.py


text:
Q: No graphics after upgrading to 17.10 do-release-upgrade

No errors. On boot, I get a nice graphical 17.10 splash screens, then a few minutes later:
[ OK ] Started GNOME Display Manager

but no graphics visible, <Ctrl><Alt><F7> does nothing.
I do have a backup of 17.04 but I'd rather get 17.10 working! Also I'm really trying to avoid a clean install, though I know this may be the "right thing to do"...
I have tried
sudo apt-get purge "nvidia*"

which I assume should now use nouveau. But exactly same occurs. So as per this bug report, I added the nomodeset boot parameter
linux /boot/bmlinuz-4.13.0-16-generic ... ro nomodeset quiet splash

But no change. There are no options to "Disable integrated graphics/GPU in your BIOS" in my BIOS. So then as per this answer I did
lspci |grep VGA
02:00.0 VGA compatible controller NVIDIA G96GL [Quadro FX 580]
03:00.0 VGA compatible controller NVIDIA G84 [GeForce 8600 GT]

ubuntu-drivers devices
== /sys/devices/pci0000:00/0000:00:07.0/0000:03:00.0 ==
modalias  : pci:v....
vendor    : NVIDIA corporation
model     : G84 [GeForce 8600 GT]
driver    : nvidia-304 - distro non-free
driver    : nvidia-340 - distro non-free recommended
driver    : xserver-xorg-video-nouveau - distro fere builtin

sudo apt-get install nvidia-340

this seems to install fine, but exactly same problem. So, then I uncommented this line
cat /etc/gdm3/custom.conf
...
WaylandEnable=false

Again no video.
Note that I have 2 Nvidia cards, but this hasn't caused any problems in the past, and the Ubuntu splash screen appears nicely on both cards.
As per this old thread I checked I have got
sudo apt list --installed |grep 'xorg-legacy'

xserver-xorg-legacy/arflu 2:1.19.5-0ubuntu2 amd64 [installed,automatic]

Anyone know how to fix this now? I am assuming this must be a graphics driver problem, but I have tried all combinations I can think of.  At this point I don't mind whether I use nouveau or nvidia, with X or wayland...


text:
Q: Continuous probability; find the probability density function Let $X$ and $Y$ be random variables and let $Z = \frac{(X+Y)}{2}$. Suppose you randomly choose two numbers $X,Y \in [1,3]$. Find the probability density function of $Z$ and the expected value $E(Z)$.
Does anybody have hint to tackle this problem?

A: *

*The probability density function is determined by convolution:
$$\begin{align}
f_Z(z) & = \int_\Bbb R f_X(x)f_Y(2z-x)\operatorname d x
\\[1ex]
& = \tfrac 1 4\int_\Bbb R \mathbf 1_{x\in[1;3]}\mathbf 1_{2z-x\in[1;3]}\operatorname d x
\\[1ex]
 & = \mathbf 1_{z\in[1;3]}\int_\Bbb R \mathbf 1_{x\in\big[\max(1,\underline{\quad});\min(3,\underline{\quad})\big]}\operatorname d x
\\[1ex]
 & = (\underline{\qquad})\mathbf 1_{z\in[1;\underline{\quad})}+ (\underline{\qquad})\mathbf 1_{z\in[\underline{\quad};3]}
\end{align}$$

*The expectation is the integral $\mathsf E(Z) = \int_\Bbb R z\,f_Z(z)\operatorname d z \\ = \int_1^{\Box} z(\underline{\qquad})\operatorname d z+\int_{\Box}^3 z(\underline{\qquad})\operatorname d z \\ = \underline{\qquad}$
Fill in the blanks

NB: $\mathbf 1_{\cdots}$ is an indicator function: $\mathbf 1_{x\in A} \mathop{:=} \begin{cases} 1 & : x\in A \\ 0 : \textsf{otherwise}\end{cases}$

A: HINTS

*

*So $Z$ is the average of 2 uniforms over $[1,3]$. What is the possible range of $Z$, say $[a,b]$?

*Fix some small $z \in [a,b]$. To compute $$F_Z(z) = \mathbb{P}[Z \le z] = \mathbb{P}[X+Y \le 2z],$$ condition this on the value of $X$, say.

*Clearly, $Z$ is a continuous r.v., so the pdf is given by $$f_Z(z) = F'_Z(z).$$

*Compute $$\mathbb{E}[Z] = \int_a^b z f_Z(z) dz$$


text:
Q: Executing a VB WebMethod from javascript I'm trying to eliminate a VB.NET button on my aspx page. Trying to use javascript and ajax to execute the same code my vb had.
I put in a script manager, set EnablePageMethods to true, added a static subroutine, and referred to it in my javascript function (BTW -- this seems a lot of work just to execute an existing subroutine). The javascript calls my code-behind and it almost works.
Problem is, now I'm getting a NullReferenceException when SimulatePrintBatchClick tries to do anything with the controls.
Error is 'Object reference not set to an instance of an object', line is 'pnlVars.Controls.Clear'
Here's the code from UW.aspx:
<WebMethod()> _
Public Shared Sub PrintBatchFromJSWM()
    Dim UWI As New UW

    UWI.SimulatePrintBatchClick()
End Sub

Sub SimulatePrintBatchClick()
    Dim Client As New LetterWriterClient

    'Run ExStream and get the PDF File
    Globals.PDF_Data = Nothing
    Globals.PDF_Data = Client.ProcessDatFile(Session("SessionID").ToString)

    'Reload the form -- turn off all controls, initialize variables and make the PDF iFrame visible
    pnlVars.Controls.Clear() 'Bombs out on THIS line of code
    pnlPDF.Visible = True
    Me.SendToBach.Visible = False
    Session.Contents("LetterVariables") = Nothing
    Session.Contents("PolicyInformation") = Nothing
    Session.Contents("Submitted") = True
    Response.Redirect("UW.aspx")
End Sub

Funny, when I run the above code in PrintBatch_Click it all executes just fine. I really don't understand why it bombs out as a subroutine.
Perhaps this is not the way to do this, but I'm at a loss for finding a different way. Originally this code was handled by an ASP/VB button, but the specs have called for it to be deleted.
Any way I can get the above code to do it's job?
Thanks,
Jason

A: You cannot use any server controls in WebMethod or AjaxMethod as they are not part of Page life cycle, access these controls in Javascript.


text:
Q: What about raise a bounty in a collaborative way in someone else's question? In order to help the owner, not to hijack. The question's owner still has the power to decide. You can only contribute.

A: https://blog.stackoverflow.com/2010/06/improvements-to-bounty-system/
This is effectively completed, because

*

*bounty system is no longer tied to accepting an answer in any way

*you can issue multiple bounties on your question if necessary


text:
Q: How to set 2 dim Array by input string without blank? This is my code:
    Scanner sc = new Scanner(System.in);
    int size = sc.nextInt();
    String[][] s = new String[size][size];

    for (int row = 0; row < s.length; row++) {
        for (int col = 0; col < s[row].length; col++) {
            s[row][col] = sc.next();
        }
    }
    for (int row = 0; row < s.length; row++) {
        for (int col = 0; col < s[row].length; col++) {
            System.out.print(s[row][col] + " ");
        }
        System.out.println();
    }

Now when i input 3, then input array value:
3
a b c
a b c
a b c

The output like this:
a b c
a b c
a b c

So I want to know how can i change the code to get same output when I input like this:
3
abc
abc
abc

A: Try this.
int size = sc.nextInt();
String[][] s = new String[size][];

for (int row = 0; row < s.length; row++) {
    s[row] = sc.next().split("");
}
for (int row = 0; row < s.length; row++) {
    for (int col = 0; col < s[row].length; col++) {
        System.out.print(s[row][col] + " ");
    }
    System.out.println();
}

A: The java.util.Scanner.next() method finds and returns the next complete token from this scanner. A complete token is preceeded and followed by input that matches the delimiter pattern. So, scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
You must use some kind of delimiter. For example, you can set delimiter to be ','
Scanner sc = new Scanner(System.in);
        sc.useDelimiter(",");

Then your input should be like this :
3,
a,b,c,
a,b,c,
a,b,c,

And Your output would be :
a b c

a b c

a b c

In your case, if you want to take input like this:
3
abc
abc
abc

and then take characters one by one, you can't do it like that, beacause you must specify some delimiter, and as I said, if you don't the default delimiter will be taken.
However, you can write a workaround code, something like this :
Scanner sc = new Scanner(System.in);
        sc.useDelimiter("\\n");

        int size = sc.nextInt();
        String[][] s = new String[size][size];

        for (int row = 0; row < s.length; row++) {
            String input = sc.next();
            for (int col = 0; col < s[row].length; col++) {

                    s[row][col] = String.valueOf(input.toCharArray()[col]);
            }
        }

        for (int row = 0; row < s.length; row++) {
            for (int col = 0; col < s[row].length; col++) {
                System.out.print(s[row][col] + " ");
            }
            System.out.println();
        }

    }

Then You pass your input like this:
3
abc
abc
abc

And you should see the following output:
a b c
a b c
a b c

A: Imho, this is the easiest way.  It also allows for each row to be a different length if you want.
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();
// clear the previous new line
sc.nextLine();
//initialize the number of rows.
String[][] s = new String[size][];

// enter the rows
for (int rows = 0; rows < size; rows++) {
    String row = sc.nextLine();
    // split between each character
    s[rows] = row.split("");
}

//print the matrix
for (String[] row : s) {
    System.out.println(String.join(" ",row));
}

For input
3
abc
def
ghi

Prints
a b c
d e f
g h i


text:
Q: Why am I getting this error message from WinLess? I'm trying to learn Less and am currently doing an exercise in which I have to write a pretty complex bit of code in Less. I'm working from a workbook and as far as I can tell I've written the code exactly as I have been told to, but I keep getting the error:

Parse error: Missing closing )

Here is the code, the section this error concerns is highlighted with two *'s at either side:
@waarde: -((38*@index)-38);
background-position: ~"@{waarde}px" 0;

.menuspan (@bgc, @col, @tshad) {
background-color: @@bgc;
color: @@col;
text-shadow: 0 0 5px @@tshad;
}

//m_item1
@bgcolor_1:     #7da315;
@color_1:       #3d4f0c;
@tshadow_1:     #99bf31;
//m_item2
@bgcolor_2:     #1e8bb4;
@color_2:       #223a44;
@tshadow_2:     #44a8d0;
//m_item3
@bgcolor_3:     #c86c1f;
@color_3:       #5a3517;
@tshadow_3:     #d28344;
//m_item4
@bgcolor_4:     #d0a525;
@color_4:       #604e18;
@tshadow_4:     #d8b54b;
//m_item5
@bgcolor_5:     #af1e83;
@color_5:       #460f35;
@tshadow_5:     #d8b54b;

.lusGuardedMixin (@index) when (@index < 0) {

@waarde: -((38*@index)-38);

**(~".m_item@{index}")** {
background-position: ~"@{waarde}px" 0px;

&:hover {
background-position: ~"@{waarde}px" -39px;
}

& span {
.menuspan(~"bgcolor_@{index}", ~"color_@{index}", ~"tshadow_@{index}")
}
}

.lusGuardedMixin(@index + 1);
}

.lusGuardedMixin (6) {}
.lusGuardedMixin (1);

The compiler seems to be looking for the ) too early, because it is definitely there but it's acting as though it isn't. How can I fix this?

A: As discussed in comments, this is not a problem with either WinLess or with Less itself. The problem is with the code that you had used for compilation. It was probably taken from an outdated source that is still using old syntax (which was deprecated a few years ago) and hence the compilation error.
The following are the errors that needed to be corrected:

*

*The first two lines in code will produce a compilation error because @index variable is available only within the mixin loop and not outside of it. This is not at all required and may just have been a copy-paste error.
@waarde: -((38*@index)-38);
background-position: ~"@{waarde}px" 0;

*Next, the selector interpolation syntax that is used is an outdated/deprecated one. The escaping, braces and quotes are not at all required in the latest version of the compiler. Instead of this,
(~".m_item@{index}"){...}
just the below is enough:
.m_item@{index} {...}

*Finally, the loop itself has an error because the guard is checking for @index less than 0 but the input values for the mixin is both greater than 0 and hence the mixin will never get invoked. Also, the two mixin calls at the end is not required and they can be changed into just .lusGuardedMixin (5);.
Making all the above mentioned changes, the code available in this demo should compile fine without any errors in the latest compiler.
(Adding my comments and demo as an answer so as to not leave the question unanswered)


text:
Q: Why do I have problems to fetch users name in javascript? I am working on a Javascript, HTML and CSS proyect. What I want is to get the name of a user using its Id. I use fetch to do that but I am getting some problems.
function getUserName(userId) {
  let userTemp = window.API_HOST + '/users/' + userId;
  return fetch(userTemp, {
    headers: { authorization: localStorage.access_token },
  })
    .then(response => response.json())
    .then(response => {
      console.log('El nombre es: ' + response.name);
      return response.name;
    });
}

The problem here is that response.name is a promise object and not the actual name. I tried to use stringify but it did not work. Any suggestions?
EDIT:
I need to call that function in a place like this:
function showOffer(newOffer) {
  if (newOffer.user_id === JSON.parse(localStorage.current_user)._id) {
    const wrapper = document.createElement('div');
    wrapper.className = 'wrap';
    const prodHolder = document.getElementById('demo').appendChild(wrapper);

    const offerBidderId = document.createElement('p');
    const offerBidderIdText = document.createTextNode(
      'Bidder id: ' + getUserName(newOffer.bidder_id),
    );
    console.log('New offer bidder id ' + newOffer.bidder_id);
    offerBidderId.appendChild(offerBidderIdText);
    wrapper.appendChild(offerBidderId);
    ....
}

Maybe here is the problem?

A: fetch returns always a Promise. So you have to handle it with then or async/await.
You can access it like this:
getUserName(1).then(name => {
   console.log('El nombre es: ' + name);
});

or inside an async function:
async function access() {
    const name = await getUserName(1);

    console.log('El nombre es: ' + name);
}

Nice article about async functions: https://developers.google.com/web/fundamentals/primers/async-functions


text:
Q: I receive the email notificaction instantly(VTiger doesn't wait for the date to arrive to send it) When I create a ToDo(or an event), and activate the "Send Notification" box, and set a future date for it to begin(for example in two days), I receive the email notification instantly(VTiger doesn't wait for the date to arrive to send it).
I've tried to find answers by myself and online, but I haven't been able to solve it. Mi cron is working OK, and I have my correct timezone configured in config.inc.php.
I'm using Vtiger CRM 6.2.0.
Do you have any idea of why this is happening, or what can I do to find out or solve it?
Thanks for your time!

A: It seems that this is the correct way in which VTiger works. Send notification tells the user that a ToDo was created and assigned to him.
Im not sure how can I email a user when a task is due.


text:
Q: How do I list FFMPEG's audio formats? I'm trying to ask FFMPEG for all the audio formats it can encode.
I can get a list of formats with ffmpeg -formats:
File formats:
 D. = Demuxing supported
 .E = Muxing supported
 --
 D  3dostr          3DO STR
  E 3g2             3GP2 (3GPP2 file format)
  E 3gp             3GP (3GPP file format)
 D  4xm             4X Technologies
  E a64             a64 - video for Commodore 64
 D  aa              Audible AA format files
 D  aac             raw ADTS AAC (Advanced Audio Coding)
...

This shows me formats that it can encode/decode, but it's impossible to tell which are audio formats and which are video formats.
I can get a list of codecs using ffmpeg -codecs:
Codecs:
 D..... = Decoding supported
 .E.... = Encoding supported
 ..V... = Video codec
 ..A... = Audio codec
 ..S... = Subtitle codec
 ...I.. = Intra frame-only codec
 ....L. = Lossy compression
 .....S = Lossless compression
 -------
 D.VI.. 012v                 Uncompressed 4:2:2 10-bit
 D.V.L. 4xm                  4X Movie
 D.VI.S 8bps                 QuickTime 8BPS video
 .EVIL. a64_multi            Multicolor charset for Commodore 64 (encoders: a64multi )
 .EVIL. a64_multi5           Multicolor charset for Commodore 64, extended with 5th color (colram) (encoders: a64multi5 )
 D.V..S aasc                 Autodesk RLE
 D.VIL. aic                  Apple Intermediate Codec
 DEVI.S alias_pix            Alias/Wavefront PIX image
...

This shows me a list of "codecs" and whether or not they are for audio/video, but these aren't formats and thus aren't suitable for using with the -f flag.
For example, here's an audio codec but it doesn't work:
DEA.L. speex                Speex (decoders: libspeex ) (encoders: libspeex )
C:\test>ffmpeg -i uwu.mp3 -f speex out.x
[NULL @ 00000000025ca260] Requested output format 'speex' is not a suitable output format
out.x: Invalid argument

So how can I get a list of formats from this thing that tell me whether or not they are audio formats?


text:
Q: Getting the date info in a MySQL friendly way Got two questions.
I pass a date like 05/16/1978 and I want it to be converted to a format that's friendly to the datetime field of a MySQL table.
And secondly, how do you get the current time in php? Something like 17:22:59

A: You'll want to look into

*

*strtotime() - Parse about any English textual datetime description into a Unix timestamp

*time() - Return current Unix timestamp

*date() - Format a local time/date

Using the date() function, you can pass an EPOCH timestamp and get back a string representing the timestamp in any format you desire -
$now = time();
$today = date("M d Y",$now);  // May 01 2012

Check out the date function documentation for details about what formats are possible...
You can always store dates in EPOCH format (seconds since 1/1/70).  I find it very easy to use and manipulate EPOCH timestamps. I use INT(10) fields in my database to store these values.

Here is a fantastic tool for you to use if you decide to implement your timestamps by EPOCH -
http://www.epochconverter.com/

A: take a look at this link please
http://php.net/manual/en/class.datetime.php
e.g.
$d = "05/16/1978";
list($month, $day, $year) = explode("/",$d);
$datetime = sprintf("%d-%d-%d", $year, $month, $day);

A: The DATETIME format is YYYY-MM-DD, in order to convert your result to that, you can do
$date = "05/16/1978";
list($month, $day, $year) = explode("/",$date);
$datetime = sprintf("%d-%d-%d", $year, $month, $day);

$datetime would now contain "1978-16-15", which MySQL will understand.
date('G:i:s') will return the current time in the format H:m:s.

A: Read this Dates in PHP and MySQL blog post, I think it might help you.

It summarizes three possibilites of managing dates that are stored in MySQL using PHP. A common way that is mentioned there is:

One common solution is to store the dates in DATETIME fields and use PHPs date() and strtotime() functions to convert between PHP timestamps and MySQL DATETIMEs.

For example:
$mysqldate = date( 'Y-m-d H:i:s', $phpdate );
$phpdate = strtotime( $mysqldate );

Hope it helps you.

A: use this code:
function convert_time_sql($date){
    $date = strtotime($date);
    $date = date("Y-m-d ",$date).date("G:i:s");
    return $date;
}

this will return the sql format time
NOTE:  Date must be of proper format see:
http://www.php.net/manual/en/function.strtotime.php
http://www.php.net/manual/en/datetime.formats.date.php
EDIT:
Use this function if time is included:
function convert_time_sql($date,$time_included=false){
    $date = strtotime($date);
    $date = date("Y-m-d ".($time_included?"G:i:s":""),$date).($time_included?"":date("G:i:s"));
    return $date;
}

If you include time, put a true after the given date.
like  convert_time_sql('05/16/1978 05:45:59 AM',true);


text:
Q: How to find css unit for this number I have a input type text
<input type="text">

Basically I am using javascript ClientRect to get caret details. ClientRect looks like this
[object ClientRect]
  {
     [functions]: ,
     __proto__: { },
     bottom: 540.7999877929687,
     constructor: { },
     height: 24,
     left: 1034.5399169921875,
     right: 1034.5399169921875,
     top: 516.7999877929687,
     width: 0
  }

This is generated on everytext input.
left: 1034.5399169921875,
left: 1065.5399169921875,
left: 1078.5399169921875,

I want to convert this number to CSS units like px/%/rem/vh. So that I can put dynamic css. How to do it?

A: Try accessing the left position of your input and subtract the left position of your caret.  This should give you an approximate width of the text in the input, if that's what you are looking for. You'll need to add an id or create a selector for your text input.
var inputElementRect = document.getElementById('YOURINPUTID').getBoundingClientRect()
var width = inputElementRect.left - caretRect.left

A: Those values are px by default ..  so just add suffix as px to that value and use it.
<input type="text">

to get that value
let text = document.querySelector('input');
let values = text.getBoundingClientRect();

let top_value = values.top + 'px';
let bottom_value = values.bottom + 'px';
let width_value = values.width + 'px';
let height_value = values.height + 'px';

console.log('top: '+ top_value);
console.log('bottom: '+ bottom_value);
console.log('width: '+ width_value);
console.log('height: '+ height_value);

here properties other than width and height are relative to the view port ( top, bottom, left, right ) ,
so if scroll this values will changes ..
to get the perfect values even if scroll add this values with window.scrollX , window.scrollY or can use window.pageXOffset , window.pageYOffset

A: So if I understand the question correctly, you have position values for the cursor inside of the input and you want to convert it into different types of CSS units, presumably so you can do something to the input or related things
The first thing to understand is that ClientRect positions are relative to the viewport. So as vhutchinson pointed out, if you want the width of text you need to compare to the input's "left" value as defined by getBoundingClientRects. That's a good start, but if you're not just influencing left but also care about top, you need to account for scrolling. If your window/page is the only scrolling container, you should be able to do this simply by adding window.scrollY to top, and window.scrollX to left to understand your offset relative to the window.
All of these units are pixels by default... if you want to convert to rem it's pretty straightforward, 1 rem = the font-size of your root element, so to convert to rem you can do something like
var remBase = parseInt(window.getComputedStyle(document.body).getPropertyValue('font-size'), 10);
var remValue = (myComputedPixelValue / remBase) + "rem";

Doing VW is similar using the answer in Get the browser viewport dimensions with JavaScript for cross-browser window dimensions, you'd end up with something that looks like
var viewportWidth = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);
var vwValue = (myComputedPixelValue / viewportWidth) + "vw";

Percentages are trickier, because you'd need to compute it based on the parent of the element you're applying the css value to, but the general idea follows the same principle.


text:
Q: How to troubleshoot a hard crash on CopyFeatures_management() I have a script that uses arcpy.CopyFeatures_management(FEATURE_CLASS_SDE, FEATURE_CLASS_LOCAL) to copy a feature class from our enterprise SDE to a local file geodatabase. For the most part, it works well. Occasionally, though, it fails in spectacular fashion.
when it fails, I get a message that states python stopped working with a minidump. That's it. I wrapped the line that performs the copy in a try...except to get more info but the exception is not caught.
Any ideas how I can troubleshoot this further?
ArcGIS 10.1 SP1 w/ QIP (Build 3300)
Update 1: When I run the script within PyCharm, I'm unable to reproduce the issue. When I call the script from a batch file, on the same workstation, the issue occurs. This workstation has 8GB RAM, plenty of HDD space available, and by watching Resource Monitor I don't see any indications we're even close to running low on resources. Python.exe is using about 300mb. There are 95k features in the this SDE FC.

A: If the crash doesn't happen when copying from a local geodatabase I'd start by looking at some aspects of the source geodatabase:

*

*The Feature Class

Bad features can cause problems with exporting data, faults such as self-intersecting or unclosed polygons, rings in the wrong direction etc.. Most DBMS have a methods for validating the geometry of the features, such as Oracle's SDO_GEOM.VALIDATE_LAYER_WITH_CONTEXT procedure.
You could try running the export with a subset of the feature class, say in 500 feature batches by objectid to see if the failure is predicable and always on the same objectID.

*Does the crash occur with different feature classes in the same ArcSDE Geodatabase ?

*Is there anything in the ArcSDE and RDBMS logs ?
For example if you are using direct connect to ArcSDE you can check the sdedc_<dbms>.log file on your workstation for any errors encountered with the export - it's usually in your profile temp directory.
If using the ArcSDE Application Server it will have it's own logfile which the DBA/SysAdmin could pull out for you.
There are some pointers but may help you to find out where the problem is.


text:
Q: Artist.findOne is not a function I am getting the error inside my Electron application when I run this code inside my FindArtist.js file:
const Artist = require('../models/artist');

/**
 * Finds a single artist in the artist collection.
 * @param {string} _id - The ID of the record to find.
 * @return {promise} A promise that resolves with the Artist that matches the id
 */
module.exports = _id => {
  return Artist.findOne({ _id: _id });
};

I definitely installed mongoose, but it seems I am no longer importing mongoose or the Artist model appropriately? Not sure.
Here is the models/artist.js file:
const mongoose = require('mongoose');
const AlbumSchema = require('./album');
const Schema = mongoose.Schema;

const ArtistSchema = new Schema({
  name: String,
  age: Number,
  yearsActive: Number,
  image: String,
  genre: String,
  website: String,
  netWorth: Number,
  labelName: String,
  retired: Boolean,
  albums: [AlbumSchema]
});

const Artist = mongoose.model('artist', ArtistSchema);

module.exports = ArtistSchema;

A: I figure out that my module.exports on my models/artist.js file was wrong.
Instead of:
// const Artist = mongoose.model('artist', ArtistSchema);

// module.exports = ArtistSchema;

it should be this:
module.exports = mongoose.model('artist', ArtistSchema);


text:
Q: Laplace transform of Heaviside function $$f(t) = \begin{cases}0 ,&  t < 4 \\t^{2}-8t+20 ,& t \ge 4\end{cases}$$
The answer is $\frac{e^{-4s}(4s^{2}+2)}{s^{3}}$, but don't know the steps to get to it. Would like some guidance, thanks.

A: Use the definition of the Laplace transform:
$$\mathcal L(f)=\int_0^\infty f(t)e^{-st}\,dt=\int_4^\infty(t^2-8t+20)e^{-st}\,dt$$ The reason that I can write the integral like this is that $f(t)=0$ for $t\leq 4$, so this region doesn't contribute to the integral. Continuing, $$\mathcal L(f)=\int_4^\infty t^2e^{-st}\,dt-8\int_4^\infty te^{-st}\,dt+20\int_4^\infty e^{-st}\,dt.$$
These integrals can be solved using integration by parts.

A: Let be $F(s)=\mathcal L\left\{ f(t)\right\}$. Recall the properties

*

*Frequency-domain general derivative
$$\mathcal L\left\{t^{n} f(t)\right\}=  (-1)^{n} F^{(n)}(s)$$

*Time shifting   $$\mathcal L\left\{f(t - a) u(t - a) \right\}=  e^{-as} F(s)$$

and observe that your function is
$$
f(t)=(t^2−8t+20)u(t-4)=[(t-4)^2+4]u(t-4)
$$
and $\mathcal L\left\{u(t)\right\}=\frac{1}{s}=U(s)$.
So you have
$$
\begin{align}
F(s)&=\mathcal L\left\{(t-4)^2u(t-4)\right\}+\mathcal L\left\{4u(t-4)\right\}\\
&=(-1)^2U''(s)e^{-4s}+4\,U(s)\,e^{-4s}\\
&=\frac{2}{s^3}e^{-4s}+\frac{4}{s}e^{-4s}\\
&=\frac{e^{-4s}(4s^2+2)}{s^3}
\end{align}
$$


text:
Q: Efficiently working with large data sets in Vue applications with Vuex In my Vue application, I have Vuex store modules with large arrays of resource objects in their state. To easily access individual resources in those arrays, I make Vuex getter functions that map resources or lists of resources to various keys (e.g. 'id' or 'tags'). This leads to sluggish performance and a huge memory memory footprint. How do I get the same functionality and reactivity without so much duplicated data?
Store Module Example
export default {
  state: () => ({
    all: [
      { id: 1, tags: ['tag1', 'tag2'] },
      ...
    ],
    ...
  }),

  ...

  getters: {
    byId: (state) => {
      return state.all.reduce((map, item) => {
        map[item.id] = item
        return map
      }, {})
    },

    byTag: (state) => {
      return state.all.reduce((map, item, index) => {
        for (let i = 0; i < item.tags.length; i++) {
          map[item.tags[i]] = map[item.tags[i]] || []
          map[item.tags[i]].push(item)
        }
        return map
      }, {})
    },
  }
}

Component Example
export default {
  ...,

  data () {
    return {
      itemId: 1
    }
  },

  computed: {
    item () {
      return this.$store.getters['path/to/byId'][this.itemId]
    },

    relatedItems () {
      return this.item && this.item.tags.length
        ? this.$store.getters['path/to/byTag'][this.item.tags[0]]
        : []
    }
  }
}

A: To fix this problem, look to an old, standard practice in programming: indexing. Instead of storing a map with the full item values duplicated in the getter, you can store a map to the index of the item in state.all. Then, you can create a new getter that returns a function to access a single item. In my experience, the indexing getter functions always run faster than the old getter functions, and their output takes up a lot less space in memory (on average 80% less in my app).
New Store Module Example
export default {
  state: () => ({
    all: [
      { id: 1, tags: ['tag1', 'tag2'] },
      ...
    ],
    ...
  }),

  ...

  getters: {
    indexById: (state) => {
      return state.all.reduce((map, item, index) => {
        // Store the `index` instead of the `item`
        map[item.id] = index
        return map
      }, {})
    },

    byId: (state, getters) => (id) => {
      return state.all[getters.indexById[id]]
    },

    indexByTags: (state) => {
      return state.all.reduce((map, item, index) => {
        for (let i = 0; i < item.tags.length; i++) {
          map[item.tags[i]] = map[item.tags[i]] || []
          // Again, store the `index` not the `item`
          map[item.tags[i]].push(index)
        }
        return map
      }, {})
    },

    byTag: (state, getters) => (tag) => {
      return (getters.indexByTags[tag] || []).map(index => state.all[index])
    }
  }
}

New Component Example
export default {
  ...,

  data () {
    return {
      itemId: 1
    }
  },

  computed: {
    item () {
      return this.$store.getters['path/to/byId'](this.itemId)
    },

    relatedItems () {
      return this.item && this.item.tags.length
        ? this.$store.getters['path/to/byTag'](this.item.tags[0])
        : []
    }
  }
}

The change seems small, but it makes a huge difference in terms of performance and memory efficiency. It is still fully reactive, just as before, but you're no longer duplicating all of the resource objects in memory. In my implementation, I abstracted out the various indexing methodologies and index expansion methodologies to make the code very maintainable.
You can check out a full proof of concept on github, here: https://github.com/aidangarza/vuex-indexed-getters

A: While I agree with @aidangarza, I think your biggest issue is the reactivity. Specifically the computed property. This adds a lot of bloated logic and slow code that listens for everything - something you don't need.
Finding the related items will always lead you to looping through the whole list - there's no easy way around it. BUT it will be much faster if you call this by yourself.
What I mean is that computed properties are about something that is going to be computed. You are actually filtering your results. Put a watcher on your variables, and then call the getters by yourself. Something along the lines (semi-code):
watch: {
  itemId() {
    this.item = this.$store.getters['path/to/byId'][this.itemId]
  }
}

You can test with item first and if it works better (which I believe it will) - add watcher for the more complex tags.
Good luck!

A: While only storing select fields is a good intermediate option (per @aidangarza), it's still not viable when you end up with really huge sets of data. E.g. actively working with 2 million records of "just 2 fields" will still eat your memory and ruin browser performance.
In general, when working with large (or unpredictable) data sets in Vue (using VueX), simply skip the get and commit mechanisms altogether. Keep using VueX to centralize your CRUD operations (via Actions), but do not try to "cache" the results, rather let each component cache what they need for as long as they're using it (e.g. the current working page of the results, some projection thereof, etc.).
In my experience VueX caching is intended for reasonably bounded data, or bounded subsets of data in the current usage context (i.e. for a currently logged in user). When you have data where you have no idea about its scale, then keep its access on an "as needed" basis by your Vue components via Actions only; no getters or mutations for those potentially huge data sets.


text:
Q: Deserialize JSON object on windows phone I need help with this:
My JSON (It's from Diablo 3 API):
{
   "name":"Exsanguinating Chopsword of Assault",
   "icon":"mightyweapon1h_202",
   "displayColor":"blue",
   "tooltipParams":"item-data/COGHsoAIEgcIBBXIGEoRHYQRdRUdnWyzFB2qXu51MA04kwNAAFAKYJMD",
   "requiredLevel":60,
   "itemLevel":61,
   "bonusAffixes":0,
   "dps":{
       "min":206.69999241828918,
       "max":206.69999241828918
    }
}

It's not complete JSON, but I'm trying to parse only this piece because I'm learning about it.
I know how to get the the strings name,icon,displayColor..... but I don't know how to get the DPS.
My model class is:
namespace Diablo_III_Profile
{
[DataContract]
public class ItemInformation : INotifyPropertyChanged
{
    private string _name;

    [DataMember]
    public string name
    {
        get
        {
            return _name;
        }
        set
        {
            if (value != _name)
            {
                _name = value;
                NotifyPropertyChanged("name");
            }
        }
    }
    //others strings and ints here

    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged(String propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (null != handler)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

What is the "format" of DPS to put in my model class?
To read the strings I'm using this:
 MemoryStream ms = new MemoryStream();
 ItemInformation data = (ItemInformation)Deserialize(ms, typeof(ItemInformation));
 MessageBox.Show(data.name);

Should be the same to DPS?
EDIT:
I DID IT! Dunno if is the best way but....
Inside my model class I put
public class DPS
    {
        public float min { get; set; }
        public float max { get; set; }
    }

    private DPS _dps;

    [DataMember]
    public DPS dps
    {
        get
        {
            return _dps;
        }
        set
        {
            if (value != _dps)
            {
                _dps = value;
                NotifyPropertyChanged("dps");
            }
        }
    }

A: Your solution is good, that is exactly what I was trying to reply with. This way you can reuse the DPS wherever you want and JSON parser should deserialize it properly to the "ItemInformation" with proper values for DPS min and max. I have used the same methodology to populate objects and child objects.
You can also use JSON.Net for Serializing to JSON and Deserializing JSON objects.
http://james.newtonking.com/projects/json/help/index.html
Cheers

A: I DID IT! Dunno if is the best way but....
Inside my model class I put
public class DPS
 {
     public float min { get; set; }
     public float max { get; set; }
 }

private DPS _dps;

[DataMember]
public DPS dps
{
    get
    {
        return _dps;
    }
    set
    {
        if (value != _dps)
        {
            _dps = value;
            NotifyPropertyChanged("dps");
        }
    }
}


text:
Q: Convert NSString into char array I have a variable of type char[] and I want to copy NSString value in it. How can I convert an NSString to a char array?

A: Rather than getCharacters:range:, I use:
[stringToCopy getCString:c_buffer maxLength:c_buffer_length encoding:NSUTF8StringEncoding];

The result is a char[] (instead of unichar[]), which is what the OP was wanting, and what you probably want to use for C compatibility.

A: mipadi's answer is the best if you just want a char* containing the contents of the string, however NSString provides methods for obtaining the data into a buffer that you have allocated yourself. For example, you can copy the characters into an array of unichar using getCharacters:range: like this:
NSUInteger length = [str length];
unichar buffer[length];

[str getCharacters:buffer range:NSMakeRange(0, length)];

for (NSUInteger i = 0; i < length; i++)
{
    doSomethingWithThis(buffer[i]);
}

If you have to use char, then you can use the more complicated getBytes:maxLength:usedLength:encoding:options:range:remainingRange: like this (demonstrated in Eastern Polish Christmas Tree notation):
NSUInteger length = [str length];
NSUInteger bufferSize = 500;

char buffer[bufferSize] = {0};

[str       getBytes:buffer
          maxLength:(bufferSize - 1)
         usedLength:NULL
           encoding:NSUTF8StringEncoding
            options:0
              range:NSMakeRange(0, length)
     remainingRange:NULL];

A: Use -[NSString UTF8String]:
NSString *s = @"Some string";
const char *c = [s UTF8String];

You could also use -[NSString cStringUsingEncoding:] if your string is encoded with something other than UTF-8.

Once you have the const char *, you can work with it similarly to an array of chars:
printf("%c\n", c[5]);

If you want to modify the string, make a copy:
char *cpy = calloc([s length]+1, 1);
strncpy(cpy, c, [s length]);
// Do stuff with cpy
free(cpy);

A: NSMutableArray *array = [NSMutableArray array];
for (int i = 0; i < [string length]; i++) {
    [array addObject:[NSString stringWithFormat:@"%C", [string characterAtIndex:i]]];
}

A: In Swift, a char array is bridged as an UnsafePointer<Int8>.  Accessing characters works the same way in Swift for an NSString:
let str: NSString = "hello"
let charStr = str.UTF8String // UnsafePointer<Int8>

For a Swift String object things are a little different:
let str = "hello"
let charStr = str.cStringUsingEncoding(NSUTF8StringEncoding)

charStr is [CChar]? where CChar is a typeailais for Int8.

A: We need to play NSString as a character array for working on coding practices which is otherwise much simpler to do in plain C coding. Using characterAtIndex: and  appendFormat: helps me. May be this will help.
NSString *str = @"abcdef";
NSMutableString *strResult = [NSMutableString string];

for (NSUInteger i = 0; i < [str length]; i++) {
  char ch = [str characterAtIndex:i];
  [strResult appendFormat:@"%c", ch];
}
NSLog(@"%@", strResult);


text:
Q: How to solve '[Errno 111] Connection Refused' in Django app on Heroku? I have just added a new app to my Django application, and everything was working fine locally. When I push it Heroku however, I get the following error when trying to access views from the new app, or admin pages related to it. The rest of the site is working fine.
Error (from the heroku application logs):
2017-02-15T10:14:13.305769+00:00 app[web.1]:     self.connection = connection_class(self.host, self.port, **connection_params)
2017-02-15T10:14:13.305769+00:00 app[web.1]:   File "/app/.heroku/python/lib/python2.7/smtplib.py", line 256, in __init__
2017-02-15T10:14:13.305770+00:00 app[web.1]:     (code, msg) = self.connect(host, port)
2017-02-15T10:14:13.305770+00:00 app[web.1]:   File "/app/.heroku/python/lib/python2.7/smtplib.py", line 316, in connect
2017-02-15T10:14:13.305771+00:00 app[web.1]:     self.sock = self._get_socket(host, port, self.timeout)
2017-02-15T10:14:13.305771+00:00 app[web.1]:     return socket.create_connection((host, port), timeout)
2017-02-15T10:14:13.305771+00:00 app[web.1]:   File "/app/.heroku/python/lib/python2.7/smtplib.py", line 291, in _get_socket
2017-02-15T10:14:13.305772+00:00 app[web.1]:   File "/app/.heroku/python/lib/python2.7/socket.py", line 575, in create_connection
2017-02-15T10:14:13.305772+00:00 app[web.1]:     raise err
2017-02-15T10:14:13.305773+00:00 app[web.1]: error: [Errno 111] Connection refused

Settings
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ******

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
TEMPLATE_DEBUG = False

ALLOWED_HOSTS = ['*']

ADMINS = (
    (***, ***),
)

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'feed',
    'cv',
    'hon',
    'blog',
    'markdown_deux',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.security.SecurityMiddleware',
)

ROOT_URLCONF = 'Site.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'Site.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Parse database configuration from $DATABASE_URL

import dj_database_url
DATABASES['default'] =
dj_database_url.config(default=os.environ.get('DATABASE_URL'))

# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/

import os
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = 'staticfiles'
STATIC_URL = '/static/'

STATICFILES_DIRS = (
 os.path.join(BASE_DIR, '../../feed/static/'),
)

I couldn't find much documentation for this particular error, so any help would be much appreciated. What's going wrong? Let me know if there's any more information I can provide that would help.
Update: Regarding the first two comments, my 'application' is a static website apart from the django admin backend, and I'm not trying to send emails anywhere in my code. The page that generates the error logs above is just the homepage of a simple blog, listing all the posts (of which there currently are none, because I'm unable to add any).

A: I'm not sure what the cause was, but this issue resolved itself after I made a dummy-change to one of the files (adding a space at the end of a line), and re-pushed the application to Heroku.


text:
Q: Do not delete *edited* vote-to-close auto-comments The autocomment when voting to close feature says:

Once the question is closed (even if it is not closed as a duplicate), these comments are deleted and the duplicate information is automatically edited into the question itself.

I'd suggest to check if a comment was edited, before deleting it this way. Sometimes I dislike the standard message and add additional information to it ... but unfortunately all I wrote gets deleted.

A: If you don't want the comment deleted, make sure it doesn't begin with "possible duplicate of"

A: ...or, to avoid editing, simply make "Community" the owner of those comments? (Some would rather not have their name attached to such auto-comment, for some vote-privacy until the question is closed, and hence it's proven that others agree.)


text:
Q: Error when accesing binance API with Delphi I am trying to do a small application (hello world for start) for accesing binance API with Delphi 10.3 using TRESTClient.
Here is the code:
procedure TfrmMain.btnInfoClick(Sender: TObject);
var workStream     : TStringStream;
    workResponse   : TStringStream;
    responseObject : ISuperObject;
    serverTIME     : Int64;
begin
  mDEBUG.Lines.Clear;
  try
    workStream   := TStringStream.Create;
    workResponse := TStringStream.Create;

    restCLIENT_MAIN.ResetToDefaults;
    restREQUEST_MAIN.ResetToDefaults;
    restRESPONSE_MAIN.ResetToDefaults;
    restCLIENT_MAIN.BaseURL := API_URL;
    serverTIME              := GetAPI_TIME;
    restREQUEST_MAIN.Resource       := '/sapi/v1/broker/info';
    restREQUEST_MAIN.ResourceSuffix := 'timestamp=' + serverTIME.ToString + '&signature=' + SECRET_KEY;
    restREQUEST_MAIN.Method         := TRESTRequestMethod.rmGET;
    restREQUEST_MAIN.AddParameter('Content-Type', 'application/json');
    restREQUEST_MAIN.AddParameter('X-MBX-APIKEY', CLIENT_KEY);
    restREQUEST_MAIN.Execute;
    workResponse   := TStringStream.Create(restRESPONSE_MAIN.JSONText);
    responseObject := TSuperObject.ParseStream(workResponse, True);
    if responseObject <> nil then begin
      mDEBUG.Lines.Add(responseObject.AsString);
    end else begin
      mDEBUG.Lines.Add(restRESPONSE_MAIN.Content);
    end;
  finally
    mDEBUG.Lines.Add('');
    mDEBUG.Lines.Add('restCLIENT_MAIN.BaseURL:' + restCLIENT_MAIN.BaseURL);
    mDEBUG.Lines.Add('restREQUEST_MAIN.Resource:' + restREQUEST_MAIN.Resource);
    mDEBUG.Lines.Add('restREQUEST_MAIN.ResourceSuffix:' + restREQUEST_MAIN.ResourceSuffix);
    FreeAndNil(workStream);
    FreeAndNil(workResponse);
  end;
end;

The result is:
Whitelabel Error PageThis application has no explicit mapping for /error, so you are seeing this as a fallback.Thu Apr 01 17:32:16 UTC 2021There was an unexpected error (type=Not Found, status=404).No message available
restCLIENT_MAIN.BaseURL:https://api.binance.com/
restREQUEST_MAIN.Resource:sapi/v1/broker/info
restREQUEST_MAIN.ResourceSuffix:timestamp=1617298336054&signature=<SECRET_KEY>

However form POSTMAN the result is different:
Because I cannot send the correct time (less than 1 second window of opportunity) I suspect that potman will always give me this kind of error.
{
    "code": -1021,
    "msg": "Timestamp for this request is outside of the recvWindow."
}

anyone can guide me?


text:
Q: Get user console input before user hitting enter I have a quite simple problem.
I want to get some console input from a user (without an enter press at the end) and do something with it right away.
I quickly saw that the input() function from python would not work. I thought maybe you could write something like this:
sys.stdout.write("Input: ")

while True:
    line = sys.stout.readline()
    // Do something with the lines

But unfortunately it does not work because stdout is not readable. With stdin it does not work either because it waits for a enter press of the user.
Is it somehow possible to get lines without the user submit it?

A: You can get input from console interactively in byte format instead of getting a string with input command.
import sys
while True:
   c = sys.stdin.read(1) # Read one byte

A: Here is what you might be looking for.
To get this working you will need to use pip install keyboard in the command line first.
import keyboard

while True:
    key_pressed = keyboard.read_key()
    print(f'You pressed {key_pressed}.')


text:
Q: Silverlight Bing map question I am planning to use Silverlight control for bing map. It will be used in a ASP.Net website.
Note: I am new to Silverlight and Bing map.
How the Silverlight bing map control will behave? Will the bing map service be called from the client browser or the web server?
Is there any architecture diagram related to this?
Please help.
Thanks
Lijo Cheeran Joseph

A: A good place to start is on the following link:
http://www.microsoft.com/maps/product/faq.aspx

A: I do not know about any architecture diagrams.  With the Silverlight control (the preferred control at this point, over the old AJAX control), the map service is called from the client browser...it is called from within the Silverlight application that hosts the map control, which like all Silverlight applications, runs exclusively on the client.
You could make calls to the Bing web services server-side, then use that data in some way, but if you're going after an interactive map, you will want the Silverlight control.


text:
Q: I am trying to install replit Collecting pycryptodomex<4.0.0,>=3.12.0 (from pyseto<2.0.0,>=1.6.11->replit)
Using cached https://files.pythonhosted.org/packages/3d/07/cfd8f52b9068877801317d26dc7225e19421bc659e1395d2cd6933b1a351/pycryptodomex-3.17.tar.gz
ERROR: Command errored out with exit status 1:
command: 'c:\program files\python38\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\bibhaw.raj_embibe\AppData\Local\Temp\pip-install-o93jw6q6\pycryptodomex\setup.py'"'"'; file='"'"'C:\Users\bibhaw.raj_embibe\AppData\Local\Temp\pip-install-o93jw6q6\pycryptodomex\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' egg_info --egg-base pip-egg-info
cwd: C:\Users\bibhaw.raj_embibe\AppData\Local\Temp\pip-install-o93jw6q6\pycryptodomex
Complete output (31 lines):
Traceback (most recent call last):
File "c:\program files\python38\lib\site-packages\setuptools\msvc.py", line 489, in _find_latest_available_vc_ver
return self.find_available_vc_vers()[-1]
IndexError: list index out of range
During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "C:\Users\bibhaw.raj_embibe\AppData\Local\Temp\pip-install-o93jw6q6\pycryptodomex\setup.py", line 488, in <module>
    set_compiler_options(package_root, ext_modules)
  File "C:\Users\bibhaw.raj_embibe\AppData\Local\Temp\pip-install-o93jw6q6\pycryptodomex\compiler_opt.py", line 327, in set_compiler_options
    clang = compiler_is_clang()
  File "C:\Users\bibhaw.raj_embibe\AppData\Local\Temp\pip-install-o93jw6q6\pycryptodomex\compiler_opt.py", line 251, in compiler_is_clang
    return test_compilation(source, msg="clang")
  File "C:\Users\bibhaw.raj_embibe\AppData\Local\Temp\pip-install-o93jw6q6\pycryptodomex\compiler_opt.py", line 82, in test_compilation
    objects = compiler.compile([fname], extra_postargs=extra_cc_options)
  File "c:\program files\python38\lib\distutils\_msvccompiler.py", line 360, in compile
    self.initialize()
  File "c:\program files\python38\lib\distutils\_msvccompiler.py", line 253, in initialize
    vc_env = _get_vc_env(plat_spec)
  File "c:\program files\python38\lib\site-packages\setuptools\msvc.py", line 185, in msvc14_get_vc_env
    return EnvironmentInfo(plat_spec, vc_min_ver=14.0).return_env()
  File "c:\program files\python38\lib\site-packages\setuptools\msvc.py", line 843, in __init__
    self.si = SystemInfo(self.ri, vc_ver)
  File "c:\program files\python38\lib\site-packages\setuptools\msvc.py", line 485, in __init__
    self.vc_ver = vc_ver or self._find_latest_available_vc_ver()
  File "c:\program files\python38\lib\site-packages\setuptools\msvc.py", line 492, in _find_latest_available_vc_ver
    raise distutils.errors.DistutilsPlatformError(err)
distutils.errors.DistutilsPlatformError: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/
Testing support for clang

I am trying to install replit but facing error. I have also updated zthe full controll in java.


text:
Q: How to show the following vector bundles are equivalent? Given a smooth sub-manifold $X$ of $\mathbb{R^n}$ and define the diagonal in $X \times X$ to be
$$\triangle = \{(x,x) \mid x \in X \} \subset \mathbb{R^n}\times \mathbb{R^n}$$
and normal bundle to $\triangle$ is defined to be
$$N(\triangle)=\{(y,w) \mid y\in \triangle, w\in T_y(X\times X) \text{ such that } w \cdot v =0 \text{ for all } v \in T_y(\triangle)\}$$
with projection $\pi : N(\triangle) \to \triangle$ given by $(y,w)\mapsto y$
Then we want to show that $N(\triangle)$ is equivalent to the tangent bundle $TX$.
I know (by definition of equivalent) that two vector bundles said to be equivalent if there are diffeomorphisms $$f:TX \to N(\triangle) \text{ and }\tilde{f}:X \to \triangle$$
such that $f$ takes each fibre $TX_x$ to $N(\triangle)_{\tilde{f}(x)}$ by a vector space isomorphism.
What do I really need to do? Should I try to write down $f$ and $\tilde{f}$ and show that $f$ is an isomorphism on fibres?
Any help would be thankful.

A: Simply note that $TX=T\Delta=\{(y, w, w)\in T_y(X\times X)=T_yX\oplus T_yX, y\in\Delta\}$ and $N\Delta=\{(y, v, -v)\in T_y(X\times X), y\in\Delta\}$. Now the isomorphism between the two vector bundles can be easily constructed.


text:
Q: Android: Widget does not load content on creation I decided to create my first Android widget this weekend and although I have gotten it to work somewhat, it does not display the dynamically-loaded content until I rotate the device (using Launcher Pro Plus which allows landscape orientation and rotation of home screens).
The widget is pretty simple, it just retrieves an image from a website and displays the image. I created a service that is started in onUpdate() of the AppWidgetProvider subclass. The service then retrieves the image, builds the RemoteViews object and then calls updateAppWidget() on the AppWidgetManager.  Here is the code for the widget:
public class PropagationWidget extends AppWidgetProvider {

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
        int[] appWidgetIds) {
    context.startService(new Intent(context, UpdateService.class));
}
public static class UpdateService extends IntentService {

    public UpdateService() {
        super("PropagationWidget$UpdateService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        ComponentName me=new ComponentName(this,
                 PropagationWidget.class);
        AppWidgetManager mgr=AppWidgetManager.getInstance(this);

        mgr.updateAppWidget(me, buildUpdate(this));
    }

    public RemoteViews buildUpdate(Context context) {
        RemoteViews views = null;

        URL imageUrl = null;

        try {
            views = new RemoteViews(context.getPackageName(),
                    R.layout.widget_layout);

            imageUrl = new URL(
                    "http://www.mountainlake.k12.mn.us/ham/aprs/path.cgi?map=na&img=node&freq=144&type=image");

            InputStream is = (InputStream) imageUrl.getContent();
            Bitmap image = BitmapFactory.decodeStream(is);
            views.setImageViewBitmap(R.id.image, image);

            Time today = new Time();
            today.setToNow();

            views.setTextViewText(R.id.last_updated, "Last updated: " + today.format("%D %r"));
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return views;
    }
}

When the widget loads, I only get the frame of the widget, but no content, which makes sense because UpdateService still hasn't retrieved the image from the website yet. However, even after UpdateService has finished retrieving the image and immediate calls updateAppWidget(), the image still does not appear. When I rotate the device, however, the image appears, and will remain upon subsequent rotations.
Also too, the widget is set in the appwidget-provider XML to update every 30 minutes. These updates do not show up until I rotate the device, and when the widget is redrawn, I then see the update.
Is there something really basic here that I'm missing?  Any insight would be greatly appreciated! Please let me know if I should provide any additional information to help with this.

A: I am doing something similar and my UpdateService updates the widget like this:
        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getApplicationContext());int [] appWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(getApplicationContext(),WidgetProvider.class));
        for (int i=0; i<appWidgetIds.length; i++)
        {
            RemoteViews views = new RemoteViews(getApplicationContext().getPackageName(),
                    R.layout.widget_layout);

            //Set Image Resource/Bitmap from Web here like: remoteViews.setImageViewBitmap(viewId, bitmap);

            appWidgetManager.updateAppWidget(appWidgetIds[i], views);
        }

But keep in mind that frequent updates of a widget might drain the battery too fast.


text:
Q: How does this example of passing arrays by reference work in Perl? I was looking on a post on how to pass arrays (or lists) with scalars when I stumbled upon this S.O. post... Passing By Value - S.O.
I found that the chosen answer solution worked, but since I am trying to learn Perl I would like to know how it worked. In this line
my($inVal, $inValTwo, $inArray, $inArrayTwo) = @_;

I see that the author is placing the input parameters that were passed to the sub program into scalar variables. Then, in this line
@{$inArray}

he said to "use the reference as arrays". What did he mean by this and what exactly is going on in the second line? I have not seen those operators combined like that.

A: The first thing to keep in mind is that arrays and lists are not the same.
A reference is a scalar that holds the memory address of something else - an array, hash, another scalar, etc. It's a fancy kind of pointer.
Subroutines in Perl take a list of arguments (and return a list of results.) This is a common stumbling block when you want to do something like
mysub( @foo, @bar )

and then you realize that the elements of @foo and @bar got flattened into a single list in your subroutine. If you know the size of @foo ahead of time you can just grab the right number of elements off the beginning of the list, but usually you don't.
References can solve this problem, since they are scalars. If you pass references to @foo and @bar, you know that your subroutine will always have two parameters to deal with, regardless of the sizes of the referant arrays.
But we still need to get at the data in those arrays. To do that, we have to tell Perl to go get the thing that the references are pointing to. This is called dereferencing.
In Perl, there are two common ways to dereference an array reference:

*

*To get the whole array, use my @array = @$ref;

*To get an element in the array, use my $elem = $ref->[42].

Note that the first example is sometimes written @{ $ref }, but the extra curlies are not required unless you need to disambiguate some nested structure. Some people prefer to always use the extra curlies but I find that they add clutter and are usually unnecessary.
For more on the exciting topic of references, check out

*

*Perl reference tutorial

*Perl reference reference

*Perl data structures cookbook

A: In perl, you pass a list of scalars to subroutines.
Scalar values can be:

*

*A primitive data type ie. String, Int, double

*A reference to an array.

*A reference to a hash

So when calling a subroutine, you can pass an entire array (because an array is a list of scalars)
my @list = (1, 2, 3);

#note the variable declaration being surrounded by parenthesis.
#that says use list context
sub getList {
    my ($foo, $bar, $baz) = @_; #(@_ is the list you passed to the sub)
}

Now, if you have 2 lists you want to pass to a subroutine, you can't do
getList(@listA, @listB);

Because the two lists will be flattened into a single array contained in @_.
So, to get around this, you use a reference, or pass the array as a reference.
my $first_list = \@listA #this points $first_list to a reference in
                         #memory where @listA is located.

getList($first_list, \@listB);

sub getList {
    my ($foo, $bar) = @_; #$foo and $bar now point to @listA and @listB

    #To dereference these, you either have to use the -> operator to access
    #Elements, or use the form @{ }. %{ } for hashes.

    my @listA = @{ $foo };
    my @listB = @{ $bar };

    #Now they are regular arrays again!
}


text:
Q: Rolling Back Repository to specific Revission I have a problem with a repository. I pulled a a list of changesets from another repository, ran the update and merged... The merge didn't work as expected and now I need to roll back to before I pulled the changesets just to pull them again.
How can I roll back more than one changeset into a specific revision?

A: If by "roll back" in this context you mean to get rid of the changesets as though you never pulled, then you can use the "strip" function part of the MQ extension.
First enable the MQ extension by editing your .hgrc (*nix) or mercurial.ini (Windows) file:
[extensions]
mq=
Then use the strip command:
hg strip REV

Warning: This will remove the changeset with the given revision hash, and any changesets that follows from that. If you're unsure about what you want to accomplish or how to use the command, make a clone of the repository before you try it, that way you can safely experiment.
Also note that if you've already pushed your merge somewhere else, you have cleanup to do in that repository as well, and depending on whether the merge is "in the wild", it might not be possible to permanently get rid of it.

A: Rollback isn't what you're describing.  If before the pull your repo looked like this:
[A]-[B]-[C]-[D]

and after the pull it looked like:
[A]-[B]-[C]-[D]
          \
           -[E]-[F]

and after the merge it looked like this:
[A]-[B]-[C]-[D]-----[G]
          \        /
           -[E]-[F]

then you don't want to undo the pull -- you still want changesets E and F -- you just want to take another try at the merge, G.
There are a few ways to do that.  The most Mercurial way to do that is to just do:
hg update D
hg merge E
... re-merge, doing it better this time ...
hg commit # creates H

Then your history will look like:
[A]-[B]-[C]-[D]-------- [G]
          \          X
           -[E]-[F]-----[H]

where that X is a crossing.  You'd then use H as your new point of development and ignore (or close G).
Second best it to remove G and then re-do the merge.  The official way to do that is to clone your repository locally getting everything except G like this:
cd ..
hg clone -r tip-1 myrepo mynewrepo

where you'll then have everything in mynewrepo except for G.  You can then re-merge.  The strip command also works, but it's disabled for a reason.
The bottom line is you don't need to remove and redo the pull; just the merge.

A: I haven't really used mercurial, only really CVS and SVN, but it should be the same. I'm presuming that you can checkout an older version based on the revision number or date, correct? If so, check out the older version in a temporary directory and re-merge that. You will need to delete any new files added in the repository though as well. That way you should effectively have the same copy of the files as 2 or more revisions ago.
This will have the same effect as rolling back, though it will be a higher revision number. The same contents, just a newer revision. I think this is the safest way to do it, as there's no way of loosing anything.

A: If you want to return to a specific revision and discard all local changes, you can simply update to the revision and pass the clean flag:
hg up -C -R 7

This line discards uncommitted changes and reverts to revision 7, as an example.


text:
Q: Install biomaRt package I am trying to install this package and I get this warning message
install.packages("biomaRt", repo="http://r-forge.r-project.org")
install.packages("biomaRt", type="source")
library("biomaRt")

  package 'biomaRt' is not available (for R version 3.2.2)
Warning in install.packages :
  cannot open: HTTP status was '404 Not Found'
Warning in install.packages :
  cannot open: HTTP status was '404 Not Found'
Warning in install.packages :
  unable to access index for repository http://r-forge.r-project.org/bin/macosx/mavericks/contrib/3.2

Can you please help me? Thanks

A: Found out:
source("https://bioconductor.org/biocLite.R")
biocLite("biomaRt")
library("biomaRt")


text:
Q: UIDocumentMenuViewController blank Options I have a problem with iCloud file import
I'm getting empty options after I choose the place to import from (iCloud, google drive, dropbox ... etc)
I have data on iCloud drive and the entitlements are right
So what is wrong with this code or is there anything about the settings may cause this problem?
here is the code
@IBAction func selectionButtonAction(_ sender: Any) {

        let types = [kUTTypePDF as String ,kUTTypePNG as String, kUTTypeImage as String,kUTTypeJPEG as String]
        UINavigationBar.appearance().isTranslucent = true
        let documentMenu = UIDocumentMenuViewController(documentTypes: types, in: .import)
        documentMenu.delegate = self
        self.viewController?.present(documentMenu, animated: true, completion: nil)
    }

    func documentMenu(_ documentMenu: UIDocumentMenuViewController, didPickDocumentPicker documentPicker: UIDocumentPickerViewController) {
        documentMenu.delegate = self
        self.viewController?.present(documentMenu, animated: true, completion: nil)
    }

    func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
        if controller.documentPickerMode == .import {
// do staff
        }
    }

Here is what I get When I run the app on iOS 10
When I Press choose File

then after pressing on iCloud

That's what I get if I run the app on iOS 9:

I'm sure I have data there like here in the iCloud Drive application

And the entitlement

A: I had the same problem, when trying to present a already used Instance of the UIDocumentMenuViewController.
I was instantiating it lazily like this:
lazy var documentMenuController: UIDocumentMenuViewController = {
    let controller = UIDocumentMenuViewController(documentTypes: ["com.adobe.pdf"], in: .import)
    controller.delegate = self
    return controller
}()

Which produced this error every time except the first time.
So I changed the code to this:
var documentMenuController: UIDocumentMenuViewController {
    let controller = UIDocumentMenuViewController(documentTypes: ["com.adobe.pdf"], in: .import)
    controller.delegate = self
    return controller
}

To obtain a fresh instance on every access of the property.


text:
Q: How to get error code from eslint when running in pre-commit hook? I have this in my .git/hooks/pre-commit:
npx eslint --max-warnings 1 --exit-on-fatal-error $(git diff --name-only HEAD **/*.ts | xargs)

status=$?

if [ $status -eq 0 ]
then
  echo "Good"
  exit 2
fi

if [ $status -eq 1 ]
then
  echo "Bad"
  exit 2
fi

if [ $status -eq 2 ]
then
  echo "Worse"
  exit 2
fi

It always prints "Good", even if I have a valid ESLint error. I can tell the ESLint errors out when I run it directly on the CLI, it outputs stuff like:
$ npx eslint --max-warnings 0 --exit-on-fatal-error make/link/fold/index.ts

./make/link/fold/index.ts
  325:14  error  Expected a default case  default-case

✖ 1 problem (1 error, 0 warnings)

How do I capture the error from eslint and prevent the commit from happening if there is an error?
I have never really done this before, always used it in other peoples projects, trying to configure now. Tried for a while, no luck.

A: What I would do:
while read -r ts; do
  npx eslint --max-warnings 1 --exit-on-fatal-error "$ts"
  status=$?

  case $status in
    0)
      echo "Good"
      exit 0
    ;;
    1)
      echo "Bad"
      exit 1
    ;;
    1)
      echo "Worse"
      exit 2
    ;;
    *)
      echo "WTF ?!"
      exit 3
    ;;
  esac
done < <(git diff --name-only HEAD **/*.ts)

The case statement lets you match a word against several patterns and execute commands based on which one matches. See http://mywiki.wooledge.org/BashGuide/TestsAndConditionals#Choices and http://wiki.bash-hackers.org/syntax/ccmd/case and 'case word in' in man bash.