text:
Q: Preparation for std::iterator Being Deprecated On March 21st the standards committee voted to approve the deprecation of std::iterator proposed in P0174:

The long sequence of void arguments is much less clear to the reader than simply providing the expected typedefs in the class definition itself, which is the approach taken by the current working draft, following the pattern set in c++14

Before c++17 inheritance from std::iterator was encouraged to remove the tedium from iterator boilerplate implementation. But the deprecation will require one of these things:

*

*An iterator boilerplate will now need to include all required typedefs

*Algorithms working with iterators will now need to use auto rather than depending upon the iterator to declare types

*Loki Astari has suggested that std::iterator_traits may be updated to work without inheriting from std::iterator
Can someone enlighten me on which of these options I should expect, as I design custom iterators with an eye towards c++17 compatibility?

A: The discussed alternatives are clear but I feel that a code example is needed.
Given that there will not be a language substitute and without relying on boost or on your own version of iterator base class, the following code that uses std::iterator will be fixed to the code underneath.
With std::iterator
template<long FROM, long TO>
class Range {
public:
    // member typedefs provided through inheriting from std::iterator
    class iterator: public std::iterator<
                        std::forward_iterator_tag, // iterator_category
                        long,                      // value_type
                        long,                      // difference_type
                        const long*,               // pointer
                        const long&                // reference
                                      > {
        long num = FROM;
    public:
        iterator(long _num = 0) : num(_num) {}
        iterator& operator++() {num = TO >= FROM ? num + 1: num - 1; return *this;}
        iterator operator++(int) {iterator retval = *this; ++(*this); return retval;}
        bool operator==(iterator other) const {return num == other.num;}
        bool operator!=(iterator other) const {return !(*this == other);}
        long operator*() {return num;}
    };
    iterator begin() {return FROM;}
    iterator end() {return TO >= FROM? TO+1 : TO-1;}
};

(Code from http://en.cppreference.com/w/cpp/iterator/iterator with original author's permission).
Without std::iterator
template<long FROM, long TO>
class Range {
public:
    class iterator {
        long num = FROM;
    public:
        iterator(long _num = 0) : num(_num) {}
        iterator& operator++() {num = TO >= FROM ? num + 1: num - 1; return *this;}
        iterator operator++(int) {iterator retval = *this; ++(*this); return retval;}
        bool operator==(iterator other) const {return num == other.num;}
        bool operator!=(iterator other) const {return !(*this == other);}
        long operator*() {return num;}
        // iterator traits
        using difference_type = long;
        using value_type = long;
        using pointer = const long*;
        using reference = const long&;
        using iterator_category = std::forward_iterator_tag;
    };
    iterator begin() {return FROM;}
    iterator end() {return TO >= FROM? TO+1 : TO-1;}
};

A: Option 3 is a strictly more-typing version of Option 1, since you have to write all the same typedefs but additionally wrap iterator_traits<X>.
Option 2 is unviable as a solution. You can deduce some types (e.g. reference is just decltype(*it)), but you cannot deduce iterator_category. You cannot differentiate between input_iterator_tag and forward_iterator_tag simply by presence of operations since you cannot reflexively check if the iterator satisfies the multipass guarantee. Additionally, you cannot really distinguish between those and output_iterator_tag if the iterator yields a mutable reference. They will have to be explicitly provided somewhere.
That leaves Option 1. Guess we should just get used to writing all the boilerplate. I, for one, welcome our new carpal-tunnel overlords.


text:
Q: Is there a word for "property manager" that also includes landlords? I'm trying to communicate something along the lines of:

Your property manager or landlord should be available in the event of an emergency.

I'd like to make "property manager or landlord" more concise.  Property manager works well for condos that are owned by a company; landlord works well for properties that are individually owned; but I don't know what word to use that clearly applies to both.

A: Assuming that you are drawing a fine distinction between the two words (often they are one and the same) you could use:

A representative of your building should be available in the event of an emergency.

Note that a representative can be even broader than either property manager or landlord. It could be, for instance, a lawyer or assistant who is authorized to speak on behalf of the owner or manager.

redpajama_set_name: RedPajamaStackExchange


text:
Q: JavaFX: handle key combination and mouse event simultaneously I need to react on a key + mouse event combination like:
Ctrl + Shift + R + left_mousebutton_clicked
But I can't figure out, how to handle the "left_mousebutton_clicked" only if the key combination of Ctrl + Shift + R occurs.
A solution like
if(MouseEvent.isControlDown())

will not work cause there may be different key combinations with any kind of the letters.
Any ideas?

A: You can use a container to store the currently pressed keys:
private final Set<KeyCode> pressedKeys = new HashSet<>();

You can attach listeners to the Scene of the control the you want to target with the mouse-click:
scene.setOnKeyPressed(e -> pressedKeys.add(e.getCode()));
scene.setOnKeyReleased(e -> pressedKeys.remove(e.getCode()));

While these listeners maintain the set, you can simply attach a listener on the target Node:
Label targetLabel = new Label("Target Label");
targetLabel.setOnMouseClicked(e -> {
    if (e.getButton() == MouseButton.PRIMARY &&
        pressedKeys.contains(KeyCode.R) &&
        e.isShortcutDown() &&
        e.isShiftDown())

        System.out.println("handled!");
});

Example Application:
public class MouseClickExample extends Application {

    private final Set<KeyCode> pressedKeys = new HashSet<>();

    public static void main(String[] args) {
        launch(args);
    }

    @Override public void start(Stage stage) {
        VBox root = new VBox();
        Scene scene = new Scene(root, 450, 250);

        scene.setOnKeyPressed(e -> pressedKeys.add(e.getCode()));
        scene.setOnKeyReleased(e -> pressedKeys.remove(e.getCode()));

        Label targetLabel = new Label("Target Label");
        targetLabel.setOnMouseClicked(e -> {
            if (e.getButton() == MouseButton.PRIMARY && pressedKeys.contains(KeyCode.R) && e.isShortcutDown() && e.isShiftDown())
                System.out.println("handled!");
        });

        root.getChildren().add(targetLabel);
        stage.setScene(scene);
        stage.show();
    }
}

Note: The meta keys are also stored in the Set but they are not used by this example. The meta keys could be also checked in the set rather than using methods on the mouse-event.

A: Both ctrl and shift can be done the way you aproached it there. The left mouse key is the PrimaryButton
if(mouseEvent.isControlDown() && mouseEvent.isShiftDown && mouseEvent.isPrimaryKeyDown){
    // Do your stuff here
}

And for the "non special" key (like r) I thnk you need to make a global boolean - and a seperate keyevent listener for it. So:
boolean rIsDown = false;

scene.setOnKeyPressed(e -> {
if(e.getCode() == KeyCode.R){
    System.out.println("r was pressed");
    //set your global boolean "rIsDown" to true
}
});

scene.setOnKeyReleased(e -> {
if(e.getCode() == KeyCode.R){
    System.out.println("r was released");
    //set it rIsDown back to false
}
});

Then use your it together with the other conditions...
    if(mouseEvent.isControlDown() && mouseEvent.isShiftDown && rIsDown &&  mouseEvent.isPrimaryKeyDown){
    // Do your stuff here
}


text:
Q: Custom Sort Order Using System.Linq.Dynamic I have records that are given a class that i need to order by.
The values are simple 0,1,2.  The problem is the client needs the records to appear in a order based on there class name not class value. The order should appear as seen below.
class (TBD)= 0
class (2/3)= 2
class (1)= 1

Using System.Linq.Dynamic i have been able to pass columns and there direction into my OrderBy(). Is there a way to pass in a expression that would force the sort order to be
Ascending:
    class (TBD)= 0,
    class (2/3)= 2 ,
    class (1)= 1
Descending:
class (1)= 1,
class (2/3)= 2,
class (TBD)= 0
I have tried
asc:
sort = "(Class = 0) desc, (Class = 2) desc, (Class = 1) desc";

desc:
sort = "(Class = 1) desc, (Class = 2) desc, (Class = 0) desc";

But i get Operator '=' incompatible with operand types 'String' and 'Int32' Before that i was using '==' and got a similar message.
 searchUniq = searchUniq.OrderBy(sort).Skip(skip).Take(25);

A: Your string is not a valid sort syntax for Dynamic Linq. Try:
sort = "iif(Class == 1, 0, iif(Class == 2, 1, 2))";

This uses the inline if expression available in Dynamic Linq (at least one flavor of it; see here for more documentation) to transform the Class values into something intuitively orderable. The vanilla SQL equivalent is to order by a case statement.


text:
Q: Kotlin. Can I get all Objects that implements specific interface I have something like:
interface Options {
    fun load(conf: JsonObject)
}

object BasicOptions : Options { }
object PersonOptions : Options { }
object CarOptions : Options { }

then I would like to get all Objects that implements Options interface and call load forEach.
fun main(args: Array) {
    configFuture.whenComplete { config ->
            options.forEach { it.load(config) }
    }
}

A: This is not supported by the language, this is why there are Dependency Injection, Registry, or Service Lookup solutions.

*

*If all objects are registered in a Dependency Injection framework, you may be able to iterate all objects registered to the framework and find the instances of your Interface.

*

*This is likely to be rather inefficient - so cache the results to avoid the extra overhead.

*Another approach is to use custom class loader and add this custom functionality. The simplest way is probably using the Reflections library, to scan and load these classes. E.g.:
val reflections = Reflections("my.project.prefix")
val allClasses = reflections.getSubTypesOf(Options::class.java)

*The simplest, and most commonly used solution would be simply maintain your own "registry" e.g. a static object holding the list of all instances. It will require manually adding any new class implementing the interface - but it will be simple, performant, and robust solution.

A: Of course, you can!
Using the Reflections library it's really easy:
First, you need to find all the java classes that implement your interface "Objects". Then you convert the java classes to kotlin classes (KClass).
KClass has the property objectInstance that is null if the class does not have an object instance... otherwise IS the singleton object instance.
So:
val reflections = Reflections(ConfigurationBuilder())
val jList = reflections.getSubTypesOf(Options::class.java)
val kList = jList.map { it.kotlin }
val oList = kList.map { it.objectInstance }.filterNotNull()

;-)

A: You can always use the Factory pattern for creating new instances of Options, that way you can have your own OptionsFactory and your own caching mechanism.
That OptionsFactory after instantiating an object keeps it in cache (could be in-memory cache or DB..etc), then anytime you can ask the factory for it's cached instances when needed.
This is fairly better when your Options objects are created in run-time/upon demand.


text:
Q: Testing performance of APIs that include several steps I want to test the performance of a REST API while simulating the actions performed by a user in the GUI. It needs to be able to perform a total of 4 requests in sequence, where request 2, 3 and 4 is based on information received in the first request (getting IDs, locations, etc, and then using those in request 2,3 and 4), and then store the results from each request.
Is there any testing frameworks that are capable of performing such actions programatically? Preferably based on JAVA, but not necessarily. I'm planning to run this for an estimation of 30 users. Any tips would be appreciated

A: The most popular Java-based test framework is REST-assured, for multithreading you can use either ExecutorService or Java Microbenchmark Harness
Alternatively you can go for a load testing tool, the most popular of the Java-based ones are:

*

*Apache JMeter - where you can create API tests using GUI, see REST API Testing - How to Do it Right for details

*Gatling - it's in Scala but runs in JVM, see API Load Testing With Gatling to get started


text:
Q: Erro tentando desenhar grafico: "comprimento do objeto maior não é múltiplo do comprimento do objeto menor" Tenho uma função:
my_gamma = function(x)
{
    f = function(t){t^(x-1) * exp(-t)}
    integrate(f, 0, Inf)
}

Estou tentando desenhar o seu gráfico com ggplot2:
plot = ggplot(data.frame(x = seq(0.01, 10)), aes(x=x))
(plot + stat_function(fun = my_gamma))

Mas está me dando o erro:
Warning messages:
1: In t^(x - 1) :
  comprimento do objeto maior não é múltiplo do comprimento do objeto menor
2: In t^(x - 1) * exp(-t) :
  comprimento do objeto maior não é múltiplo do comprimento do objeto menor
3: Computation failed in `stat_function()`:
evaluation of function gave a result of wrong length

O que estou a fazer de errado?

A: O principal problema é que a função não está vetorizada.
O segundo problema é que integrate retorna uma lista, mas stat_function precisa de um vetor de números.
Então, primeiro corrige-se a função.
my_gamma <- function(x){
  f <- function(t){t^(x - 1) * exp(-t)}
  integrate(f, 0, Inf)$value
}

Agora vetoriza-se e testa-se a forma vetorizada.
myGamma <- Vectorize(my_gamma)
myGamma(seq(0.1, 10, length.out = 20))
# [1] 9.513504e+00 1.442807e+00 9.356940e-01 9.021743e-01 1.092452e+00
# [6] 1.551187e+00 2.488839e+00 4.409250e+00 8.490126e+00 1.756589e+01
#[11] 3.871311e+01 9.026446e+01 2.214427e+02 5.690236e+02 1.525743e+03
#[16] 4.255200e+03 1.230969e+04 3.684868e+04 1.139016e+05 3.628800e+05

Finalmente, o gráfico. Incluí um argumento length.out em seq.
plot <- ggplot(data.frame(x = seq(0.01, 10, length.out = 20)), aes(x=x))
plot + stat_function(fun = myGamma)


text:
Q: How to cache custom pages using W3 Total Cache? Some posts are requested through Ajax.
<?php
// Filename: ajax-posts.php
require_once "wp-load.php";
echo my_get_post($_GET["id"]);
?>

How can I make theese Ajax requests cacheable by W3 Total Cache?

A: Short answer: You can't. Getting W3 Total Cache to talk to a non-WP call in manor listed above isn't (easily) possible. I completely agree with @allenericr comments. The Transients API is very straight forward and quite simple to implement. In addition, @allenericr, comment on using admin-ajax.php is also spot on. It's not sure it's best practices to just include wp-load and call it good (sounds like a big security hole).


text:
Q: grails button to do ajax call to change textbox I have a method in my controller
def returnJames = {
    JSONObject jsonObject = new JSONObject()
    jsonObject.put("name","James")
    return jsonObject
}

and then I have a view:
<html>
<!--import gsp that has all the jquery imports-->
<script>
function changeName()
    {
        $.ajax({
            url:"<g:createLink url="[action:'returnJames',controller:'mycontroller']" />",
            dataType: "json",
            asnyc: false,
            success: function(data) {
                $('mytextbox').val(it.name)
            }
        });
    }
</script>
<g:form controller="mycontroller" method="post" >
<g:textField name="mytextbox" value="" />
<button name = "mybutton" id = "mybutton" onclick="changeName()">change name</button>
</g:form>
</html>

However it just tries to change the page to the index view of the mycontroller controller which doesn't exist.  How can I get it to just fill in the textbox with "James"?

A: User render instead of return
render jsonObject

and change in jQuery
success: function(data) {
    $('#mytextbox').val(data.name)
}

change button to
<input type="button" id = "mybutton" onclick="changeName()" value="change name"/>


text:
Q: SharePoint Web Part & Singletons I have a sharepoint project where we override search box and some other things. We also have a web part page that responds to the search box. All these components should share single configuration. I thought about creating a singleton, but I am not sure how would that ever get cleaned up / removed from the memory / uninstalled.
Any ideas? Any warnings about using singletons in sharepoint? Also, is there a proper way to share an instance of an object between all these componenets?
Edit: I was thinking about a very simple singleton. Configuration only needs to contain 5-20 strings and a dozen integers at most. No complex objects :)

A: As long as the objects being managed by your singleton class are thread-safe there shouldn't be an issue.
EXAMPLE:
I have a series of object-calls that were taking a long-time to process (7+ seconds). So, I decided to try using a comet-styled long-polling technique to process them.  As such, I host a service (as a static singleton) in a single thread and process requests using asynchronous HttpHandler's...and it works GREAT!  And because I'm using the service asynchronously it's highly efficient because the calling thread gets released immediately (upon completion of processing the service completes the callback).
EDIT:
But your problem of a long processing time still exists, so you still (probably) need an asynchronous solution for the initial fetch. Hows this?  Why not COMBINE the asych-solution with custom-caching?
For various (accessibility) reasons, I save my appSetting's in the database and use a custom-cache for access thereafter.
EXAMPLE of a Custom Cache:
public enum ConfigurationSection
{
    AppSettings
}

public static class Utility
{
    #region "Common.Configuration.Configurations"

    private static Cache cache = System.Web.HttpRuntime.Cache;

    public static String GetAppSetting(String key)
    {
        return GetConfigurationValue(ConfigurationSection.AppSettings, key);
    }

    public static String GetConfigurationValue(ConfigurationSection section, String key)
    {
        Configurations config = null;

        if (!cache.TryGetItemFromCache<Configurations>(out config))
        {
            config = new Configurations();
            config.List(SNCLavalin.US.Common.Enumerations.ConfigurationSection.AppSettings);
            cache.AddToCache<Configurations>(config, DateTime.Now.AddMinutes(15));
        }

        var result = (from record in config
                      where record.Key == key
                      select record).FirstOrDefault();

        return (result == null) ? null : result.Value;
    }

    #endregion
}

namespace Common.Configuration
{
    public class Configurations : List<Configuration>
    {
        #region CONSTRUCTORS

        public Configurations() : base()
        {
            initialize();
        }
        public Configurations(int capacity) : base(capacity)
        {
            initialize();
        }
        public Configurations(IEnumerable<Configuration> collection) : base(collection)
        {
            initialize();
        }

        #endregion

        #region PROPERTIES & FIELDS

        private Crud _crud; // Db-Access layer

        #endregion

        #region EVENTS
        #endregion

        #region METHODS

        private void initialize()
        {
            _crud = new Crud(Utility.ConnectionName);
        }

        /// <summary>
        /// Lists one-to-many records.
        /// </summary>
        public Configurations List(ConfigurationSection section)
        {
            using (DbCommand dbCommand = _crud.Db.GetStoredProcCommand("spa_LIST_SecConfiguration"))
            {
                _crud.Db.AddInParameter(dbCommand, "@Section", DbType.String, section.ToString());

                _crud.List(dbCommand, PopulateFrom);
            }

            return this;
        }

        public void PopulateFrom(DataTable table)
        {
            this.Clear();

            foreach (DataRow row in table.Rows)
            {
                Configuration instance = new Configuration();
                instance.PopulateFrom(row);
                this.Add(instance);
            }
        }

        #endregion
    }

    public class Configuration
    {
        #region CONSTRUCTORS

        public Configuration()
        {
            initialize();
        }

        #endregion

        #region PROPERTIES & FIELDS

        private Crud _crud;

        public string Section { get; set; }
        public string Key { get; set; }
        public string Value { get; set; }

        #endregion

        #region EVENTS
        #endregion

        #region METHODS

        private void initialize()
        {
            _crud = new Crud(Utility.ConnectionName);
            Clear();
        }

        public void Clear()
        {
            this.Section = "";
            this.Key = "";
            this.Value = "";
        }
        public void PopulateFrom(DataRow row)
        {
            Clear();

            this.Section = row["Section"].ToString();
            this.Key = row["Key"].ToString();
            this.Value = row["Value"].ToString();
        }

        #endregion
    }
}

A: If your object is simply configuration (loaded once, and stays read only from that point) I'd not worry about it beeing singleton or about if/when it will be garbage collected (object will not be collected unless you set it to null).
In general in server environment (like SharePoint) you want to make sure 2 things about object before thinking about making it singleton:

*

*technical aspects (mainly thread safety as pointed by Prisoner ZERO, but also how much memory it uses, if it holds critical resources likle files)

*security aspects - it is extremly easy to leak user's information into singleton object and use it by mistake by some other user. It also possible to cache some information in singleton that one user have access to and than retrive by another user that should not have access to such information.

A: I think you may be over complicating this and falling into the trap of premature optimisation.
You indicate that your object doesn't have anything more than a couple of dozen strings/integers so presumably you're not doing any expensive setup and therefore is there actually anything to be gained going the singleton approach?
Furthermore the real question here is where these strings/integers are going to be stored - if its hardcoded into your class then you can't update it easily so it would be better to store that config somewhere else.
Six Ways to to store settings in SharePoint
But IHMO the best way to do this is following the MSDN SharePoint Guidance Library which uses the Property Bag storage for their implementation of a hierarchical Configuration Manager which allows you to do things like a farm wide setting but overridden for certain site collections/sites etc.
So in conclusion I personally would

*

*Implement the config object as a simple object reading values from config manager

*Montor/profile and change to a singleton if necessary


text:
Q: Simple number guessing game using binary search algorithm in C This program requires me to: Write a program that plays a simple number-guessing with its user. The user thinks of a number and then answers a series of questions asked by the computer until it correctly guesses the
number.
My problem is that the compiler says that: 'arr' undeclared (first use in this function)
Here is my code so far:
#include <stdio.h>
#include "strlib.h"
#include "simpio.h"

#define size 200

int binSearch (int num);
void getArray (int arr[]);

main()
{
      printf("Think of a number in the range of 1-200 and I'll guess it.\n");
      int arr[size];
      getArray(arr);
      binSearch(arr);
      getchar();
}

void getArray (int numbers[])
{
      int number;

      for(number=1;number>=200;number++)
      {
                 arr[number]=number;
      }
}

int binSearch(int num)
{
      int low, high, mid;
      string strReply;

      low=0;
      high=size-1;

      while(low<=high);
      {
                 mid=low+high/2;
                 printf("\nIs the number %d ?\t", mid);
                 strReply= GetLine();
                 if(StringEqual(strReply, "no"))
                 {
                          printf("Is the number less than %d ?\t", mid);
                          if(StringEqual(strReply, "no"))
                          {
                                     high=mid-1;
                          }
                          else if(StringEqual(strReply, "yes"))
                          {
                                     low=mid+1;
                          }
                 }
                 else if(StringEqual(strReply, "yes"))
                 {
                          return(mid);
                 }
                 else
                 {
                          return(-1);
                 }
}

Thank you :)

A: void getArray (int numbers[])
{
  int number;

  for(number=1;number>=200;number++)
  {
             arr[number]=number;     // this should be numbers[number]
  }
}

You pass the array to the function, but use the array as if it were global.

A: What @Adrian Jandl said.
Also note your loop is wrong twice:
for(number=0; number<200; number++) ...

*

*Arrays are zero based in C.

*You count while number<200, not until number>=-200.

A: arr is not defined or declared in getArray function. And also arr is not global variable. You can move arr int main() function to global area.


text:
Q: When connecting my NAS to a switching hub port why doesn't the LNK led light up? I have two NAS devices. One LinkSys an one Netgear. When connecting either of them (via Category-5 LAN cable) to a 10/100M switching hub port, the LNK lamp for that port does not light up? If I connect a normal PC to the same port (with the same cable) the LNK lamp lights up and that PC can be seen on the network.
NOTE: If I connect wither of my NAS devices to the ports on the router the LNK lamps light up and they can be seen on my network.
Why does this happen? Is it due to different standards? My switching hub came out about 10 years before home NAS devices were available or affordable.

A: Try to use a cross over cable. Normally the hubs(old switches too) aren't capable of make the auto switching like common switches
Check this URL DTE and DCE


text:
Q: Deleting rows in a foreach I'm trying to update a sheet with an import of a .CSV file..
I can read and update all the information. After the update I want to remove some data. All the rows with D empty must be deleted (whole row).
For that, I have a foreach that checks D3:D486 (is last row).
After running the macro, there are some rows deleted, but not all the rows.
    Dim rCell As Range
    Dim rRng As Range
    Debug.Print CStr(LastRow)

    Set rRng = Worksheets("sheet1").Range("D3:D" + CStr(LastRow))

    For Each rCell In rRng.Cells
        If Not IsEmpty(rCell) Then
            Debug.Print rCell.Row
        Else
            Debug.Print "Empty"
            Worksheets("sheet1").Rows(rCell.Row).Delete
        End If
    Next rCell

I guess there is a problem with the for-each.. By example, If he delete row 100, the next time he goes to row 101.. But thats previous row 102..
I can save the cells maybe in an array, but then it would be the same.
Except if I go the other way (from bottom to top). How can I solve this?

A: i think you've answered your own question: from bottom to top...
and you can try range.EntireRow.Delete method too, something like below
Dim rCell As Range
Dim lastRow, i
lastRow = 1000
For i = lastRow To 1 Step -1
    ' if condition met
    Worksheets("Sheet1").Range("D:" + i).EntireRow.Delete
Next

A: I would do it like this:
Dim i As Integer
Dim rRng As Range
Debug.Print CStr(LastRow)

Set rRng = Worksheets("sheet1").Range("D3:D" + CStr(LastRow))

For i = 1 To rRng.Cells.Count
    If Not IsEmpty(Worksheets("Sheet1").Range("D:" + i).Value) Then
        Debug.Print rCell.Row
    Else
        Debug.Print "Empty"
        Worksheets("Sheet1").Range("D:" + i).EntireRow.Delete
        i = i - 1
    End If
Next

A: Rex answer is correct, if you want to get cute you can also do it this way:
Sub DeleteRowsWithCriteria()
Dim rng As Range, rngCell As Range, rngDelete As Range
Set rng = Worksheets("sheet1").UsedRange.Columns("D:D").Cells 'Watch out here, if columns A-C are not all used, this doesn't work
For Each rngCell In rng
    If rngCell.Value = "" Then
        If rngDelete Is Nothing Then
            Set rngDelete = rngCell
        Else
            Set rngDelete = Union(rngDelete, rngCell)
        End If
    End If
Next rngCell
rngDelete.EntireRow.Delete xlShiftUp
End Sub


text:
Q: How to indicate index of NSIndexSet object? everyone.
I want to indicate index of NSIndexSet object.
Find various method but I can't find.
How to indicate index of NSIndexSet object?
NSMutableArray *array = [[NSMutableArray alloc]initWithObjects:@"A",@"B",@"C",@"A", nil];

NSIndexSet *indexset = [array indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
    return [obj isEqual:@"A"];
}];

NSLog(@"%@",[array objectsAtIndexes:indexset]);

// I want to indicate index of NSIndexSet object.
NSLog(@"%d",[indexset ?]);

A: If you want to get number of indices stored in NSIndexSet then use count property:
NSLog(@"%d",[indexset count]);

A: From, iOS 4.0 and > there's few method which enumerates the NSIndexSet,
here's the one which answering to this question, - (void)enumerateIndexesUsingBlock:(void (^)(NSUInteger idx, BOOL *stop))block
[indexset enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {
    NSLog(@"%d=>%@",idx,[array objectAtIndex:idx]);
}];


text:
Q: What are some of the more interesting ways you have used memcached? After implementing a memcached caching layer into my schema tools I'm wondering if there is more capability to use memcached services other than the canonical:
rec = cache.get(make_cache_key(k))
if rec: return rec
rec = dbi.execute(query_string(k))
cache.set(make_cache_key(k), rec)
return rec

usage of row caching?
Anything like JSON/XML caching of structured data? Graph data? Images?

A: At that point, redis starts looking far more useful!
http://www.redis.io/


text:
Q: How to solve the problem which is a sum of convex and nonconvex functions? I attempt to solve an optimization which is a sum of two convex functions and one non-convex function described as follows:
$$g(x,y) = a{\log_2}{\left( {1 + x} \right)} + b\log_2 \left[ 1 + c(x - dy) \right] - x(y+e)$$
The two logarithm terms are convex (can prove the convexity using hessian matrix) while the third term in the function $g(x,y)$ is non-convex.
Could anyone give me a suggestion to solve this problem? Thanks a lot.


text:
Q: python labelling new data points in a histogram I am currently using this code to draw a histogram.
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import FormatStrFormatter

data = np.random.randn(82)
fig, ax = plt.subplots()
counts, bins, patches = ax.hist(data, facecolor='yellow', edgecolor='gray')

# Set the ticks to be at the edges of the bins.
ax.set_xticks(bins)
# Set the xaxis's tick labels to be formatted with 1 decimal place...
ax.xaxis.set_major_formatter(FormatStrFormatter('%0.1f'))

# Change the colors of bars at the edges...
twentyfifth, seventyfifth = np.percentile(data, [25, 75])
for patch, rightside, leftside in zip(patches, bins[1:], bins[:-1]):
    if rightside < twentyfifth:
        patch.set_facecolor('green')
    elif leftside > seventyfifth:
        patch.set_facecolor('red')

# Label the raw counts and the percentages below the x-axis...
bin_centers = 0.5 * np.diff(bins) + bins[:-1]
for count, x in zip(counts, bin_centers):
    # Label the raw counts
    ax.annotate(str(count), xy=(x, 0), xycoords=('data', 'axes fraction'),
        xytext=(0, -18), textcoords='offset points', va='top', ha='center')

    # Label the percentages
    percent = '%0.0f%%' % (100 * float(count) / counts.sum())
    ax.annotate(percent, xy=(x, 0), xycoords=('data', 'axes fraction'),
        xytext=(0, -32), textcoords='offset points', va='top', ha='center')

# Give ourselves some more room at the bottom of the plot
plt.subplots_adjust(bottom=0.15)
plt.show()

I want to add x marks (labelled with "orange", "apple", "pineapple") of a given histogram x-axis value on the histogram as shown:
How should I do so?
The x marks do not have a y value.

A: All stays the same except for these lines:
...
# Change the colors of bars at the edges...
left = []
right = []
twentyfifth, seventyfifth = np.percentile(data, [25, 75])
for patch, rightside, leftside in zip(patches, bins[1:], bins[:-1]):
    if rightside < twentyfifth:
        patch.set_facecolor('green')
        left.append(leftside)

    elif leftside > seventyfifth:
        patch.set_facecolor('red')
        right.append(rightside)

ax.text(left[int(len(left)/2)], 1, 'orange\n    x')
ax.text(right[0], 1, 'pineapple\n       x')
ax.text((left[int(len(left)/2)] + right[0]) / 2, 1, 'apple\n   x')

# Label the raw counts and the percentages below the x-axis...
bin_centers = 0.5 * np.diff(bins) + bins[:-1]
...

Output:

---edit---
OP added the data and asked for an edit.
The code from OP in the question stays as it is, the following lines are to be added after.
data = {'product_name': ['laptop', 'printer', 'tablet', 'desk', 'chair'],'price': [2, 0.1, 2.4, 2.2, 1]}
ax.scatter(data['price'], [1]*len(data['price']), zorder=2, marker='x', c='k')
for i in range(len(data['price'])):
    ax.text(data['price'][i]-0.2, 1.5, f"{data['product_name'][i]}")

Output:

The annotations are overlapping, but this is expected due to the x-values given by the OP (very close to each other).


text:
Q: Is SO supposed to be a knowledge database? I think it should be. Reading Embrace the non-Googlers gives me confidence I'm not the only one. But I got burned today. I asked a question (Setting up Python for web development on Windows) with a sort of long introduction, hoping it will help generate detailed answers in a true knowledge-database style.
Unfortunately, an experienced user saw my introduction as off-topic, deleted it, and I got a few answers that have little to do with my question, before others closed it, because it "will likely solicit debate, arguments, polling, or extended discussion".
OK, humor may be perceived as off-topic, but my introduction was a part of the question, and without it, the question has a totally different meaning. Now it's useless to me and everyone else.
When you see a trivial question, or the one that you find stupid, to long, unclear, whatever... Should you edit it to your likeness, close it, downvote it without explanation, or call it stupid in a comment or an answer? Would that be constructive? Or should you try and explain why it's not good, why it probably won't get any good answers, educate the asker, or just ignore it if you don't care wasting time?
I don't mind being downvoted, that's what the voting system is for, but please don't change my words. They won't pollute the Internet. And if someone would spare this hour of her/his time to post the answer to my question as asked originally, I think that could be of big help to many. So, why preventing them, it's not your time they're going to be wasting.
EDIT: I got it all wrong. If majority of people see my intro as noise - it's noise. Knowledge database should not hold any noise, and in order to avoid it, questions should be asked in purely technical manner.

A: Yes, Stack Overflow is aiming to be an easily searchable repository of commonly asked technical questions with focused answers. To that goal, we want focused questions where people don't have to read a multi-paragraph setup in order to get to the meat of the question. Everyone over a certain reputation level has the ability to edit questions and answers to refine them towards this goal.
Your intro:

<rant> I don't understand why is it so hard to write a good explanation/guide/tutorial, to include some kind of graphical
  representation of what is going on, to explain each step so one can
  understand what she/he is doing and not just carbon copy (so she/he
  could know what to google when the problem arises in the course of
  installation/setup).
Yes, I know most/all of these tools are for free, and people make them
  and write guidelines in there spare time so newbies can use them
  without having to read tons of books, and get to know all the
  technologies involved, but... I do staff for free too, and help
  people, but if I give a hungry man a can of food, I won't tell him "go
  find a can opener for yourself" if I have one in my back pocket.
If I understand the purpose of Stack Overflow, this should be the
  place where you can find the answers you need in a familiar format,
  not the links to possible answers in an unfamiliar format. Of course I
  can google (I did google before I posted the question, and was
  overwhelmed by vast variety of tutorials and answers to questions
  similar to mine, that were not really helpful in my specific case),
  but I think this post nailed it: [Embrace the non-Googlers][1]. If no
  one would have an answer to this question, hopefully I will find it
  myself and give the can opener to other hungry people out
  there.</rant>

has nothing to do with the core technical issue you're asking about, and is unnecessary here. Therefore, the edit to remove it was justified. Why should someone visiting the site in the future care about your feelings towards other tutorials? They're going to hit your question to find out an answer to what you're asking, and they want to read only items relevant to that.


text:
Q: plotting list object using ggplot I'm running some simulations that I was wondering to plot the outcomes in a beautiful ggplot, but it seems that ggplot can't deal with list objects. Does anyone knows how to paste the results into ggplot chart?
   N <- 8619170
   nn <- c(1000, 1200, 3000)
   p <- .27
   nsim <- 100

    phat <- list()
    for (i in 1:length(nn)) {
    n <- nn[i]
    x <- rhyper(nsim, N * p, N * (1 - p), n)
    phat[[i]] <- x / n
    }

Ugly solution:
    names(phat) <- paste("n=", nn)
    stripchart(phat, method="stack")
    abline(v=p, lty=2, col="red")

A: ggplot2 need a data.frame as a source data. So you need to :

*

*transform the data with reshape2 (or plyr or many other tools)

*plot using qplot or ggplot
e.g
 ## transform data
 require(reshape2)
 h <- do.call(cbind, phat)
 h.melt <- melt(h)

 ## rename variables so they look nicer on plots
 names(h.melt) <- c("test","N","value")

 ## stripchart (not shown)
 qplot(data = h.melt, x = value,y = N,color=N)+geom_point()

 ## histogram (not shown)
 ggplot(h.melt,aes(x=value,fill=N))+geom_histogram()+facet_grid(N~.)

 ## dotplot with rug (not shown)
 ggplot(h.melt,aes(x=value,fill=N))+geom_dotplot()+facet_grid(N~.)+geom_rug()

 ##density plot with rug (shown below)
 ggplot(h.melt,aes(x=value,fill=N))+geom_density()+facet_grid(N~.)+geom_rug()

A: The best I could do following your clue is:
qplot(data = h.melt, x = value,y = Var2)+ geom_point(shape=1, size=5)

but still it doesn't reflect the probabilities; the points should be stacked as a sort of histogram to reflect the probabilities.
A different approach is using the density function, but it can messy things if I have many samples categories to plot out.
ggplot(h.melt, aes(x=value, fill=Var2)) + geom_density(alpha=.5, position="identity")


text:
Q: How to call function in one javascript from other javascript I have to access cellid in index.html from signal.js java script file , cellid is defined in signal.js file. currently am using require function in index.html to get signal object, but this is not working

**index.html**

<!DOCTYPE html>
<html>
  <head>
  <script type="text/javascript" charset="utf-8" src="signal.js"></script>
  <script type="text/javascript" charset="utf-8">
    var signal = require ("signal");
    alert("CellID : "+  signal.cellID);
    var CellID = signal.cellID;
  </script>
  </head>
</html>

signal.js

var exec = require('cordova/exec'),
    cordova = require('cordova');

var Signal = function() {
    this.imei = null;
    this.operator = null;
    this.cellID = null;
    this.lac = null;
    this.neighbors = {};
    // Create new event handlers on the window (returns a channel instance)
    this.channels = {
        watchingnetwork: cordova.addWindowEventHandler("watchingnetwork")
    };
    for (var key in this.channels) {
        this.channels[key].onHasSubscribersChange = Signal.onHasSubscribersChange;
    }

};

Signal.onHasSubscribersChange = function() {
    exec(signal.status, signal.error, "Signal", "getSignalInfo", []);
}

/**
 * Callback for signal initiated
 *
 * @param {Object} info            keys: imei, isPlugged
 */
Signal.prototype.status = function(info) {
    cordova.fireWindowEvent("watchingnetwork", info);
    if (info) {
        if (signal.imei !== info.imei || signal.operator !== info.operator) {

            if (info.imei == null && signal.imei != null) {
                return; // special case where callback is called because we stopped listening to the native side.
            }

            // Something changed. Fire watching network event

            signal.imei = info.imei;
            signal.operator = info.operator;
            signal.cellID = info.cellID;
            signal.lac = info.lac;
            signal.neighbors = info.neighbors;
        }
    }
};

/**
 * Error callback for signal initiated
 */
Signal.prototype.error = function(e) {
    console.log("Error initializing advanced network plugin: " + e);
};

var signal = new Signal();

module.exports = signal;

how can i do this.?

A: Just have signal.js be first,
<script src="signal.js"></script>
<script>
    // Your code here
</script>

Then the second <script> can use anything defined in signal.js.

A: actually , if you want to use the function Signal :
// signal.js
var Signal = function() {

    // ....
};

// use function Signal
Signal();

if you want to use the Signal() , you must stay in the scope with it .
so...
<script src="signal.js"></script>
<script>
    // some code ...
</script>

the above code is mean that put the code in signal.js file and some code into one scope . when you include the js file : signal.js , just like :
<script>
var Signal = function() {

    // ....
};

// some code ...
Signal()
<script>

include the code into one scope ~


text:
Q: Assembly: problems incrementing memory location I am just beginning 6502 assembly,  and I am trying to figure out the basics. I'm using a JavaScript emulator on my phone to assemble the code. I'm trying to get it to increment p (my memory location) and store A in both addresses (as a prelude to a loop later). But, when run, it's only storing A to $0205 and not $0206 (which is what I am trying to get it to do). Any help appreciated.
LDA #$01
define p $0205
STA p
INC p
STA p

A: The code you have written doesn't do what you think it does. p is just a defined name for the number $205. In effect, your program is
LDA #$01
; define p $0205
STA $0205
INC $0205
STA $0205

The INCinstruction increments the contents of location $0205 but then it is immediately overwritten by the second STA.
There are several ways to do what you want. Firstly, if it is always the location p and the next one, depending on your assembler, you should be able to write
LDA #$01
define p $0205
STA p
STA p+1

That will put 1 in $0205 and $0206. An alternative, if you want to do the incrementing at run time is to use an index register, of which there are two X and Y.
LDA #$01
define p $0205
LDY #0
STA p,Y
INY
STA p,Y

That's not really better than the previous, but it can be used in a loop.
define p $0205
define count 10

    LDA #$01
    LDY #count
loop:
    DEY        ; Decrement Y by 1 setting the zero flag if zero
    STA p,Y    ; Store the result in p + Y (flags are unaffected)
    BNE loop   ; Go round the loop if the zero flag is not set

The above will fill the locations from p to p + 9 with the constant 1. Note that it does it by going downwards through memory.
If p is unknown until runtime, you can do the same thing but using a zero page indirect address.
define p $0205
define count 10
define ptr $50 ; A random zero page location

    LDA #$01
    LDY #count

; First load the address in the zero page location

    LDA <p     ; < is a common notation for the low byte of a 16 bit number ($05 in this case)
    STA ptr
    LDA >p     ; and > is for the high byte ($02 in this case)
    STA ptr+1

; Now a similar loop to before

loop:
    DEY        ; Decrement Y by 1 setting the zero flag if zero
    STA (ptr),Y; Store the result in p + Y (flags are unaffected)
    BNE loop   ; Go round the loop if the zero flag is not set

A: I think you put the address(0205) into an index register (I think the 6502 has 2 of these). The store A into the address that the index register is pointing, increment the index register, and store A into the address that the index register is pointing.


text:
Q: jquery accessing form element after ajax reply I'm sending form to server and when I receive it back I need to access its elements
Here goes code.
some html
<here is the form>

and javascript
pic_type=($(this).attr('pic_type'));
pic_number=($(this).attr('pic_number'));

explanation : pic_type gets > user_pic and pic_number gets > 1
so the form is user_pic_form_n_1
$('#'+pic_type+'_form_n_'+pic_number).ajaxSubmit({
    success: function(responseimage)
    {
$('#'+pic_type+'_n_'+pic_number).html(responseimage);

now when the form gets into div, I need to get it's inputs values.
please write code sample of how can I Access it
In my example i'm trying to get values by alert like this but probably I write with mistakes
alert($(\"#'+pic_type+'_form_n_'+pic_number+' input[name=error]\").val());

elements name is 'error' so I'm trying to get it from the form.
UPDATE
Here is HTML form which I get from AJAX
<form id='user_pic_form_n_1' name='user_pic_form_n_1'   action='/serv/pic_processor.php' method='POST'>
<input type='hidden' name='error' value='456'/>
</form>

So when it gets from server into responseimage variable, I put that into Div and then I want to access this form and alert value of tag named 'error'

A: You can pass the element contain the response html as a context along with selector.
selectorElem = '#'+pic_type+'_n_'+pic_number;
$(selectorElem).html(responseimage);
$('form[name=A] #B', $(selectorElem))

Edit, based on comments
Live demo
Html
<form id='user_pic_form_n_1' name='user_pic_form_n_1'   action='/serv/pic_processor.php' method='POST'>
<input type='hidden' name='error' value='456'/>
</form>

Javascript
pic_type = 'user_pic';
pic_number= '1';
selectorElem = pic_type+'_form_n_'+pic_number;
selectorElem = 'form[name='+selectorElem +'] :hidden[name=error]';
alert($(selectorElem).val());

A: After you have done this:
$('#'+pic_type+'_n_'+pic_number).html(responseimage);

and you are looking for val of #b inside form with class a, it would be as:
$('#'+pic_type+'_n_'+pic_number+ ' form.a #b').val()


text:
Q: How to set silent notifications for specific token? I am using Firebase Cloud Messaging, with Cordova.
I want to allow the user to set silent notifications in the app settings.
However, I often push notifications to the whole topic subscribers and therefore I cannot set it silent for specific users.
I think that the correct approach is to send an http request to the fcm servers and tell them that this particular token should receive silent notifications. If this is the right approach.
How can I do that?

A: In Service:-
token='key=AAAA7SRV_tKJ1NzRT8d2VJ5NGkayEx1HT9SxrdTT5G5a4kx5c6GoDvmWmzhCTWDRCqrdACrctF5Gjy5Df2qf6ZCNJHt7oHfH7BC'

createNotification(data) {
    const headers = new HttpHeaders({
      'Content-Type': 'application/json',
      'Authorization': this.token
    });
    console.log('Res from Frontend=>', data)
    return this.http.post('https://fcm.googleapis.com/fcm/send', data, { headers: headers }).subscribe(res => {
      console.log('Res from APi', res)
    })

  }

In component.ts:-
const fcm = {
        "notification": {
          "title": '',
          "body": '',
          "sound": "default",
          "click_action": "FCM_PLUGIN_ACTIVITY",
          "icon": "./../../assets/images/logos/arabic-purpal-logo.png"
        },
        "data": {
          "hello": "This is a Firebase Cloud Messagin  hbhj g Device Gr new v Message!",
        },
        "to": 'FCM Token Here'
      };
      this.service.createNotification(fcm)
    }
Note:- Put the token in string, it send only for that user only


text:
Q: Parse body as object in node I have the following code and I want parse the body string into an object but I have the following error

SyntaxError: Unexpected token < in JSON at position 2

var http = require('http') ;

http.get('http://www.w3schools.com/' , function (resp) {
    var respContent = '' ;
    resp.on('data' , function (data) {
        respContent += data.toString() ;//data is a buffer instance
    }) ;
    resp.on('end' ,  function() {
      var profile=JSON.parse(respContent);
      console.dir(profile);
    }) ;
}).on('error' , console.error) ;

A: Unfortunately you can't use JSON.parse on XML content. It's waiting a string formatted like JSON.
var string = '{"test":"magie", "that":"work", "number": 1}';
var jsonObject = JSON.parse(string);
console.log(jsonObject);

A: I found the answer.Instead of 'http' I have to use 'https'


text:
Q: What's the benefits of docker with Jenkins Pipelines? I'm new to Jenkins/Docker. So far I've found lots of Jenkins official Documents recommended to be used with Docker. But the necessity and advantages of running Jenkins as a docker container remain vague to me. In my case, it's a node/react app and environment required is not complicated.
Disadvantages I've found running Jenkins as a Docker container:

*

*High usage of hard drive

*Directory path in docker container is more complicated to deal with, esp when working with ssh in pipeline scripts

Without docker, I can easily achieve the same and there's also blueocean plugin available.
So, what's the main benefits of Docker with Jenkins/Jenkins Pipeline? Are there pitfalls for my node application using Jenkins without Docker? Articles to help me dive into are also appreciated.

A: Jenkins as Code
The main advantages of Jenkins in Docker is that it helps you to get: Jenkins as Code
Advantages of Jenkins as code are:

*

*SCM: Code can be in put under version control

*

*History is transparant, backup and roll-back becomes easy.

*The code is the documentation of your Jenkins setup.

*Jenkins becomes portable, so you can run Jenkins locally to try new plugins etc.

*Jenkins pipelines work really well with Docker. As @Ivthillo mentioned: there is no need to install additional tools, you just use images of these tool. Jenkins will download them from internet for you (Docker Hub).
For each stage in the pipeline you can use a different image (i.e. tool). Essentially you get "micro Jenkins agents" which only exists temporary. This makes your Jenkins setup much more clean.

Disadvantage is:

*

*Jenkins initial (Groovy) configuration is poorly documented on the web.

Simple Node setup
Most arguments also holds for a simple Node setup.

*

*Change the node version or run multiple job each with a different Node version becomes easy.

*Add your Jenkinsfile inside the Node repo. So everyone with a Jenkins+Docker setup can run your CI/CD.

*And finaly: gather knowledge on running your app inside a container will enable your to run your production app in Docker in the future.

Getting started
A while ago I have written an small blog on how to get started with Jenkins and Docker, i.e. create a Jenkins image for development which you can launch and destroy in seconds.


text:
Q: Uncaught TypeError: Cannot convert "undefined" to int in Opencv.js I am trying to detect document from an image locally by uploading from input file. To detect those followed steps available online by adding grayscale and blur to image and canny edge now when trying to find contours it's giving error.

Also, when I tried the steps through console it ran perfectly without giving any errors. Any idea why this is happening?

Here is my full code:

function fileLoad(input) {
  if (input.files && input.files[0]) {
    let reader = new FileReader();
    reader.onload = (e) => {
      document.getElementById('ip').src = e.target.result;
    }

    reader.readAsDataURL(input.files[0]);
  }

}

function drawContours() {
  let org_img = cv.imread('ip');
  let img = new cv.Mat();

  // change color and adding gaussian blur

  cv.cvtColor(org_img, img, cv.COLOR_RGBA2GRAY, 0);
  cv.GaussianBlur(img, img, new cv.Size(5, 5), 0, 0, cv.BORDER_DEFAULT);

  console.log('chnage color and blur added');

  // canny edge

  cv.Canny(img, img, 75, 200, 3, false);

  console.log('canny done');

  // find contours
  console.log('init draw', img);

  let con = new cv.MatVector() ;
  cv.findContours(img, con, new cv.Mat(), cv.RETR_CCOMP, cv.CHAIN_APPPROX_SIMPLE);

  console.log('contours found', con);

  cv.drawContours(org_img, con, -1, new cv.Scalar(125, 120, 20), 1, cv.LINE_8, new cv.Mat(), 100);

  // for(let i=0; i< con.size(); i++){
  //     cv.drawContours(org_img, con, i, new cv.Scalar(125,100,20), 1, cv.LINE_8, new cv.Mat(), 100) ;
  // }

  console.log('finish draw');

  cv.imshow('op', org_img);
}

function ready() {
  cv['onRuntimeInitialized'] = () => {
    console.log('opencv loaded');
    // init() ;
  }
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    function ready() {
  cv['onRuntimeInitialized'] = () => {
    //console.log('opencv loaded');
  }
}
  </script>
  <input type="file" accept="image/jpeg" onchange="fileLoad(this);" style="display: block;">
  <img id="ip" width="300" height="400" />
  <canvas width="300" height="400" id="op"></canvas>

  <button onclick="drawContours()">draw contour</button>
  <script asnyc src="https://docs.opencv.org/4.6.0/opencv.js" onload="ready()"></script>
</body>

</html>

A: As suggested by @Shrimp I wrote cv.CHAIN_APPROX_SIMPLE with cv.CHAIN_APPPROX_SIMPLE so that's why error is for argument having undefined.


text:
Q: File import not initializing in constructor ionic native. The cordova file plugin and javascript file interface is conflicting .? import { File } from '@ionic-native/file/ngx';

I can't use the class File from cordova-plugin-file in my application cause there is another interface from JavaScript also called File.
This name conflict impedes my app to access the cordova-plugin-file functions I want.
File from JavaScript has this description : "
interface File
Provides information about files and allows JavaScript in a web page to access their content.".
File from cordova-plugin-file should (alias) const File: FileOriginal
import File
'File' is declared but its value is never read
Here is my code :
import { File } from '@ionic-native/file/ngx';
export class Tab1Page {
constructor(public file: File) {}
...
}

A: Just so that it helps someone. Workaround was to declare cordova-plugin-file outside constructor.
import { File as cordova_file } from '@ionic-native/file/ngx';
private file: typeof cordova_file
constructor(


text:
Q: Algorithm for comparing two images with orientation hai
     Any algorithm for comparing two images with any orientation? Can any one help?
     Give me some link.
Thank you

A: Computer Vision/Computer Graphics Collaboration Techniques
Code to compare two images in c#
public bool doImagesMatch(ref Bitmap bmp1, ref Bitmap bmp2)
{
    try
    {
        //create instance or System.Drawing.ImageConverter to convert
        //each image to a byte array
        ImageConverter converter = new ImageConverter();
        //create 2 byte arrays, one for each image
        byte[] imgBytes1 = new byte[1];
        byte[] imgBytes2 = new byte[1];

        //convert images to byte array
        imgBytes1 = (byte[])converter.ConvertTo(bmp1, imgBytes2.GetType());
        imgBytes2 = (byte[])converter.ConvertTo(bmp2, imgBytes1.GetType());

        //now compute a hash for each image from the byte arrays
        SHA256Managed sha = new SHA256Managed();
        byte[] imgHash1 = sha.ComputeHash(imgBytes1);
        byte[] imgHash2 = sha.ComputeHash(imgBytes2);

        //now let's compare the hashes
        for (int i = 0; i < imgHash1.Length && i < imgHash2.Length; i++)
        {
            //loops, found a non-match, exit the loop
            //with a false value
            if (!(imgHash1[i] == imgHash2[i]))
            return false;
        }
    }
    catch (Exception ex)
    {
       MessageBox.Show(ex.Message);
        return false;
    }
    //we made it this far so the images must match
    return true;
}


text:
Q: Stuck to append Images Using Azure Append blob in C# can I append Images byte... ? I tried that but not works.. its increase the size but not reflect images.. its always return first image that I append first.. So Please help how can I append images ? json/text files are working fine but I m stuck on append image..
So,Please Help how can i do that..
Here is my code
        CloudAppendBlob cloudAppendBlob = cloudBlobContainer.GetAppendBlobReference(fileName);
        bool exist = await cloudAppendBlob.ExistsAsync();
        if(!exist)
        {
            await cloudAppendBlob.CreateOrReplaceAsync();
        }
        cloudAppendBlob.Properties.ContentType = fileType;
        stream.Position = 0;

        await cloudAppendBlob.AppendBlockAsync(stream);

A: You can not append images with the same name. If you do that, it will replace the image file with the same name. If you upload another image then it would create a new image as per the uploaded one. Try the code below.
private CloudBlobContainer blobContainer;
    public AzureBlobHelper()
    {

        try
        {
            // Get azure table storage connection string.

            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));

            CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();
            blobContainer = cloudBlobClient.GetContainerReference(CloudConfigurationManager.GetSetting("StorageContainer"));

            // Create the container and set the permission
            if (blobContainer.CreateIfNotExists())
            {
                blobContainer.SetPermissions(
                    new BlobContainerPermissions
                    {
                        PublicAccess = BlobContainerPublicAccessType.Blob
                    }
                );
            }
        }
        catch (Exception ExceptionObj)
        {
           // throw ExceptionObj;
        }
    }

    public string UploadFile(string FileName, string LocalPath, string AzureBlobPath, string ContentType = "")
    {
        string AbsoluteUri;

        try
        {
            CloudBlockBlob blockBlob;
            // Create a block blob
            blockBlob = blobContainer.GetBlockBlobReference(AzureBlobPath + FileName);
            // Set the object's content type
            blockBlob.Properties.ContentType = ContentType;

            blockBlob.UploadFromFile(LocalPath);
            // get file uri
            AbsoluteUri = blockBlob.Uri.AbsoluteUri;
        }
        catch (Exception ExceptionObj)
        {
            throw ExceptionObj;
        }
        return AbsoluteUri;
    }


text:
Q: mssql_execute fails from php When I try to call a procedure from php using mssql_execute, it fails.
But when I try calling it from SQL server studio tool, the same works with same parameters.
The execution time is bit higher, but it works,
There is no error shown on PHP side, but if I write a die like
mssql_execute($stms) or die('Not Working');

the die works.
What might be the reason for this?
mssql_get_last_message()

returns NULL

A: Issue resolved by increasing the value in php.ini
mssql.timeout = 120;

Which was mssql.timeout = 60; before.


text:
Q: TYPO3 Neos - Access Media Management files through TypoScript? is it possible to access files uploaded in the media management using typoscript in TYPO3 Neos?
I'm trying to create a site listing all pdfs uploaded by the editors, but I couldn't figure out a way to access these pdfs via typoscript.

A: It is currently (state of Neos 1.2 beta) not possible to gather a list of assets with the built-in TypoScript objects / Eel helpers. There are two ways to implement your requirement:

*

*Create a plugin that renders the list of PDFs

*Create a new TypoScript object or Eel helper to fetch a list of assets

A plugin can be created following the guide on the Neos documentation. If you want to render the list via TypoScript, it's easy to create such a TypoScript object in your own site package:
use TYPO3\Flow\Annotations as Flow;

class AssetCollection extends \TYPO3\TypoScript\TypoScriptObjects\AbstractTypoScriptObject {

    /**
     * @Flow\Inject
     * @var \TYPO3\Media\Domain\Repository\AssetRepository
     */
    protected $assetRepository;

    public function evaluate() {
        return $this->assetRepository->findAll();
    }

}

And then use that new object in TypoScript:
prototype(TYPO3.NeosDemoTypo3Org:AssetCollection) {
    @class = 'TYPO3\\NeosDemoTypo3Org\\TypoScriptObjects\\AssetCollection'
}

page.body.assets = TYPO3.NeosDemoTypo3Org:AssetCollection


text:
Q: &&= in C#? (boolean expression)
Possible Duplicate:
Why are there no ||= or &&= operators?

By pure accident I found out today that
 a &= GetBool();

is NOT the same as
 a = a && GetBool();

I must have misunderstood that for years. In the first Example, "GetBool()" is executed even if "a" is false. In the second, it isn't.
Is there anything to achieve something like "&&=" in C#?

A:
Is there anything to achieve something like "&&=" in C#?

Well, you can write
a = a && getBool();

instead... I can't think of many situations where I'd actually want to do anything different, to be honest. Even the above is pretty rare, IME.
There's no compound assignment operator defined for &&, || or ?? (which are the obvious "short-circuiting" operators). See section 7.17 of the C# 4 spec for the full list of compound assignment operators, and section 7.17.2 for more details about what exactly compound assignment does.

A: From the documentation:

An expression using the &= assignment operator, such as
x &= y
is equivalent to
x = x & y
except that x is only evaluated once. The & operator performs a
  bitwise logical AND operation on integral operands and logical AND on
  bool operands.

I would say, to avoid evaluation of y when not necessary, use
x = x && y

and to avoid evaluation of x twice (whatever this means), use
x &= y

You can't combine both.
Micro-optimized (at least for a theoretical case), it would be:
if (x) x = y;

You don't need to do anything if x is already false.


text:
Q: Conc Mark and Sweep Garbage Collector difference between java 1.6 and 1.7 I was using jdk 1.6 with CMS GC and when I tried to migrate to JDK 1.7, the heap usage increases and the process becomes slow.
Is there a major difference in GC behavior in these versions? What is the workaround if it has become slower in JDK 1.7?

A: in jdk 1.7 below are 2 major changes related to cms.
The default out-of-the-box heap size and shape parameters for the concurrent mark sweep collector (CMS) have been modified. The new settings take advantage of faster platforms that have been introduced since JDK 6 was released. Like the other collectors in HotSpot, CMS will now use the available physical memory on the platform to size its heap, while attempting to shape that heap to keep pause times associated with minor collections "reasonable". The specific shape of the heap may be platform-dependent in other ways as well. Users can override all or some of these default settings by explicitly sizing or shaping the heap, AKA "heap tuning", to suit their specific needs.
The JDK 6 release notes included performance enhancements for CMS. To provide a mechanism to continue using the behavior provided by JDK 5, the CMSUseOldDefaultsflagwasprovided.This flag restored a number of settings to a default state. During the last few years, this flag has received minimal use and most customers prefer the improved CMS performance. The CMSUseOldDefaults flag is now removed in jdk7.
Source : Java Virtual Machine Enhancements in JDK 7


text:
Q: Can I pick which meta data to use from photos to be able to use ALAssetsLibrary with location services off? I found that using ALAssetsLibrary gives an error when location services are disabled or not granted to my app.
I am using enumerateGroupsWithTypes:usingBlock:failureBlock: and the documentation says:

Special Considerations
This method will fail with error ALAssetsLibraryAccessGloballyDeniedError if the user has not enabled Location Services (in Settings > General).

Is it possible to fine grain which meta data I am going to use from the photos, so I can still get them from the library? I actually don't need the location where the photo was taken.

A: No it's not possible (yet? it's not possible in iOS 5.1)
The only way to access photos in the library without having the location warning is to present a UIImagePickerController, but obviously that doesn't help much for most projects where you need to display a custom gallery, or access more than one picture at a time.

A: We have found that there is not location permission request in iOS 6. Maybe iOS 6 has other privacy control on Photos. So you don't need to asking location permission. Our solution is to check the [[UIDevice currentDevice]systemVersion] and only using ALAssetsLibrary when iOS >= 6.


text:
Q: MacBook Retina with non-retina External Monitor has wrong resolutions I have just gotten a MacBook Pro retina Early 2015, which I want to connect with non-retina external display. I'm using a VGA to display port adapter to connect it and it does work. However the resolution is not correct. It's all blurry. I have tried to option click the scale button in display settings and tried them all. Non of them seem to fit the screen. When using HDMI instead it works like a charm. Am I doing anything wrong?

A: Try hold option while clicking 'scaled' radio button in external monitor Display settings. It will show you more options.


text:
Q: java.lang.IllegalArgumentException: Specification to merge with cannot be null in method waitSystemActive i am trying to add method with @Test and use dependsOnMethods in my class.
If I have only 33 @Test in this class, it can be run without any errors, but if I try to add only one more @Test, I have java.lang.IllegalArgumentException: Specification to merge with cannot be null
I checked, and my @BeforeClass does use the testing library.
Please help, I can provide screenshots, if needed.

A: I fixed this error, when I replaced same streams on method:
private String getActualEndDate(List userAppRoles, UrengoyApprole appRole) {
return userAppRoles.stream()
.filter(role -> role.get_ouid().equals(appRole.get_ouid()))
.findFirst().get().getEndDate();
}


text:
Q: Universal password for effective handling of bug reports When a user of my website submits a bug report, I would like to be able to log into the staging website (so that a non-production copy of the database is used) as him to see exactly what he sees. I could achieve this by changing his user email address to mine and then resetting the password. However, it would simplify things if I could enable a universal password for the staging website, using which I could login as any user. Is there a way to achieve this with Django authentication?
Update: I have stumbled upon the django-master-password project (the term master password did not come to my mind initially). Any other alternatives?


text:
Q: Are there characteristic classes for symplectic vector bundles? Given a real vector bundle, say the tangent bundle of a manifold, some obstructions to this being the underlying real bundle of a complex bundle come from characteristic classes. These can prove the lack of complex structure on the underlying manifold. I was wondering if perhaps there was a similar set of classes for symplectic manifolds?

A: You have classifying spaces $BSp(n)$ and $BGl(2n)$ and from the inclusion $Sp(n)$ into $Gl(2n)$ you get a map $\iota \colon BSp(n) \to BGl(n)$.
A characteristic class for a real vector bundle is nothing else than a cohomology class of $BGl(n)$ (This follows from naturality). And you can define characteristic classes analogously for symplectic bundles by taking cohomology classes for $BSp(n)$. A symplectic structure of your vector bundle now corresponds to a lift of the classifying map to $BGl(n)$ into $BSp(n)$.
But now if you understand $\iota^*$ you can get that certain characteristic classes can't occure if you have such a lift. For example if you were looking at real bundles and asking for a complex structure you would get that every odd Stiefel-Whitney-Class would have to vanish since the complex grassmanian has no cohomology in odd dimensions.
I'm not aware of how the cohomology ring of $BSp(n)$ looks like, but with that information and a little computation of $\iota^*$ you would get explicit classes, that obstruct such a lift.


text:
Q: Java OOM Automatic Heap Dump File Name in K8S An answer to this question is available at https://stackoverflow.com/a/34077693/1525813 but not from a Kubernetes perspective.
For my k8s app, I specify the JVM options as an environment variable in the k8s YAML (below). This has been giving issues where the pod crashes on container start-up (running Linux) as the command substitution isn't working as expected.
ENV VAR
spec:
  template:
    spec:
      containers:
      - name: myapp
        command: [ '/bin/sh', '-c' ]
        args:
          - exec java $JVM_OPTS -jar myapp.jar
#         - exec startup.sh # For few other apps
        env:
        - name: JVM_OPTS
          value: >-
            -XX:+HeapDumpOnOutOfMemoryError
            -XX:HeapDumpPath=/logs/heapdump/hd_$(date +%F_%H-%M-%S)_pid$$.hprof
            -XX:+CrashOnOutOfMemoryError
            -XX:OnError=/scripts/threaddump.sh
            -XX:ErrorFile=/logs/error/hs_err_$(date +%F_%H-%M-%S)_pid$$.log
            -Xlog:gc*=debug:file=/logs/gc/gc_%t_pid%p.log:time,uptimemillis,pid,tid,level,tags

ERROR LOGS on container startup
Error: Could not find or load main class +%F_%H-%M-%S)_pid$.hprof"
Caused by: java.lang.ClassNotFoundException: +%F_%H-%M-%S)_pid$.hprof"

What am I missing here?

SUB-QUESTION
The earlier config was -XX:HeapDumpPath=/logs/heapdump/hd_%t_pid%p.hprof which was not interrupting the container start-up but the heap dump file was being created with the name hd_%t_pid%p.hprof i.e. %t and %p were not being substituted for -XX:HeapDumpPath but were substituted for -Xlog:gc*.
What could be the cause of discrepancy here?
Thanks

A: See for details https://github.com/kubernetes/kubernetes/issues/112645

I added these values for JVM_OPTS in a shell script and used it to invoke the JAR. Then invoked the script from the k8s YAML args.


text:
Q: Image appears on image when hover

I need another image to appear while hovering over the current image.

A: give your div's an id>
something like:
html:

css:
.image1:hover .overlay {
  position:absolute;
  width: 48px;
  height: 48px;
  z-index: 100;
  background: transparent url('image2.png') no-repeat;
  cursor: pointer;
}

A:

add style

A: If you want to make these buttons images. I suggest using the technique of css sprite.
Basically you will use the hover to change the image itself.
Here's a link to better understand http://css-tricks.com/css-sprites/
Bye.
*If the solution please voteup.


text:
Q: Ajax file upload using aspupload I have read everything i could find.
Yes, im still using classic asp
Im trying to figure out how to upload a file to the server using the aspupload component but with ajax.
I get a lot of php examples .net and client side that doesnt realy do anything
So how can i get the input content via class? Cause i will have more than one uploader in the page: $(".file").val() is not the way so what is?
I dont mind useing ajax on any form. I do know i can have <form target=iframe></form><iframe name=iframe></iframe> but not sure i want alot of iframe on the page

A: it's complicated, check jQuery File Upload Plugin By BlueImp,
it's a nice component to upload files support Ajax, Iframe's etc ....
there is a Asp-Classic example that comes with the download file, check if adecuates to your needs.


text:
Q: Is it possible to provide a default value for a template function argument? Consider the following code:
protocol Foo {
    func f() -> Void
}

class Bar1: Foo {
    func f() {
        print("Bar1 f")
    }
}

class Bar2: Foo {
    func f() {
        print("Bar2 f")
    }
}

func function<T:Foo>(arg:T = Bar2()) {
    arg.f()
}

It gives an error Value of type Bar2 cannot be converted to type T, which seems to be pure nonsense, because T is guaranteed to be compatible with Foo and this is the context within which the assignment should operate.
To prove it:
let global: Foo = Bar2()
global.f()

This works just fine.
I am wondering why such a discrepancy exists and if there is any workaround for it?

A: Cast the Bar2() as Generic type T
func function<T:Foo>(arg:T = Bar2() as! T) {
        arg.f()
}


text:
Q: Reading the pixels values from the Frame Buffer Object (FBO) using Pixel Buffer Object (PBO) Can I use Pixel Buffer Object (PBO) to directly read the pixels values (i.e. using glReadPixels) from the FBO (i.e. while FBO is still attached)?
If yes,

*

*What are the advantages and disadvantages of using PBO with FBO?

*What is the problem with following code

{
//DATA_SIZE = WIDTH * HEIGHT * 3 (BECAUSE I AM USING 3 CHANNELS ONLY)
// FBO and PBO status is good
.
.
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fboId);
//Draw the objects

Following glReadPixels works fine
glReadPixels(0, 0, screenWidth, screenHeight, GL_BGR_EXT, GL_UNSIGNED_BYTE,  (uchar*)cvimg->imageData);

Following glReadPixels DOES NOT WORK :(
glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, pboId);
//yes glWriteBuffer has also same target and I also checked with every possible values
glReadBuffer(GL_COLOR_ATTACHMENT0_EXT);
glReadPixels(0, 0, screenWidth, screenHeight, GL_BGR_EXT, GL_UNSIGNED_BYTE, (uchar*)cvimg->imageData);
.
.
glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); //back to window framebuffer

A: Yes, we can use FBO and PBO together.
Answer 1:
For synchronous reading: 'glReadPixels' without PBO is fast.
For asynchronous reading: 'glReadPixels' with 2/n PBOs is better- one for reading pixels from framebuffer to PBO (n) by GPU and another PBO (n+1) to process pixels by CPU. However fast is not granted, it is problem and design spefic.
Answer 2:
Christian Rau's explanation is correct and revised code is below
glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, pboId);
glReadBuffer(GL_COLOR_ATTACHMENT0_EXT);
//glReadBuffer(GL_DEPTH_ATTACHMENT_EXT);

glReadPixels(0, 0, screenWidth, screenHeight, GL_BGR, GL_UNSIGNED_BYTE, 0);

//GLubyte* src = (GLubyte*)glMapBufferARB(GL_PIXEL_PACK_BUFFER_ARB, GL_READ_ONLY_ARB);
//OR
cvimg->imageData = (char*) glMapBufferARB(GL_PIXEL_PACK_BUFFER_ARB, GL_READ_ONLY_ARB);
if(cvimg_predict_contour->imageData)
{
  //Process src OR cvim->imageData
  glUnmapBufferARB(GL_PIXEL_PACK_BUFFER_ARB);     // release pointer to the mapped buffer
}
glBindBufferARB(GL_PIXEL_PACK_BUFFER_ARB, 0);

A: When using a PBO as target for glReadPixels you have to specify a byte offset into the buffer (0, I suppose) instead of (uchar*)cvimg->imageData as target address. It is similar to using a buffer offset in glVertexPointer when using VBOs.
EDIT: When a PBO is bound to the GL_PIXEL_PACK_BUFFER, the last argument to glReadPixels is not treated as a pointer into system memory but as a byte offset into the bound buffer's memory. So to write the pixels into the buffer just pass a 0 (write them to the start of the buffer memory). You can then later acces the buffer memory (to get the pixels) by means of glMapBuffer. The example link you provided in your comment does that, too, just read it extensively. I also suggest reading the part about vertex buffer objects they mention at the start, as these lay the ground to understand buffer objects.


text:
Q: Optional Model Properties Binding in .NET Core MVC I have created one AccountModel which has following properties
public class AccountModel
{
    [Required]
    [EmailAddress]
    public string Email { get; set; }

    [Required]
    [StringLength(10, MinimumLength = 6)]
    public string Password { get; set; }

    [NotMapped] // Does not effect with your database
    [Compare("Password")]
    [BindRequired]
    public string ConfirmPassword { get; set; }
}

I am trying to use same model for SignUp and SignIn. This model is perfectly working for signup but when I am using same model for SignIn my model becomes Invalid.
I know the reason because, I am not passing value for Confirm Password property. I tried following

*

*I made NULLABLE by using "?" bu it is giving me warning (See attached screenshot)

*I have also tried [BindRequired] annotation which is also not working.
I am using ASP.NET Core 3.1 and trying to use single Model for both login and signup.
Is there any solution for that? I am learning .NET Core & MVC so having less knowledge about this subject.
Help is appreciated in advance.

A: This is called Nullable contexts, based on its documentation:

Nullable contexts enable fine-grained control for how the compiler interprets reference type variables. The nullable annotation context of any given source line is either enabled or disabled. You can think of the pre-C# 8.0 compiler as compiling all your code in a disabled nullable context: any reference type may be null. The nullable warnings context may also be enabled or disabled. The nullable warnings context specifies the warnings generated by the compiler using its flow analysis.

You can get rid of this warning like this:
#nullable enable
    public string? ConfirmPassword { get; set; }
#nullable disable

As another workaround, if you want to always get rid of this warning in your project, you can add the Nullable element in your .csproj file. Right click on your project and click "Edit Project File", then add the Nullable element to your PropertyGroup section, just like the following:
<PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <Nullable>enable</Nullable>
</PropertyGroup>

You just need to Re-Build your project once to see the result.


text:
Q: Make Scale / Window Picker preserve relative window positions? When I use the Scale feature in Ubuntu 14.04, the miniature versions of the windows are not in the same relative positions on the screen as the actual windows.
Suppose, for example, that I have 2 terminal windows open, one on the left and one on the right.  They look essentially identical in miniature, but must be distinguished from each other, e.g., because they have different environment variables and pwds.  Hence, I keep them separate on the screen, one on the left and one on the right.
When I use Scale to navigate to one of these windows (among several other non-terminal windows), it sometimes (though not always) shows the the left window on the right and the right window on the left.  So, I click on the wrong one and I essentially can't use Scale to navigate identical looking windows based on geometry.
Is there a way to make Scale preserve relative positions as much as possible, esp. for windows that are running the same application and thus look identical in miniature?


text:
Q: How do i enable auto fill option in Visual studio I just started game development on unity and wanted to write some code in Visual Studio 2019 but when I started typing some code no syntax was being shown below.
I mean when I write a dot in c# a dropdown menu should appear with commonly used lines with their definition.
Sorry for using bad terms I hope you are understanding and I want this to help me in C#.

A: The first thing you need to do is go to visual studio installer and download tools for unity, if that doesn't work, inside unity navigate to edit > preferences then under external tools make sure you have visual studio selected and not open by file extension.

A: VS-code is more better if you are starting out and it is light weight.
Install VS-Code from here
If you mean to say you want to enable unity-intellisense, then in your unity editor go under edit > preferences. See the image below.
Select VS-Code as your ide and for generate .csproj files uncheck all and check only registry packages, then hit regenrate .csproj files. It will take time to generate them.
In Vs-Code install the c-sharp extension and reload the window. Then you should be ready to start using it for game developement in unity.
preferences image
c-sharp extension image
But if you want for Visual Studio only install Visual Studio depedencies from unity hub while installing the version
unityhub installation for visual studio
Please check the images and link given too


text:
Q: Generate flat PDF I currently generate complex pdf using xsl-fo.
Is it possible to create pdf that contains binary image of its content?
I want to basically render document inside transformation.
Maybe there are some rendering options?
My xsl is pretty complex, so I want to minimize changes.


text:
Q: Disable Vertical Scroll in niceScroll Js I need horizontal scroll only in this section and hide vertical scroll
I have tried everything like overflow-x:hidden in every thing but its not working.

All Complex Ecosystems Have Parasites

All Complex Ecosystems Have Parasites

 Cory Doctorow

 doctorow@craphound.com

 For the O’Reilly Emerging Technology Conference

 San Diego, California

 16 March 2005

—

This text is dedicated to the public domain, using a Creative Commons public domain dedication:

> Copyright-Only Dedication (based on United States law) > > The person or persons who have associated their

  work with this > document (the “Dedicator”) hereby dedicate the entire copyright > in the work of authorship

  identified below (the “Work”) to the > public domain. > > Dedicator makes this dedication for the

  benefit of the public at > large and to the detriment of Dedicator’s heirs and successors. > Dedicator intends

  this dedication to be an overt act of > relinquishment in perpetuity of all present and future rights > under

  copyright law, whether vested or contingent, in the Work. > Dedicator understands that such relinquishment of all

  rights > includes the relinquishment of all rights to enforce (by lawsuit > or otherwise) those copyrights in

  the Work. > > Dedicator recognizes that, once placed in the public domain, the > Work may be freely reproduced,

  distributed, transmitted, used, > modified, built upon, or otherwise exploited by anyone for any > purpose, commercial

  or non-commercial, and in any way, including > by methods that have not yet been invented or conceived.

—

AOL hates spam. AOL could eliminate nearly 100 percent of its subscribers’ spam with one easy change: it could simply

  shut off its internet gateway. Then, as of yore, the only email an AOL subscriber could receive would come from another

  AOL subscriber. If an AOL subscriber sent a spam to another AOL subscriber and AOL found out about it, they could terminate

  the spammer’s account. Spam costs AOL millions, and represents a substantial disincentive for AOL customers to remain

  with the service, and yet AOL chooses to permit virtually anyone who can connect to the Internet, anywhere in the world,

  to send email to its customers, with any software at all.

[…]

A free ebook from http://manybooks.net/

A: For remove the horizontal scroll of script Nicescroll you must insert this option horizrailenabled:false.
So the script for you case is:
$(document).ready(function(){
        $(".do-nicescrol").niceScroll("{horizrailenabled:false}");
});

A: There is an option of overflowx inside nicescroll plugin which remains true by default. Hope, this option will solve your issue. You can check details in below image or at https://github.com/inuyaksa/jquery.nicescroll/blob/master/jquery.nicescroll.js

A: $("body").niceScroll({
    horizrailenabled:false,
});


text:
Q: WebResponse reading with callbacks I have an app where the user can choose to download all content and this was done with this method on other platforms
 resp.GetResponseStream().BeginRead(mBuffer, 0, 1448, new AsyncCallback(EndRead), resp);

but a BeginRead-method is not present in the .NET framework used by UWP applications. I need a way to do this in the same way as the other platforms do it, so I can use the callback-function for progressbar updating.
Any ideas?

A:
I need a way to do this in the same way as the other platforms do it, so I can use the callback-function for progressbar updating.

You can use this way as a workaround:
        var request = WebRequest.CreateHttp("http://www.bing.com");

        var response = await request.GetResponseAsync();

        byte[] buffer = new byte[1024];

        var stream = await response.GetResponseStream().ReadAsync(buffer, 0, 1024);

        // add callback actions here


text:
Q: Dont understand mean values and std dev values when convertig .pb to ff-lite I am trying to quantizate a tensoflow graph stored in .pb.
The input of the network is a matrix, that each row is normalized with mean 0 and std 1.
I want to create a tensorflow-lite model quantizate to inteference faster.
I do not know how to pass the inputs to the line conversion. Is it a just one value? a vector with 64 values? how is it passed?
The model is well converted without quantization.
tflite_convert \
    --output_file=model_simple_weight_q.tflite \
    --graph_def_file=model_simple.pb \
    --inference_type=QUANTIZED_UINT8 \
    --input_arrays=input \
    --output_arrays=LogSoftmax \
    --mean_values= # dont know  \
    --std_dev_values=# dont know

If I pass two single values, --mean_values=127 and --std_dev_values=128 for instance. Just to know what happens, I get the following error:
F tensorflow/lite/toco/graph_transformations/resolve_constant_gather.cc:108] Check failed: coords_array.data_type == ArrayDataType::kInt32 Only int32 indices are supported
Aborted (core dumped)

A: The error you are seeing is not related to mean/std_dev values. It is an error while converting your graph in general. It is saying that in one of your graph operations, an index is used in a tf.gather (or maybe a slicing) and it has a type that is not int32, but that's the only supported index type.
Unfortunately the TFLite conversion errors will often not tell you the source code that caused the error, so you'll have to make informed guesses.
Regards mean/std_dev values, I suggest you take a look at this answer : https://stackoverflow.com/a/58096430/834565

A: As each row of the input is normalized with mean 0 and std 1, you should give --mean_values=0 and     --std_dev_values=1 . Also, when you are doin a 'Dummy post traing quantization', you need to provide the minimum and maximum range for the activation functions. You need to provide --default_ranges_min= and --default_ranges_max= .
As tensorflow doesn't provide very clear describtion about how to calculate the activation range, it is better to do 'post training full integer quantization' with a small calibration data- here . In this methode the range of the activation function are calculated with the calibration images.
Regards,


text:
Q: Discord .NET API Bot - Commands not working Since i am pretty new to .NET and programming in general, i got stuck while creating a bot with the Discord .NET API.
using Discord;
using Discord.Interactions;
using Discord.WebSocket;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Discord.Commands;
using System.Reflection;
using System.Windows.Input;

public class Program
{
    public static Task Main(string[] args) => new Program().MainAsync();

    private static DiscordSocketClient _client;
    private CommandHandler _commandHandler;
    private static CommandService _commands;

    public async Task MainAsync()
    {
        _client = new DiscordSocketClient();
        _commands = new CommandService();
        _commandHandler = new CommandHandler(_client, _commands);
        await _commandHandler.InstallCommandsAsync();

        _client.Log += Log;

        var token = "XXXXXX";

        await _client.LoginAsync(TokenType.Bot, token);
        await _client.StartAsync();

        // Block this task until the program is closed.
        await Task.Delay(-1);
    }

    //--Commandhandler--//

    public class CommandHandler
    {
        private readonly DiscordSocketClient _client;
        private readonly CommandService _commands;

        // Retrieve client and CommandService instance via ctor
        public CommandHandler(DiscordSocketClient client, CommandService commands)
        {
            _commands = commands;
            _client = client;
        }

        public async Task InstallCommandsAsync()
        {
            // Hook the MessageReceived event into our command handler
            _client.MessageReceived += HandleCommandAsync;

            // Here we discover all of the command modules in the entry
            // assembly and load them. Starting from Discord.NET 2.0, a
            // service provider is required to be passed into the
            // module registration method to inject the
            // required dependencies.
            //
            // If you do not use Dependency Injection, pass null.
            // See Dependency Injection guide for more information.
            await _commands.AddModulesAsync(assembly: Assembly.GetEntryAssembly(),
                                            services: null);
        }

        private async Task HandleCommandAsync(SocketMessage messageParam)
        {
            // Don't process the command if it was a system message
            var message = messageParam as SocketUserMessage;
            if (message == null) return;

            // Create a number to track where the prefix ends and the command begins
            int argPos = 0;

            // Determine if the message is a command based on the prefix and make sure no bots trigger commands
            if (!(message.HasCharPrefix('!', ref argPos) ||
                message.HasMentionPrefix(_client.CurrentUser, ref argPos)) ||
                message.Author.IsBot)
                return;

            // Create a WebSocket-based command context based on the message
            var context = new SocketCommandContext(_client, message);

            // Execute the command with the command context we just
            // created, along with the service provider for precondition checks.
            await _commands.ExecuteAsync(
                context: context,
                argPos: argPos,
                services: null);
        }
    }

    public class InfoModule : InteractionModuleBase<SocketInteractionContext>
    {
        // ~say hello world -> hello world
        [Command("say")]
        public Task SayAsync(string echo)
        {
           return ReplyAsync(echo);
        }

    }
    public class ExampleCommands : InteractionModuleBase<SocketInteractionContext>
    {
        // dependencies can be accessed through Property injection, public properties with public setters will be set by the service provider
        public InteractionService Commands { get; set; }
        private CommandHandler _handler;

        // constructor injection is also a valid way to access the dependecies
        public ExampleCommands(CommandHandler handler)
        {
            _handler = handler;
        }

        // our first /command!
        [SlashCommand("8ball", "find your answer!")]
        public async Task EightBall(string question)
        {
            // create a list of possible replies
            var replies = new List<string>();

            // add our possible replies
            replies.Add("yes");
            replies.Add("no");
            replies.Add("maybe");
            replies.Add("hazzzzy....");

            // get the answer
            var answer = replies[new Random().Next(replies.Count - 1)];

            // reply with the answer
            await RespondAsync($"You asked: [**{question}**], and your answer is: [**{answer}**]");
        }
    }

    private Task Log(LogMessage msg)
    {
        Console.WriteLine(msg.ToString());
        return Task.CompletedTask;
    }

}

My problem is that the bot does not respond to the 2 command modules that i have already added in.
Some of this code is from the API-guide... the bot does not respond to these commands...
I have given it permission to Send messages, read message history and use slash commands.
Already tried adding in the .InstallCommandsAsync() in the Main but i don't know where to go from now. Am i not calling methods that i need to call in the main? What am i doing wrong?


text:
Q: Too many Primary partitions (MBR) after installing Ubuntu I am using a Sony (sve15118fnb) laptop. Recently I installed windows 10 and decided to dual boot it with Ubuntu. The disk uses MBR partition table, so the maximum number of primary partitions allowed is 4.
The disk partitions before installing Ubuntu, the red boundary indicates what was a logical partition before installing Ubuntu:

This makes 3-primary and 1-logical partition. But while installing Ubuntu, I went with the default (primary) as the partition type for swap and root directories. And after installing Ubuntu, the disk management shows partitions like this after installing Ubuntu

This makes 5-primary!! and 1-logical partition. How is this possible?
PS: While installing Ubuntu, I didn't get any error/warning about the max number of primary partitions allowed. But every time before booting into Ubuntu this message shows up and only shows when booting to Ubuntu and not while booting to Windows:

A: These non-named partitions on Windows 10 device management are created from Linux Ubuntu and not created from Windows because there are the partitions that would not show up in Computer but you will see it on Device Management and you are unable to access these drives, so you might get the partitions beyond the limit.


text:
Q: What does it mean SIZE in top command? I have a c++ app. its run on freebsd. I have a problem ı guess its about memory.
Normally my app work normaly 3-4 days. I sometimes  check top command in ssh. SIZE always increase 4mb. Its not regular increase (sometime increase 4mb after 5 min sometimes 30min etc)
My application is 32bit(yes its old project) if size reach 4gb my app core its crash and down.
ı would like to learn. Which processes include in SIZE value.
Image from SSH top command


text:
Q: Customizing WebTaggingDialog.JS file on SharePoint2010 When I open dialog that edits metadata of a SharePoint2010 object, I see that the web page loads various JavaScript files. One of them is WebTaggingDialog.JS. I need to customize functions in this JavaScript file.

*

*Does anybody know if this is a static file that comes somewhere from the server?

*Is there any SharePoint feature that forces this file to be generated on the fly and/or influence its content?

Can anybody confirm that this is not possible at all?


text:
Q: Kähler Potential on Blowup of $\mathbb{C}/\{\pm 1\}$ The book Joyce: Riemannian Holonomy Groups and Calibrated Geometry contains on page 205 the Eguchi-Hanson space as an example:

Consider $\mathbb{C}^2$ with complex coordinates $(z_1,z_2)$, acted upon by the involution $-1:(z_1,z_2) \mapsto (-z_1,-z_2)$.
  Let $(X,\pi)$ be the blow-up of $\mathbb{C}^2/\{\pm 1\}$ at $0$.
  Then $X$ is a crepant resolution of $\mathbb{C}^2/\{\pm 1\}$.
  (...)
  Define $f:X \setminus \pi^{-1}(0) \rightarrow \mathbb{R}$ by
  $$
f=
\sqrt{r^4+1}+2 \log r - \log \left( \sqrt{r^4+1} +1 \right),
$$
  where $r=\left( |z_1|^2 + |z_2 |^2 \right)^{1/2}$ is the radius function on $X$.
Define a $2$-form $\omega_1$ on $X \setminus \pi^{-1}(0)$ by $\omega_1=i \partial \overline{\partial} f$.
  Then $\omega_1$ extends smoothly and uniquely to $X$.

Question:

How can I see that $\omega_1$ extends to $X$?

Writing $r= \sqrt{z_1 \overline{z_1}+z_2 \overline{z_2}}$ I can compute $\omega_1$ explicitly.
The expressions are long, so I used Mathematica.
All partial derivatives $\frac{\partial}{\partial \overline{z_i}}\frac{\partial}{\partial z_k}f$ tend to $\infty$ as $r \rightarrow 0$.
So it seems to me as if $f$ cannot be extended.
What am I missing?

A: Eguchi-Honson should be singular at the origin of $\mathbb{C}^{2}$
and you have correctly found this fact by getting the limit $r \rightarrow 0$.
you have missed the point that you need to extend the metric over $\pi^{-1}(0)$ on $X$, not over $0 \in \mathbb{C}^{2}/\mathbb{Z}^{2}$!
To be more precise: the blow-up space $X$ is  $\mathcal{O}_{\mathbb{CP}_{1}}(-2) \cong T^{*}\mathbb{CP}_{1}$ and $\pi^{-1}(0) = \text{Zero section of the bundle} \cong \mathbb{CP}_1 $. You need to check that "the metric is smoothly extendable over the zero section". Pullback $f$ with $\pi$ over $X/\pi^{-1}(0)$. By getting a local chart over a point of the zero section you will be able to check that $\partial \bar{\partial} \pi^{*}f$ can extend smoothly over the zero section.
The computation is subtle and using Mathematica would be useful.