Q: Can one cast an EnvDTE.Project into a VCProject I have seen two posts so far that concern my question. I am wondering how can one cast an EnvDTE.Project into a VCProject.
In this post, fun4jimmy's answer does that exactly in the following line of code (taken from his answer) :

VCProject vcProject = project.Object as VCProject;

I have tried doing the same thing in my solution :
using EnvDTE;
using Microsoft.VisualStudio.VCProjectEngine;
[...]
private List<string> BuildAssembliesAndReturnTheirName(EnvDTE80.DTE2 dte)
{
    Solution sln = dte.Solution;

    bool isDirty = false;
    foreach (Project project in sln.Projects)
    {
        VCProject vcProject = project.Object as VCProject;
        Configuration activeConfiguration = project.ConfigurationManager.ActiveConfiguration;
        foreach (VCConfiguration vcConfiguration in vcProject.Configurations)
        {
            //business logic
        }
    }
[...]

A solution is opened in VS. The solution contains a few C# projects. Everything seems to be in order for this code to execute until I reach
foreach (VCConfiguration vcConfiguration in vcProject.Configurations)

only to realise that this cast
VCProject vcProject = project.Object as VCProject;

returns null.
Can anyone tell me why that is? I've seen this post in which hveiras suggests

There is a VCCodeModel.dll for each VS version.

If that's the case for VCProjectEngine.dll as well, how can I fix my issue?
I have changed my reference to VCProjectEngine.dll so that it uses the one for Visual Studio 2012 (what I'm working with) but vcProject remains null.

A: VCProject is for C++ projects, in order to use a similar interface with C#/VB project you'll have to use VSProject.
There are a number of VSLangProj overloads/extensions and you'll have to find the one that is specific to the version you need to use. See: https://msdn.microsoft.com/en-us/library/1xt0ezx9.aspx for all the VSLangProj interfaces from 2 through 100 (I think thats Version 2 through Version 10).

A: You can't cast the Project object itself, because there's no inheritance relationship.
But you can use the inner object:
VCProject vcProject = project.Object as VCProject;


Q: Why some members are unable to participate at war? When I tried to initiate a 10x10 clan war (I was the clan leader), it appears that 2 members of my clan couldn't participate.
Why does that occur?

A: There could be two reasons. Either the amount of people in your clan is not a multiple of five, or some of your clan members are ineligible for war.
Not a multiple of five

Clan wars matchmaking will only match clans of similar sizes, and a few members (between 1-4 per clan) may be put into spectator mode when the clans are matched to even out team sizes. The members in spectator mode will be those with the lowest trophy count in their clan (or those who are ineligible for war).
10 vs 10 members is the smallest possible team size for a clan war. Other possible team sizes are: 15 vs 15, 20 vs 20, 25 vs 25, 30 vs 30, 35 vs 35, 40 vs 40, 45 vs 45 and 50 vs 50.

Ineligible for war
Sometimes you will have a clan member that is ineligible for war and cannot participate:

Members who are new to your clan will be ineligible for war if they left their previous clan while a war was in progress. They will become eligible for war again when the previous war is completed. You can check your clan member list to see if any members are ineligible for war, and see when they will be eligible again. If you start the clan war while members are still ineligible, those members will not be able to participate.

Quotes from the "Clan Wars FAQ" page on the wiki.


Q: Improving a workflow for importing BibTeX citations I am hoping to draw upon the expertise of other LaTeX/BibTeX user to help improve a common workflow of mine.
Currently, I download and import BibTex citations from the likes of IEEE/Springer/ScienceDirect and then cut and paste the citation into JabRef.  That is, it goes something like this:

*

*(In firefox) IEEE/Springer/Whatever -> Export as BibTeX

*Open export.bib in gedit

*Create new article in JabRef

*Copy-paste citation text from gedit into Jabref.

Trying to open the export.bib file into Jabref has it open the BibTeX file as a new database and I have to copy and paste the citation anyway.
I would like to improve this workflow to a one-click "Open With" when I save the .bib from Firefox and it gets added to my BibTeX database.
I currently use JabRef, but would be willing to switch BibTeX managers if something else (in Linux) offers this feature.  Of course, a script with cat $FILE >> /path/to/my_database.bib might work, but I then still have to find that reference to link it to the paper I just saved :)

A: Here is my workflow.

*

*Get the DOI of the article to cite. You find the DOI on the download page of the paper and it is also usually printed on the first page of the paper.

*Paste the DOI into the Jabref search plugin DOI to BibTeX and press "fetch".

*You will get a "list" of the search results, which is in most cases only one item. Click "OK" to import them.

*Check the new entry in your bib file.

The benefit is that you need less time to import a new article. The DOI is also often easier to spot then the Export button on the web page.

A: I typically create a BibTeX file with very basic information, e.g., just the title,
@article{ocv,
  title={The optimal centroidal Voronoi tessellations and the gersho's conjecture in the three-dimensional space},
}

and then run betterbib on it:
betterbib my.bib out.bib

%comment{This file was created with BetterBib v2.1.0.}

@article{ocv,
  author = {Du, Qiang and Wang, Desheng},
  publisher = {Elsevier BV},
  doi = {10.1016/j.camwa.2004.12.008},
  title = {The optimal centroidal Voronoi tessellations and the gersho's conjecture in the three-dimensional space},
  url = {http://dx.doi.org/10.1016/j.camwa.2004.12.008},
  journal = {Computers & Mathematics with Applications},
  number = {9-10},
  month = may,
  volume = {49},
  source = {CrossRef},
  year = {2005},
  pages = {1355-1373}
}

A: Today there is a AddOn for Firefox called JabFox. It uses functionality of Zotero (which should be installed) to 1-click-import things into JabRef. Works fine.

A: If you have the BibTeX-Code available and copy that to your clipboard (either by opening the export.bib or by copying it from the homepage) and you click on the JabRef window (so that it has the focus) you can just paste (Ctrl+V) it as a new entry.
I knew that from BibDesk (Mac OS) which I am using and found the same for JabRef here http://sourceforge.net/projects/jabref/forums/forum/318825/topic/1653744

A: You can set up Jabref to automatically import a reference from Firefox into the current database, but it's somewhat arcane. Here is my solution under Linux:
1) Select Options -> Preferences -> Advanced -- and check "Listen for remote operation ..." I don't think it matters which port.
2) Create a small bash script (text file) named "jabref-import" that looks like this:
#!/usr/bin/env bash
java -jar ~/local/jabref/JabRef-2.8.1.jar -i --importToOpen "$*"

Replace "~/local/jabref/JabRef-2.8.1.jar" with the path to your Jabref .jar file on your machine. Or if you have a working executable called "jabref", you can replace everything before the "-i" with "jabref". Just make sure your executable accepts command-line options (mine didn't).
In Ubuntu 13.04, the following variant of the script works:
#!/usr/bin/env bash
jabref -i --importToOpen "$*"

3) Make the file executable:
chmod ugo+x jabref-import

4) Make sure Jabref is already open. Go to Firefox, download a citation file. It could be a .bib or .ris or .ref or whatever. Select the "Open with..." option in the dialog, and select the jabref-import executable that you just made. The import dialog should pop up in Jabref with your citation.

A: My answer is a variation to Damien's for KDE (4.14):
1) the same - check "Listen for remote operation ..."
2) Go to the KDE System settings > File Assosiations.
3) Create new file type (button "+ Add..." in the bottom):

*

*group - text

*type name - bibliography
4) Select bibliography and in the right part of window "Add...":

*

*Filename Patterns: *.ris, *.bib, *.ref, *.enw and so on.

*Application Preference Order: Education > Science > JabRef(or write here command like /usr/local/bin/jabref %f - this is for
PC-BSD)

5) Apply.
Now you can click on file in browser and select "Open..." - import window will arise (you should start JabRef firstly!).


Q: Is it possible to retrieve a Javascript file from a server? In Python, I can retrieve Javascript from an HTML document using the following code.
import urllib2, jsbeautifier
from bs4 import BeautifulSoup

f = urllib2.urlopen("http://www.google.com.ph/")

soup = BeautifulSoup(f, "lxml")
script_raw = str(soup.script)

script_pretty = jsbeautifier.beautify(script_raw)
print(script_pretty)

But how about if the script comes from a Javascript file on the server, like:
<script src="some/directory/example.js" type="text/javascript">

Is it possible to retrieve "example.js"? If so, how?
Context: I'm examining the Javascript of phishing web pages.

A: <script src="some/directory/example.js" type="text/javascript">

the code above will get some/directory/example.js from server
you just make folders and file structure follow the pattern above

A: The easiest way is to right click on that page in your browser, choose page script, click on that .js link, and it will be there.

A: If you want to load at run time, like some part of your javascript is dependent on other javascript, then for loading javascript at run time, you can use require.js .


Q: Switching Permissions of User Files I am new to Bash and trying to write a find command that finds all files that don't have read, write, or execute permissions for the user, and then changes the mode to enable read access.
I've tried a few different ways including:
find . ! -perm /u+rwx | -exec chmod u+r {} \;
Am I on the right track?


Q: how to get the file sent in xml response in perl? Using the LWP user agent I am sending the request and getting the response.
I will get the response in html format and a file attached in it.
eg:
     `

      <title>Download Files</title>
      <meta http-equiv=\'Content-Type\' content=\'text/html; charset=utf-8\'>
      <link rel=\'stylesheet\' href=\'http://res.mytoday.com/css/main.css\' type=\'text/css\'>
      <link rel=\'stylesheet\' href=\'http://res.mytoday.com/css/Menu.css\' type=\'text/css\'>
      <link rel=\'stylesheet\' href=\'/statsdoc/freeze.css\' type=\'text/css\'>

      No.
      File Name
      File Size

      1
      1-1.csv.zip
     	487 bytes

     Download all
    `

From this response I need to get the file. Can anyone help me to get the file from response.

A: Use a parser to extract the information. I used XML::LibXML, but I had to remove the closing br tags that made the parser fail.
#!/usr/bin/perl
use warnings;
use strict;

my $html = '

      <title>Download Files</title>
      <meta http-equiv=\'Content-Type\' content=\'text/html; charset=utf-8\'>
      <link rel=\'stylesheet\' href=\'http://res.mytoday.com/css/main.css\' type=\'text/css\'>
      <link rel=\'stylesheet\' href=\'http://res.mytoday.com/css/Menu.css\' type=\'text/css\'>
      <link rel=\'stylesheet\' href=\'/statsdoc/freeze.css\' type=\'text/css\'>

      No.
      File Name
      File Size

      1
      1-1.csv.zip
     	487 bytes

     Download all
    ';

use XML::LibXML;
my $dom = 'XML::LibXML'->load_html( string => $html );
print $dom->findvalue('/html/body/table/tr[2]/td[2]/a/@href');

You could also use the recover flag to parse invalid HTML:
my $dom = 'XML::LibXML'->load_html( string => $html, recover => 1 );


Q: Failed to use Apache RewriteRule I would like to use Apache RewriteRule to change the URL target page to abc.php. I have set RewriteEngine On but I found this problem.
Regexp I used:
RewriteRule ^viewthread\.php.tid=12345$ abc.php

The URL string to match:
viewthread.php?tid=12345

Why it is not successfully matched?

A: Rewriting URLs with query strings is slightly more complicated than rewriting plain URLs. You'll have to write something like this:
RewriteCond %{REQUEST_URI}  ^/viewthread\.php$
RewriteCond %{QUERY_STRING} ^tid=12345$
RewriteRule ^(.*)$ http://mydomain.site/abc.php [R=302,L]

See those articles for more help:

*

*http://www.simonecarletti.com/blog/2009/01/apache-query-string-redirects/

*http://www.simonecarletti.com/blog/2009/01/apache-rewriterule-and-query-string/

A: i think because you have missed the ? in the rule...
RewriteRule ^viewthread.php?tid=12345$ abc.php

A: Shouldn't it be:
RewriteRule ^/viewthread\.php\?tid=12345$ /abc.php


Q: LTSPICE - How to create PWM with rise time A simple PWM circuit is simple to create using LTSPICE, such as:
VIN VSIN 0  SIN(0 1 10 0 0)
 VP VTRI 0 PULSE(-1.5 1.5 0 9.998m 1u 1u 10m)
 B1 VOUT 0 V=U(V(Vtri)-V(Vsin))*5

But voltage reflection simulations, i need the PWM rising edge to be more realistic, i.e. with a time delay on the rising edge like this:

I have tried using a PULSE, but its frequency and on-time is fixed.
What I need is something that activates a given pulse, or a behavioral voltage source that can create a pulse if a certain condition is true. The pulse has to be as long as the condition is true - as with conventional PWM.
An example of what I have tried, but which caused a syntax error:

The syntax error is that in the B2-element (to the right), cannot use "V1" as voltage output. It has to be 5 (volts) or something.
How to I solve this? I just started using SPICE two days ago, and I bet there is a few tricks I am not aware of yet

A: The proposed methods will work, but you're much better off using a dedicated element for this job: [Digital]/diffschmitt:

You can specify separate rise and fall times through trise and tfall. For more about it, see the help, LTspice > Circuit Elements > A. Special functions.

A: Try using a piece-wise linear voltage source (in the advanced dialog).
This uses a time-value pair sequence and can be defined in the source dialog or from a file.
LTSpice will interpolate from a given pair to the next in a linear fashion.
If I start with time=0 and v=0 and the next pair is at time=1m with v=3, then you will get a rising signal at 3v/millisecond.
Add more points to get the precise wavrform you want.
This is incredibly useful when you have measured a waveform and saved it from a scope to do what-if analysis with a circuit in the simulator, to name at least one other application.

A: This works for me.

I had to change the prefix to BV for [B]V4. And also use net names; it doesn't seem to take the voltage sources' names in those behavioral expressions.

What I need is something that activates a given pulse, or a behavioral voltage source that can create a pulse if a certain condition is true.

What you seem to actually want however is a PWL triggered ramp like so:

Also what you're describing is not actually called PWM. If you somehow need to modulate the width instead of triggering then see this solution.

Well assuming you only want non-zero rise (as in your graph) but zero fall time, and you want that combined with PWM, then you basically have to combine the above two solutions:


Q: unable to create sqlite database in Android i have class CreateDB
public class CreateDB extends SQLiteOpenHelper{   // SQLiteOpenHelper auto create if db not exists.

    private static final int DB_VERSION = 1;
    private static final String DB_NAME = "mydb.db";

    public CreateDB(Context ctx) {
        super(ctx, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE friends (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, phonenumber INTEGER);");
    }}

i call createdb in another class which act as background thread
public class manager extends AsyncTask<Void, Void, String> {

 public  Context context;

    @Override
    protected String doInBackground(Void... params) {

        CreateDB dbhelp = new CreateDB(context);
}

}
when i run it then it stop working and emulator give error that app stop responding
but when i run `CreateDB dbhelp = new CreateDB(this);   in main activity then it works and database is created .  so please help so that i can create database in background thread .

A:
but when i run CreateDB dbhelp = new CreateDB(this); in main
  activity then it works and database is created

Because you forgot to initialize your context object in your AsyncTask.
public class manager extends AsyncTask<Void, Void, String> {

 public  Context context; <-- Declared but not initialized

    @Override
    protected String doInBackground(Void... params) {

        CreateDB dbhelp = new CreateDB(context);
}

You could create a constructor for your AsyncTask :
public manager(Context context) {
   this.context = context;
}

And then in your activity :
new manager(this).execute();

Also try to respect name conventions.

A: You need to pass valid context as a parameter:
CreateDB dbhelp = new CreateDB(getContext());


Q: Dispatch all methods in class C# Is there any way to dispatch all methods in class in easy way?
For example my class is a adapter for UI items and contains static methods.
So instead of dispatching all methods separately in class, it could be done like this: Who ever is calling a method from this class, everything is dispatched through UI thread.
Like from:
public MyClass
{
   ...

   public static void Method1
   {
      Application.Current.Dispatcher.Invoke(() =>
      {
          /* do something */
      }
   }

   public static bool Method2
   {
      return Application.Current.Dispatcher.Invoke(() =>
      {
          return UIitem.SomeProperty;
      }
   }
}

To this:
[DispatcherAttribute] /* or something similar */
public MyClass
{
   ...

   public static void Method1
   {
      /* do something */
   }

   public static bool Method2
   {
      return UIitem.SomeProperty;
   }
}


Q: Convergence of solutions from a 1st order ODE Given the following initial value problem
$$\left\{\begin{array}{l}x'(t)+p(t)x(t)=g(t) \\ x(0)=1 \end{array}\right.$$
I have to find $p(t)$ and $g(t)$ such that the solutions $x(t)$ converge to $0$ when $t\to+\infty$
Using the integrating factor, I didn't find anything that I think it could help me - just $x(t)$ written as integral of $e^{p(t)}$ etc. On Google, the articles I found are in a high level that I can't understand.
My question is: is there a simple way to make it? Or should I just try to get some functions, like $p(t)=x^2$ and $g(t)=1$ and solve the problem and evaluate the limit?

A: If I understood you question correctly, one can determine a relation between $p(t)$ and $g(t)$ by setting $x(t) = e^{-t}$ in the equation you get
$$
- e^{-t} + p(t) e^{-t} = g(t)
$$
Obviously $x(t) \to 0$ as $t \to \infty$ and $x(0) = 1$ as the boundary conditions. Set for example $p(t) = x^2$ you get
$$
g(t) = (p(t) - 1)e^{-t} =  (x^2 - 1)e^{-t}
$$
Try setting $x(t) = e^{-t^2}$ in the equation you get
$$
- 2t e^{-t^2} + p(t) e^{-t^2} = g(t)
$$
you get
$$
g(t) = ( + p(t) - 2t) e^{-t^2}
$$
and as before $x(t) \to 0$ as $t \to \infty$ and $x(0) = 1$


Q: AppLocalizations missing reference - Internationalization - Flutter flutter_gen applocalizations missing reference in Visual Studio Code.

I already tried

*

*flutter upgrade

*flutter pub cache clean

*flutter clean / flutter pub get

*Dart: Restart Analysis Server (VS Code)

*Developer: Reload Window (VS Code)

My pubspec.yaml has

*

*generate: true

*flutter_localizations:sdk: flutter

A: Solution:

*

*My machine was with 2 flutter sdk installed. I unnistalled one, and everything worked again.


Q: how to use actors in akka client side websockets i am using akka client websockets https://doc.akka.io/docs/akka-http/current/client-side/websocket-support.html
i have a server which takes requests and respond in json
this is the pattern of my request and response
request #1

{
        "janus" : "create",
        "transaction" : "<random alphanumeric string>"
}
response #1
{
   "janus": "success",
   "session_id": 2630959283560140,
   "transaction": "asqeasd4as3d4asdasddas",
   "data": {
        "id": 4574061985075210
   }
}

then based on response #1 i need to initiate request #2 and upon receiving response #2 i need to initiate request #3 and so on
for example
then based on id 4574061985075210 i will send request #2 and receive it response
request # 2 {
 }

response # 2 {
}
----

how can i use the actors with source and sink and re use the flow
here is my initial code
import akka.http.scaladsl.model.ws._

import scala.concurrent.Future

object WebSocketClientFlow {
  def main(args: Array[String]) = {
    implicit val system = ActorSystem()
    implicit val materializer = ActorMaterializer()
    import system.dispatcher

    val incoming: Sink[Message, Future[Done]] =
      Sink.foreach[Message] {
        case message: TextMessage.Strict =>
          println(message.text)
//suppose here based on the server response i need to send another message to the server and so on do i need to repeat this same code here again ?????

      }

    val outgoing = Source.single(TextMessage("hello world!"))

    val webSocketFlow = Http().webSocketClientFlow(WebSocketRequest("ws://echo.websocket.org"))

    val (upgradeResponse, closed) =
      outgoing
        .viaMat(webSocketFlow)(Keep.right) // keep the materialized Future[WebSocketUpgradeResponse]
        .toMat(incoming)(Keep.both) // also keep the Future[Done]
        .run()

    val connected = upgradeResponse.flatMap { upgrade =>
      if (upgrade.response.status == StatusCodes.SwitchingProtocols) {
        Future.successful(Done)
      } else {
        throw new RuntimeException(s"Connection failed: ${upgrade.response.status}")
      }
    }
connected.onComplete(println)
    closed.foreach(_ => println("closed"))
  }
}

and here i used Source.ActorRef
   val url = "ws://0.0.0.0:8188"
    val req = WebSocketRequest(url, Nil, Option("janus-protocol"))

    implicit val system = ActorSystem()
    implicit val materializer = ActorMaterializer()

    import system.dispatcher

    val webSocketFlow = Http().webSocketClientFlow(req)

    val messageSource: Source[Message, ActorRef] =
      Source.actorRef[TextMessage.Strict](bufferSize = 10, OverflowStrategy.fail)

    val messageSink: Sink[Message, NotUsed] =
      Flow[Message]
        .map(message => println(s"Received text message: [$message]"))
        .to(Sink.ignore)

    val ((ws, upgradeResponse), closed) =
      messageSource
        .viaMat(webSocketFlow)(Keep.both)
        .toMat(messageSink)(Keep.both)
        .run()

    val connected = upgradeResponse.flatMap { upgrade =>
      if (upgrade.response.status == StatusCodes.SwitchingProtocols) {
        Future.successful(Done)
      } else {
        throw new RuntimeException(s"Connection failed: ${upgrade.response.status}")
      }
    }

    val source =
      """{ "janus": "create", "transaction":"d1403sa54a5s3d4as3das"}"""
    val jsonAst = source.parseJson

    ws ! TextMessage.Strict(jsonAst.toString())

now i need help in
how can i initiate the second request here because i need the "id" returned from the server to initiate request #2


Q: C# Property Grid Pass Constructor Variable I'm using the C# property grid to add new objects and change settings of a specific object.  I need to know how to pass a a variable to the constructor using the Component Model.  Reason why is because a parameter is required to correctly define the initial values of the chart object.
List<Chart> charts = new List<Chart>();
[Description("Charts")]
[Category("4. Collection Charts")]
[DisplayName("Charts")]
public List<Chart> _charts
{
    get { return charts; }
    set { charts = value ; }
}

public class Chart
{
    public static string collectionName = "";

     int chartPosition = GetMaxChartIndex(collectionName);
     [Description("Chart posiion in document")]
     [Category("Control Chart Settings")]
     [DisplayName("Chart Position")]
     public int _chartPosition
     {
         get { return chartPosition; }
         set { chartPosition = value; }
     }

    public Chart(string _collectionName)
    {
        collectionName = _collectionName;

    }
}

A: What you can do is declare a custom TypeDescriptionProvider for the Chart type, early before you select your object into the PropertyGrid:
...
TypeDescriptor.AddProvider(new ChartDescriptionProvider(), typeof(Chart));
...

And here is the custom provider (you'll need to implement the CreateInstance method):
public class ChartDescriptionProvider : TypeDescriptionProvider
{
    private static TypeDescriptionProvider _baseProvider = TypeDescriptor.GetProvider(typeof(Chart));

    public override object CreateInstance(IServiceProvider provider, Type objectType, Type[] argTypes, object[] args)
    {
        // TODO: implement this
        return new Chart(...);
    }

    public override IDictionary GetCache(object instance)
    {
        return _baseProvider.GetCache(instance);
    }

    public override ICustomTypeDescriptor GetExtendedTypeDescriptor(object instance)
    {
        return _baseProvider.GetExtendedTypeDescriptor(instance);
    }

    public override string GetFullComponentName(object component)
    {
        return _baseProvider.GetFullComponentName(component);
    }

    public override Type GetReflectionType(Type objectType, object instance)
    {
        return _baseProvider.GetReflectionType(objectType, instance);
    }

    public override Type GetRuntimeType(Type reflectionType)
    {
        return _baseProvider.GetRuntimeType(reflectionType);
    }

    public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance)
    {
        return _baseProvider.GetTypeDescriptor(objectType, instance);
    }

    public override bool IsSupportedType(Type type)
    {
        return _baseProvider.IsSupportedType(type);
    }
}


Q: HTML- HREF Tag inside a Button This is my button code, which has a reference tag, and the URL takes me to an index action correctly
<button type="submit" class="btn btn-primary"><a style="color:white" href="<?php echo $this->basePath('calendar/details/index').'?month='.$this->previousMonth?>"> Previous </button>

and this is the picture of the button

The problem is that only the text Previous on button is clickable, other than that any click on the blue part of the button does not work. How to make the whole area of the button work, without disturbing the URL?

A:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
Previous

<a class="btn btn-primary" style="color: white" href="<?php echo $this->basePath('calendar/details/index').'?month='.$this->previousMonth?>">Previous


Q: How do I override a plugin registration in MVVMCross I'm using the WPF Sqlite plugin in MVVMCross, but I want to override the directory that the database is written to. I've written a custom ISQLiteConnectionFactory which currently resides in my WPF bootstrapper project:
internal class CustomMvxWpfSqLiteConnectionFactory : ISQLiteConnectionFactory
{
    const string DirectoryName = "ProductName";

    public ISQLiteConnection Create(string address)
    {
        var appData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
        var dir = Path.Combine(appData, DirectoryName);
        Directory.CreateDirectory(dir);

        var path = Path.Combine(dir, address);
        return new SQLiteConnection(path, SQLiteOpenFlags.ReadWrite | SQLiteOpenFlags.Create, false);
    }
}

What I can't figure out is how to override the Mvx.RegisterSingleton<ISQLiteConnectionFactory>(new MvxWpfSqLiteConnectionFactory()); that Cirrious.MvvmCross.Plugins.Sqlite.Wpf.Plugin does.
My PCL project's App registers a singleton service that depends on ISQLiteConnectionFactory during Initialize, so I obviously want to override the IOC registration before then. But no matter what I do, the plugin's registration of MvxWpfSqLiteConnectionFactory rather than my own registration of CustomMvxWpfSqLiteConnectionFactory seems to take precedence.
I've tried putting my register call in all sorts of overrides in my WPF Setup.cs, but nothing has worked so far.

A: An article on how plugins are loaded is included in https://github.com/MvvmCross/MvvmCross/wiki/MvvmCross-plugins#how-plugins-are-loaded
The Sqlite plugin by default is initialised during PerformBootstrapActions in Setup - see https://github.com/MvvmCross/MvvmCross/wiki/Customising-using-App-and-Setup#setupcs for where this occurs in the start sequence.
From your question, it's not clear which overrides in Setup you've tried - I'm not sure which positions "all sorts" includes. However, it sounds like want to register your ISQLiteConnectionFactory at any point after PerformBootstrapActions and before InitializeApp - so one way to do this would be to override InitializeApp:
protected virtual void InitializeApp(IMvxPluginManager pluginManager)
{
    // your code here
     base.InitializeApp(pluginManager);
}

Some possible other ideas to consider:

*

*if you want to prevent the Sqlite plugin from self-initializing in the Wpf case, then you could remove the Sqlite bootstrap file from your Wpf project (but beware that nuget might try to add it again later)

*the new "community fork" of the MvvmCross sqlite project has source code updated to the latest SQLite-net version (via @jarroda) and has a BasePath CreateEx option to allow the folder to be specified - see https://github.com/MvvmCross/MvvmCross-SQLite/blob/master/Sqlite/Cirrious.MvvmCross.Community.Plugins.Sqlite.Wpf/MvxWpfSqLiteConnectionFactory.cs#L24


Q: How to set select all data up to data_upload_max_number_fields (example 500) in django admin listing page First of all sorry if is there any question already please let me know that because I am fresh in this community
And thanks in advance for your valuable responses
In the below screenshot in Django admin, How can I override the select all 1005 with some custom number like select up to 500. As you know data_upload_max_number_fields has only a 1000 limit but I don't want to increase the limit every time. Because it might be possible I have 100000 data then how much will increase the
data_upload_max_number_fields in django settings.
So is there any way that I can override this select all thing to less than the upload max field
for example select all up to first 500 data

I don't want like the default one shown in the 2nd image

A: Well, there does not seem to be a direct attribute/method to change the max limit but what you can do is set a custom value in the 'list_per_page' attribute of the ModelAdmin class admin.py like below:
class MyAppAdmin(admin.ModelAdmin):

    list_per_page = 500

    class Meta:
        model = MyApp

The default value of list_per_page is 100 hence now after modifying it you can directly select all 500(in your case) at once per page and perform the requisite operation.


Q: Unable to Update Global State for Redux Flow in SwiftUI I am trying to implement the Redux state in SwiftUI and I am stuck with updating the global state after the action creator has been executed. I am lost as what to do in the Store dispatch function.
// Store.swift

typealias ActionCreator = (_ dispatch: @escaping (Action) -> ()) -> ()

func getMovies() -> ActionCreator {
    return { dispatch in

        DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
            dispatch(.populateMovies([Movie(title: "ABC")]))
        }

    }
}

class Store: ObservableObject {

    var reducer: Reducer
    @Published private (set) var appState: AppState

    init(appState: AppState, reducer: Reducer) {
        self.appState = appState
        self.reducer = reducer
    }

    func dispatch(_ dispatch: ActionCreator) {
        // how to send the movies to the reducer to update the state
        //self.reducer.update(&appState, dispatch)
    }
}

// ContentView:

store.dispatch(getMovies())


Q: Speed of "sum" comprehension in Python I was under the impression that using a sum construction was much faster than running a for loop.  However, in the following code, the for loop actually runs faster:
import time

Score = [[3,4,5,6,7,8] for i in range(40)]

a=[0,1,2,3,4,5,4,5,2,1,3,0,5,1,0,3,4,2,2,4,4,5,1,2,5,4,3,2,0,1,1,0,2,0,0,0,1,3,2,1]

def ver1():
    for i in range(100000):
        total = 0
        for j in range(40):
            total+=Score[j][a[j]]
    print (total)

def ver2():
    for i in range(100000):
        total = sum(Score[j][a[j]] for j in range(40))
    print (total)

t0 = time.time()
ver1()
t1 = time.time()
ver2()
t2 = time.time()

print("Version 1 time: ", t1-t0)
print("Version 2 time: ", t2-t1)

The output is:
208
208
Version 1 time:  0.9300529956817627
Version 2 time:  1.066061019897461

Am I doing something wrong? Is there a way to do this faster?
(Note that this is just a demo I set up, in my real application the scores will not be repeated in this manner)
Some additional info: This is run on Python 3.4.4 64-bit, on Windows 7 64-bit, on an i7.

A: This seems to depend on the system, probably the python version. On my system, the difference is is about 13%:
python sum.py
208
208
('Version 1 time: ', 0.6371259689331055)
('Version 2 time: ', 0.7342419624328613)

The two version are not measuring sum versus manual looping because the loop "bodies" are not identical. ver2 does more work because it creates the generator expression 100000 times, while ver1's loop body is almost trivial, but it creates a list with 40 elements for every iteration. You can change the example to be identical, and then you see the effect of sum:
def ver1():
    r = [Score[j][a[j]] for j in range(40)]
    for i in xrange(100000):
        total = 0
        for j in r:
            total+=j
    print (total)

def ver2():
    r = [Score[j][a[j]] for j in xrange(40)]
    for i in xrange(100000):
        total = sum(r)
    print (total)

I've moved everything out of the inner loop body and out of the sum call to make sure that we are measuring only the overhead of hand-crafted loops. Using xrange instead of range further improves the overall runtime, but this applies to both versions and thus does not change the comparison. The results of the modified code on my system is:
python sum.py
208
208
('Version 1 time: ', 0.2034609317779541)
('Version 2 time: ', 0.04234910011291504)

ver2 is five times faster than ver1. This is the pure performance gain of using sum instead of a hand-crafted loop.
Inspired by ShadowRanger's comment on the question about lookups, I have modified the example to compare the original code and check if the lookup of bound symbols:
def gen(s,b):
    for j in xrange(40):
        yield s[j][b[j]]

def ver2():
    for i in range(100000):
        total = sum(gen(Score, a))
    print (total)

I create a small custom generator which locally binds Score and a to prevent expensive lookups in parent scopes. Executing this:
python sum.py
208
208
('Version 1 time: ', 0.6167840957641602)
('Version 2 time: ', 0.6198039054870605)

The symbol lookups alone account for ~12% of the runtime.

A: Since j is iterating over both lists, I thought I'd see if zip worked any better:
def ver3():
    for i in range(100000):
        total = sum(s[i] for s,i in zip(Score,a))
    print (total)

On Py2 this runs about 30% slower than version 2, but on Py3 about 20% faster than version 1. If I change zip to izip (imported from itertools), this cuts the time down to between versions 1 and 2.


Q: Problem with order id after migrating from Magento 1 to 2 Problems with increment_id
We just migrated from magento 1 to 2, and when we did a purchase test, the new orders instead follow the continuation of the last id, started from the beginning.
Example last order in magento1 migrated to magento 2
300017136
I should continue in the
300017137
But he came out with
300000001
Can someone help me solve this please?

A: Please open  sequence_order_1 table.
Changes the increment value  to  300017138    using MySql query.


Q: Help with Generics in VB Im new to VB. I am coming from a Java background. In the following code

Sub PrintList(Of T)(ByVal list As List(Of T))
        For Each obj As T In list
            Console.Write(obj.ToString() + " ")
        Next
        Console.WriteLine()
    End Sub

Can someone help me to understand what Sub PrintList(Of T)(ByVal list As List(Of T)) means?
Why do you need the (Of T) part? Why isn't (ByVal list As List(Of T)) sufficient?

A: In Java, this would be something like:
public static <T> void printList(List<T> list)

The (Of T) after PrintList is the equivalent to the <T> before void in the Java version. In other words, it's declaring the type parameter for the generic method.

A: Adding to what Jon Skeet said, this sub appears to be able to take any type of list.  If PrintList(Of T) was just PrintList, then you would be stuck specifying what type of List you want to use for your parameter.  You could no longer have 2 calls to this sub taking two different types of lists without overloading the sub.
What I mean by 2 different types of lists is:
List(of string)
List(of integer)


Q: An "identity" functor $f:\mathbf{Rel} \to \mathbf{Rel}^{OP}$ Looking at the category $\mathbf{Rel}$ and its opposite, I would like to know if there is something I'd call identity functor, $f:\mathbf{Rel} \to \mathbf{Rel}^{OP}$ that sends a set to itself and also every relation to itself. If you have a relation $R\subseteq A\times B$, you could say that it is also a morphism of $\mathbf{Rel}^{OP}$. So to my mind, $f$ is an isomorphism between $\mathbf{Rel}$ and $\mathbf{Rel}^{OP}$ because it respects concatenation of arrows.
The definition of arrows $f:A\to B$ in the opposite category just says that they are arrows $f:B\to A$ in the category itself. Now I do not know whether I can say: "The functor is well-defined because there is a corresponding relation $R'\subseteq B\times A$".
I doubt but hope that my question is understandable.

A: This is not called a identity functor. It maps a relation $R \subseteq A \times B$ to the relation $R^{\dagger} \subseteq B \times A$ defined by $R^{\dagger} := \{(b,a) : (a,b) \in R\}$. In fact, this defines a dagger-structure on $\mathsf{Rel}$. See Wikipedia for some information about dagger categories.


Q: Add a border around parts of a region, matplotlib/geopandas I'll have a map showing the municipalities of Stockholm. Displayed below.

fig, ax = plt.subplots(1, figsize=(4, 4))

matplotlib.rcParams["figure.dpi"] = 250
ax.axis('off')

ax1 = geo_df1.plot(edgecolor='black', column=geo_df1.rel_grp, cmap=my_cmp, linewidth=0.3, ax=ax, categorical=True)#,

plt.show(ax1)

I want to add an amplified border to the east. Something like this. How can I do this in matplotlib?

A: *

*question does not include geometry, so have sourced

*it's a simple case of plotting a LineString that is the eastern edge.  Have generated one for purpose of example

import requests
import geopandas as gpd
import shapely.ops
import shapely.geometry
res = requests.get("http://data.insideairbnb.com/sweden/stockholms-län/stockholm/2021-10-29/visualisations/neighbourhoods.geojson")

# get geometry of stockholm
gdf = gpd.GeoDataFrame.from_features(res.json()).set_crs("epsg:4326")

# plot regions of stockholm
ax = gdf.plot()

# get linestring of exterior of all regions in stockhold
ls = shapely.geometry.LineString(shapely.ops.unary_union(gdf["geometry"]).exterior.coords)
b = ls.bounds
# clip boundary of stockholm to left edge
ls = ls.intersection(shapely.geometry.box(*[x-.2 if i==2 else x  for i,x in enumerate(b)]))

# add left edge to plot
gpd.GeoSeries(ls).plot(edgecolor="yellow", lw=5, ax=ax)


Q: Xserver doesn't want to start I have a problem with 14.04, my machine wouldn't come back as usual from stand-by to showing me the password prompt but it displayed some message that didn't contain much information on a shell screen instead.
So, I power cycled my machine and on bootup, I didn't get to the X11 login screen but instead, it throws me to a shell login. I've tried to restart sudo service lighdm start manually but that just gets me a black screen with a cursor flashing in the top left corner. Now can can I get my X back? I don't know what happened, in /var/log/Xorg.0.log I see something like Device(s) dtected, but none match those in the config file - how can I get this adjusted for my two screens to match? My /etc/X11/xorg.conf looks like:
$ cat /etc/X11/xorg.conf
# nvidia-xconfig: X configuration file generated by nvidia-xconfig
# nvidia-xconfig:  version 331.49  (buildmeister@swio-display-x86-rhel47-10)  Wed Feb 12 21:00:07 PST 2014

Section "ServerLayout"
    Identifier     "Layout0"
    Screen      0  "Screen0"
    InputDevice    "Keyboard0" "CoreKeyboard"
    InputDevice    "Mouse0" "CorePointer"
EndSection

Section "Files"
EndSection

Section "InputDevice"
    # generated from default
    Identifier     "Mouse0"
    Driver         "mouse"
    Option         "Protocol" "auto"
    Option         "Device" "/dev/psaux"
    Option         "Emulate3Buttons" "no"
    Option         "ZAxisMapping" "4 5"
EndSection

Section "InputDevice"
    # generated from default
    Identifier     "Keyboard0"
    Driver         "kbd"
EndSection

Section "Monitor"
    Identifier     "Monitor0"
    VendorName     "Unknown"
    ModelName      "Unknown"
    HorizSync       28.0 - 33.0
    VertRefresh     43.0 - 72.0
    Option         "DPMS"
EndSection

Section "Device"
    Identifier     "Device0"
    Driver         "nvidia"
    VendorName     "NVIDIA Corporation"
EndSection

Section "Screen"
    Identifier     "Screen0"
    Device         "Device0"
    Monitor        "Monitor0"
    DefaultDepth    24
    SubSection     "Display"
        Depth       24
    EndSubSection
EndSection

$

I have two monitors connected, one is a HP 2511x and the other one is an acer AL2216W
edit 1
automatically created xorg.conf by nvidia-xconfig
$ cat /etc/X11/xorg.conf
# nvidia-xconfig: X configuration file generated by nvidia-xconfig
# nvidia-xconfig:  version 331.38  (buildmeister@swio-display-x64-rhel04-15)  Wed Jan  8 19:53:14 PST 2014

Section "ServerLayout"
    Identifier     "Layout0"
    Screen      0  "Screen0" 0 0
    InputDevice    "Keyboard0" "CoreKeyboard"
    InputDevice    "Mouse0" "CorePointer"
EndSection

Section "Files"
EndSection

Section "InputDevice"

    # generated from default
    Identifier     "Mouse0"
    Driver         "mouse"
    Option         "Protocol" "auto"
    Option         "Device" "/dev/psaux"
    Option         "Emulate3Buttons" "no"
    Option         "ZAxisMapping" "4 5"
EndSection

Section "InputDevice"

    # generated from default
    Identifier     "Keyboard0"
    Driver         "kbd"
EndSection

Section "Monitor"
    Identifier     "Monitor0"
    VendorName     "Unknown"
    ModelName      "Unknown"
    HorizSync       28.0 - 33.0
    VertRefresh     43.0 - 72.0
    Option         "DPMS"
EndSection

Section "Device"
    Identifier     "Device0"
    Driver         "nvidia"
    VendorName     "NVIDIA Corporation"
EndSection

Section "Screen"
    Identifier     "Screen0"
    Device         "Device0"
    Monitor        "Monitor0"
    DefaultDepth    24
    SubSection     "Display"
        Depth       24
    EndSubSection
EndSection

/var/log/Xorg.0.log:
$ cat /var/log/Xorg.0.log
[  2426.198]
X.Org X Server 1.15.1
Release Date: 2014-04-13
[  2426.198] X Protocol Version 11, Revision 0
[  2426.198] Build Operating System: Linux 3.2.0-61-generic x86_64 Ubuntu
[  2426.198] Current Operating System: Linux regDesktopHome 3.13.0-40-generic #69-Ubuntu SMP Thu Nov 13 17:53:56 UTC 2014 x86_64
[  2426.198] Kernel command line: BOOT_IMAGE=/boot/vmlinuz-3.13.0-40-generic root=UUID=b0488ebc-79a6-49dc-b86f-fd3d9b1d746a ro quiet splash nomdmonddf nomdmonisw nomdmonddf nomdmonisw
[  2426.198] Build Date: 30 July 2014  12:21:54AM
[  2426.198] xorg-server 2:1.15.1-0ubuntu2.1 (For technical support please see http://www.ubuntu.com/support)
[  2426.198] Current version of pixman: 0.30.2
[  2426.198]    Before reporting problems, check http://wiki.x.org
        to make sure that you have the latest version.
[  2426.198] Markers: (--) probed, (**) from config file, (==) default setting,
        (++) from command line, (!!) notice, (II) informational,
        (WW) warning, (EE) error, (NI) not implemented, (??) unknown.
[  2426.198] (==) Log file: "/var/log/Xorg.0.log", Time: Sat Dec  6 12:56:33 2014
[  2426.199] (==) Using config file: "/etc/X11/xorg.conf"
[  2426.199] (==) Using system config directory "/usr/share/X11/xorg.conf.d"
[  2426.199] (==) ServerLayout "Layout0"
[  2426.199] (**) |-->Screen "Screen0" (0)
[  2426.199] (**) |   |-->Monitor "Monitor0"
[  2426.199] (**) |   |-->Device "Device0"
[  2426.199] (**) |-->Input Device "Keyboard0"
[  2426.199] (**) |-->Input Device "Mouse0"
[  2426.199] (==) Automatically adding devices
[  2426.199] (==) Automatically enabling devices
[  2426.199] (==) Automatically adding GPU devices
[  2426.199] (WW) The directory "/usr/share/fonts/X11/cyrillic" does not exist.
[  2426.199]    Entry deleted from font path.
[  2426.199] (WW) The directory "/usr/share/fonts/X11/100dpi/" does not exist.
[  2426.199]    Entry deleted from font path.
[  2426.199] (WW) The directory "/usr/share/fonts/X11/75dpi/" does not exist.
[  2426.199]    Entry deleted from font path.
[  2426.199] (WW) The directory "/usr/share/fonts/X11/100dpi" does not exist.
[  2426.199]    Entry deleted from font path.
[  2426.199] (WW) The directory "/usr/share/fonts/X11/75dpi" does not exist.
[  2426.200]    Entry deleted from font path.
[  2426.200] (==) FontPath set to:
        /usr/share/fonts/X11/misc,
        /usr/share/fonts/X11/Type1,
        built-ins
[  2426.200] (==) ModulePath set to "/usr/lib/x86_64-linux-gnu/xorg/extra-modules,/usr/lib/xorg/extra-modules,/usr/lib/xorg/modules"
[  2426.200] (WW) Hotplugging is on, devices using drivers 'kbd', 'mouse' or 'vmmouse' will be disabled.
[  2426.200] (WW) Disabling Keyboard0
[  2426.200] (WW) Disabling Mouse0
[  2426.200] (II) Loader magic: 0x7fd6d26ead40
[  2426.200] (II) Module ABI versions:
[  2426.200]    X.Org ANSI C Emulation: 0.4
[  2426.200]    X.Org Video Driver: 15.0
[  2426.200]    X.Org XInput driver : 20.0
[  2426.200]    X.Org Server Extension : 8.0
[  2426.200] (II) xfree86: Adding drm device (/dev/dri/card0)
[  2426.201] (--) PCI:*(0:1:0:0) 10de:1040:1043:83c6 rev 161, Mem @ 0xfa000000/16777216, 0xe8000000/134217728, 0xf0000000/33554432, I/O @ 0x0000e000/128, BIOS @ 0x????????/524288
[  2426.201] Initializing built-in extension Generic Event Extension
[  2426.201] Initializing built-in extension SHAPE
[  2426.201] Initializing built-in extension MIT-SHM
[  2426.201] Initializing built-in extension XInputExtension
[  2426.201] Initializing built-in extension XTEST
[  2426.201] Initializing built-in extension BIG-REQUESTS
[  2426.201] Initializing built-in extension SYNC
[  2426.201] Initializing built-in extension XKEYBOARD
[  2426.201] Initializing built-in extension XC-MISC
[  2426.201] Initializing built-in extension SECURITY
[  2426.201] Initializing built-in extension XINERAMA
[  2426.201] Initializing built-in extension XFIXES
[  2426.201] Initializing built-in extension RENDER
[  2426.201] Initializing built-in extension RANDR
[  2426.201] Initializing built-in extension COMPOSITE
[  2426.201] Initializing built-in extension DAMAGE
[  2426.201] Initializing built-in extension MIT-SCREEN-SAVER
[  2426.201] Initializing built-in extension DOUBLE-BUFFER
[  2426.201] Initializing built-in extension RECORD
[  2426.201] Initializing built-in extension DPMS
[  2426.201] Initializing built-in extension Present
[  2426.201] Initializing built-in extension DRI3
[  2426.201] Initializing built-in extension X-Resource
[  2426.201] Initializing built-in extension XVideo
[  2426.201] Initializing built-in extension XVideo-MotionCompensation
[  2426.201] Initializing built-in extension SELinux
[  2426.201] Initializing built-in extension XFree86-VidModeExtension
[  2426.201] Initializing built-in extension XFree86-DGA
[  2426.201] Initializing built-in extension XFree86-DRI
[  2426.201] Initializing built-in extension DRI2
[  2426.201] (WW) "glamoregl" will not be loaded unless you've specified it to be loaded elsewhere.
[  2426.201] (II) "glx" will be loaded by default.
[  2426.201] (WW) "xmir" is not to be loaded by default. Skipping.
[  2426.201] (II) LoadModule: "glx"
[  2426.201] (II) Loading /usr/lib/xorg/modules/extensions/libglx.so
[  2426.213] (II) Module glx: vendor="X.Org Foundation"
[  2426.213]    compiled for 1.15.1, module version = 1.0.0
[  2426.213]    ABI class: X.Org Server Extension, version 8.0
[  2426.213] (==) AIGLX enabled
[  2426.213] Loading extension GLX
[  2426.213] (II) LoadModule: "nvidia"
[  2426.213] (WW) Warning, couldn't open module nvidia
[  2426.213] (II) UnloadModule: "nvidia"
[  2426.213] (II) Unloading nvidia
[  2426.213] (EE) Failed to load module "nvidia" (module does not exist, 0)
[  2426.213] (==) Matched nvidia as autoconfigured driver 0
[  2426.214] (==) Matched nouveau as autoconfigured driver 1
[  2426.214] (==) Matched nvidia as autoconfigured driver 2
[  2426.214] (==) Matched nouveau as autoconfigured driver 3
[  2426.214] (==) Matched modesetting as autoconfigured driver 4
[  2426.214] (==) Matched fbdev as autoconfigured driver 5
[  2426.214] (==) Matched vesa as autoconfigured driver 6
[  2426.214] (==) Assigned the driver to the xf86ConfigLayout
[  2426.214] (II) LoadModule: "nvidia"
[  2426.214] (WW) Warning, couldn't open module nvidia
[  2426.214] (II) UnloadModule: "nvidia"
[  2426.214] (II) Unloading nvidia
[  2426.214] (EE) Failed to load module "nvidia" (module does not exist, 0)
[  2426.214] (II) LoadModule: "nouveau"
[  2426.214] (II) Loading /usr/lib/xorg/modules/drivers/nouveau_drv.so
[  2426.215] (II) Module nouveau: vendor="X.Org Foundation"
[  2426.215]    compiled for 1.15.0, module version = 1.0.10
[  2426.215]    Module class: X.Org Video Driver
[  2426.215]    ABI class: X.Org Video Driver, version 15.0
[  2426.215] (II) LoadModule: "modesetting"
[  2426.215] (WW) Warning, couldn't open module modesetting
[  2426.215] (II) UnloadModule: "modesetting"
[  2426.215] (II) Unloading modesetting
[  2426.215] (EE) Failed to load module "modesetting" (module does not exist, 0)
[  2426.215] (II) LoadModule: "fbdev"
[  2426.215] (II) Loading /usr/lib/xorg/modules/drivers/fbdev_drv.so
[  2426.215] (II) Module fbdev: vendor="X.Org Foundation"
[  2426.215]    compiled for 1.15.0, module version = 0.4.4
[  2426.215]    Module class: X.Org Video Driver
[  2426.215]    ABI class: X.Org Video Driver, version 15.0
[  2426.215] (II) LoadModule: "vesa"
[  2426.215] (II) Loading /usr/lib/xorg/modules/drivers/vesa_drv.so
[  2426.216] (II) Module vesa: vendor="X.Org Foundation"
[  2426.216]    compiled for 1.15.0, module version = 2.3.3
[  2426.216]    Module class: X.Org Video Driver
[  2426.216]    ABI class: X.Org Video Driver, version 15.0
[  2426.216] (II) NOUVEAU driver Date:   Thu Nov 7 14:56:48 2013 +1000
[  2426.216] (II) NOUVEAU driver for NVIDIA chipset families :
[  2426.216]    RIVA TNT        (NV04)
[  2426.216]    RIVA TNT2       (NV05)
[  2426.216]    GeForce 256     (NV10)
[  2426.216]    GeForce 2       (NV11, NV15)
[  2426.216]    GeForce 4MX     (NV17, NV18)
[  2426.216]    GeForce 3       (NV20)
[  2426.216]    GeForce 4Ti     (NV25, NV28)
[  2426.216]    GeForce FX      (NV3x)
[  2426.216]    GeForce 6       (NV4x)
[  2426.216]    GeForce 7       (G7x)
[  2426.216]    GeForce 8       (G8x)
[  2426.216]    GeForce GTX 200 (NVA0)
[  2426.216]    GeForce GTX 400 (NVC0)
[  2426.216] (II) FBDEV: driver for framebuffer: fbdev
[  2426.216] (II) VESA: driver for VESA chipsets: vesa
[  2426.216] (++) using VT number 7

[  2426.220] (EE) [drm] KMS not enabled
[  2426.220] (EE) [drm] KMS not enabled
[  2426.220] (EE) [drm] KMS not enabled
[  2426.220] (EE) [drm] KMS not enabled
[  2426.220] (EE) [drm] KMS not enabled
[  2426.220] (II) Loading sub module "fbdevhw"
[  2426.220] (II) LoadModule: "fbdevhw"
[  2426.220] (II) Loading /usr/lib/xorg/modules/libfbdevhw.so
[  2426.221] (II) Module fbdevhw: vendor="X.Org Foundation"
[  2426.221]    compiled for 1.15.1, module version = 0.0.2
[  2426.221]    ABI class: X.Org Video Driver, version 15.0
[  2426.221] (EE) open /dev/fb0: No such file or directory
[  2426.221] (WW) Falling back to old probe method for fbdev
[  2426.221] (II) Loading sub module "fbdevhw"
[  2426.221] (II) LoadModule: "fbdevhw"
[  2426.222] (II) Loading /usr/lib/xorg/modules/libfbdevhw.so
[  2426.222] (II) Module fbdevhw: vendor="X.Org Foundation"
[  2426.222]    compiled for 1.15.1, module version = 0.0.2
[  2426.222]    ABI class: X.Org Video Driver, version 15.0
[  2426.222] (EE) open /dev/fb0: No such file or directory
[  2426.222] vesa: Ignoring device with a bound kernel driver
[  2426.222] (WW) Falling back to old probe method for vesa
[  2426.222] (EE) Screen 0 deleted because of no matching config section.
[  2426.222] (II) UnloadModule: "fbdev"
[  2426.222] (II) UnloadSubModule: "fbdevhw"
[  2426.222] (EE) Screen 0 deleted because of no matching config section.
[  2426.222] (II) UnloadModule: "vesa"
[  2426.222] (EE) Device(s) detected, but none match those in the config file.
[  2426.222] (EE)
Fatal server error:
[  2426.222] (EE) no screens found(EE)
[  2426.222] (EE)
Please consult the The X.Org Foundation support
         at http://wiki.x.org
 for help.
[  2426.222] (EE) Please also check the log file at "/var/log/Xorg.0.log" for additional information.
[  2426.222] (EE)
[  2426.223] (EE) Server terminated with error (1). Closing log file.
$

edit 2
$ sudo apt-get install nvidia-331
[sudo] password for ron:
Reading package lists... Done
Building dependency tree
Reading state information... Done
nvidia-331 is already the newest version.

So I did a sudo apt-get remove nvidia-331 followed by a sudo apt-get install nvidia-331

A: Since we indicated through the comments that the NVIDIA Drivers are not installed try to reinstall the nvidia drivers by following the the linked doc under section Installation without X / from the console
https://help.ubuntu.com/community/BinaryDriverHowto/Nvidia
sudo apt-get install --reinstall nvidia-331 did the trick. (Check Edit 2)


Q: MySQL insert record I have this SQL query:
insert into messages
(message, hash, date_add)
values
('message', 'hash', NOW())
ON DUPLICATE KEY IGNORE

hash is unique, what is wrong with query? i got the error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IGNORE' at line 1

A: According to MySQL doc the syntax should be :
INSERT IGNORE INTO messages (message, hash, date_add)
  VALUES('message', 'hash', NOW());


Q: Show tags between question title and body That would help some of us who don't always see them to answer questions more accurately.

A: I'm not sure how this helps. You (generally) see them before you click on the question. If you didn't, then the question was interesting enough in its own right, and you can look at the tags when you're done reading it.
Besides, they also appear on the top right of the screen next to the question.

A: Here's a userscript for you that does this.
Click to install---Source
(Requires FireFox with Greasemonkey or Chrome)


Q: JsonDecode FormatException? Could someone help me find out why, the flutter is saying that my json:

=FormatException: Unexpected character: "variable1 : nul "

already checked my json file, and it is coming right, however when giving Json decode, this problem is occurring. this its the json example, its a list with like 1000 itens.
[
{
    "id":2,
    "first_name":"NRD",
    "phone":"",
    "description":"",
    "created_at":"2020-12-22 08:02:20",
    "aveg":112,
    "updated_at":"2020-12-22 08:02:20",
    "long":1,
    "lat":"1",
    "link":"localhost:8000",
    "temperature_id":1,
    "email":"sem@email.com",
    "user":"null"
},
]


Q: pattern example for apache index of When reading the following documentation:
https://httpd.apache.org/docs/2.2/mod/mod_autoindex.html
I see the option:

*

*P=pattern lists only files matching the given pattern

However, I can't find an example anywhere and can get it to work.
Does someone know?

A: Its quite simple really. Let's suppose:

*

*Your DocumentRoot is /var/www

*You have defined Options Indexes or +Indexes for /var/www

*Your DocumentRoot has this file list: a,b,c,d,d1,d2,f,g

*You want to list files starting with d.

In this case all you have to do is request this:
http://example.com/?P=d*
The pattern to use is similar or like used since DOS, ? for a caracter * for matching lots of characters. So if you wanted to match files which third character is a "n" you would use this pattern ??n*
and it will list only files matching that pattern. Try it out.


Q: context.GetInput returns base class instead of specified derived class in $Type Using Azure Durable Functions, I am trying to use the context.GetInput<model>() function which returns the specified model. The model being used has a parameter that is another model which is a derived class. The model that is outputted from context.GetInput<model>() returns the model with the base class instead of the derived class.
I have checked the $type specified in the context, which shows the derived class, but when checking the outputted model, the result is the base class.
for example:
public class Student{
   public Book book {get;set;}
}

public class Textbook:Book {
   public string classfor {get;set;}
}

public class Book {
   public string title {get;set;}
}

[ActivityTrigger] DurableActivityContextBase context is a parameter to the function.
Then I would be calling :
var model = context.GetInput<Student>()

where the context includes
{
  "$type": "Student",
    "book" : {
       "$type": "Textbook",
       "classfor" : "Math",
       "title" : "PreAlgebra"
    }
}

Yet the result is
Model of student which contains a Book instead of Textbook, where the title is assigned "PreAlgebra"
I expect the output of Student model to have a Textbook with properties:
title = "PreAlgebra"
classfor = "Math"

but the actual Student output contains a Book with the property
title = "PreAlgebra"

A: I've encountered the same problem you did last week. Unfortunately right now Azure Functions (even 2.x) don't support polymorphism for durable functions. The durable context serializes your object to JSON, but there's no way to pass JSON serialization settings as described here on GitHub. There's also another issue about this specific problem.
In my case I have an abstract base class, but you can use the same approach for your derived types. You can create a custom JSON converter that will deal with picking the correct type during deserialization. So for example if you have this sort of inheritance:
[JsonConverter(typeof(DerivedTypeConverter))]
public abstract class Base
{
    [JsonProperty("$type")]
    public abstract string Type { get; }
}

public class Child : Base
{
    public override string Type => nameof(Child);
}

public class Child2 : Base
{
    public override string Type => nameof(Child2);
}

Then you can have your а JSON Converter:
public class BaseDerivedTypeConverter : DefaultContractResolver
{
    // You need this to protect yourself against circular dependencies
    protected override JsonConverter ResolveContractConverter(Type objectType)
    {
        return typeof(Base).IsAssignableFrom(objectType) && !objectType.IsAbstract
            ? null
            : base.ResolveContractConverter(objectType);
    }
}

public class DerivedTypeConverter : JsonConverter
{
    private static readonly JsonSerializerSettings Settings =
        new JsonSerializerSettings()
        {
            ContractResolver = new BaseDerivedTypeConverter()
        };

    public override bool CanConvert(Type objectType) => (objectType == typeof(Base));

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        JObject jsonObject = JObject.Load(reader);

        // Make checks if jsonObject["$type"].Value<string>() has a supported type
        // You can have a static dictionary or a const array of supported types

        // You can leverage the array or dictionary to get the type you want again
        var type = Type.GetType("Full namespace to the type you want", false); // the false flag means that the method call won't throw an exception on error

        if (type != null)
        {
            return JsonConvert.DeserializeObject(jsonObject.ToString(), type, Settings);
        }
        else
        {
            throw new ValidationException("No valid $type has been specified!");
        }
    }

    public override bool CanWrite => false;

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) => throw new NotImplementedException();
}

In my usage when I call context.GetInput<Base>() I can get either Child or Child1 because Base is abstract.
In your case it can be Book or Student depending on what's the actual value. This also applies for other durable function operations like like
var foobar = await context.CallActivityAsync<Base>("FuncName", context.GetInput<int>());
The converter will deal with that and you'll get the object you want inside foobar.

A: Per my understanding, the class Textbook extends Book, so "Book" is parent class and "Textbook" is subclass. In your context, you want to turn the child class(Textbook) to the parent class(Book). After that, "book" will just have the attribute "title" which is their common attribute but doesn't have the specific attribute "classfor". You can refer to the code below:

A: Tracked the updates to pass in Json serialization to Azure Functions here showing that it will be in v2.1!


Q: Indefinite Integration of real-variable function gives complex logarithm Integrating real-variable function in Mathematica
 Integrate[1/Sqrt[2 x - x^2], x]

gives following output with complex logarithm
$$
\frac{2 \sqrt{x-2} \sqrt{x} \log \left(\sqrt{x-2}+\sqrt{x}\right)}{\sqrt{-(x-2) x}},
$$
while I expected $\arcsin (x-1)$ as a result of integration.
I tried to specify some assumptions like
Integrate[1/Sqrt[2 x - x^2], x, Assumptions -> x > 0 && x < 2]

but this doesn't help.
Is it possible to avoid this complex logarithm and to tell Mathematica to integrate only over reals?

A: $Version

(* "12.0.0 for Mac OS X x86 (64-bit) (April 7, 2019)" *)

Clear["Global`*"]

Your result is
f1[x_] = 2 Sqrt[x - 2] Sqrt[x] Log[Sqrt[x - 2] + Sqrt[x]]/Sqrt[-(x - 2) x];

The version 12 result is
f2[x_] = Integrate[1/Sqrt[2 x - x^2], x]

(* -2 ArcSin[Sqrt[1 - x/2]] *)

f2 is real when
fd = FunctionDomain[f2[x], x]

(* 0 <= x <= 2 *)

The difference between the results in the domain of interest is
Assuming[fd,
 ReIm[f1[x] - f2[x]] // ComplexExpand[#, TargetFunctions -> {Re, Im}] & //
  FullSimplify]

(* {0, Log[2]} *)

The real parts are equal and the imaginary parts differ by a constant. Consequently, as pointed out by @Roman, the indefinite integrals are equivalent.
More generally, for x real
ReIm[f1[x] - f2[x]] // ComplexExpand[#, TargetFunctions -> {Re, Im}] & //
 FullSimplify[#, Element[x, Reals]] &

The difference is a piecewise constant. Again, showing that the indefinite integrals are equivalent.


Q: Make grep print missing queries I'm using grep -f and would like to make grep print also lines in file 1 that are missing in file 2:
file1:
hello
my
name
is
bernardo

file 2:
hello 1
my 2
name 3
is 4

ideal output:
hello 1
my 2
name 3
is 4
bernardo

A: This will print the lines in file2 that are not in file1:
fgrep -F -x -v -f file1 file2

The -F means to treat the input as fixed strings rather than patterns, the -x means to match the whole line, the -v means to print lines that don't match rather than those that do match, and -f file1 uses file1 as a list of patterns.
Your question is kind of unclear but I'm guessing that you want all of the lines that appear in one or the other file but not both.  There's several ways to do that.  One is to do two greps:
fgrep -F -x -v -f file2 file1; fgrep -F -x -v -f file1 file2

Another, if the order of the lines in the output doesn't matter, is to sort
them and use comm:
sort file1 -o sortfile1
sort file2 -o sortfile2
comm -3 sortfile1 sortfile2

A: grep -f file1 file2 && grep -o -f file1 file2 | sed s'/^\(.*\)$/-e "\1"/g' | tr '\n' ' ' | xargs grep -v file1

What this does is print all matches from file2 by patterns in file1, and after that print all lines from file1 that do not match files in file2. The second part is done as follows:

*

*grep -o -f file1 file2 returns matches between file and file2, but only the matching parts of the lines;

*sed s'/^\(.*\)$/-e "\1"/g' | "\1"/g' | tr '\n' ' ' prefixes those matching parts with -e, encases them in double quotes, and replaces newlines printed by the grep -f command with spaces. This builds a string of the form -e "[pattern1]" -e "[pattern2]" ..., which is what grep uses for multiple patterns matching. The quotes (hopefully) ensure that spaces in patterns will not be a problem;

*xargs grep -v file1 builds and executes the command grep -v file1 [whatever was piped to xargs]. The result is all lines from file1 that have not match in the output of the first command (and, thus, in file2).

I'm not completely sure this solves your problem since non-matching lines from file1 are printed at the end (by far the easiest option), and you do not say where you want them. It probably could be done more elegantly, too.
Here's a sample output:
sh-4.3$ cat file1
hello
my
name
is
bernardo

sh-4.3$ cat file2
hello 1
my 2
name 3
is 4

sh-4.3$ grep -f file1 file2 && grep -o -f file1 file2 | sed s'/^\(.*\)$/-e "\1"/g' | tr '\n' ' ' | xargs grep -v file1
hello 1
my 2
name 3
is 4
bernardo


Q: how to livestream webcam server in c++? I am working on a personal project, i want to learn how to create a livestream webcam server. I was trying to upload files and POST them to my server, but the lag results to be too large to be livestream. does anyone have some source code examples for a c++ webcam server? or any pointers that would be helpful?
thanks.

A: RTSP, as suggested by its name, should suit better for real-life streaming applications. To reduce the lag you can play with bitrate and dropping frames. There is proprietary pvServer though, which is capable of HTTP-streaming.


Q: How to retrieve the A1-style reference of an Excel worksheet cell in VBA How do I retrieve the A1-style reference of an Excel worksheet cell in VBA? I'm using Access 2007 VBA.
So where for example for the cell MyWorksheet.Range("A1").Offset(2, 3) the value "D3" is returned.
It seems such a simple question.

A: To print the A1 style address to the Immediate Window, use the following. By specifying that you don't want the columns or rows to be absolute, you don't have to use the replace function.
Public Sub Test()
    Debug.Print Range("A1").Offset(2, 3).Address(RowAbsolute:=False, ColumnAbsolute:=False)
End Sub

A: MyWorksheet.Range("A1").Offset(2,3).Address(False,False)

The arguments (all optional) for address are
RowAboslute - False for no dollars signs
ColumnAbsolute - False for no dollar signs
ReferenceStyle - default is xlA1 (constant value is 1 if your late binding)
External - include the workbook/worksheet name
RelativeTo - This one's a complete mystery to me.  It never works how I expect.


Q: How to migrate from string column to foreign key pointing to row in other table with same string value in Laravel? I am using Laravel 5.6 and need some help migrating a column from a populated table preserving the content logic. There is a table pages with a column named icon that accepts string values.
Ex:
Schema::create('pages', function (Blueprint $table) {
        $table->increments('id');
        ...
        $table->string('icon')->nullable();
}

The pages table is populated and the icon column, being nullable, is not always used.
A new icons table was created to store all the usable icon classes.
Ex:
Schema::create('icons', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
});

How can i migrate the icon column from the pages table to be a foreign key that points to the icons table row that has the same value in the name column or null if not populated?

A: I'd suggest a polymorphic many-to-many approach here so that icons are reusable and don't require a bunch of pivot tables, should you want icons on something other than a page.
Schema::create('icons', function(Blueprint $table) {
    $table->increments('id');
    $table->string('name');
});

Schema::create('iconables', function(Blueprint $table) {
    $table->integer('icon_id');
    $table->integer('iconables_id');
    $table->integer('iconables_type');
});

Now you just need to determine if the pages have an existing Icon. If they do, then hold reference to them so you can insert them:
$pagesWithIcons = Page::whereNotNull('icon')->get();

At this point you need to define the polymorphic relations in your models:
// icon

class Icon extends Model
{
    public function pages()
    {
         return $this->morphedByMany(Page::class, 'iconable');
    }
}

// page

class Page extends Model
{
    public function pages()
    {
         return $this->morphToMany(Icon::class, 'iconable');
    }
}

Now you just need to create the icons (back in our migration), and then attach them if they exist:
$pagesWithIcons->each(function(Page $page) {
    $icon = Icon::firstOrNew([
        'name' => $page->icon
    });

    $icon->pages()->attach($page);
});

The above is creating an Icon if it doesn't exist, or querying for it if it does. Then it's attaching the page to that icon. As polymorphic many-to-many relationships just use belongsToMany() methods under the hood, you have all of the available operations at your leisure if this doesn't suite your needs.
Finally, drop your icons column from pages, you don't need it.
Schema::table('pages', function(Blueprint $table) {
    $table->dropColumn('icon');
});

And if you need to backfill support for only an individual icon (as the many-to-many will now return an array relationship), you may add the following to your page model:
public function icon()
{
    return $this->icons()->first();
}

Apologies if typos, I did this on my phone so there may be some mistakes.


Q: Web application in Apache cannot access another web application on the same server running on localhost? We have an Angular application running on Apache. This needs to access services from a backend application. This is a Java application running on localhost:9090

The website loads but on pages with backend calls, i'm seeing CORS errors:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:9090/cord/titlesAuthors/. (Reason: CORS request did not succeed).
I searched and SO.. there are several posts about CORS but most of them refer to localhost within Apache.

*

*The site is running on Apache (on CentOS 8, VM) at http://cordboard.info.

*The page http://cordboard.info/papers internally calls a service at  http://localhost:9090/cord/titlesAuthors

*The service is also running on the same VM and can also fetch data if i do a curl -v  http://localhost:9090/cord/titlesAuthors

*Not sure where i am going wrong.. public site works, service individually works.

Questions:

*

*If needed, i can change the ip and port for the backend application. What should it be? Thought since the angular application needs to only access the backend localhost would be fine (backend not needed to be public).

*Is there something we should do on Google Cloud VM's network / rules /  firewall?
Our setup:

*

*Google cloud platform - VM (static ip <-- website domain has an A record)

*Apache configs
/etc/httpd/sites-enabled/cordboard.info.conf

<VirtualHost *:80>
  ServerName www.site.com
  ServerAlias site.info
  DocumentRoot /var/www/site.com/html
  ErrorLog /var/www/site.com/log/error.log
  CustomLog /var/www/site.com/log/requests.log combined
  <Directory "/var/www/site.com/html">
    Order Allow,Deny
    Allow from all
    AllowOverride All
  </Directory>
</VirtualHost>

and
/etc/httpd/conf/httpd.conf

LoadModule headers_module modules/mod_headers.so
LoadModule rewrite_module modules/mod_rewrite.so

*Backend application running as a service on localhost

sudo systemctl status cord-java

...
Loaded: loaded (/etc/systemd/system/cord-java.service; enabled; vendor preset: disabled)
Active: active (running) since Wed 2020-05-20 21:42:39 UTC; 32min ago


Q: Rails Functional Tests and OAuth Parameter problem I've been pulling my hair out over an issue with using OAuth signed requests in Rails functional tests.
I'd appreciate help, or pointers to working examples.
I'm trying to work with the built in ActionController::TestRequest overrides that are in the oauth gem (0.4.5).
I'd already tried this solution to no avail: http://d.hatena.ne.jp/falkenhagen/20091110/1257830144
This is what I'm doing now...
require 'oauth/client/action_controller_request'

I've created a method for doing the login to which I can pass one of my OauthConsumer objects (ActiveRecord), and my URL parameters (for the query string).
def _do_oauth(consumer, params = {})
  c=OAuth::Consumer.new(consumer.consumer_key, consumer.consumer_secret)
  t=OAuth::AccessToken.new(c)
  ActionController::TestRequest.use_oauth=true
  @request.configure_oauth(c, t, params)
end

and call it like so in my test case:
params = { :store => 'foo' }
_do_oauth(oauth_consumers(:one), params) # currently not working for passing params
get :index, { :format => :json }.merge(params)

But it doesn't look like the requests are pick up the "params" or encoding them properly.
The error I'm getting is (which occurs on the "get" line above):
ArgumentError: comparison of Array with Array failed
/home/sp/.rvm/gems/ruby-1.9.2-p180/gems/oauth-0.4.5/lib/oauth/helper.rb:37:in `sort'
/home/sp/.rvm/gems/ruby-1.9.2-p180/gems/oauth-0.4.5/lib/oauth/helper.rb:37:in `normalize'
/home/sp/.rvm/gems/ruby-1.9.2-p180/gems/oauth-0.4.5/lib/oauth/request_proxy/base.rb:98:in `normalized_parameters'
/home/sp/.rvm/gems/ruby-1.9.2-p180/gems/oauth-0.4.5/lib/oauth/request_proxy/base.rb:113:in `signature_base_string'
/home/sp/.rvm/gems/ruby-1.9.2-p180/gems/oauth-0.4.5/lib/oauth/signature/base.rb:77:in `signature_base_string'
/home/sp/.rvm/gems/ruby-1.9.2-p180/gems/oauth-0.4.5/lib/oauth/signature/hmac/base.rb:12:in `digest'
/home/sp/.rvm/gems/ruby-1.9.2-p180/gems/oauth-0.4.5/lib/oauth/signature/base.rb:65:in `signature'
/home/sp/.rvm/gems/ruby-1.9.2-p180/gems/oauth-0.4.5/lib/oauth/signature.rb:23:in `sign'
/home/sp/.rvm/gems/ruby-1.9.2-p180/gems/oauth-0.4.5/lib/oauth/client/helper.rb:45:in `signature'
/home/sp/.rvm/gems/ruby-1.9.2-p180/gems/oauth-0.4.5/lib/oauth/client/helper.rb:75:in `header'
/home/sp/.rvm/gems/ruby-1.9.2-p180/gems/oauth-0.4.5/lib/oauth/client/action_controller_request.rb:54:in `set_oauth_header'
/home/sp/.rvm/gems/ruby-1.9.2-p180/gems/oauth-0.4.5/lib/oauth/client/action_controller_request.rb:50:in `apply_oauth!'
/home/sp/.rvm/gems/ruby-1.9.2-p180/gems/oauth-0.4.5/lib/oauth/client/action_controller_request.rb:14:in `process_with_new_base_test'
/home/sp/.rvm/gems/ruby-1.9.2-p180/gems/actionpack-3.0.7/lib/action_controller/test_case.rb:412:in `process'
/home/sp/.rvm/gems/ruby-1.9.2-p180/gems/actionpack-3.0.7/lib/action_controller/test_case.rb:47:in `process'
/home/sp/.rvm/gems/ruby-1.9.2-p180/gems/actionpack-3.0.7/lib/action_controller/test_case.rb:350:in `get'
test/functional/deals_controller_test.rb:56:in `block in <class:DealsControllerTest>'

I'm assuming it's something to do with the query params not being encoded correctly, or the header not being formatted properly. Any help (or even pointers to examples that do work) would be greatly appreciated.
I should also point out that the app in question I am trying to test is a 2-legged OAuth provider. So, the app is just parsing the signature and checking that the consumer key/secret check out.

A: This probably won't help with the initial problem at this point but it might save someone a few minutes.
The problem is that the sort method on hash freaks out if a hash has a mixture of symbol and string keys.  Oauth adds some entries keyed by strings into the params hash.


Q: Multiple threads increases wifi speed? Why? I used my laptop to set up a hostednetwork and tested the wifi speed between my laptop and my android phones. The two phones are the same by the way.
I first connect my laptop and one of my phone, and transmit a file of 400 Mb from laptop to phone and it took 169.6s on average.
Then, I connect my laptop with two phones and use two threads to transmit a file of 200 Mb to each phone respectively. So totally 400 Mb data is transmitted. And on average, it only took 136.2s, which is less than 169.6s.
My question is, since my laptop only have one wifi chipset, how can it be faster when I use two threads to transmit data of the same size? One thing I am sure is that it cannot be the interference from other wifi devices since it occurs all the time, even when there is no wifi devices around. Is it possible that when I did it using one thread, the computer didn't allocate all the wifi resources to that thread?


Q: "My tags" tab for main question page Inspired by the new behavior for my tags: (see meta:1338)
Can we get a "My tags" tab for the main list of questions at https://stackoverflow.com/questions?


Q: How should I apply this function to the strings of a list given this situation? How can I apply the above function to each string of this list?:
lis = ['hi how are you',
 'pretty good',
 'the quick brown fox',
 'the is quick brown fox play',
 'play the quick brown fox']

I tried to:
[ request(x) for x in lis ]

I also tried to map over the elements of the list and it did not worked.

A: I believe that the problem lies in your global variable, lis_.  You manipulate this through all of the lis entries.  You return the list reference for each element of your comprehension, but continue to update the list on later parsing.
What you get is a list of identical pointers (each one is the reference to lis_), each of which contains all of the processing.
To fix this, use proper encapsulated programming practices.  Use local variables, clean them on each call, and return only the value needed in the calling program.
Does that get you moving?

A: Would this be helpful?
lis = ['hi how are you',
       'pretty good',
       'the quick brown fox',
       'the is quick brown fox play',
       'play the quick brown fox']

def requ(text):
    # This mimics the request
    output = []
    for word in text.split():
        # This just mimics getting some ID for each word
        xyz = "".join(str([ord(x) for x in word])).replace(", ", "")
        # This mimics the word root part
        if word in ["are", "is"]:
            output.append((word, "be", xyz))
        else:
            output.append((word, word, xyz))
    return output

new_lis = [requ(w) for w in lis]

print(new_lis)

Output:
[[('hi', 'hi', '[104105]'), ('how', 'how', '[104111119]'), ('are', 'be', '[97114101]'), ('you', 'you', '[121111117]')], [('pretty', 'pretty', '[112114101116116121]'), ('good', 'good', '[103111111100]')], [('the', 'the', '[116104101]'), ('quick', 'quick', '[11311710599107]'), ('brown', 'brown', '[98114111119110]'), ('fox', 'fox', '[102111120]')], [('the', 'the', '[116104101]'), ('is', 'be', '[105115]'), ('quick', 'quick', '[11311710599107]'), ('brown', 'brown', '[98114111119110]'), ('fox', 'fox', '[102111120]'), ('play', 'play', '[11210897121]')], [('play', 'play', '[11210897121]'), ('the', 'the', '[116104101]'), ('quick', 'quick', '[11311710599107]'), ('brown', 'brown', '[98114111119110]'), ('fox', 'fox', '[102111120]')]]

A: Your list comprehension is fine, the reason you get strange output looks to be that the request function always returns a reference to the global variable lis_, which you keep appending things to. You should create lis_ as a local variable inside convert().


Q: override ip address or host label in Ansible play On my personal network I have a simple list of hosts:
[host1]
192.168.1.2
[host2]
192.168.1.10

When I set up a local host, say 'host2', it has a random (dhcp) IP address. I've changed my hosts.ini and overriden the host IP address, then I use host vars to actually set the IP address I want into its dhcpcd.conf.
My play has all of my local machines, so I need the host label to match. But I can't get this to work on the first boot without some manual work.
I can think of a few workarounds:

*

*override the IP in a manual inventory on the ansible-playbook commandline

*specify a host ip and hostname in a manual inventory on the ansible-playbook commandline

*set a ansible host name on the ansible-playbook commandline

The problem is I can't get any of them to work:
ansible-playbook play.yml -i "[host2]\n192.168.0.123," --limit host2
 [WARNING]: Could not match supplied host pattern, ignoring: host2

ansible-playbook play.yml -i "192.168.0.123 ansible_host=host2," --limit host2
 [WARNING]: Could not match supplied host pattern, ignoring: host2

ansible-playbook play.yml -i "192.168.0.123," -e "ansible_host=host2" --limit host2
 [WARNING]: Could not match supplied host pattern, ignoring: host2

I really think the third idea has merit, I just can't get there from here. Since this is a oneshot type of problem I don't want to have to create a temporary hosts file, but I'm unsure of another way to do it.
Note having an earlier play/task that calls add_hosts almost works, but given host2 already exists in inventory, I either have to null out my inventory or (somehow) call my host exclusively. Remember, this is for bootstrapping, so the idea is to avoid any magic later.
Apologies for this being kinda long. I wanted to give context for the XY problem and also ask my specific strategy/problem.

A: Why not using a dynamic inventory based on the mac address of your devices?
Just a small example. Of course it needs to be improved but it is for your reference:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

import json
import socket
import subprocess
import re

def main():
    print(json.dumps(inventory(), sort_keys=True, indent=2))

def inventory():
    ip_address = find_ip()

    return {
        'all': {
            'hosts': [ip_address],
            'vars': {},
        },
        '_meta': {
            'hostvars': {
                ip_address: {
                    'ansible_ssh_user': 'ansible',
                }
            },
        },
        'ip': [ip_address]
    }

def find_ip():
    lines = subprocess.check_output(['arp', '-a']).decode('utf-8').split('\n')
    for line in lines:
        if re.search('a0:d7:95:1a:80:f8', line):
            ip = re.search(r"(\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b)", line)
            return ip.group(1)

if __name__ == '__main__':
    main()

Output:
{
  "_meta": {
    "hostvars": {
      "192.168.0.100": {
        "ansible_ssh_user": "ansible"
      }
    }
  },
  "all": {
    "hosts": [
      "192.168.0.100"
    ],
    "vars": {
      "ansible_connection": "local"
    }
  },
  "ip": [
    "192.168.0.100"
  ]
}

Example:
ansible-playbook -i inventories/dynamic/mydyn.py hosts.yml

PLAY [Test wait] ****************************************************************************************************************

TASK [Debug] ********************************************************************************************************************
ok: [192.168.0.100] => {
    "ansible_host": "192.168.0.100"
}

TASK [Ping] *********************************************************************************************************************
ok: [192.168.0.100]

PLAY RECAP **********************************************************************************************************************
192.168.0.100              : ok=2    changed=0    unreachable=0    failed=0


Q: How to use a third variable to choose color for scatter plot in Matplotlib I have a data set which provides latitude, longitude, and temperature for a time series of oceanographic readings.
Right now I am plotting the trajectory through lat/lon space thus:
fig = plt.figure()
ax = fig.add_subplots(111)
ax.plot(lon, lat, 'o')

I want to have each dot display in a color representative of the temperature at that location (and display a colorbar). How would I go about doing this? If it's pertinent, this is actually a map from the basemaps toolkit. Thanks.
This was marked as duplicate; none of the solutions provided in the questions which it purportedly duplicates works.
Here is the code in its entirety:
map = Basemap(llcrnrlon = -160, llcrnrlat = -90, urcrnrlon = 40,
urcrnrlat = 10, resolution = 'l')

map.drawcoastlines()
map.drawcountries()
map.fillcontinents(color='gray')
map.drawmapboundary(

cs = map.scatter(lon,lat, c = temp[0])

plt.savefig('test.pdf')

plt.show()

It raises this error:
ValueError: Invalid RGBA argument: <xarray.DataArray 'TEMP' ()>
array(6.459000110626221)


Q: Bind Caliburn Micro to EF Entity Error I'm binding an Entity Framework 6.0 Entity to a Caliburn Micro View:
<aura:AuditView Grid.Row="0" x:Name="SelectedAudit" cal:View.Model="{Binding SelectedAudit}" cal:View.Context="SelectedAudit"/>

The error produced on screen is:
"Cannot find view for System.Data.Entity.DynamicProcies.Audit_9B5A..."

SelectedAudit is the entity property on the ViewModel. Should I create a map (AutoMapper) from + to entity to a new AuditModel? Or am I missing something magical?
EDIT: code for aura:AuditView
<UserControl x:Class="Aura.AuditView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:aura="clr-namespace:Aura"
             xmlns:cal="http://www.caliburnproject.org"
             mc:Ignorable="d"
             d:DesignHeight="300" d:DesignWidth="300">
    <UserControl.Resources>
        <Style x:Key="LockedTextBox" TargetType="{x:Type TextBox}">
            <Setter Property="Focusable" Value="False"/>
            <Setter Property="IsHitTestVisible" Value="False"/>
            <Setter Property="IsReadOnly" Value="True"/>
            <Setter Property="Background" Value="#FFEFE2E2"/>
        </Style>
    </UserControl.Resources>

    <Grid Grid.Row="0">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Label Grid.Row="0" Grid.Column="0" Content="Description" HorizontalAlignment="Right"/>
        <TextBox Grid.Row="0" Grid.Column="1" Text="{Binding Description}" Margin="3" />

        <Label Grid.Row="1" Grid.Column="0" Content="User" HorizontalAlignment="Right"/>
        <TextBox Grid.Row="1" Grid.Column="1" Text="{Binding UserId}" Margin="3" Style="{StaticResource LockedTextBox}"/>

        <Label Grid.Row="0" Grid.Column="2" Content="Begin date" HorizontalAlignment="Right"/>
        <DatePicker Grid.Row="0" Grid.Column="3" SelectedDate="{Binding BeginDate}" Margin="3"/>

        <Label Grid.Row="1" Grid.Column="2" Content="Deadline" HorizontalAlignment="Right"/>
        <DatePicker Grid.Row="1" Grid.Column="3" SelectedDate="{Binding Deadline}" Margin="3"/>

        <Label Grid.Row="2" Grid.Column="2" Content="End date" HorizontalAlignment="Right"/>
        <TextBox Grid.Row="2" Grid.Column="3" Text="{Binding EndDate, StringFormat=dd/MM/yyyy}" Margin="3" Style="{StaticResource LockedTextBox}"/>
    </Grid>
</UserControl>

A: I believe you actually want
cal:Bind.Model="{Binding SelectedAudit}"
Otherwise you are trying to do viewmodel-first resolution in which case Caliburn Micro will look to resolve a view for the VM instead of using the view that you have provided.
e.g.
<aura:AuditView Grid.Row="0" x:Name="SelectedAudit" cal:Bind.Model="{Binding SelectedAudit}" />


Q: Delete row before insert a new one How can I achieve to Delete a row before Insert a new one in the same Table. I tried it with a Trigger but I read that it is not possible because it could cause a deadlock.
I also wanted to save the row which should be deleted to another table (example Table B) before delete it and then Insert a new one (into Table A).
Is there any other ways to do it ?
PS: They will have the same key

A: You could use UPDATE...
UPDATE tbl
SET col1 = newCol1,
    col2 = newCol2
WHERE etc = etc

And If you want to insert updated row to another table you could use TRIGGER AFTER UPDATE for that.
CREATE TRIGGER TriggerName ON Tbl
AFTER UPDATE
AS
INSERT INTO Log (Col1, Col2)
SELECT Col1, Col2
FROM deleted


Q: Pivot table custom aggregation function I have a table like this in an excel spreadshhet:
    Col1    |    Col2   |    Col3
 -----------+-----------+-----------
     A      |     X     |      1
     A      |     Y     |      2
     B      |     X     |      3
     B      |     Y     |      4
     B      |     Z     |      5

I want to use the aggregation feature of the pivot table.
Using the typical SUM of VALUES aggregation, provided by Excel, I get:
    Col1    |    Col3
 -----------+-----------
     A      |     3
     B      |     12

But I want to use a different aggregation function. I want to use something that does:
 Square root of ( Sum of (Square(x)))

So that in the end I get the table:
    Col1    |    Col3
 -----------+-----------
     A      |     SQRT(5)      <= Sqrt(1*1 + 2*2)
     B      |     SQRT(50)     <= Sqrt(3*3 + 4*4 + 5*5)

Is there ANY way (VBA, C++, assembly, whatever it takes) I can specify my own functions in the aggregation list?
NOTE: I KNOW HOW TO DO THIS IN A SHEET, DON'T BOTHER ANSWERING IF IT'S NOT ABOUT WRITING CUSTOM AGGREGATION FUNCTIONS FOR PIVOTTABLE

A: Its not possible to write a custom aggregation function for a standard pivot table. But you can probably do what you want using MDX... maybe an MDX expert would like to comment?


Q: How to resolve "Dependency convergence error" when using maven enforcer plugin? I am just trying to pickup with maven-enforcer-plugin using a small pom (before I jump in to my project pom which has 100+ dependencies.)
After I have added the enforcer plugin, I am seeing Dependency convergence error.
The pom.xml file is below (sorry its not tidy).
How can i fix the errors with out disabling the enforcer plugin.
Basically I want to understand the concept behind how to use dependencyConvergence rule.
<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.demo</groupId>
    <artifactId>enforcer</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <dependencyManagement>
        <dependencies>
            <!--
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-beans</artifactId>
                <version>5.2.13.RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-aop</artifactId>
                <version>5.2.13.RELEASE</version>
            </dependency>
            -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-core</artifactId>
                <version>5.2.10.RELEASE</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.3.5</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>5.4.5</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-enforcer-plugin</artifactId>
                <version>3.0.0-M3</version>
                <executions>
                    <execution>
                        <id>dependency-convergence</id>
                        <goals>
                            <goal>enforce</goal>
                        </goals>
                        <configuration>
                            <rules>
                                <dependencyConvergence/>
                            </rules>
                        </configuration>
                    </execution>
                </executions>
                <configuration>
                    <rules>
                        <dependencyConvergence />
                    </rules>
                </configuration>
            </plugin>
        </plugins>

    </build>

</project>

Does it mean that, I have to declare each non converging dependency in the dependencyManagement explicitly as in this version of pom.xml(added dependencies to dependencyManagement).
The problem with spring-context  still exists as I have added it as direct dependency and then in the dependency management with different version.
Basically - am able to fix the error, but not able to grasp the rules crystal clear yet.

*

*fix one - pom.xml - updated the version in dependency management to the one used explicitly. So now there is no need to give the version explicitly in dependencies. But this would require me to have access to dependencyManagment of parent pom. If my statement is right, this might not be the situation every time.

*fix two pom.xml - excluded spring-context from spring-security-web and it worked. But if there are a dozen of exclusion to be done, its going to be a pain.
If this is the way to go about with the convergence rule? In an enterprise project with 100+ dependencies and 100+ of their transitive dependencies, then the Bill of Materials(BOM) is gonna be quite huge and take time to build. hhhmmm. (I agree, there is going to be more control over the versions used and using property like <xyz.version>, upgrades can be done easily).
I will very much appreciate if anyone can list down the rules involving convergence.

A: A dependency convergence error means that

*

*the dependency is not in dependencyManagement

*there are different versions of the dependency in the dependency tree

The typical resolution is to define an entry in dependencyManagement that resolves the issue or to import an appropriate BOM into the dependencyManagement.
This is best done in the main POM of a multi module project, but also possible in modules.
Note that it is better to leave out the <version> tag in the <dependencies> section so that dependencyManagement will be used everywhere.


Q: Correct way to implement a connection pool I'm trying to write a multithreading program that connects to a MySQL database and processes the returned set for a query (which has thousands of rows). The problem is that I have implemented the connection pool and I get every thread to open the connection to the database and get the resulting set. But I don't understand which is the advantage of using connection-pooling if retrieving that big set takes such a lot of time. It wouldn't be better if I get the whole set with only one connection (without using pooling) and then I use thread pooling to process it? Or is there a way that every thread takes the next row of the resulting set?

A: If you have a limited number of threads, I would have a connection per thread.
A connection pool is more efficient if the number of threads which could use a connection is too high and those thread use the connections a relatively low percentage of the time.


Q: What thread calls the delegate when using iPhone CoreLocation framework? If I create CLLocationManager, assign it's delegate, and finally tell it to start updating, exactly which thread is calling the delegate? Some system thread?

A: Since the documentation doesn't say anything, you can safely assume that the delegate will be called from the run loop (main thread or UI thread, depending on which term you prefer).


Q: No value retrieved from dropdown list with python mechanize when scraping a dynamic webpage I'm completely new to web scraping. I'm trying to follow the code snippet found in this question Web Scraper for dynamic forms in python
I'm doing similar search with http://www.goodlifefitness.com/fitness-classes/find-a-class/. Filling in Province, City and Class Name, and search for schedule.
But I'm stuck with step one, retrieving a list of Provinces
#!/usr/bin/env python

import re
import mechanize
from bs4 import BeautifulSoup

br = mechanize.Browser()
br.open('http://www.goodlifefitness.com/fitness-classes/find-a-class/')

br.select_form('aspnetForm')
ctl = br.form.find_control('ctl00$Copy$ddlRegion')

But it seems that I cannot even get anything from the dropdown list
>>> items=ctl.get_items()
>>> items
[<Item name='' id=None selected='selected' contents='' value='' label=''>]

But when I inspect the element on the webpage, clearly there are values in the first dropdown list
<select name="ctl00$Copy$ddlRegion" id="ctl00_Copy_ddlRegion" title="Select a Province" class="dropdown" onchange="comboBoxSearch_onChange(this);">

<option value="">Select a Province</option><option value="Alberta">Alberta</option><option value="British Columbia">British Columbia</option><option value="Manitoba">Manitoba</option><option value="New Brunswick">New Brunswick</option><option value="Newfoundland">Newfoundland</option><option value="Nova Scotia">Nova Scotia</option><option value="Ontario">Ontario</option><option value="Saskatchewan">Saskatchewan</option></select>

Why ctl.get_items() returned nothing?
Any pointers will be much appreciated.

A: As you can see if you do View Source in Firefox, the items you're looking for aren't in the original HTML markup sent by the server. In fact, they are added by a JavaScript after the page has loaded. Mechanize doesn't run JavaScript, so it can't see those items; it only sees what's in the HTML.
As an aside, this completely unnecessary use of JavaScript is a plague on modern Web development and makes doing things like you're trying to do much harder than they should be. (But then, maybe that's why they do it.)
Anyway, to scrape that information from the page, you need to use something that actually loads the page in a real Web browser, such as Selenium.
The other SO question you linked is different because the targeted site actually sends an HTTP POST when you select from the menus, and receives a whole new HTTP page back. This page doesn't do that.