text:
Q: Reading packets with Linux::TunTap I've put together a perl script that reads packets into userspace via Linux::TunTap, and it all seems to work fine:
#!/usr/bin/perl
use warnings;
use strict;
use Linux::TunTap;

$tun = new Linux::TunTap(NAME => 'localtun')
or die "Couldn't connect to IF\n";

while (my $packet = $tun->get_raw()) {
        print Dumper($packet);
}

Now the question is: How do I turn the string representing the raw IP packet as read from the tuntap device into a proper datastructure for processing? In particular I'm after the source, destination, and sequence number.
Obviously, the raw IP packet isn't very human readable in its original format. Here's the output after sending a ping through the tuntap interface:
{{{�}/��8V�| !"#$%&'()*+,-./0123456ET��@@4
How do I proceed from here to be able to process this data programatically?

A: Based on the comment made by SteffenUlrich, I had a look at NetPacket::IP, which did the trick for me through its decode() method. It worked pretty much out of the box after baking it into my code, with the only caveat being that the first four bytes has to go from the raw data (see lazy regex below), as these bytes form an additional header added by the TunTap layer.
My code now looks like this, and works as intended:
#!/usr/bin/perl
use warnings;
use strict;
use Linux::TunTap;
use NetPacket::IP;

$tun = new Linux::TunTap(NAME => 'localtun')
or die "Couldn't connect to IF\n";

while (my $rawdata = $tun->get_raw()) {
        $rawdata =~ s/^....//;  # Using regex to strip 4 bytes, because I'm lazy
        my $packet = NetPacket::IP->decode($rawdata);
        print "$packet->{id} $packet->{src_ip} -> $packet->{dest_ip} $packet->{proto} $packet->{len}\n";
}

The above code prints the sequence, source IP, destination IP, protocol number, and packet length.


text:
Q: How to filter an array of object by comparing its id with the values of a different array I have an array of object 'compareJson' using this I am displaying a list in html. I have an array 'Cars', using which I need to compare its value(1,4..) with 'id' attribute of 'compareJson' and needs to display the same list in HTML on click 'duplicate' button. If there is same id in multiple objects ,those all objects should display
app.component.html
<button (click)="duplicate()" >Get values </button>
<div *ngFor="let item of  compareJson">Item listed - {{item.details}}</div>

app.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  name = 'Angular';
  compareJson = [
    {
      id: '1',
      details: 'Photography details'
    },
    {
      id: '1',
      details: 'Writing details'
    },
    {
      id: '3',
      details: 'Painting Details'
    }
  ];

  Cars = [1, 4];
}

A: If I understand your question correctly, you want to get the objects from compareJson where the id attribute exists in the Cars array?
You could filter compareJson with values in the Cars array like this:
const matches = compareJson.filter((object) => Cars.includes(object.id));.
With your example matches would equal [{ id: '1', details: 'Photography details'}]

redpajama_set_name: RedPajamaStackExchange


text:
Q: ConnectionRefused when trying to connect to hadoop using cloudera When I try to do a command that connects with hadoop I get an exception
For example:
command: hdfs dfs -ls /user/cloudera
result:ls: Call From quickstart.cloudera/10.0.2.15 to quickstart.cloudera:8020 failed on connection exception: java.net.ConnectException: Connection refused; For more details see:  http://wiki.apache.org/hadoop/ConnectionRefused
In addition, when I used such commands before, I did not have that problem.
Thanks

A: You need to go to Cloudera manager in the browser. Usually this is bookmarked on Firefox as "Cloudera manager". Login "cloudera/clousera". Then start "HDFS" service. The "hadoop fs" commands should start working now.


text:
Q: Not able to identify iPad Pro devices by using Javscript I am trying to identify iPad devices by using various methods in JS. As per the latest research on this, newer versions of iPad Pro behaving same as desktop versions(Same user agent). Since both iPad and Mac shows same user agent details, it's very difficult to differentiate iPad and Mac devices.
Can anyone help on this?
Thanks in advance

A: You can try this way:
var isIPadPro = /Macintosh/.test(navigator.userAgent) && 'ontouchend' in document;


text:
Q: How to expose the DataContext from with-in a DataContext class? Is it possible to expose the DataContext when extending a class in the DataContext? Consider this:
public partial class SomeClass {
    public object SomeExtraProperty {
        this.DataContext.ExecuteQuery<T>("{SOME_REALLY_COMPLEX_QUERY_THAT_HAS_TO_BE_IN_RAW_SQL_BECAUSE_LINQ_GENERATES_CRAP_IN_THIS INSTANCE}");
    }
}

How can I go about doing this? I have a sloppy version working now, where I pass the DataContext to the view model and from there I pass it to the method I have setup in the partial class. I'd like to avoid the whole DataContext passing around and just have a property that I can reference.
UPDATE FOR @Aaronaught
So, how would I go about writing the code? I know that's a vague question, but from what I've seen online so far, all the tutorials feel like they assume I know where to place the code and how use it, etc.
Say I have a very simple application structured as (in folders):

*

*Controllers

*Models

*Views

Where do the repository files go? In the Models folder or can I create a "Repositories" folder just for them?
Past that how is the repository aware of the DataContext? Do I have to create a new instance of it in each method of the repository (if so that seems in-efficient... and wouldn't that cause problems with pulling an object out of one instance and using it in a controller that's using a different instance...)?
For example I currently have this setup:
public class BaseController : Controller {
    protected DataContext dc = new DataContext();
}

public class XController : BaseController {
    // stuff
}

This way I have a "global" DataContext available to all controllers who inherit from BaseController. It is my understanding that that is efficient (I could be wrong...).
In my Models folder I have a "Collections" folder, which really serve as the ViewModels:
public class BaseCollection {
    // Common properties for the Master page
}

public class XCollection : BaseCollection {
    // X View specific properties
}

So, taking all of this where and how would the repository plug-in? Would it be something like this (using the real objects of my app):
public interface IJobRepository {
    public Job GetById(int JobId);
}

public class JobRepository : IJobRepository {
    public Job GetById(int JobId) {
        using (DataContext dc = new DataContext()) {
            return dc.Jobs.Single(j => (j.JobId == JobId));
        };
    }
}

Also, what's the point of the interface? Is it so other services can hook up to my app? What if I don't plan on having any such capabilities?
Moving on, would it be better to have an abstraction object that collects all the information for the real object? For example an IJob object which would have all of the properties of the Job + the additional properties I may want to add such as the Name? So would the repository change to:
public interface IJobRepository {
    public IJob GetById(int JobId);
}

public class JobRepository : IJobRepository {
    public IJob GetById(int JobId) {
        using (DataContext dc = new DataContext()) {
            return dc.Jobs.Single(j => new IJob {
                Name = dc.SP(JobId)  // of course, the project here is wrong,
                                     // but you get the point...
            });
        };
    }
}

My head is so confused now. I would love to see a tutorial from start to finish, i.e., "File -> New -> Do this -> Do that".
Anyway, @Aaronaught, sorry for slamming such a huge question at you, but you obviously have substantially more knowledge at this than I do, so I want to pick your brain as much as I can.

A: Honestly, this isn't the kind of scenario that Linq to SQL is designed for.  Linq to SQL is essentially a thin veneer over the database; your entity model is supposed to closely mirror your data model, and oftentimes your Linq to SQL "entity model" simply isn't appropriate to use as your domain model (which is the "model" in MVC).
Your controller should be making use of a repository or service of some kind.  It should be that object's responsibility to load the specific entities along with any additional data that's necessary for the view model.  If you don't have a repository/service, you can embed this logic directly into the controller, but if you do this a lot then you're going to end up with a brittle design that's difficult to maintain - better to start with a good design from the get-go.
Do not try to design your entity classes to reference the DataContext.  That's exactly the kind of situation that ORMs such as Linq to SQL attempt to avoid.  If your entities are actually aware of the DataContext then they're violating the encapsulation provided by Linq to SQL and leaking the implementation to public callers.
You need to have one class responsible for assembling the view models, and that class should either be aware of the DataContext itself, or various other classes that reference the DataContext.  Normally the class in question is, as stated above, a domain repository of some kind that abstracts away all the database access.
P.S. Some people will insist that a repository should exclusively deal with domain objects and not presentation (view) objects, and refer to the latter as services or builders; call it what you like, the principle is essentially the same, a class that wraps your data-access classes and is responsible for loading one specific type of object (view model).

Let's say you're building an auto trading site and need to display information about the domain model (the actual car/listing) as well as some related-but-not-linked information that has to be obtained separately (let's say the price range for that particular model).  So you'd have a view model like this:
public class CarViewModel
{
    public Car Car { get; set; }
    public decimal LowestModelPrice { get; set; }
    public decimal HighestModelPrice { get; set; }
}

Your view model builder could be as simple as this:
public class CarViewModelService
{
    private readonly CarRepository carRepository;
    private readonly PriceService priceService;

    public CarViewModelService(CarRepository cr, PriceService ps) { ... }

    public CarViewModel GetCarData(int carID)
    {
        var car = carRepository.GetCar(carID);
        decimal lowestPrice = priceService.GetLowestPrice(car.ModelNumber);
        decimal highestPrice = priceService.GetHighestPrice(car.ModelNumber);
        return new CarViewModel { Car = car, LowestPrice = lowestPrice,
            HighestPrice = highestPrice };
    }
}

That's it.  CarRepository is a repository that wraps your DataContext and loads/saves Cars, and PriceService essentially wraps a bunch of stored procedures set up in the same DataContext.
It may seem like a lot of effort to create all these classes, but once you get into the swing of it, it's really not that time-consuming, and you'll ultimately find it way easier to maintain.

Update: Answers to New Questions

Where do the repository files go? In the Models folder or can I create a "Repositories" folder just for them?

Repositories are part of your model if they are responsible for persisting model classes.  If they deal with view models (AKA they are "services" or "view model builders") then they are part of your presentation logic; technically they are somewhere between the Controller and Model, which is why in my MVC apps I normally have both a Model namespace (containing actual domain classes) and a ViewModel namespace (containing presentation classes).

how is the repository aware of the DataContext?

In most instances you're going to want to pass it in through the constructor.  This allows you to share the same DataContext instance across multiple repositories, which becomes important when you need to write back a View Model that comprises multiple domain objects.
Also, if you later decide to start using a Dependency Injection (DI) Framework then it can handle all of the dependency resolution automatically (by binding the DataContext as HTTP-request-scoped).  Normally your controllers shouldn't be creating DataContext instances, they should actually be injected (again, through the constructor) with the pre-existing individual repositories, but this can get a little complicated without a DI framework in place, so if you don't have one, it's OK (not great) to have your controllers actually go and create these objects.

In my Models folder I have a "Collections" folder, which really serve as the ViewModels

This is wrong.  Your View Model is not your Model.  View Models belong to the View, which is separate from your Domain Model (which is what the "M" or "Model" refers to).  As mentioned above, I would suggest actually creating a ViewModel namespace to avoid bloating the Views namespace.

So, taking all of this where and how would the repository plug-in?

See a few paragraphs above - the repository should be injected with the DataContext and the controller should be injected with the repository.  If you're not using a DI framework, you can get away with having your controller create the DataContext and repositories, but try not to cement the latter design too much, you'll want to clean it up later.

Also, what's the point of the interface?

Primarily it's so that you can change your persistence model if need be.  Perhaps you decide that Linq to SQL is too data-oriented and you want to switch to something more flexible like Entity Framework or NHibernate.  Perhaps you need to implement support for Oracle, mysql, or some other non-Microsoft database.  Or, perhaps you fully intend to continue using Linq to SQL, but want to be able to write unit tests for your controllers; the only way to do that is to inject mock/fake repositories into the controllers, and for that to work, they need to be abstract types.

Moving on, would it be better to have an abstraction object that collects all the information for the real object? For example an IJob object which would have all of the properties of the Job + the additional properties I may want to add such as the Name?

This is more or less what I recommended in the first place, although you've done it with a projection which is going to be harder to debug.  Better to just call the SP on a separate line of code and combine the results afterward.
Also, you can't use an interface type for your Domain or View Model.  Not only is it the wrong metaphor (models represent the immutable laws of your application, they are not supposed to change unless the real-world requirements change), but it's actually not possible; interfaces can't be databound because there's nothing to instantiate when posting.
So yeah, you've sort of got the right idea here, except (a) instead of an IJob it should be your JobViewModel, (b) instead of an IJobRepository it should be a JobViewModelService, and (c) instead of directly instantiating the DataContext it should accept one through the constructor.
Keep in mind that the purpose of all of this is to keep a clean, maintainable design. If you have a 24-hour deadline to meet then you can still get it to work by just shoving all of this logic directly into the controller.  Just don't leave it that way for long, otherwise your controllers will (d)evolve into God-Object abominations.

A: Replace {SOME_REALLY_COMPLEX_QUERY_THAT_HAS_TO_BE_IN_RAW_SQL_BECAUSE_LINQ_GENERATES_CRAP_IN_THIS INSTANCE} with a stored procedure then have Linq to SQL import that function.
You can then call the function directly from the data context, get the results and pass it to the view model.
I would avoid making a property that calls the data context. You should just get the value from a service or repository layer whenever you need it instead of embedding it into one of the objects created by Linq to SQL.


text:
Q: Django: how to redirect to mailto I have a Django admin action called "Email selected members". Check some members and click the Go button and the user's mail program is opened. The emails of the selected members have been pre-entered.
This works by a Django HttpResponseRedirect(uri) with the uri being "mailto:email1,email2..
where the addresses email1, email2 ... were looked up on the server.
The only problem is that that the browser re-directs to a blank page as well a opening the client mail program.
Is there any way to avoid this?
-- Peter

A: This question is a little old, but I just went through this and I think I can help anyone looking for an answer in the future.
I ran into this problem because the website I was building had a built-in tracking system that tracked the URLs of outbound links for self-hosted ads. If I don't redirect, there is no way (without changing the way it was implemented) to track the click, since I'm not using an API or anything.
The easy fix was to do what you did, sending back an HttpResponse() whose content is the meta tag
<meta http-equiv="refresh" content="0;url=mailto:youremail@test.com" />

This causes the page to refresh on load, which triggers the mailto: action.
Now we're left with an open window, but we can't close the window using Javascript's window.close() method. I do believe that this solution should work, however. Call that Javascript function after the refresh has been successful.
Unfortunately, I haven't tested this, but these two methods should accomplish a mailto: redirect that does not leave a blank window/tab behind.
Hope this helps!

A: Don't use HttpResponseRedirect. Just make the mailto: line a link. Email selected members

A: I don't think it is possible. RFC 2616 says re 302 redirect:

The temporary URI SHOULD be given by
  the Location field in the    response.
  Unless the request method was HEAD,
  the entity of the    response SHOULD
  contain a short hypertext note with a
  hyperlink to  the new URI(s)

So the blank page that I see is the (very) short hypertext note. The browser gets the redirect instruction, pops up a temporary page with the redirect message, then retrieves the redirected URL. But with a mailto: URL the temporary page obviously remains.


text:
Q: Does Dijkstra's algorithm always return the "shortest" (least number of edges) path? There are two functions that I wish to minimize:
a. the number of "obstacles" on the path (assume each obstacle increases the cost); and
b. total number of edges between the source and the destination.
If I had to minimize just (a), I would have used Dijkstra's algorithm; if I had to minimize just (b), I would have used BFS.
But given that I have to minimize both, can I use Dijkstra's algorithm only?  In other words, if I find the path with the least cost from the obstacles, does Dijkstra's algorithm also guarantee that the path length thus obtained (between source and destination) would be the shortest?

A: When discussing paths on weighted graphs, the term "shortest path" means the path with the lowest total cost.  Think of the weights as distances.  This is the path that Dijkstra's algorithm will find.
You can use any cost function you like, as long as the cost to get from one vertex to another is always positive or zero.  As mentioned in comments, however, you can only minimize one function at a time.  This is a general fact that has nothing to do with Dijkstra's algorithm.
The cost function that you seem to suggesting is perfectly fine -- the cost to move to a normal vertex is 1, while the cost to move to an "obstacle" vertex is higher.  Dijkstra's algorithm is the appropriate way to find a path with lowest total cost.


text:
Q: Is there an elegant way to rewrite getting or creating an Option using a `match` statement? I boiled my code down to these lines:
#[derive(Debug)]
struct Config {
    values: Vec<String>,
    compiled: Option<Vec<String>>,
}

impl Config {
    fn comp_values(&mut self) -> &Vec<String> {
        if self.compiled.is_none() {
            self.compiled = Some(self.values.clone());
        }
        self.compiled.as_ref().unwrap()
    }

    fn comp_values_match(&mut self) -> &Vec<String> {
        match self.compiled {
            Some(_) => self.compiled.as_ref().unwrap(),
            None => {
                self.compiled = Some(self.values.clone());
                self.compiled.as_ref().unwrap()
            }
        }
    }
}

fn main() {
    let mut c = Config {
        values: vec![String::from("a"), String::from("b")],
        compiled: None,
    };
    println!("config before: {:?}", c);
    println!("compiled: {:?}", c.comp_values());
    println!("config after: {:?}", c);
}

What I would like to have is something like:
match self.compiled {
    Some(v) => v,
    None => {
        // assemble v and assign it to self.compiled
        v
    },
}

just like in the closure chapter in the book. Is it possible in the book it only worked, because u32 implements the Copy trait? If I change the match line to match self.compiled.as_ref() the Some(v) => v, works. In the None arm I then can't assign like self.compiled = ... since I have have the variable 'open' (or referenced with self.compiled.as_ref()) in that block.
Are my assumptions correct? Is the comp_values() method the most elegant solution in that case?

A: Not a match statement, but I think you are looking for get_or_insert_with.


text:
Q: Dojox tree grid in XPages Does anyone knows how to build a dojox Tree Grid in Xpages.
I have tried to make a grid based on the information providet by http://xcellerant.net.
I have created the xAgent that load the data from Database view but, when I load the test page I got an error.
Here is the code for xAgent that loads the data from view
<?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core">

    <xp:this.afterRenderResponse><![CDATA[#{javascript:// Read view data and write out the JSON data for the categorized grid
// Each view entry is written out at the top level, but each category has a children property that is an array of IDs of child entries to indent.
// There can be any number of categorization levels -- just add 'children' properties to child entries.
// NOTE: It needs the newlines after each line between the write() statements or the browser doesn't see the output as JSON

var externalContext = facesContext.getExternalContext();
var writer = facesContext.getResponseWriter();
var response = externalContext.getResponse();

response.setContentType('application/json');
response.setHeader('Cache-Control', 'no-cache');

writer.write("{\n");
writer.write("identifier: 'id',\n");
writer.write("label: 'name', \n");
writer.write("items: [\n");

var categoryItem = "";
var childItems = "";

// Walk the view and build the JSON data
var vw:NotesView = database.getView('Vrakkoder');
var nav:NotesViewNavigator = vw.createViewNav();
var ve:NotesViewEntry = nav.getFirst();

while (ve != null) {
    var cv = ve.getColumnValues();

    // When a categorized entry is reached:
    // (a) write out the previous category and children
    // (b) set up the new category element
    if (ve.isCategory()) {
        // Write out the previous category and child entries
        if (categoryItem != "") {
            // Trim the trailing comma and space off the category item.
            // (The child items still need to end with a comma before the next category item starts.)
            categoryItem = categoryItem.substring(0, categoryItem.length - 2);
            writer.write("\n" + categoryItem + "] }, \n" + childItems);
        }

        // Start building the new category and child entries
        categoryItem = "  {id:'" + cv[0] + "', type: 'vrakgruppe', vrakgruppe:'" + cv[0] + "', children:[";
        childItems = "";

    } else {
        // This isn't a category, so simultaneously build the children property and the child entries, until the next category is reached.
        categoryItem += "{_reference:'" + ve.getUniversalID() + "'}, ";
        childItems += "{id:'" + ve.getUniversalID() + "', vrakode:'" + cv[1] + "', vrak_aarsak_kode:'" + cv[2] + "'}, "

    }

    // Get the next entry and recycle the current one
    var tmpentry = nav.getNext();
    ve.recycle();
    ve = tmpentry;
}

// Write out the last category and children, without the trailing commas
categoryItem = categoryItem.substring(0, categoryItem.length - 2);
childItems = childItems.substring(0, childItems.length - 2);
writer.write("\n" + categoryItem + "] }, \n" + childItems);

// Close the JSON string
writer.write("]}");
writer.endDocument();}]]></xp:this.afterRenderResponse>
</xp:view>

Here is the code to produce the tree grid in xpage
<?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core"
    xmlns:xe="http://www.ibm.com/xsp/coreex" dojoParseOnLoad="true"
    dojoTheme="true">

    <xp:this.resources>
        <xp:dojoModule name="dojox.grid.TreeGrid"></xp:dojoModule>
        <xp:dojoModule name="dijit.tree.ForestStoreModel"></xp:dojoModule>
        <xp:dojoModule name="dojo.data.ItemFileWriteStore"></xp:dojoModule>

        <xp:styleSheet
            href="/.ibmxspres/dojoroot/dojox/grid/resources/Grid.css">
        </xp:styleSheet>
        <xp:styleSheet
            href="/.ibmxspres/dojoroot/dijit/themes/tundra/tundra.css">
        </xp:styleSheet>
        <xp:styleSheet
            href="/.ibmxspres/dojoroot/dojox/grid/resources/tundraGrid.css">
        </xp:styleSheet>
    </xp:this.resources>

    <xp:eventHandler event="onClientLoad" submit="false">
        <xp:this.script><![CDATA[var layout = [
  { name: "Vrakgruppe", field: "vrakgruppe"},
  { name: "Vrakkode", field: "vrakkode"},
  { name: "Vrak aarsak kode", field: "Vrak_aarsak_kode"}
];

var jsonStore = new dojo.data.ItemFileWriteStore({ url: "TreeGrid_DataStore.xsp"});

var treeModel = new dijit.tree.ForestStoreModel({
  store: jsonStore,
  query: {type: 'vrakgruppe'},
  rootId: 'groupRoot',
  rootLabel: 'Group',
  childrenAttrs: ['children']
});

var grid = new dojox.grid.TreeGrid({
  treeModel: treeModel,
  structure: layout
}, 'treeGrid');

grid.startup();

dojo.connect(window, "onresize", grid, "resize");]]></xp:this.script>
    </xp:eventHandler></xp:view>

Can Someone help me. I'm stuck.

A: You are very close to your solution. The only thing you have to add is rendered="false" to your XAgent "TreeGrid_DataStore.xsp"

Without this paramater your XAgent delivers not only the grid data but some additional header information too. You can see the difference when you open your XAgent in browser - with and without rendered="false"


text:
Q: Ethernet device MTU setting implications in packet ingress path What is the behavior of an ethernet device in the packet ingress path?
If the sender is sending a larger-than-MTU frame, then:
1) does the receiver's device drop it directly in hardware,
2) or accept it and send it up for the kernel's IP stack to handle it?
3) when is ICMP frag-required sent?
4) does it make a difference if the ethernet device is say on a intermediate router vs a end host?

A: It is impossible to answer 1), 2) definitively for all devices and networking stacks. The Ethernet standard defines an MTU of 1500 bytes so that is all you can rely on and in general you should expect frames with larger MTUs to be dropped.
However in reality it is likely in an end host that if the network interface hardware doesn't drop the oversized frame (which is typically referred to as giant) then it will make it's way up the software stack and be processed. Even though the stack may not drop the oversized frame due to it being over the MTU it may still get dropped for other reasons, e.g. due to an internal queue exhaustion.
Although the maximum MTU of an Ethernet frame has remained constant the maximum size of an Ethernet frame has grown over time to encompass features like 802.1Q VLAN single and double tags. MPLS further increases the frame size to include label stacks. This means intermediate switches are usually tolerant of frames that exceed the interface MTU by some amount. One major vendor effectively tolerates a max MTU of 2000 bytes by default in their current switches. Older switches may be less tolerant.
To get a definitive answer you'll need to do some research into the specific hardware and software that you care about.


text:
Q: What are the rules about concurrently accessing a persistent database It seems the rules about concurrent access are undocumented (on the Haskell side) and simply assume the developer is familiar with the particular backend being used.  For production needs this is a perfectly legitimate assumption, but for casual prototyping and development it would be nice if the persistent-* packages were a bit more self contained.
So, what are the rules governing concurrent access to persistent-sqlite and family?  Implicitly, there must be some degree of concurrency allowed if we have pools of connections, but trivially creating a single connection pool and calling replicateM x $ forkIO (useThePool connectionPool) gives the below error.
user error (SQLite3 returned ErrorBusy while attempting to perform step.)

EDIT: Some example code is now below.
In the below code I fork off 6 threads (an arbitrary number - my actual application does 3 threads).  Each thread constantly stores and looks up a record (a unique record from the one being accessed by the other threads, but that doesn't matter), printing one of the fields.
{-# LANGUAGE TemplateHaskell, QuasiQuotes
           , TypeFamilies, FlexibleContexts, GADTs
           , OverloadedStrings #-}
import Control.Concurrent (forkIO, threadDelay)
import Database.Persist
import Database.Persist.Sqlite hiding (get)
import Database.Persist.TH
import Control.Monad
import Control.Monad.IO.Class

share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persist|
SomeData
    myId Int
    myData Double
    MyId myId
|]

main = withSqlitePool "TEST" 40 $ \pool -> do
  runSqlPool (runMigration migrateAll) pool
  mapM_ forkIO [runSqlPool (dbThread i) pool | i <- [0..5]]
  threadDelay maxBound

dbThread :: Int -> SqlPersist IO ()
dbThread i = forever $ do
   x <- getBy (MyId i)
   insert (SomeData i (fromIntegral i))
   liftIO (print x)
   liftIO (threadDelay 100000) -- Just to calm down the CPU,
                               -- not needed for demonstrating
                               -- the problem

NB The values of 40, TEST, and all records are arbitrary for this example.  Many values, including more realistic ones, cause the same behavior.
Also note that, while it might be obviously broken when you nest a non-terminating action (via forever) inside of a DB transaction (started by runSqlPool), this isn't the core issue.  You can invert those operations and make the transactions arbitrarily small but still end up with periodic exceptions.
The output is usually like:
$ ./so
Nothing
so: user error (SQLite3 returned ErrorBusy while attempting to perform step.)
so: user error (SQLite3 returned ErrorBusy while attempting to perform step.)
so: user error (SQLite3 returned ErrorBusy while attempting to perform step.)
so: user error (SQLite3 returned ErrorBusy while attempting to perform step.)
so: user error (SQLite3 returned ErrorBusy while attempting to perform step.)
so: user error (SQLite3 returned ErrorConstraint while attempting to perform step.)

A: Something worth noting is that SQLite has issues with locking when stored on NFS-like volumes (vboxsf, NFS, SMB, mvfs, etc.) on many systems which cause SQLite to give that error even before you've successfully opened the database.  These volumes may implement fcntl() read/write locks incorrectly. ( http://www.sqlite.org/faq.html#q5 )
Assuming that's not the issue, it's also worth mentioning that SQLite doesn't really natively support concurrent "connections" ( http://www.sqlite.org/faq.html#q6 ) as it uses file system locks to ensure that two writes don't occur at the same time. (See section 3.0 of http://www.sqlite.org/lockingv3.html)
Assuming all of this is known, you may also check which version of sqlite3 you have available to your environment, as some changes to the way in which different kinds of locks are acquired occurred in the the 3.x series: http://www.sqlite.org/sharedcache.html
Edit:
Some additional information from the persist-sqlite3 library
This package includes a thin sqlite3 wrapper based on the direct-sqlite package, as well as the entire C library
'Thin' wrapper made me decide to take a look at it to see just how thin it is; looking at the code it doesn't look as if the persistent wrapper has any guards against a statement to the pool failing except the required guard to translate/emit the error and interrupt execution, though I must provide the caveat that I am not comfortable with Haskell.
It appears that you will have to guard against a statement in the pool failing and reattempt, or that you limit the pool size at initialization to 1 (which seems less than ideal.)


text:
Q: using gulp-cached with gulp-sass-ruby how do I use gulp-cached in latest gulp-sass-ruby, here's my source.
g.task('style', function(){
    return sass('../scss/header.scss', {style:'compressed', sourcemap: true})
    .on('error', notify.onError(function (error){
        return "Error: " + error.message;
    }))
    .pipe(cache('cached'))
    // For file sourcemaps
    .pipe(sourcemaps.write('.', {
        includeContent: false,
        sourceRoot: 'source'
    }))
    .pipe(g.dest('../css'))
    .pipe(notify('scss converted to css and compressed <%= file.relative %>'));

});


text:
Q: What magic happens when IntelliJ compiles my Kotlin project? I currently know that kotlinc hello.kt -include-runtime -d hello.jar compiles my hello world program written in kotlin. Furthermore I am able to execute my program via java -jar hello.jar.
Setting up a Kotlin "Hello world!" console application example in IntelliJ I may choose between different Build Systems (Maven, Gradle, IntelliJ).
I would like to know what happens in the background using the IntelliJ Build System for example?
It seems that there is an ant script running considering the Build Output:
Executing pre-compile tasks…
Loading Ant configuration...
Running Ant tasks...
Running 'before' tasks
Checking sources
Kotlin: connecting to daemon
Kotlin: compiling [firstKotlinApp]
Kotlin: kotlinc-jvm 1.6.10-release-923 (JRE 17.0.1+12-39)
Kotlin: performing incremental compilation analysis
Checking dependencies… [firstKotlinApp]
Dependency analysis found 0 affected files
Updating dependency information… [firstKotlinApp]
Running 'after' tasks
Finished, saving caches…
Executing post-compile tasks…
Loading Ant configuration...
Running Ant tasks...
Synchronizing output directories…
04.01.22, 07:59 - Build completed successfully in 6 sec, 686 ms

Can someone help me out and direct me to the right place to look?
I already  tried to find information with several search engines.


text:
Q: Arguments check controll logic and syntax confusion I am trying to validate users input to a small script I am writing that checks that there should be: 2 arguments and the the first argument should be wither 'mount' or ' unmount'
I have the following:
if [ ! $# == 2 ] || [ $1 != "mount" -o $1 != "unmount" ]; then

However it seems to be a bit overzelouse at meeting the conditions I want. For example with the current || operator, nothing gets past the validator but if I use the && operator everything does.
if [ ! $# == 2 ] && [ $1 != "mount" -o $1 != "unmount" ]; then

Can someone help me figure this out?
Here is the whole block and intended usage
if [ ! $# == 2 ] || [ $1 != "mount" -o $1 != "unmount" ]; then
  echo "Usage:"
  echo "encmount.sh mount remotepoint       # mount the remote file system"
  echo "encmount.sh unmount remotepoint   # unmount the remote file system"
  exit
fi

A: You could do it like this:
if [ "$#" -ne 2 ] || [ "$1" != "mount" -a "$1" != "unmount" ]; then
    echo "Usage:"
    echo "encmount.sh mount remotepoint       # mount the remote file system"
    echo "encmount.sh unmount remotepoint   # unmount the remote file system"
    exit -1
fi
echo "OK"

You have a small logical error in your test, since you should enter the usage branch if $1 is not equal to both "mount" and "unmount". Also you should compare numbers with the -eq and -ne operators (see here), or use the (( )).
Note that you should quote your variables inside a test ([ ])
You can also combine the two expressions like this:
if [ "$#" -ne 2 -o \( "$1" != "mount" -a "$1" != "unmount" \) ]; then

If you have bash, you can also use the [[ ]] syntax:
if [[ $# -ne 2 || ( $1 != "mount" && $1 != "unmount" ) ]]; then


text:
Q: curl file upload details I have a custom system running on a server which expects a certain file type.
when uploading a file via posts, the $_FILES variable in PHP contains information such as [type] = image/png. Where does this information come from?
When i manually try to curl to my website via SSH, and i add -F "file=@/a/b/c/d.pqx" the type is set to "application/octet-stream".
Is the curl command translating the uploaded file and suppling this information or is the server/php parsing the file and providing this information?
Is it possible to make a POST request to my website and have the filetype show up as "application/pqx" (pqx is a custom file extension) ? I am more interested in a way to make the right POST request rather than changing the PHP code. Can i customize the curl request to the website and supply the filetype myself?
thanks for all your help!


text:
Q: How can I continue permutation/combination where I stopped the program? It's my second time asking here and straight to the point. I can't seem to find a solution and I know it's not impossible. I wrote a java program that can generate a set of combination of any length, when I stop the program I don't want to start from the beginning how can I pick up from where I stopped?
Thanks.
Example (for length 3):
If I start from aaa ==> 9zI and I stop the program here, I don't want to start from aaa all over but start from 9zI and continue to 999. I just want to continue from where I left off.
public class Main {

public static void main(String[] args) {
    S_Permutation sp = new S_Permutation();
    String text = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    FileClass.fileExist("new.txt", true);
    System.out.println("");

    sp.permutation(text, "", 7, "sha256.txt","Kaaaaaa");
  }
}

=====================================================================
public class S_Permutation {

private List<String> permutation;

public S_Permutation() {
    permutation = new ArrayList<>();
}

public boolean saveThis(String words, char a, int limit) {
    int count = 0;
    limit++;
    for (char character : words.toCharArray()) {
        if (count == limit) {
            return false;
        }

        if (character == a) {
            count++;
        } else {
            count = 0;
        }
    }

    return count < limit;
}
private int counter = 0;
private boolean seen = false;
public void permutation(String str, String prefix, int lengthOfPermutationString, String filename, String startPoint) {
    if (prefix.equalsIgnoreCase(startPoint))
    {
        seen = true;
    }
    if (counter == 0) {
        if (startPoint.length() != lengthOfPermutationString) {
            for (int i = startPoint.length(); i < lengthOfPermutationString; i++) {
                startPoint += str.charAt(0);
            }
        }
        counter = -45;
    }
    if (prefix.length() == lengthOfPermutationString) {
        boolean savethis = true;

        for (int i = 0; i < prefix.length(); i++) {
            savethis = this.saveThis(prefix, prefix.charAt(i), 13);
            if (!savethis) {
                break;
            }
        }
        if (savethis && seen) {
            System.out.println(prefix);
            //permutation.add(prefix);
        }

    } else {
        for (int i = 0; i < str.length(); i++) {
            if (permutation.size() == 1000) {
                FileClass.WriteFile("new.txt", permutation);
                permutation.clear();
            }

            permutation(str, prefix + str.charAt(i), lengthOfPermutationString, filename, startPoint);
        }
        FileClass.WriteFile("new.txt", permutation);
        permutation.clear();

      }
  }
 }

=========================================================================
public class FileClass {

public static boolean WriteFile(String filename, List<String> doc) {

    try {
        if (!filename.contains(".txt")) {
            filename += ".txt";
        }

        RandomAccessFile raf = new RandomAccessFile(filename, "rw");
        String writer = "";

        writer = doc.stream().map((string) -> string + "\n").reduce(writer, String::concat);
        raf.seek(raf.length());
        raf.writeBytes(writer);
        raf.close();
    } catch (Exception e) {
        System.out.println(e.getMessage());
        System.out.println("Error");
        new Scanner(System.in).nextLine();

        return false;
    }

    return true;
}
static RandomAccessFile raf;
public static boolean fileExist(String filename, boolean delete){
    File file = new File(filename);
    if (file.exists() && delete)
    {
        return file.delete();
    }
    return file.exists();
}
public static void WriteFile(String filename, String text) {

    try {
        if (!filename.contains(".txt")) {
            filename += ".txt";
        }

        raf = new RandomAccessFile(filename, "rw");
        long length = raf.length();
        raf.setLength(length + 1);
        raf.seek(raf.length());
        raf.writeBytes(text + "\n");

    } catch (Exception e) {
    }

}

private static void write(List<String> records, Writer writer) throws IOException {
    for (String record : records) {
        writer.write(record);
    }
    writer.flush();
    writer.close();

}

public static void stringWriter(List<String> records, String filename) {

    try {
        File file = new File(filename);
        FileWriter writer = new FileWriter(file, true);
        write(records, writer);
    } catch (Exception ex) {
        System.out.println(ex.getMessage());
        new Scanner(System.in).nextLine();
    }
}

public static boolean CloseFile() {
    try {
        raf.close();
        return true;
    } catch (Exception e) {
        return false;
    }
  }
 }

A: In order to add a "Resume" mechanism, you need to make your program  idempotent. One way to do it, is instead of saving the permutations - save to file the parameters that are sent to permutation on each iteration:
now each time that the program starts, it will check what were the last parameters that permutation was called with (the last line in the file), and start from there (when the program starts on the first time, nothing will be written in the file - so it will start from the beginning).
After that the recursion finished, we can call another method that will go over the lines of the file, and read only the permutations (ignoring the other parameters) and write them into a cleaner "final_result.txt" file.
Needless to say that this implementation is more costly (all the additional reads and write from disc) but that's the tradeoff for having it support "resume" operation.

A: To save/restore process in the middle of its work, you need something we can call a "state" and implement generating combinations in iterative way.
In my implementation the "state" is pos object (I assume set and k will not change on "resume").
My implementation of the problem would be following:
public class RepeatComb {
    private int[] pos;
    private String set;
    public RepeatComb(String set, int k) {
        this.set = set;
        pos = new int[k];
    }
    public int[] getState() {return Arrays.copyOf(pos, pos.length);}
    public void resume(int[] a) {pos = Arrays.copyOf(a,a.length);}
    public boolean next() {
        int i = pos.length-1;
        for (int maxpos = set.length()-1; pos[i] >= maxpos; ) {
            if (i==0) return false;
            --i;
        }
        ++pos[i];
        while (++i < pos.length) pos[i]=0;
        return true;
    }
    public String getCur() {
        StringBuilder s = new StringBuilder(pos.length);
        for (int i=0; i < pos.length; ++i)
            s.append(set.charAt(pos[i]));
        return s.toString();
    }

    public static void main(String[] args) {
        int[] state;
        String text = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        RepeatComb comb = new RepeatComb(text, 3);
        int stop = 10; //break after 10
        do {
            if (stop-- == 0) break;
            System.out.println(comb.getCur());
        } while (comb.next());
        //save state
        state = comb.getState();
        System.out.println("---------");

        //resume (with the same args: text,3)
        stop = 10; //break after 10
        comb = new RepeatComb(text, 3);
        comb.resume(state); // resume here
        do {
            if (stop-- == 0) break;
            System.out.println(comb.getCur());
        } while (comb.next());
    }
}

Update: I've added functions for getting state and resuming from it
and example of use. state array can be saved in file, then restored.


text:
Q: How to store and sort dictionary in heapq? I am getting below while storing dictionary in heapq. Does anyone know how to solve this ?
'<' not supported between instances of 'dict' and 'dict'
import heapq
PQ = []
heapq.heappush(PQ, {"1": "animal"})
heapq.heappush(PQ, {"2": "vechile"})
heapq.heappush(PQ, {"3": "music"})
print(PQ)

heapq.heappush(PQ, {"2": "vechile"})
TypeError: '<' not supported between instances of 'dict' and 'dict'

A: Here are a few options:

*

*wrap your dictionaries in a class instance that defines a order over them

*convert your dictionaries to a type that already has a order

The issue is what does {"1": "animal"} < {"2": "vechile"} mean?
Are the keys actually priorities and the values data in which case shouldn't they be tuples or namedtuples or orderable objects. ("1", "animal") < ("2", "vechile") has a meaning although the ordering of strings of decimals is not the same as the order of their numeric values. This is the "10" < "2" vs 2 < 10 issue.


text:
Q: How to call javascript after frame is fully rendered? I am looking for a way to modify an iFrame attribute (a textbox value actually). The iFrame is on another domain and I do have access to it. From what I understand I must do that after the entire page (iFrame included) is rendered. I tryed something like that:
<script type="text/javascript">
$(window).load(function() {
    alert("test");
    d = document.getElementById("myframe");
    d.contentWindow.document.getElementById("frametxtbox");
});
</script>

But I always get the following error:

Cannot call method 'getElementById' of undefined

I also noticed that the alert pops up BEFORE the iFrame is rendered, so I think my script is executed before page has access to frame values and, therefore I get the error. I have very few knowledge of web-related programming (always worked on backend side) so forgive me if my question maybe makes no sense.

A: If the iframe points to another domain, it'll be subject to same origin policy. This means that before you try to access its document you'll have to check the wiki and relax the policy (check the link for details). After that you'll need to bind ready event to the iframes document, rather than your main page doc.
$(window.frames['myframe'].document).ready(function() { alert('moo'); });

See if this helps :)


text:
Q: A lookup table in netlogo I have the following list:
set mylist [[1 100] [3 300]]

and I'm uing the following to return 100 or 300 whenever my input is 1 or 3:
to-report itemz [a]

report item 1 (item 0 filter [(item 0 ?) = a] mylist)

end

and it all works fine:
itemz 1

returns 100.
I'd like to rewrite the list so that instead of 100 it returns the value of a slider. I think I need to use the list primitive to re-create my list but I can't figure out how to do it.

A: That's what tables are for:
extensions [table]
globals [mytable]

to setup
  let mylist [[1 "s1"] [3 "s2"]]
  set mytable table:from-list mylist
end

to-report lookup [#key]  ;; if you really want ...
  let slidername table:get mytable #key
  report (runresult slidername)
end

to test
  print runresult table:get mytable 1
  print lookup 1
  print runresult table:get mytable 3
  print lookup 3
end

A: Let's say you have two sliders called s1 and s3 whose values should be referred by the values 1 and 3, you can build the desired list as follow:
 set mylist (list (list 1 s1) (list 3 s3))

and use your function calling
itemz 1 or itemz 3 to get the desired slider value


text:
Q: How do i make http request from RabbitMQ message - nodejs import * as Amqp from "amqp-ts";

const fetch = require('node-fetch');

let connection = new Amqp.Connection("amqp://admin:admin@localhost");
let exchange = connection.declareExchange("ExchangeName");
let queue = connection.declareQueue("nodejs");
queue.bind(exchange);
queue.activateConsumer(async (message) => {
  const site: string = message.getContent().site;
  console.log(site)
  const response = await fetch(site)
  console.log(response.status);
});

Pretty simple little snippet, the issue is that JS gets a message from RabbitMQ, then fires off a request and the gets a new message from RabbitMQ.
The issue is that it first gets all the messages and fires of all the requests, then tries to resolve them - so it just ends up taking all messages for it self.
What would be a good way (or just a way that would work) to set a max number of messages nodejs should be allowed to handle at any one time?

A: import * as Amqp from "amqp-ts";

const fetch = require('node-fetch');
const axios = require('axios')

let connection = new Amqp.Connection("amqp://admin:admin@localhost");
// let exchange = connection.declareExchange("ExchangeName");
let queue = connection.declareQueue("nodejs");
// queue.bind(exchange);

queue.prefetch(500);
queue.activateConsumer(async (message) => {
  const site: string = message.getContent().site;
  console.log(site)
  axios(site).then((response: any) => {
    console.log(response.status);
    message.ack();
  })
}).then(({consumerTag}) => {
  console.log(consumerTag)
});

So found an answer, the solution i found was first of all to acknowledge a successfull message comsumed
 message.ack();

and second to add a max allowed of messages in unacked
queue.prefetch(500);

This worked like a charm!


text:
Q: bootstrap 4 : button groups with a.btn in the middle I have a button group but the middle button is a link so it should b a tag (i can change its button and use js to navigate but I prefer not to )
here is the code

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">

  <button type="button" class="btn btn-warning yekan create-wallet"> down</button>
   center
  <button type="button" class="btn btn-warning yekan ">up   </button>

here is the result

as you can see the middle btn has a border and gradient, how can I change it so it would look like buttons? i've tried adding border:none to all .btn and button group it didn't work

A: Simply remove type=button from the a

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">

       <button type="button" class="btn btn-warning yekan create-wallet"> down</button>
        center
       <button type="button" class="btn btn-warning yekan " >up   </button>


text:
Q: How come XHP can alter PHP syntax and yet be wholly implemented as an extension? I think what I'm asking is this:

*

*To make PHP understand $a=<div>{$stuff}</div> one must alter the PHP parser

*The above can not be done in a PHP extension or even a Zend extension. To introduce new syntax one has to modify the Zend Engine.

*XHP does (1) as a simple extension !

What am I missing ?


text:
Q: Unknotting algorithm in higher dimensions? Suppose we are given a 2-knot (say by a movie).  Is there an algorithm to tell if it is unknotted ? I suppose that it could matter if I say "topologically" or "smoothly" here since those could be different - I am interested in results in either direction.
Is there an algorithm to tell if the fundamental group of the complement is $\mathbb{Z}$?
While I am mainly interested in the 4-dimensional case, I imagine the above problems are hard (although I can't find a reference) - maybe something is known in higher dimensions?  Here there is an algebraic characterization (due to Kervaire) of the knot complements that can occur (namely finitely-presentable groups, generated by a single conjugacy class, has cyclic first homology, and 0 second homology), so maybe there is a result that says that in this class of groups there is no algorithm to recognize $\mathbb{Z}$?

A: The version of the problem in dimensions higher than 4 is undecidable, by work of Nabutovsky and Weinberger:
https://link.springer.com/content/pdf/10.1007/BF02566428.pdf
This is related to the undecidability of the triviality problem for group presentations.
The 4-dimensional version is thought to be undecidable, but this is not known.  The relevant question in geometric group theory is: is it decidable whether a "balanced" group presentation (one that has the same number of generators and relations) presents the trivial group? Or $\mathbb{Z}$?  For some limited recent progress on this problem, see this paper by Lishak and Nabutovsky:
https://arxiv.org/abs/1510.02773
This is all in the smooth or PL case.  For topological knots, it's not clear to me how you would represent them computationally in a finite way.  (Perhaps there are even uncountably many types of them?  Someone who is better with topological topology should chime in here.)


text:
Q: In MySQL can I write a query to find if a given month has any dates between two dates? Apologies on the question title I'm having a hard time articulating this.  It's much easier via example:
I have a table with two date fields; start_date and end_date.  Dummy data:
+----+------------+------------+
| id | start_date | end_date   |
+----+------------+------------+
| 1  | 2012-01-10 | 2012-04-13 |
| 2  | 2012-02-09 | 2012-05-12 |
| 3  | 2012-03-08 | 2012-06-11 |
| 4  | 2012-04-07 | 2012-07-10 |
| 5  | 2012-05-06 | 2012-08-09 |
+----+------------+------------+

So now I have a given month, let's say March 2012.  Is there a way to see if March 2012 falls within start_date and end_date for id 2?  How about 3 (3 is a bit different as parts of March 2012 fall between start_date and end_date which is fine, we don't need the whole month, parts are fine)?
I've been sitting here trying to think of how to write a query and am completely stumped

A: As I understand your question, you want to check if each date-range has some overlap with march, 2012.
Let

*

*A be the maximum of <beginning of march> and start_date and let

*B be the minimum of <end of march> and end_date
Now check if A < B.

A: If you can use the exact month range (i.e. give exact day of start end day) then such query should work fine:
SELECT id FROM MyTable
WHERE start_date <= '2012-03-31'
AND end_date >= '2012-03-01'


text:
Q: What do I need to consider when developing on the localhost a website with SSL I'm new to php . currently I'm developing my first website in my life. I'm developing on my personal windows computer with XAMPP . I'm planning to deploy the website on a Linux server with SSL certificate .
While the development stage I always keep in my mind that this code will work on Linux. So I try to consider the differences between the 2 operating systems -according to my limited experience with Linux systems- . for example in my code I replaced
fwrite($handle,"a line of text\r\n");

with
fwrite($handle,"a line of text" . PHP_EOL);

and
$path = "c://xampp/htdocs/index.php";

with
$path = $_SERVER['DOCUMENT_ROOT'] ."index.php";

My question now. Is there any thing I need to consider about SSL certificate while developing in this environment ?

A: Not really no, the SSL certificate is nothing to do with your php coding. The only thing that i can think of that will create a nuisance in your website is linking none secure content. EG a css file called with http instead of https. you can solve that by simply calling scripts images and the like with just // to eliminate the protocol dependency.
By that i mean, //path/to/file or //example.com/path/to/script.js and so on. If calling over ssl any remote host must also support ssl although you will most likely be using a CDN witch generally do support it.


text:
Q: Creating a favicon How can I create a favicon for my website?

A: You create a icon file that's 16x16 or 32x32 or 64x64.  Name it favicon.ico and place it in the root of your website public folder.
There are websites that will convert other graphic formats to .ico for you.  ie. http://tools.dynamicdrive.com/favicon/

A: One of the best online favicon tools is FaviconGenerator.com.  Fast, modern design, no fluff.

A: If you already have a logo image that you want to transform into a favicon, then you can convert it using http://www.favicomatic.com/.
It creates crisp favicons, and I haven't had to edit them after creating them.
It will generate favicons at 16x16 and 32x32 and to quote them: "Every damn size, sir!". The site also supports/preserves transparency present in some pngs.
Also, their site looks cool and is easy to use.
For example here is a stackoverflow logo:

Here are some of the generated favicons:

They also generate the needed html:
<link rel="apple-touch-icon-precomposed" sizes="57x57" href="apple-touch-icon-57x57.png" />
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="apple-touch-icon-114x114.png" />
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="apple-touch-icon-72x72.png" />
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="apple-touch-icon-144x144.png" />
<link rel="apple-touch-icon-precomposed" sizes="60x60" href="apple-touch-icon-60x60.png" />
<link rel="apple-touch-icon-precomposed" sizes="120x120" href="apple-touch-icon-120x120.png" />
<link rel="apple-touch-icon-precomposed" sizes="76x76" href="apple-touch-icon-76x76.png" />
<link rel="apple-touch-icon-precomposed" sizes="152x152" href="apple-touch-icon-152x152.png" />
<link rel="icon" type="image/png" href="favicon-196x196.png" sizes="196x196" />
<link rel="icon" type="image/png" href="favicon-96x96.png" sizes="96x96" />
<link rel="icon" type="image/png" href="favicon-32x32.png" sizes="32x32" />
<link rel="icon" type="image/png" href="favicon-16x16.png" sizes="16x16" />
<link rel="icon" type="image/png" href="favicon-128.png" sizes="128x128" />
<meta name="application-name" content=" "/>
<meta name="msapplication-TileColor" content="#FFFFFF" />
<meta name="msapplication-TileImage" content="mstile-144x144.png" />
<meta name="msapplication-square70x70logo" content="mstile-70x70.png" />
<meta name="msapplication-square150x150logo" content="mstile-150x150.png" />
<meta name="msapplication-wide310x150logo" content="mstile-310x150.png" />
<meta name="msapplication-square310x310logo" content="mstile-310x310.png" />

I looked at the first 20 or so google results, and this was by far the best.

A: If you want to create .ico files, you can also use GIMP to create favicons.  Modern browsers can use normal image files, but originally I think it was just .ico files.  It's an open source image editor similar to Photoshop.  Create and edit an image of the right size (say 32 x 32), flatten to one layer (Unless you want multiple icons in the same file), and save as a .ico.  It'll format it correctly, then use Stefano's <link rel="SHORTCUT ICON" HREF="/favicon.ico"> to use it in your webpage.

A: I use the open source Paint.net program along with the Icon plugin.
You can then create and save an image in the .ico format with all the different sizes embedded into the .ico file.

A: When creating a favicon, you want to take the following factors into account:

*

*Supported platforms Ten years ago, you only wanted to support desktop browsers and the solution was to generate the classic favicon.ico picture. Nowadays, you want to support iOS (and iOS Safari) and Android (and Android Chrome). Maybe Windows 10 (and Edge) and the new Mac Book Pro Touch Bar, too (macOS Safari). You cannot just use a single "one size fits all" image anymore.

*Design As soon as you support multiple platforms, you are facing multiple design guidelines. For example, Google is using transparent icons for its own native apps on Android, while iOS icons cannot be transparent at all. You cannot just use a "single design fits all" approach.

*Generated icons and HTML code For two or three years, the reference has been to generate as many icons as possible in order to cover all cases. I am afraid I created this trend all by myself :-/ The problem is that you end up with 20-something lines or HTML, which is way too much. In order to have a satisfying technical solution, you need to balance the amount of generated icons/HTML and the supported platforms.

As usual, you can create all these assets manually. Unless you have very, very specific needs and a budget, this is definitely not the way to go.
The right way for most people is to use a favicon generator that lets you decide of the look of all the icons and takes care of all the details. The only one which does this is Real Favicon Generator. Full disclosure: I am the author of this site.

A: GIMP is a good program for that. Just save the image as PNG, then add
 <link rel="SHORTCUT ICON" HREF="/favicon.png">

on the <HEAD>section of your page.

A: I make my favicons either 16 x 16 or 32 x 32 using Photoshop. I save it as gif then and I use IrfanView to convert the gif to an ico.

A: Searching about favicons, I discovered I needed more than 10 kinds of files to work in all browsers and devices :(
I got pissed and created my own favicon generator, that creates all these files and the correct HTML header for each one of them: faviconit.com
Hope you enjoy it.

A: And if you are using asp.net try this way to apply favicon to your page :
<link runat="server" rel="shortcut icon" href="~/favicon.ico" type="image/x-icon" />
<link runat="server" rel="icon" href="~/favicon.ico" type="image/ico" />

but you can find more information here : http://doctype.com/


text:
Q: How can I change AirPod volume with one hand? (while riding a bike) I need to adjust the volume of the AirPods while riding my bike.  This could be because the audio is now in "loud commercial mode" or because I need to pay closer attention to my surroundings.

*

*What is the quickest, most immediate, way of adjusting volume on the AirPods, aside from removing one from the ear?  (and pausing the audio)

A: You can pause the audio by modifying the settings of the AirPods so that when you double tap on an AirPod, instead of activating Siri, it plays/pauses instead. This can be done in Settings > Bluetooth > AirPods. As for volume, I don't think there's a way. I personally have my iPhone mounted to my bike (with a Quad Lock case), and I control the volume with the iPhone volume buttons.

A: The only way to change the volume with one hand is to use Siri.
But triggering Siri may cause you to miss something of the audio that is playing (especially when it's an audio book).
I've configured my left AirPod to play/pause, and the right one to trigger Siri. So then:

*

*Double-tap left AirPod to pause.

*Double-tap right AirPod to trigger Siri.

*Say "increase volume", "decrease volume", "volume to max", or something like that to change the volume.

*Double-tap left AirPod to play.

By default, both AirPods trigger Siri. You'll need to change the double-tap action for the left AirPod. See https://support.apple.com/en-us/HT207009.
Note: In the initial AirPod firmware, it was impossible to assign different actions to each AirPod.


text:
Q: stack1.peek() == stack2.peek() return false with the same elements in both stack in java I was solving the leetcode problem (link:https://leetcode.com/problems/min-stack/) by making two stacks, but in the pop function if I compare s.peek() == ss.peek() if statement does not execute why?
class MinStack {
        Stack <Integer> s = new Stack<>();
        Stack <Integer> ss = new Stack<>();

    public MinStack() {

    }

    public void push(int val) {
        if(ss.isEmpty() || val<=ss.peek()) ss.push(val);
        s.push(val);
        return;
    }

    public void pop() {
        if(s.isEmpty()) return;
        int a = s.peek();
        int b = ss.peek();

        if(s.peek() == ss.peek(){
        //this does not work
            ss.pop();
        }

        if(a == b){
            ss.pop();
        }
        s.pop();
        return;
    }

    public int top() {
        if(s.isEmpty()) return -1;
        return s.peek();
    }

    public int getMin() {
        if(ss.isEmpty()) return -1;
        return ss.peek();
    }
}
/**
 * Your MinStack object will be instantiated and called as such:
 * MinStack obj = new MinStack();
 * obj.push(val);
 * obj.pop();
 * int param_3 = obj.top();
 * int param_4 = obj.getMin();
 */

A: Comparison will only work for values between -128 and 127
This snippet will return true
Stack<Integer> s1 = new Stack<Integer>();
Stack<Integer> s2 = new Stack<Integer>();
s1.push(127);
s2.push(127);
System.out.println(s1.peek() == s2.peek());

Whereas, this will return false
Stack<Integer> s1 = new Stack<Integer>();
Stack<Integer> s2 = new Stack<Integer>();
s1.push(128);
s2.push(128);
System.out.println(s1.peek() == s2.peek());

Use s1.peek().equals(s2.peek()) for values outside range [-128,127]


text:
Q: Ошибка 'laravel/homestead' could not be found при наличии laravel/homestead box v. 10.0.0 На ubuntu 18.04 добавил командой
vagrant box add --insecure laravel/homestead
Получил box successful added v 10.0.0
Проверил командой
vagrant box list
Получил
laravel/homestead (virtualbox, 10.0.0)
После выполнения команды
vagrant up

Получаю ошибку
Bringing machine 'homestead' up with 'virtualbox' provider...
==> homestead: Box 'laravel/homestead' could not be found. Attempting to find and install...
homestead: Box Provider: virtualbox
homestead: Box Version: ~> 9.5.0
==> homestead: Loading metadata for box 'laravel/homestead'
homestead: URL: https://vagrantcloud.com/laravel/homestead
==> homestead: Adding box 'laravel/homestead' (v9.5.1) for provider: virtualbox
homestead: Downloading: https://vagrantcloud.com/laravel/boxes/homestead/versions/9.5.1/providers/virtualbox.box

Не могу понять, почему начинается попытка скачать более старую версию 9.5.1 при наличии v10.0.0
Версия vagrant самая последняя Vagrant 2.2.10
Выполнил все предложения из темы https://stackoverflow.com/questions/34946837/box-laravel-homestead-could-not-be-found
но вопрос не решился

A: Разобрался сам. Дело в том, что в большинстве туториалов по установке laravel/homestead после команды
vagrant box add laravel/homestead

предлагают сделать
vagrant up

Возможно в более старых версиях vagrant это прокатывало, не могу сказать точно, но сейчас после добавления бокса нужно сделать
vagrant init laravel/homestead

И уже потом поднимать вагрант. Долго я искал эту команду, наткнулся случайно, очень жаль, что слишком часто приходится отвечать самому на свои же вопросы. Всегда задаюсь в таких случаях вопросом: "Неужели из той кучи людей, просмотревших этот вопрос, никто не знал этой команды? Или им просто было лень написать одну строку".


text:
Q: How do I use SPMemember.ID property to get User or Group I have to write a utility to enumerate and manage the owners of groups within a SharePoint site. I know I can use the Groups property of the SPWeb object to retrieve a collection of groups. And I know I can use the Owner property of the group to get back the owner.
My problem is that I do not know what to do next. The SPGroup.Owner property returns a SPMember object. The member object has one property called ID that returns the unique ID (an integer) of the member. What I cannot seem to find information on is how to use that integer value to determine if the member is a User or a Group and how to get back additional details (say the name).
Any ideas?
Thanks.

A: You can try casting the SPMember to a specific type:- For example
using (SPWeb web = s.OpenWeb())
{
    SPGroup members = web.AssociatedMemberGroup;
    if (members.Owner is SPUser)
    {
        SPUser user = members.Owner as SPUser;
    }
    else if (members.Owner is SPGroup)
    {
        SPGroup group = members.Owner as SPGroup;
    }
}


text:
Q: How to give assertion in soapui for rest API testing?
In the below picture, I have given assertion value as it is(Used response) ..it is working.
Whereas how to use "data" for assertion here...I tried in the same way but i got failed response.
Please help me out some one.

A: Have you tried parsing response in script assertion and asserting
 import groovy.json.JsonSlurper
def response = messageExchange.response.responseContent
def slurper = new JsonSlurper()
def json = slurper.parseText(response)
assert json.response.data!=null


text:
Q: Show that $\int_0^1[1+f(x)]dx\int_0^1\frac{1}{1+f(x)}dx\le1.125$ Show that
$$\int_0^1[1+f(x)]dx\int_0^1\frac{1}{1+f(x)}dx\le1.125$$
where $f:[0,1]\rightarrow [0,1]$.
In the beginning, I was going to use Chebyshev's inequality but then noticed that we don't have any info about monotonicity :) Now I don't know how to do it. Any hint is appreciated.

A: Note that since $0 \le f(x) \le 1$ in $[0,1]$, denoting $1 \le g(x) := 1 + f(x) \le 2$ $$\left(2 - g(x)\right)\left(\frac{1}{g(x)} - 1\right) \le 0 \implies \frac{2}{g(x)} + g(x) \le 3$$
Integrating both sides \begin{align*} 2\int_0^1 \frac{1}{g(x)}\,dx + \int_0^1 g(x)\,dx \le 3 \end{align*}
By AM-GM inequality $$2\left(\int_0^1 \frac{1}{g(x)}\,dx\right) \left( \int_0^1 g(x)\,dx\right) \le \frac{1}{4}\left(2\int_0^1 \frac{1}{g(x)}\,dx + \int_0^1 g(x)\,dx\right)^2 \le \frac{9}{4}$$ proving the claim.

A: Hint. Show that $f([0,1])\subseteq [0,1]$ implies
$$\frac{1}{2}\left((1+f(x))+\frac{2}{1+f(x)}\right)\leq \frac{3}{2}.$$


text:
Q: Jenkins is showing "zombie" pipeline runs after restart - how to purge? After restarting our Jenkins 2.107.2 instance, it shows many previously finished pipeline runs in the "master" section of the homepage, with a partly-completed progress bar.
When looking at the console log for these runs, they were completed days ago (long before the restart), but are showing a "resuming" message afterwards.
[Pipeline] End of Pipeline
Finished: SUCCESS
Resuming build at Tue May 01 06:02:42 PDT 2018 after Jenkins restart
Resuming build at Thu May 03 16:11:45 PDT 2018 after Jenkins restart

How can I purge these old runs from Jenkins (where does Jenkins keep the state for these runs)? I have hundreds of them; stop/kill doesn't remove them either.
I see this in the run's build.xml file - is that what's causing it?
 <completed>false</completed>

A: https://issues.jenkins-ci.org/browse/JENKINS-50199 seemed to be the root cause.
After updating the pipeline plugins (latest "stable" versions as of 2018-05-07), the zombie runs disappeared and all is good again.


text:
Q: Invalid appsecret_proof provided in the API argument i have created an app in my facebook account and done post to my friend using my access token (php).
But another user cannot post to their friend using my app id and secret and getting the error

Invalid appsecret_proof provided in the API argument

i have disabled

Required app secret proof in my app settings

any solution please?
public function facebookUsershare() {
require '../facebook/src/facebook.php'; $facebook = new Facebook(array( 'appId' => 'app     id', 'secret' => 'secret_key', ));

$privacy = array( 'description' => 'Vladimir Sergeevich', 'value' => 'CUSTOM', 'friends'   =>'friend id' 'allow' => 'loged in user' );
try {
$result = $facebook->api('/me/feed', 'POST', array( "access_token" => 'access_token',   'picture' => "path to image", 'link' => "gmail.com";, 'name' => "Go wi6 7", 'caption' =>   "capn", 'privacy' => json_encode($privacy) ));

echo 'Successfully posted to Facebook Personal Profile'; //return $facebookfrndids; }   catch(Exception $e) {
echo $e->getMessage();
return false; }

A: finally i got the answer....
disable Required app secret proof in the advanced settings of app, and comment the following code in base_facebook.php sdk
if (isset($params['access_token'])) {
  $params['appsecret_proof'] = $this->getAppSecretProof($params['access_token']);
}

A: As for documentation:

Graph API calls can be made from clients or from your server on behalf
  of clients. Calls from a server can be better secured by adding a
  parameter called appsecret_proof.

So you need to specify additional param appsecret_proof togather with access_token. The appsecret_proof is digital signature of access_token that signed with your app secret. The signature need to confirm access_token. To get appsecret_proof you need to calculate signature like this:
secret = 'app secret'
token = 'access token'
digest = OpenSSL::Digest.new('sha256')
proof = OpenSSL::HMAC.digest(digest, secret, token)

# result params:
"access_token=#{token}&appsecret_proof=#{proof}"

The example is on Ruby language but this is not language problem. Please refer your language manual to refer for hmac signature api.


text:
Q: How to modify my tooltip on a td <?php

include('db_connect.php');
?>
<link rel="stylesheet" type="text/css" href="comment-style.css" media="screen" />

B-House/Dorm Name
Address
Price Range
Date Added
Status

<?php

$q=mysql_query("select * from property");
    while( $f=mysql_fetch_array($q, MYSQL_ASSOC))
    {
                                            $p_id=$f["p_id"];

    echo"

                                                <input type='hidden' id='tool-id' value='".$p_id."' />

                                                ".$f['p_name']."
                                                ".$f['address']."
                                                ".$f['p_name']."
                                                ".$f['payment_type']."
                                                ".$status."

    ";

    }

    ?>

A: You can use one of the built in jQuery tooltip plugins. http://flowplayer.org/tools/tooltip/index.html
Here's an example of using it with a table: http://flowplayer.org/tools/demos/tooltip/table.html
$(document).ready(function(){
    $("#my-table td").hover(function() {
        $("#property-hover").html("
Put some loading text here while the ajax call loads
");

        var prop = 0; //TODO: this variable needs to be retrieved from somewhere

        $.ajax({
            type: "POST",
            url: "description-hover.php",
            data: {id:prop},
            success: function(data) {
                $("#property-hover").html(data);
            }
        });
    });

    $("#my-table td").tooltip({tip: '#property-hover'});
});

A: I believe the problem you're having is that you're using the onmouseover method to do something that Tooltip allows you to do as an event. You really shouldn't be using onmouseover or onclick. Instead, the tooltip function has options for handling events before it's shown.
In this case, I would use the onBeforeShow event to load the tool tip via ajax.
Here's a simple example of how to use onBeforeShow:
Michael

function load_user_info(event){
  //functionality to ajaxy load info here
}
$('td.user_name').tooltip({
  ...
  onBeforeShow: load_user_info,
  ...
});

I started creating a solution here: http://jsfiddle.net/mimercha/r7Hxf/23/ and ran out of time. Will try to finish the solution later.

A: Recommend using the following for creating the tooltips.  This will allow you to include static or ajax loaded content into your tooltips - jQuery qTip


text:
Q: by use mybatis ,when the column name include dot notation, like this 'test.name' ,it will return nested Object,how to solve it? his is my test sql:
<select id="getMap" resultType="java.util.LinkedHashMap">
    select "test.name" from test where id = 1
</select>

java:
List<LinkedHashMap<String, String>> map = dataMapper.getMap();
log.info("{}", map);

output: [{test={name=628}}]
correct output should be: [{test.name=628}]
just like:mybatis autoMapping map and the column name has spot like this 'test.name' , the name will be split


text:
Q: glimmer.js IE Support a new untouched glimmerjs app with ember new my-app -b @glimmer/blueprint ran in firefox and chrome but not in ie or edge.
Edge gave me following error:
SCRIPT1028: Expected identifier, string or number:
app.js (3386,11)

IE11:
SCRIPT1002: Syntaxfehler
app.js (7,1)

After adding IE11 in config/targets.js the app runs with "Microsoft Edge", but still not with IE11.
IE11 provides following error, which referes to a let Symbol:
SCRIPT5009: "Symbol" ist undefiniert
app.js (9804,1)

Any other settings we need to change?
Also it's a little bit strange that with setting IE11 the Edge problem got fixed.
Or that the default setting 'last 2 Edge versions' does not transpile to a edge compatible version...

A: We got a little bit further with IE 11 and Edge support in https://github.com/glimmerjs/glimmer.js/issues/8
But still were not able to completely solve it in order to support IE 9 and 10 also.


text:
Q: Dashed lines for a google line chart I'd like to have a google line chart with one of the line series a dashed line.
Is this possible using the google jsapi (javascript)?
I'm actually planning on using a ComboChart, with an AreaChart for most of the data, but one series using a LineChart.  And I'd like that line to be a dashed line...

A: Please refer : LineChart Customization Doc by Google
Solution
    var options =
            {
                lineWidth: 2,
                series: {0: {type: 'line',lineDashStyle: [2, 2]}}
            };
    chartLineWithDash.draw(data, options);

Example : Run Snippet

A: Yes, you can.
Just read about the data table roles on the doc
Every point you draw could be certain (certainty : true) or uncertain (certainty : false). Between two points, if one or both are uncertain, the line between will be dashed.
you just have to do like this :
var data = new google.visualization.DataTable();
data.addColumn('string', 'Month');
data.addColumn('number', 'Sales');
data.addColumn({type:'boolean',role:'certainty'}); // certainty col.
data.addRows([
  ['April',1000,  true],
  ['May',  1170,  true],
  ['June',  660,  true],
  ['July', 1030,  false]
]);
var chartLineWithDash = new google.visualization.LineChart(yourDiv);
chartLineWithDash .draw(data);

the line between June and July will be dashed.
For the moment it is style "Experimental", but feel free to ask! :)
Hope it has helped you!


text:
Q: How can I (efficiently) reference nuget library and update it's source? I am depending on an open-source library via NuGet and need to fix the code. How can i efficently do that? (without changing all references or and fiddling with version numbers).
I have the following specific scenario in Visual Studio 2015 for .NET:

*

*My Application contains multiple solutions that use "Metrics.NET", referenced in via NuGet packages

*There is an issue in Metrics.NET (ActionScheduler causes cascading Task-creation when having many Timers which ends up consuming all threads).

I have tried:

*

*Searching the web and reading the NuGet documentation :)

*Including the library as source in my solution => Runtime errors of with missing (conflicting) references unless I change the reference in every single project in the solution

*Generating a NuGet library from the Metrics.Net Sources => Hacking around in the versions of Metrics.NET for each change iteration (to make it update) and slow update-cycles, a local nuget-path and a solution wide update to the new (locally compiled) pre-release package (which almost certainly will collide with other packages on version-numbering). This approach also requires (temporarily) checking in the compiled package or setting up a NuGet distribution point and coordinating with other developers.
There must be a simpler workflow! What is it?

A: You can try NuGet Reference Switcher.
Note however, that it has a big number of opened issues, so it may not work exactly as you want.
See also related question How to see source code from github in Visual Studio IDE, but compile with dlls from Nuget?


text:
Q: Data revert in my Android app I have released an app on Google Play made with Construct 2, and I have a big problem.
One of the users of my app have complained on losing data, but not entirely. For example, he was on level 27 and had 240 coins, and somehow he was sent back to level 12 with less coins. It has nothing to do with the code, and it happened only to him and me.
How come the value for the level, coins and all progress is reverted to some value that was stored before?
I am also having a problem with huge data size. The data of my app is 40MB, and I am only saving a 2260 long value as JSON..
Is it possible that my data is accumulating every time it saves? For example, the values for levels are not replaced but saved as new instead of only saving the highest level, so in the data there are multiple level values (1,2,3,4....20) and they sometimes conflict and load a wrong (lower level) value.
This would explain the huge data size, but what may cause it?


text:
Q: Retry: Neo4j Query on first query result to get insight in to what is returned I had asked this question few days back but maybe as I was not clear as I didn't get much response.
let me try to rephrase my question to something like this:
I have few customers who are placing the orders with various products. and I am interested in knowing orders placed for various combinations of products and customers then bucket them into the number of orders last week, last fortnight, last month etc.
I am able to query the orders based on my criteria, but I am unable to understand how to then use this result in to data I need.
lets say my data is like this:
(c:Customer)<-[:PLACED_BY]-(o:Order)-[:HAS_PRODUCT]->(p:Product), (o)-[:PLACED_ON]->(d:Date)
and assuming that I have successfully found the Order's I am looking for, then how do I efficiently get the count i want out of these selected orders.
{... some queries that returns (o:Order) of interest ...}
With o
RETURN ??? as CountLastWeek, ??? as LastFortnight,  ??? as LastMonth

BTW i also have OrderedDate property on the Order if that helps simplify the query.
is it even possible to achieve this in Cypher?

A: What you're looking to do is date time indexing. This is most certainly possible to achieve with Cypher.
You'll need to index your nodes via relationships. Each date is a day, you need to batch those into groups. Each day has a week that it is in, and a month that it is in. You just need to add in those groups to your dates and then aggregate on the collections of dates belonging to a week, a fort night, or a month.


text:
Q: Blob image url to php not working This is my first time trying to deal with blob data.
I'm trying to send the blob image url via ajax to php for uploading the icon but it's not working, I am not sure if I'm even doing it correctly, can someone help me out?
console.log(apk.app.icon_url); // Prints: blob:http://localhost/9ca5a837-fdb4-4288-a21a-18e9650e6ac5

let data = new FormData();

data.append('icon', apk.app.icon_url);

$.ajax({
    url: "testicon.php",
    type: 'POST',
    data: data,
    contentType: false,
    processData: false,
    success: function(data) {
      alert(data); // PHP array returns empty
    }
});


text:
Q: iOS5 application failing to install on iPad 1 and iPad 2 I have application developed on xCode 4.3.1 with following build settings:
Architecture : standard (armv7) - $(ARCHS_STANDARD_32_BIT)
Base SDK : iOS5
Build Active Architecture Only : NO
Valid Architectures : armv6 armv7
In info.plist, the Required Device Capabilities does not have any entry.
I am trying to install on iPad1, iPad 2 and latest iPad (3). The provisioning file has been created with all Device IDs included. The application Archive file (.ipa) file has been created with above build setting.
While the application gets installed on Latest iPad (3) successfully, on both other iPads (iPad 1 and iPad 2) I get " Failed to Install" message when sync through iTunes is attempted as per defined procedure.
Kindly help if any change in build setting is required. I have already tried setting Architecture to armv6 + armv7.


text:
Q: Use valgrind xml-file and log-file option together Has anyone tried to use valgrind such that both the text log as well as the xml output are created?
I have tried:
1. To use these options together: --xml=yes --xml-file=log.xml --log-file=log.txt
   [ This only created the xml file. log.txt was empty]
2. All sorts of redirections ( &>, 2>&1, & tee) to create the log.txt since creating the xml is happening with the above mentioned xml flags
   [ Only the std output messages from my program came on to log.txt ]
Any other way to do this?

A: No need of using tool option to set it to 'memcheck', since by default valgrind uses 'memcheck' as the tool. Just for your information. Even there is no issue also, in using tool option.
Try using the below command, to get the logs in both XML file and log file.
valgrind --xml=yes --xml-file=XMLFile.log > Textlog.log 2>&1 test

Is this one you are expecting?
more information can be found in below link,
http://valgrind.org/docs/manual/manual-core.html#manual-core.basicopts

A: From the core manual for valgrind.

When enabled, the important parts of the output (e.g. tool error messages) will be in XML format rather than plain text.

I turned on verbose, --verbose, to get less important stuff to be printed and I now have my log and xml files populated while turned on at the same time.


text:
Q: Hard time adjusting string to fill Class I'm writing a Class library to extract data from a 3D model in a CAD software called SpaceClaim.
When I extract data from the model I get a string, the 3 usable possibilities below:
{Cone: Origin = (0.006, -0.006, 0.01), Direction = (0, 0, 1), Radius = 0.008, HalfAngle = 0.785398163397448}
{Cylinder: Origin = (-0.003, 0.001, 0), Direction = (0, 0, 1), Radius = 0.00921954445729289}
{Plane: Origin = (0, 0, 0.01), DirX = (1, 0, 0), DirY = (0, 1, 0), DirZ = (0, 0, 1)}

So first we have the type ( Plane, Cone Or Cilinder), then the Origin is a weird looking Array ( replace () with []), and for now i just need the Radius (if Type = Cone or Cilinder) and the HalfAngle (if Type = Cone)
I made a class called FaceInfo:
public class FaceInfo
    {
        public string Type { get; set; }
        public Coordinates Origin { get; set; }
        public double Radius { get; set; } = 0;
        public double HalfAngle { get; set; } = 0;
    }
public class Coordinates
    {
        public double X { get; set; }
        public double Y { get; set; }
        public double Z { get; set; }

        public Coordinates(string value)
        {
            string [] split = value.Split(new char[] { '(', ')', ',' });
            X = double.Parse(split[0]);
            Y = double.Parse(split[1]);
            Z = double.Parse(split[2]);
        }
    }

I've tried replacing characters, splitting, substrings.
All fails at some point.
Please some help. Thank you
PS. the coordinates class still takes () for the array, need to fix that too. But first, the returned string. No point in working with () or [] if the data is unreadable.

A: To extract the data you can use the following solution.
string pattern = @"\((?<origin>.*)\).+=\s*\((?<direction>.*)\).+=\s*(?<radius>[\d\.]*).+=\s*(?<halfAngle>.*)\}"; // continue the pattern for your needs
Regex rx = new Regex(pattern);

Match m = rx.Match(searchString);

FaceInfo faceInfo = new FaceInfo();

if (m.Success)
{
    faceInfo.Origin = new Coordinates(m.Groups["origin"].Value);
    faceInfo.Direction = new Coordinates(m.Groups["direction"].Value);
    faceInfo.Radius = Convert.ToDouble(m.Groups["radius"].Value);
    faceInfo.HalfAngle = Convert.ToDouble(m.Groups["halfAngle"].Value);
}

And modify the Coordinate class to
public class Coordinates
{
    public double X { get; set; }
    public double Y { get; set; }
    public double Z { get; set; }

    public Coordinates(string value)
    {
        string[] split = value.Split(new char[] { ',' });
        X = double.Parse(split[0]);
        Y = double.Parse(split[1]);
        Z = double.Parse(split[2]);
    }
}

A: It sounds like a parsing task. So I would go with (pseudo-code, so check me on this)
var lines = input.Split("\n");
Console.WriteLine(lines[0]); // for QA

foreach(var line in lines) {
 int index1= line.indexOf(":");
 string _type = line.SubString(1,index1);
 Console.WriteLine(_type); // for QA;
 string restOfLine = line.SubString(index1+1, line.Length - index1);
 Console.WriteLine(restOfLine); // for QA;
 var parts = restOfLine.Split(',');
  foreach(var p in parts) {
     Console.WriteLine(p); // for QA;
     // ... continue the parsing....
  }

  FaceInfo f = new FaceInfo();
  f.Type = _type;
  // f. .... whatever = whatever...
}

something like that? make sure you parse in a very correct way, since this text is not exactly in standard JSON format....that's what all the // for QA comments are for.

A: So let the string value is the input string you get from your CAD program. You already put sample inputs so I will use them too.
    {Cone: Origin = (0.006, -0.006, 0.01)
     ,
     Direction = (0, 0, 1), Radius = 0.008
     ,
     HalfAngle = 0.785398163397448}

When you use split with
      new char[] { '('  ,  ')'  , ',' }

it will parse the string whenever it sees a '(' , ')' or ','
So your output array from the split method will be look something like
0 => Cone: Origin
1 =>  0.006
2 =>  -0.006
3 =>   0.01
...
To see elements of your array, you can use
Simple way:
foreach(string element in splitOutputArray)
{
    // If you use form
    MessageBox.Show(element);

    // If you use console
    Console.WriteLine(element);
}

The more proper way: Use breakpoints.
https://learn.microsoft.com/en-us/visualstudio/debugger/using-breakpoints?view=vs-2022
So when you look at elements of your array you will notice the problem. Your indexing is not true.
Possible Solution:
Both your fields (Origin,Direction...) and values in the fields(0.006, -0.006, 0.01) split with ','. So you must look at elements of your output and correct your indexes.
        X = double.Parse(split[0]);
        Y = double.Parse(split[1]);
        Z = double.Parse(split[2]);

must be something like this
        X = double.Parse(split[1]);
        Y = double.Parse(split[2]);
        Z = double.Parse(split[3]);

Summary:
You did most of the work right but you must correct indexes (split[index]). Sorry if ı overexplained ı don't know your level.


text:
Q: Is there a good web front end to network shares My question is an offshoot of this question (Best Pratices for a Network File Share?). I feel like this has to have been asked, but I can't seem to find what I am looking for.
We are prepared to take the scorched earth path to fix our 8 years of "cruft" (per the suggestion of the cited question), but we also would like to make searching a bit easier. I have to feel like there is a better way access/manage/search a organization file share instead of having users SSH in or access through SMB.
So my question is broad, but what is the best way to run an organization file share?


text:
Q: .net 4.5 changing how Response.IsRequestBeingRedirected behaves on ajax calls - why? We've got an http module and some response filters that we've used for a long time to encrypt query string values on urls handled by our application.  Up until our QA dept installed .net 4.5.1 it had been working fine, and then it started to blow up.
Digging into it a little, it appears that .net 4.5(.1) changed how HttpContext.Current.Response.IsRequestBeingRedirected worked, but I haven't been able to find anything googling to explain why.
On one of our pages, for example, we have a button in an UpdatePanel that initiates an ajax call back to the server.  That ajax call results in a Response.Redirect call, which is turned into an ajax pageRedirect operation.
Pre-4.5.1, our added HttpResponse.Filter did the encryption on the redirect url, and when the request floated through our HttpModule.EndRequest handler,
HttpContext.Current.Response.IsRequestBeingRedirected = false;
HttpContext.Current.Response.RedirectLocation = null;
Now that we have 4.5.1,
HttpContext.Current.Response.IsRequestBeingRedirected = true;
HttpContext.Current.Response.RedirectLocation = null;
Having IsRequestBeingRedirected = true; has our module trying to encrypt a url that isn't there.
I've been trying to find a post or a summary explaining the behavior change but so far no luck.  Can anyone explain the reason for the change?
Thanks
Mark


text:
Q: Cambiar a PDO la consulta Tengo el siguiente código que me genera un archivo JSON, funciona bien, pero debo cambiarlo para envíar los datos entre el controlador y el modelo.
include "conex.php";

$sql= "select * from timetables";
$query = $con->query($sql);

// Fetch tha data from the database
$timetables = array();
while ($row = mysqli_fetch_array($query)) {
    $timetable = new stdClass();
    $timetable->name = $row{'name'};
    $timetable->image = $row{'image'};
    $timetable->date = date('j', strtotime($row{'date'})); // date : type DATE. For example: 2016-09-07
    $timetable->month = date('n', strtotime($row{'date'}));
    $timetable->year = date('Y', strtotime($row{'date'}));
    $timetable->start_time = $row{'start_time'} ? date('H:i', strtotime($row{'start_time'})) : ''; // start_time : Must be 24 hour format. For example: 18:00
    $timetable->end_time = $row{'end_time'} ? date('H:i', strtotime($row{'end_time'})) : ''; // end_time : Must be 24 hour format. For example: 20:30
    $timetable->color = $row{'color'};
    $timetable->description = utf8_encode(nl2br($row{'description'}));

    array_push($timetables, $timetable);
}

echo json_encode($timetables);

Yo hice lo siguiente pero con eso no puedo dividir el campo date como sucede en el código anterior.
class IdController{
    public function idController(){
        $id_URL = $_GET["id"];
        $respuesta = IdModels::idModel($id_URL, "timetables");
        echo json_encode($respuesta);
    }
}

Necesito en el controller poder dividir el date como esto:
$timetable->date = date('j', strtotime($row{'date'}));
$timetable->month = date('n', strtotime($row{'date'}));
$timetable->year = date('Y', strtotime($row{'date'}));

¿Cómo podría hacerlo?
Este es el Model:
class IdModels{
    public function idModel($id, $tabla){
        $stmt = Connex::conect()->prepare("SELECT name, image, date, start_time, end_time, color, description FROM $tabla WHERE court = $id");
        $stmt -> execute();
        return $stmt -> fetchAll();
        $stmt -> close();
    }
}


text:
Q: MongoDB, sort the results by the number of matching elements between two arrays In my project I use MongoDB as a database (specifically the mongoose driver for typescript, but this shouldn't matter) and I have a collection of posts that follow this schema:
export const PostSchema = new Schema({
  author: { type: Types.ObjectId, required: true, ref: 'User' },
  text: { type: String, required: true },
  tags: [{ type: Types.ObjectId, required: true, ref: 'Tag' }],
  location: { type: PointSchema, required: true },
}

export const PointSchema = new Schema({
  type: {
    type: String,
    enum: ['Point'],
    required: true,
  },
  coordinates: {
    type: [Number],
    required: true,
  },
  locationName: {
    type: String,
    required: true,
  },
});

My question is if it is possible to write a query (I think an aggregation is needed) that returns all posts that meet a condition (such as that the position must be at a specific distance) and orders the results by a specific array of tags passed as an argument (in my case the array varies from user to user and represents their interests).
That is, choosing the array ["sport", "music", "art"] as an example, I would like a query that retrieves from the database all the posts that meet a certain condition (irrelevant in this question) and orders the results so that first are documents whose array of tags share elements with the array ["sport", "music", "art"], and only at the end the documents without any correspondence.
That is, something like this:
[
{
  _id: "507f191e810c19729de860ea",
  tags: ["sport", "art", "tennis"] // 2 matches
},
{
  _id: "507f191e810c1975de860eg",
  tags: ["sport", "food"] // 1 matches
},
{
  _id: "607f191e810c19729de860ea",
  tags: ["animals", "art"] // 1 matches
},
{
  _id: "577f191e810c19729de860ea",
  tags: ["animals", "zoo"] //0 matches
}
]

A: if your collection looks like this:
[
    {
        "author": "John",
        "tags": [
            ObjectId("60278ce8b370ff29b83226e2"), // Sport
            ObjectId("60278ce8b370ff29b83226e8"), // Music
            ObjectId("60278ce8b370ff29b83226e5"), // Food
        ]
    },
    {
        "author": "Dheemanth",
        "tags": [
            ObjectId("60278ce8b370ff29b83226e7"), // Tech
            ObjectId("60278ce8b370ff29b83226e5"), // Food
            ObjectId("60278ce8b370ff29b83226e2")  // Sport
        ]
    },
    {
        "author": "Niccolo",
        "tags": [
            ObjectId("60278ce8b370ff29b83226e2"), // Sport
            ObjectId("60278ce8b370ff29b83226e8"), // Music
            ObjectId("60278ce8b370ff29b83226e3")  // Art
        ]
    }
]

then this is the solution:
db.posts.aggregate([
  {
    $lookup: {
      from: "tags",
      let: { "tags": "$tags" },
      pipeline: [
        {
          $match: {
            $expr: { $in: ["$_id", "$$tags"] }
          }
        }
      ],
      as: "tags"
    }
  },
  {
    $addFields: {
      "tagCount": {
        $size: {
          $filter: {
            input: "$tags",
            as: "tag",
            cond: { $in: ["$$tag.name", ["sport", "music", "art"]] }
          }
        }
      }
    }
  },
  {
    $sort: { tagCount: -1 }
  },
  {
    $project: {
      _id: 1,
      tags: "$tags.name"
    }
  }
])

Output:
[
  {
    "_id": ObjectId("60278e14b370ff29b83226eb"),
    "tags": ["sport", "art", "music"]
  },
  {
    "_id": ObjectId("60278e14b370ff29b83226e9"),
    "tags": ["sport", "food", "music"]
  },
  {
    "_id": ObjectId("60278e14b370ff29b83226ea"),
    "tags": ["sport", "food", "tech"]
  }
]