text:
Q: How to get database variables from JSON object in grails I'm trying to create a map which show all location in database.
I can do this for one object but I could not for all.
In my controller I get all shops and send to angularjs file
 def getalllocation(){
    def shops=Shop.findAll()
    [shops:shops] as JSON
}

javascriptfile; //this works for one shop
 $scope.getshopinfo = function () {
        $http.post("/shop/getshoplocation", data = {shopId: $("#shopId").val()}).success(function (json) {
            $scope.shop = json;
            //$scope.map = {center: {latitude: 45, longitude: -73}, zoom: 8};
            //$scope.map = {center: {latitude: $scope.shop.shopLattitude, longitude: $scope.shop.shopLongitude}, zoom: 8};
            $scope.map = {
                center: {latitude: $scope.shop.shopLattitude, longitude: $scope.shop.shopLongitude},
                zoom: 10,
                events: mapevents
            };
            $scope.searchbox = {
                template: "searchbox.tpl.html",
                events: searchevents
            };
            $scope.marker = {
                coords: {latitude: $scope.shop.shopLattitude, longitude: $scope.shop.shopLongitude},
                id: '2'
            };
            $("#shopLattitude").val($scope.shop.shopLattitude);
            $("#shopLongitude").val($scope.shop.shopLongitude);
           // $scope.$apply();
        }).finally(function () {
        });
    };
    if ($("#shopId").val()) {
        $scope.getshopinfo();
    }

}]);

I can create a map with multiple markers but not from the database;
var locations = [
[
    "New Mermaid",
    36.9079,
    -76.199,
    1,
    "Georgia Mason",
    "",
    "Norfolk Botanical Gardens, 6700 Azalea Garden Rd.",
    "coming soon"
],
[
    "1950 Fish Dish",
    36.87224,
    -76.29518,
    2,
    "Terry Cox-Joseph",
    "Rowena's",
    "758 W. 22nd Street in front of Rowena's",
    "found"
]]

var marker, i;
for (i = 0; i < locations.length; i++) {
    marker = new google.maps.Marker({
    position: new google.maps.LatLng(locations[i][1], locations[i][2]),
    map: map
});

google.maps.event.addListener(marker, 'click', (function (marker, i) {
    return function () {
        infowindow.setContent(locations[i][0], locations[i][6]);
        infowindow.open(map, marker);
    }
})(marker, i));

I dont know how I combine this codes and get a map with multiple markers from database location. thanks for help

A: I think I understand the issue here. I have also upped your question since you got a negative. I guess it is due to your question actually containing a lot of code and not so much detail as to actual issue.
Anyways I hope by what I am about to say will help you and others approach situations in a different way when it comes to problems like this.
This bit kind of contradicts:
create a map which show all location in database. I can do this for one object but I could not for all, when looking at the controller code:
def getalllocation(){
    def shops=Shop.findAll()
    [shops:shops] as JSON
}

In effect in your gsp you have

$http.post("/shop/getshoplocation", data = {shopId:
  $("#shopId").val()}).success(function (json) {

You are sending a params but then in the controller you are looking up all objects.
 def getalllocation(){
        // Firstly when creating new methods always use debug
        // like this to figure out what you are getting
        println "my params are $params"

        //I can see you are passing in an actual shopId so
        //lets add some logic to either list all or a given shopId
        //No idea what the object here is
        def shops
        if (params.shopId) {
              shops=Shop.where{id==params.shopId}.findAll()
        } else {
             shops=Shop.findAll()
        }
        [shops:shops] as JSON
    }

With that you should hopefully having it working, since in your code it does state show it when a shop id is clicked.
As to your contradiction, you say you want it to show all shops and it only displays one

"although your code has been defined to pass shopId to controller ?"

Eitherway the reason it can't display or show the current map is because you are returning a JSON map of all your shop entries but then when you receive the json you appear to attempt to parse the list containing the json lists once. I think you need to iterate through it.
Something like this:
  $http.post("/shop/getshoplocation", data = {shopId: $("#shopId").val()}).success(function (json) {

        $scope.companies = json.forEach(function(entry) {
            center: {latitude: $entry.shopLattitude, longitude: $entry.shopLongitude},
                zoom: 10,
                events: mapevents
         }
}

I don't have access to any of this, and all of the above after something like this is all guess work and may not be a 100% it is just giving you an idea as to where it may be going wrong.


text:
Q: Sifting needle (String array) through haystack (larger String array) in Java I need to return the index position of where in the haystack
 array the needle array occurs and -1 if otherwise. For example if String haystackArray = [red, blue, green] and String needleArray = [blue, green] it should return a 1 for the 1 index position of the haystack that the needle occurs.
Here is what my code looks like:
    public static int FindSequence(String[] haystack, String[] needle)
    {
        int numInSequence = 0;
        int counter = 0;

        if(haystack.length == 0 || needle.length == 0)
            return -1;
        if(needle.length > haystack.length)
            return -1;
        for(int i = 0; i < haystack.length-1; i++) //for the length of haystack
        {
            if(needle[0].equals(haystack[i]))//if the first item in needle is equivalent to this particular item in haystack...
            {
                numInSequence = i;
                numInSequence+=1;
                for(int j = 1; j < needle.length-1; j++, numInSequence++){ //for the remaining length of the needle...
                    if(needle[j].equals(haystack[numInSequence])){ //checks to see if the next item in needle is equivalent to the next item in haystack and if this
                        counter++;
         if((needle[needle.length-1]).equals(haystack[numInSequence])){ // if the last item in needle is equivalent to an item in haystack...
                            return numInSequence - counter - 1; // return our desired index
                        }
                    }
                    break;
                }
                break;
            }
        }
        return -10;
    }

For some reason, pretty much any array tests I try, I get the -10 returned. Any suggestions or help would be greatly appreciated.

A: Change the loop condition to
for(int i = 0; i < haystack.length; i++)

and
 for(int j = 1; j < needle.length; j++, numInSequence++){

With your current current code, you are skipping the last index.
Also, if j < needle.length -1, how can it enter your
if((needle[needle.length-1]).equals(haystack[numInSequence])){

and return return numInSequence - counter - 1;. That is the source of the bug.
To give an example, if there are 10 elements in the array, you have indices from 0-9. And you are checking < 9 instead of < 10. So, the index 9 is not checked by your code.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Searching in Array of complex collection of NSDictionary I have an array of dictionaries, similar to the following:
{
  "categories": [
    {
      "category_id": "1",
      "parent_id": "0",
      "en_name": "Category 1",
      "sub": [
        {
          "category_id": "2",
          "parent_id": "1",
          "en_name": "Abc Pqr",
          "businessCount": "5"
        },
        {
          "category_id": "5",
          "parent_id": "1",
          "en_name": "Xyz Model",
          "businessCount": "7"
        }
      ]
    },
    {
      "category_id": "3",
      "parent_id": "0",
      "en_name": "Category 2",
      "sub": [
        {
          "category_id": "4",
          "parent_id": "1",
          "en_name": "Test",
          "businessCount": "15"
        },
        {
          "category_id": "6",
          "parent_id": "1",
          "en_name": "Dummy",
          "businessCount": "9"
        }
      ]
    }
  ]
}

I want to search for "en_name" of element "sub". Please suggest me ASAP

A: i am assuming that you have the categories array...that u got from webApi..
then enumerating that categories array...as it is the array of dictionaries....
then sub also an array of dictioanries..enumerating that will give u that u want...
for(NSDictionary *dict in categories)
    {
      for(NSDictionary * dict1 in [dict objectForKey :@"sub"])
      {
         NSString *name = [dict1 objectForKey :@"en_name"];

       }
    }


text:
Q: Trouble understanding Set comprehensions I don't quite understand why their is a C in the beginning of the {}. Is this just syntax for comprehensive sets?
x= {c for c in "I've got plenty of nothing"}
print(sorted(x))
This prints: [' ', "'", I, 'e', 'f', 'g', 'h', 'i', 'l', 'n', 'o', 'p', 't,' 'v', 'y']
 Can someone explain why I need a c before the for loop?


text:
Q: How can I load startup programs without logging in during system start Many of my startup programs do not load until I log on to my account, when the computer starts.
If I set up auto login, the system is ready - and anyone who switches the comp on gets access to my account. I don't want that.
How can I setup my PC to wait for my password, while having loaded all my startup programs in the background?


text:
Q: Set OptionSetValue to null in Dynamics CRM Plugin I´ve already found a similar question but the answer just did'nt work for me so I wondered if there might be lilke any newer information on this topic.
What I want to do is assign null to an OptionSetValue.
What I've tried so far:

*

*someEntity.Attributes["myfield"] = 899270000; //Works

*someEntity.Attributes["myfield"] = null; //Not working

*someEntity.Attributes["myfield"] = 0; //Not working

*someEntity.Attributes["myfield"] = -1; //Also not working

Thanks in advance.

A: Doing
someEntity["myfield"] = null;
service.Update(someEntity);

Or the strong stype equivalent:
someEntity.myfield = null;
service.Update(someEntity);

Should definetely work.


text:
Q: How Do I Use Column Value in Window Function for a Dynamic Frame with Postgres? I'm not sure if this is possible with Postgres, but I would like each row to compute its window function "frame".
So how would I use a column from the current row as an argument to ROWS in a window function with Postgres?
For instance..
create table items (
  id serial primary key, name varchar, price integer, precede_by integer
);

insert into items (name, price, precede_by)
  values
  ('A', 1, 2), ('A', 1, 3),
  ('B', 1, 1),('B',1, 2), ('B', 1, 1), ('B', 2, 2),
  ('C', 1, 2), ('C', 1,2), ('C', 1, 2), ('C', 1, 5);

I would like to use the integer value set in the precede_by column.. E.g., something like this..
select name, sum(price) over
  (partition by name rows between precede_by preceding and current row)
from items;

But this doesn't work. I receive ERROR:  argument of ROWS must not contain variables

A: No, it is not possible to write the window function as you want. I believe that CROSS JOIN LATERAL can do the trick
with oitems as
(
  select *, row_number() over (partition by name order by id) rn from items
)
select *
from oitems i1
cross join lateral
(
  select sum(price)
  from  oitems i2
  where i1.name = i2.name and i2.rn >= i1.rn - i1.precede_by and i2.rn <= i1.rn
) t

and another (maybe more elegant) solution is to just use self-join with GROUP BY
with oitems as
(
  select *, row_number() over (partition by name order by id) rn from items
)
select i1.id, i1.name, i1.price, sum(i2.price)
from oitems i1
join  oitems i2 on i1.name = i2.name and i2.rn >= i1.rn - i1.precede_by and i2.rn <= i1.rn
group by i1.id, i1.name, i1.price

dbfiddle demo


text:
Q: ID generation strategy supported by MySQL This is related to Hibernate Framework. Which ID generation strategies are supported by MySQL ?
Through hibernate documentation I came to know that it does't support "sequence" class.
I am able to successfully persist the object when I use "assigned" and "increment" classes.
But use of "identity" is resulting in an sql exception caused by "Field id (the property that maps to primary key in table) doesn't have default value". Do we have to assign some default value before using the "identity" class?

A: There are four strategies.
@GeneratedValue(strategy=GenerationType.TABLE)

*

*AUTO   -- with auto_increment

*IDENTITY  -- with auto_increment

*SEQUENCE -- not supported

*TABLE  -- with  hibernate_sequences TABLE

Tested directly with MYSQL5.2

A: To use identity strategy you have to use auto_increment, something like

create table 'table_name' (  'id' int not null auto_increment, ......
  ... )

That should do I guess.


text:
Q: ASP.NET MVC vs Angularjs com WEBAPI Em um projeto web(tipo um "pequeno" ERP, rs) onde algumas empresas iriam administrar suas filiais podendo existir vários usuários conectados, o que seria melhor em questão de performance e desempenho (sei que cada caso é um caso, mas no geral) na opinião de vocês o que seria melhor:
ASP.NET MVC ou Angularjs com WEBAPI? nos dois casos a arquitetura seria DDD com EF e dapper. Obrigado.

A: Opa, tudo bem?
Essa é uma questão bastante abstrata, mas acho que este link pode lhe ajudar:
https://www.quora.com/What-should-I-choose-Angular-js-or-NET-MVC-Which-language-has-better-career-prospects
Se for levar em consideração apenas a performance, AngularJs, à grosso modo, terá um melhor desempenho por ser um framework javascript e rodar no navegador. Mas isso pode mudar facilmente caso as requisições que a camada apresentação fizer para a web-api sejam lentas, pois a performance acabará se equivalendo e você não terá ganho algum no uso do AngularJs(Caso sua preocupação seja apenas performance). Entretanto há muitos fatores a se considerar, como curva de aprendizagem e segurança. Além do beneficio da performance, a solução do angular, por utilizar uma web-api pode ser uma boa, visto que ela pode ser utilizada por outros sistemas no futuro, como um aplicativo mobile ou uma exposição para outras aplicações consumirem.
Bom, não sei se ajudei, expus um pouco da minha opinião, mas a questão é realmente difícil de ser definida com uma resposta absoluta.


text:
Q: Remove duplicate rows in t-sql query results I have a some T-SQL below and i am facing a problem where each row is being returned twice with the same values. How can ensure each is returned once or force a select Distinct
;WITH CTE_ReportDetails
AS (
    SELECT
        CASE(GROUPING(M.Acronym))
            WHEN 0 THEN [Acronym]
            WHEN 1 THEN 'GRAND TOTAL'
            END AS [Company],

        CASE(GROUPING(DC.Name))
            WHEN 0 THEN DC.[Name]
            WHEN 1 THEN 'N/A'
            END AS [CatName],

        CASE(GROUPING(D.[Name]))
            WHEN 0 THEN D.[Name]
            WHEN 1 THEN 'Total '+ '('+DC.[Name]+')'
            END AS [Name],

        SUM(ISNULL(B.One, 0)) AS One,
        SUM(ISNULL(B.Two, 0)) AS Two,
        SUM(ISNULL(B.Three, 0)) AS Three,
        ISNULL(B.Description, '') AS Description,
        GROUPING(M.Acronym) AS CompanyGrouping,
        GROUPING(DC.[Name]) AS DCatGroup,
        GROUPING(D.[Name]) AS DGroup
    FROM Dee D
        INNER JOIN DeeCategory DC ON D.DeeCategoryId = DC.DeeCategoryId
        INNER JOIN BD B ON B.DeeId = D.DeeId
        INNER JOIN Report R ON R.RptId = B.RptId
        INNER JOIN Company M ON R.CompanyId = M.CompanyId
    WHERE (R.ReportDate >= @StartDate AND R.ReportDate <= @EndDate) AND (R.CompanyId IN (SELECT DATA FROM SPLIT(@CompanyIds,',')))
    GROUP BY M.Acronym, DC.Name, D.Name,B.Description
    WITH ROLLUP
)
SELECT Company, Name As [Dee],
        One,
        Three,
        Two,
        (One + Three + Two) AS Total,
        Description
FROM CTE_ReportDetails

A: Your report should have a unique combinations of values from the group by.  So, these four columns should be unique:
GROUP BY M.Acronym, DC.Name, D.Name,B.Description

If I had to guess, you are getting duplicates because B.Description is duplicated in the B table.  I would suggest removing it from the GROUP BY and changing this line:
    ISNULL(B.Description, '') AS Description,

to
    ISNULL(max(B.Description), '') AS Description,


text:
Q: JavaFX: Drawing a infinite symbol and moving along I need to create a JavaFX application that generates a path in the form of an infinite symbol, and then create a rectangle that will move across that path.
So far I know to create a circle and square and with transitionPath to move that rectangle , but how to create an infinity shape? I'm very fresh in JavaFx (and in development as well) so please don't be harsh :)
Here is my code with Circle shape:
 import javafx.animation.PathTransition;
 import javafx.animation.Timeline;
 import javafx.application.Application;
 import javafx.scene.Scene;
 import javafx.scene.layout.Pane;
 import javafx.scene.paint.Color;
 import javafx.scene.shape.Rectangle;
 import javafx.scene.shape.Circle;
 import javafx.stage.Stage;
 import javafx.util.Duration;

 public class PathTransitionDemo extends Application {
 @Override
 public void start(Stage primaryStage) {

 Pane pane = new Pane();

 Rectangle rectangle = new Rectangle (0, 0, 25, 50);
 rectangle.setFill(Color.ORANGE);

 Circle circle = new Circle(125, 100, 50);
 circle.setFill(Color.WHITE);
 circle.setStroke(Color.BLACK);

 pane.getChildren().add(circle);
 pane.getChildren().add(rectangle);

 PathTransition pt = new PathTransition();
 pt.setDuration(Duration.millis(4000));
 pt.setPath(circle);
 pt.setNode(rectangle);
 pt.setOrientation(
 PathTransition.OrientationType.ORTHOGONAL_TO_TANGENT);
 pt.setCycleCount(Timeline.INDEFINITE);
 pt.setAutoReverse(true);
 pt.play();

 circle.setOnMousePressed(e -> pt.pause());
 circle.setOnMouseReleased(e -> pt.play());

 Scene scene = new Scene(pane, 250, 200);
 primaryStage.setTitle("PathTransitionDemo"); // Unos nayiva pozornice e
 primaryStage.setScene(scene);
 primaryStage.show();
 }

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

I looked everywhere for some hint, but without luck :(

A: I found on the web an SVG path to draw an "infinity" shape, so replace your circle with:
SVGPath svg = new SVGPath();
svg.setFill(Color.TRANSPARENT);
svg.setStrokeWidth(1.0);
svg.setStroke(Color.BLACK);
svg.setContent("M 787.49,150 C 787.49,203.36 755.56,247.27 712.27,269.5 S 622.17,290.34 582.67,279.16 508.78,246.56 480,223.91 424.93,174.93 400,150 348.85,98.79 320,76.09 256.91,32.03 217.33,20.84 130.62,8.48 87.73,30.5 12.51,96.64 12.51,150 44.44,247.27 87.73,269.5 177.83,290.34 217.33,279.16 291.22,246.56 320,223.91 375.07,174.93 400,150 451.15,98.79 480,76.09 543.09,32.03 582.67,20.84 669.38,8.48 712.27,30.5 787.49,96.64 787.49,150 z");

and use it for drawing, transition and event catching.
You may need to adapt it to your need.
If you are looking for better "infinity" shapes, then search for "lemniscate".


text:
Q: Need help with custom villager trading Ok, I've been using a command block to spawn a villager that has custom trades. There's no problem with that at all- I'm just wondering if it's possible to have a villager trade me an item that has a custom name (eg. Key). Or is this unchangeable, so I'd need to name it with an anvil after purchase?
/summon Villager ~ ~1 ~ {Offers:{Recipes:[{buy:{id:"minecraft:emerald",Count:4},sell:{id:"minecraft:leather_helmet",Count:1}},{buy:{id:"minecraft:emerald",Count:6},sell:{id:"minecraft:leather_chestplate",Count:1}},{buy:{id:"minecraft:emerald",Count:5},sell:{id:"minecraft:leather_leggings",Count:1}}]}}

The code is fully functional, it's just integrating custom names for the item he sells.

A: NBT you would include in /give commands for items goes inside the "tag" compound. https://minecraft.gamepedia.com/Player.dat_format#Item_structure
/summon Villager ~ ~1 ~ {Offers:{Recipes:[{buy:{id:"minecraft:emerald",Count:4b},sell:{id:"minecraft:leather_helmet",Count:1b,tag:{display:{Name:"Foo"}}}},{buy:{id:"minecraft:emerald",Count:6b},sell:{id:"minecraft:leather_chestplate",Count:1b}},{buy:{id:"minecraft:emerald",Count:5b},sell:{id:"minecraft:leather_leggings",Count:1b}}]}}

A: You are wanting to add data that would require adding a data tag.  Lets look at the first item sold:
sell:{id:"minecraft:leather_chestplate",Count:1}

The give command to give this item is:
/give @p minecraft:leather_chestplate 1

To add a name to the give command, the dataTag argument needs to be specified:
/give @p minecraft:leather_chestplate 1 0 {display:{Name:"The custom name"}}

In your command, everything contained within the sell compound is defining the item.  This requires following the item structure, which means the data tag information has to be within a tag compound:
tag:{display:{Name:"The custom name"}}

This would give you a final sell compound of:
sell:{id:"minecraft:leather_chestplate",Count:1b,tag:{display:{Name:"The custom name"}}}

You can add the tag compound to any of the buy or sell compounds in your summon command.
You can also specify enchantments, attribute modifiers, flags, lore, etc. within the tag compound.


text:
Q: How can I create a buy now button for a specific product variant with Shopify BuyButton.js I am using Shopify BuyButton.js to create a buy button and shopping cart on my site.
I have a product with multiple variants.
I can easily create a buy button for a product with the following:
ui.createComponent('product', {
    id: [productid],
    node: document.getElementById('container'),
    options: {
        product: {
            layout: 'horizontal',
            contents: {
                img: false,
                title: false,
                options: true
            }
        },
        cart: {
            startOpen: false,
        }
    }
});

This product has several variants that can be chosen with a drop down and the first variant is the selected one.
What I want to do is create a buy button but only for a specific variant of the product. No drop down and  clicking 'Add to Cart' will add that product with the specific variant selected.
I can hide the drop down by setting options: false but the variant selected is the first one and I can't set the specific variant.

A: Under your line id: [productid], put in:
variantId: [variantid],
Where variantid is ID of the variant. This can be found in the URL when you click to edit the variant in the Shopify dashboard.


text:
Q: Check if a setting is set I need for my APP the right time. So, I was thinking to check if it is not set the Automatic time, forcing to the user to set it. Is there any way to check that?
Thanks

A: AFAIK, there is no way to force the user to use the network time on their devices. Even if you do manage that, the network time itself could be incorrect.
A better solution would be to get the time from your server and adjust it for the user's time zone.


text:
Q: Subdomain Domain using .htacces for every users I am using Amazon Ec2.
I am not professional in .htaccess , i have referred following .htaccess
RewriteCond %{HTTP_HOST}    ^([\w-]+).example.com$
RewriteCond %{REQUEST_URI}  !^/example.com/
RewriteRule ^(.*)$          /example.com/$1?subdomain=%1 [LAST,QSA]

when i try to execute this username.example.com to example.com/subdomain?id=username
I am using EC2 amazon server.
1st issues is if i am trying to execute username.example.com then this domain is not getting resolved.
2nd issue the above htaccess is not working for me . If any one could solve this will be helpful

A: You cannot do this using .htaccess file, you need to setup a wild card virtual host and then rewrite it to the URL you need.
This information might be useful, you can also refer to this question.


text:
Q: Is it possible to prove that if $g \in G$ with $G$ finite, then $o(g) \mid |G|$ without using Lagrange's theorem? While this is a straightforward result which follows almost immediately from Lagrange's theorem (by considering the subgroup generated by $\langle g\rangle $), is there any way this can be proven without using Lagrange or any other theorem which derives from it?
One approach I thought of is that if it can be proven that for $ g \in G$ we have $ g^{|G|} = e$ then the result follows as $ g^n = e \iff o(g) \mid n $ , but I've had no success going down this line of attack.
While I have no idea if it is possible to do so, I suspect it is as it's from a past paper question which says we can't use Lagrange's theorem or the Orbit-Stabiliser theorem to prove the result without proving these beforehand. If the result could only be deduced from Lagrange, then I would assume the question would first ask for a proof of it and then have this as a corollary.

A: Considering the free action of $G$ on itself by left multiplication, the permutation induced by $g$ must be a product of disjoint cycles each having length $o(g)$. Therefore $|G|$ is a multiple of $o(g)$. However, this is very similar to how one proves Lagrange's theorem for this special case.


text:
Q: I mark error in line setOnRefreshListener me marca este error The method setOnRefreshListener(PullToRefreshListView.OnRefreshListener) in the type PullToRefreshListView is not applicable for the arguments (activity)
my code is this
private class ListViewPagerAdapter extends PagerAdapter {

    @Override
    public View instantiateItem(ViewGroup container, int position) {
        Context context = container.getContext();

        PullToRefreshListView plv = (PullToRefreshListView) LayoutInflater.from(context).inflate(
                R.layout.layout_listview_in_viewpager, container, false);

        ListAdapter adapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1,
                Arrays.asList(STRINGS));
        plv.setAdapter(adapter);

        plv.setOnRefreshListener(activity.this);

        // Now just add ListView to ViewPager and return it
        container.addView(plv, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);

        return plv;
    }


text:
Q: Beginner confused by berkshelf and chef I'm new to chef and berkshelf, and very confused I have tried seeking help in open board questions but no luck please help me..

*

*Does berkshelf install my recipes along resolving the dependencies? Meaning the recipes has MySQL so after vagrant up will MySQL be installed?

*Should I use vagrantfile in vagrant root or the one with berkshelf?

*Why does vagrantfile in berkshelf (even without recipes) always have the entries for MySQL: server_root/Debian/repl passwords!!!!)

Thank you

A: Berkshelf is a cookbook dependency manager.
Assuming you have already installed the chef development kit, first generate a cookbook:
$ chef generate cookbook demo
$ tree
.
└── demo
    ├── Berksfile
    ├── chefignore
    ├── metadata.rb
    ├── README.md
    ├── recipes
    │   └── default.rb
    ├── spec
    │   ├── spec_helper.rb
    │   └── unit
    │       └── recipes
    │           └── default_spec.rb
    └── test
        └── integration
            ├── default
            │   └── serverspec
            │       └── default_spec.rb
            └── helpers
                └── serverspec
                    └── spec_helper.rb

The Berksfile holds the configuration and its format is documented on the website. The cookbook generator creates a default setting that tells berkshelf to download dependencies from the Chef supermarket and to use the metadata file to list those dependencies:
source 'https://supermarket.chef.io'

metadata

So let's edit the metadata.rb file adding mysql as a dependency
name 'demo'
maintainer 'The Authors'
maintainer_email 'you@example.com'
license 'all_rights'
description 'Installs/Configures demo'
long_description 'Installs/Configures demo'
version '0.1.0'

depends "mysql"

So now if you decide to run berkshelf, it will resolve your cookbook's dependencies for you automatically.
$ berks vendor cookbooks
Resolving cookbook dependencies...
Fetching 'demo' from source at .
Using demo (0.1.0) from source at .
Using mysql (8.1.1)
Vendoring demo (0.1.0) to cookbooks/demo
Vendoring mysql (8.1.1) to cookbooks/mysql

Hopefully this answers some of your questions, but to conclude could I recommend that you look at test kitchen? The cookbook generator also configures this to use Vagrant to both run chef and test your cookbook at the same time:
$ kitchen test default-ubuntu-1404

Be a happy Chef!


text:
Q: "Notice: Undefined index: " message for the following code on localhost I have written a code - It takes user input and displays sha1() string for the input.
I get the 'undefined index' notice on local host even after declaring the variables and using isset() function.

Notice: Undefined index: enc in C:\Program Files\EasyPHP-12.1\www\MySQL\localhost_drupal\encrypt.php on line 61

It works fine on the remote (production) server.
What is the fault in the following code?
<?php

//variable declaration
$enc = $len = "";

// checking with isset
if(isset($_POST['enc'])) {

//sha1()
$enc = sha1($_POST['enc']);

// strlen function
$len = strlen($_POST['enc']);
}
?>

//HTML
<!DOCTYPE html>

<title>Generate Password</title>

<form name = "encry" action = "encrypt.php" method = "post">

<input type = "text" name = "enc" >

<input type = "submit" value = "Submit">

</form>

//OUTPUT
<?php

//Line 61

echo "
 You entered :" . $_POST['enc']."
";

echo "
 Length of the string you entered :" . $len. "
";
echo "
 Your Password is : ". $enc  . "
";

?>

A: The reason being for the error is that your entire code is inside one page and errors out on initial load. Error reporting is set on one server, but isn't on the other.
You should be using isset() against a named submit button (which I have named) and around where you're using
echo "
 You entered :" . $_POST['enc']."
"; etc..
Change your code to the following:
<?php

//variable declaration

$enc = $len = "";

// checking with isset

if(isset($_POST['enc'])) {

//sha1()

$enc = sha1($_POST['enc']);

// strlen function

$len = strlen($_POST['enc']);
}
?>

//HTML

<!DOCTYPE html>

<title>Generate Password</title>

<form name = "encry" action = "encrypt.php" method = "post">

<input type = "text" name = "enc" >

<input type = "submit" value = "Submit" name = "submit">

</form>

//OUTPUT

<?php

if(isset($_POST['submit'])) {
//Line 61

echo "
 You entered :" . $_POST['enc']."
";

echo "
 Length of the string you entered :" . $len. "
";
echo "
 Your Password is : ". $enc  . "
";

}
?>

To set error reporting on:
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

// rest of your code

Sidenote: Error reporting should only be done in staging, and never production.

A: It's an E_NOTICE. Likely on production you suppress error messages (or at least notices). This is fine, but it does explain why it breaks in development.
Fix the issue and the notice will go away.


text:
Q: MVC using Action Filter to check for parameters in URL. stop action from executing I want to make the following:
when the url doesn't have an instID, i want to redirect to the "Instelling" action
in this controller, every method needs the instID.
        [RequiredParameter(parameterName="instID", controllerToSend="Instelling")]
        public ActionResult Index(int? instID) {
            //if (!instID.HasValue) {
            //    return RedirectToAction("Index", "Instelling");
            //}

            var facts = _db.Instellingens.First(q => q.Inst_ID == instID).FacturatieGegevens;

            return View(facts);
        }

so this is in the controller.
the actionfilter:
namespace MVC2_NASTEST.Controllers {
    public class RequiredParameterAttribute : ActionFilterAttribute {

        public string parameterName { get; set; }
        public string actionToSend { get; set; }
        public string controllerToSend { get; set; }

        public override void OnActionExecuting(ActionExecutingContext filterContext) {

            if (parameterName != string.Empty) {
                if (filterContext.ActionParameters.ContainsKey(parameterName) && filterContext.ActionParameters[parameterName] != null) {
                    string s = "test";
                    //all is good
                } else {
                    //de parameter ontbreekt. kijk of de controller en de action geset zijn.
                    if (actionToSend == string.Empty)
                        actionToSend = "Index";
                    if (controllerToSend == string.Empty) {
                        controllerToSend = filterContext.Controller.ToString();
                        controllerToSend = controllerToSend.Substring(controllerToSend.LastIndexOf(".") + 1);
                        controllerToSend = controllerToSend.Substring(0, controllerToSend.LastIndexOf("Controller"));
                    }

                    UrlHelper helper = new UrlHelper(filterContext.RequestContext);
                    string url = helper.Action(actionToSend, controllerToSend);

                    HttpContext.Current.Response.Redirect(url);
                    //filterContext.HttpContext.Response.Redirect(url, true);
                }
            }

            base.OnActionExecuting(filterContext);
        }

        public override void OnActionExecuted(ActionExecutedContext filterContext) {

            base.OnActionExecuted(filterContext);
        }

    }
}

the thing is: it does work, however, the action itself first gets executed, THEN the redirect happens. this is not what I wanted.
Perhaps i shouldnt use actionfilters but just add a route?
in this case, how would i redirect the route to another controller if the instID is missing?

A: Rather than creating an action filter (which runs just before the return of the action method), you could consider changing to an Authorization Filter which would allow you to redirect to an alternative controller & action
Something like this (pseudo code):
public class RequiredParameterAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        // read instID from QueryString
        // if instId is null, return false, otherwise true
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.result = new RedirectToRouteResult( new { controller = "MyController" , action = "MyAction" }  )
    }

}

A: This was the first result on a question I asked on Google, so I'd like to propose a different answer. Instead of doing the redirect from the action assign a redirect to the filterContext.Result like this:
filterContext.Result = new RedirectResult(url);

If the result property of the filterContext is not null then the underlying action will not be executed. Because you're performing a redirect outside the context of the call you will still execute the action method.


text:
Q: This makes possible to I came across the sentence below in a book on Linguistics:
This makes possible to consider language as a regulator not only of its perception, but also of its representation and action.
I cannot tell if the sentence is correct. Should not it read "makes it possible to...?" Thanks.

A: Certainly a noun phrase may follow "This makes possible" as the direct object of makes.  From the Congressional Record in 1960:

This makes possible the elimination of unnecessary delay and
  difficulty to everyone concerned,....

It seems possible to allow a gerund as that noun phrase.  From a US patent application:

This makes possible eliminating the time needed for the next
  position determination process.

To my ears, an infinitive won't do without a dummy subject it:

This makes it possible to eliminate the time needed for the next
  position determination process.

However, the infinitive alone appears in print.  It's certainly distinctly disfavored: the google finds 27.5M instances of "this makes it possible to" but only but only 274K instances of "this makes possible to."  For books, the counts are 884K for the former, only 12.3K for the latter.
A look unto fatigue at the search results in the Ngram viewer containing "this makes possible to" finds numerous authors from non-Anglophone countries using the phrasing and numerous editors from non-Anglophone countries allowing it.  The usage appears predominantly in publications covering science, medicine, and technology, and it slips into prose that otherwise seems natural and fluent.
The rare locution* seems more common than can be written off as editing errors, but it also seems that native speakers have not adopted it.
* That is, when the infinitive is the direct object of make.
EDIT: I have removed an erroneous cite to a US source, which I find I cannot replace.

A: It's ungrammatical. The sentence means:

*

*This makes [to consider language as a regulator not only of its perception, but also of its representation and action] possible.

However, in modern English we don't like to use infinitival clauses as direct Objects of verbs like MAKE. They are difficult to process. Instead we insert an it as a dummy Direct Object and move the infinitival clause to the end of the sentence:

*

*This makes it possible [to consider language as a regulator not only of its perception, but also of its representation and action].

In the example from the book, the infinitival clause has been moved to the end of the sentence. However, the sentence is now lacking an obligatory (syntactic) Direct Object -  because the dummy it has not been inserted.

A: This makes possible to consider language as a regulator not only of its perception, but also of its representation and action.
If followed by an infinitive, "possible" definitely requires "it possible", but it is a fairly convoluted sentence at best.


text:
Q: How do I fix the error of call to undefined function for add_settings_field()? I followed exactly this tutorial and I got this error:

Fatal error: Call to undefined function add_settings_field() in
  /home/content/41/11334041/html/test/wp-content/themes/mothereffintheme/functions.php
  on line 47

I'm new to working with the Wordpress API and I don't have any idea to how to fix it.

A: I saved it in my FTP program instead of the the theme editor. It worked!

A: Are you sure you loaded WordPress? add_settings_field() is a WordPress function rather than a default PHP function, if it's undefined it would indicate that the WordPress core hasn't been loaded. A bit of code might help.
http://codex.wordpress.org/Function_Reference/add_settings_field


text:
Q: How to implement a Non scrollable listview inside a SingleChildScrollView Im trying to implement a non scrollable ListView builder here but can't seem to find how to do it. Reason is because i want everything to be scrollable and i dont want to have a Scrollable widget inside a scrollable parent.
class _DashboardState extends State<Dashboard> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text('App Bar Here')),
        body: SingleChildScrollView(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text('Hello World'),
              Container(
                child: ListView.builder(
                  itemBuilder: (context, index) {
                    return Card(
                      child: Padding(
                        padding: const EdgeInsets.all(16.0),
                        child: Column(
                          children: <Widget>[
                            Container(
                                color: Color(0xffaaaaaa),
                                height: 20,
                                child: Text('Jss One')),
                            Text(
                              'English',
                              style: TextStyle(fontSize: 20),
                            ),
                          ],
                        ),
                      ),
                    );
                  },
                  itemCount: 50,
                ),
              ),],),));
  }}

A: class _DashboardState extends State<Dashboard> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text('App Bar Here')),
        body: SingleChildScrollView(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text('Hello World'),
              Container(
                child: ListView.builder(
                  physics: NeverScrollableScrollPhysics() //add this line,
                  itemBuilder: (context, index) {
                    return Card(
                      child: Padding(
                        padding: const EdgeInsets.all(16.0),
                        child: Column(
                          children: <Widget>[
                            Container(
                                color: Color(0xffaaaaaa),
                                height: 20,
                                child: Text('Jss One')),
                            Text(
                              'English',
                              style: TextStyle(fontSize: 20),
                            ),
                          ],
                        ),
                      ),
                    );
                  },
                  itemCount: 50,
                ),
              ),],),));
  }}

set physics property to NeverScrollablePhysics() in order to not scroll the lisview

A: try using physics property of listview
physics: NeverScrollableScrollPhysics()

hope it helps..

A: The Solution to what i was going for.
What happens here is the ListBuilder widget will build a List of items not in a Scrollable widget. The parent widget itself is scrollable which makes the whole Screen scrollable. To do this, add shrinkWrap: true and physics: NeverScrollableScrollPhysics() to the ListView.builder() property.
class _DashboardState extends State<Dashboard> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text('App Bar Here')),
        body: SingleChildScrollView(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text('Hello World'),
              Container(
                child: ListView.builder(
                  shrinkWrap: true, //add this line
                  physics: NeverScrollableScrollPhysics() //add this line,
                  itemBuilder: (context, index) {
                    return Card(
                      child: Padding(
                        padding: const EdgeInsets.all(16.0),
                        child: Column(
                          children: <Widget>[
                            Container(
                                color: Color(0xffaaaaaa),
                                height: 20,
                                child: Text('Jss One')),
                            Text(
                              'English',
                              style: TextStyle(fontSize: 20),
                            ),
                          ],
                        ),
                      ),
                    );
                  },
                  itemCount: 50,
                ),
              ),],),));
  }}


text:
Q: How do i make a serializer field show only to the logged in user in django rest framework Hi how are you? I am making an e-commerce API and the issue I am facing is that when a user signs up it shows the user who signed up and the data along with it. How do I just make that data available to a user in json if he is logged into his or her account?
when you sign up in the /sign-up endpoint it shows all the data a user just entered!
how do I restrict that data to be viewed only by the authenticated owner of his or her account?
The field is write_only, I want to extract the data in dict format like I would do with a read_only field.
thanks!


text:
Q: Get listitem with shortest length from a python list I have a orginal list with three words: 'hello', 'hi' and 'Good day'.
I want to create a new_list containing the item with the shortest length. How do I write that code? I use Python 2.7.
original_list=['hello','hi','Good day']

 Word      Length
'Hello'      5
'Hi'         2
'Good day'   8

Expected output (since I only want the item with the shortest length):
new_list=['Hi']

A: min() takes a key function as an argument, use len as a key function:
>>> original_list = ['hello','hi','Good day']
>>> new_list = [min(original_list, key=len)]
>>> new_list
['hi']

This though does not handle multiple items with the same shortest length - e.g. ['hello','hi','Good day', 'me'] input list.


text:
Q: is there any way for me to know if a file has been modified? I am making a program that detects if a file has been modified. but the file is not from me. I wanna know if it is possible to know if the files I'm getting were already modified or not.
Is there a way for me to know that? I've tried the creation date and date modified but sometimes when I modify a file their values will be the same.
P.S. I don't have the original file. I wanna know if it is possible to know if the I'm getting were unchanged before i get it.

A: The following example creates a FileSystemWatcher to watch the directory specified at run time. The component is set to watch for changes in LastWrite and LastAccess time, the creation, deletion, or renaming of text files in the directory. If a file is changed, created, or deleted, the path to the file prints to the console. When a file is renamed, the old and new paths print to the console.
Use the System.Diagnostics and System.IO namespaces for this example.
using System;
using System.IO;
using System.Security.Permissions;

public class Watcher
{

    public static void Main()
    {
    Run();

    }

    [PermissionSet(SecurityAction.Demand, Name="FullTrust")]
    public static void Run()
    {
        string[] args = System.Environment.GetCommandLineArgs();

        // If a directory is not specified, exit program.
        if(args.Length != 2)
        {
            // Display the proper way to call the program.
            Console.WriteLine("Usage: Watcher.exe (directory)");
            return;
        }

        // Create a new FileSystemWatcher and set its properties.
        FileSystemWatcher watcher = new FileSystemWatcher();
        watcher.Path = args[1];
        /* Watch for changes in LastAccess and LastWrite times, and
           the renaming of files or directories. */
        watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
           | NotifyFilters.FileName | NotifyFilters.DirectoryName;
        // Only watch text files.
        watcher.Filter = "*.txt";

        // Add event handlers.
        watcher.Changed += new FileSystemEventHandler(OnChanged);
        watcher.Created += new FileSystemEventHandler(OnChanged);
        watcher.Deleted += new FileSystemEventHandler(OnChanged);
        watcher.Renamed += new RenamedEventHandler(OnRenamed);

        // Begin watching.
        watcher.EnableRaisingEvents = true;

        // Wait for the user to quit the program.
        Console.WriteLine("Press \'q\' to quit the sample.");
        while(Console.Read()!='q');
    }

    // Define the event handlers.
    private static void OnChanged(object source, FileSystemEventArgs e)
    {
        // Specify what is done when a file is changed, created, or deleted.
       Console.WriteLine("File: " +  e.FullPath + " " + e.ChangeType);
    }

    private static void OnRenamed(object source, RenamedEventArgs e)
    {
        // Specify what is done when a file is renamed.
        Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath);
    }
}

Reference: Microsoft MSDN

A: If you want to know if the content of a file changed, compute its hash:
using System.IO;
using System.Security.Cryptography;

using (HashAlgorithmalgorithm = new .SHA512Managed())
{
    using (Stream fileStream = new FileStream(@"path", FileMode.Open))
    {
        byte[] hash = algorithm.ComputeHash(fileStream);
    }
}

Persist the hash as you like on the first run, then recompute it and match it upon the saved value. If they are different, the file changed.

A: I think this question has a few issues, as there are multiple ways to answer this.
1) If the question is, "I have received a file (that previously was not on the computer/network/location), and want to know if it has been modified...", then the answer is - no, because you're looking at a just a chunk of bits, then all of those bits are subject to being modified and adjusted in any way the sender wants - timestamps, file-status indicators (For instance, the 'archive' tag on Windows systems, or structured metadata on newer file systems) or anything else about that file can be set to what they want.
2) If the question is, "I have a file (on the local network or file-system that I can 'poke' every so often, or locally on the drive that I can 'poke' every so often) and I want to know if it has been modified between the times my application has run", then probably the easiest way to do this is to store a computed hash of that file (As answered by @Albireo).
3) If the question is, "I have a file (on the local network or file-system) and I want to know if it was modified prior to any running of my application", then you're looking at something that may or may not be possible, and will not be possible in a completely reliable way - having some understanding of the underlying structure and what you're expecting in that file will be necessary, and you'd be better off updating your question with more details of what the file consists of and why you're looking for changes programatically so that we can determine the best way of doing this.


text:
Q: CUDA implementation for arbitrary precision arithmetics I have to multiply two very large (~ 2000 X 2000) dense matrices whose entries are floats with arbitrary precision (I am using GMP and the precision is currently set to 600). I was wondering if there is any CUDA library that supports arbitrary precision arithmetics? The only library that I have found is called CAMPARY however it seems to be missing some references to some of the used functions.
The other solution that I was thinking about was implementing a version of the Karatsuba algorithm for multiplying matrices with arbitrary precision entries. The end step of the algorithm would just be multiplying matrices of doubles, which could be done very efficiently using cuBLAS. Is there any similar implementation already out there?

A: Since nobody has suggested such a library so far, let's assume that one doesn't exist.
You could always implement the naive implementation:

*

*One grid thread for each pair of coordinates in the output matrix.

*Each thread performs an inner product of a row and a column in the input matrices.

*Individual element operations will use the code taken from the GMP (hopefully not much more than copy-and-paste).

But you can also do better than this - just like you can do better for regular-float matrix multiplication. Here's my idea (likely not the best of course):
Consider the worked example of matrix multiplication using shared memory in the CUDA C Programming Guide. It suggests putting small submatrices in shared memory. You can still do this - but you need to be careful with shared memory sizes (they're small...):

*

*A typical GPU today has 64 KB shared memory usable per grid block (or more)

*They take 16 x 16 submatrix.

*Times 2 (for the two multiplicands)

*Times ceil(801/8) (assuming the GMP representation uses 600 bits from the mantissa, one bit for the sign and 200 bits from the exponent)

*So 512 * 101 < 64 KB !

That means you can probably just use the code in their worked example as-is, again replacing the float multiplication and addition with code from GMP.
You may then want to consider something like parallelizing the GMP code itself, i.e. using multiple threads to work together on single pairs of 600-bit-precision numbers. That would likely help your shared memory reading pattern. Alternatively, you could interleave the placement of 4-byte sequences from the representation of your elements, in shared memory, for the same effect.
I realize this is a bit hand-wavy, but I'm pretty certain I've waved my hands correctly and it would be a "simple matter of coding".


text:
Q: Initializing elements in an array in C would not be inserted in another Data structure I am creating a code here in C where I declared and initialized an array of integers. I am to place all of these elements in a Partially Ordered Tree. But first, before I make a heapify function to satisfy the POT property, I tested first the insert function. But when all elements are displayed, only one element will be displayed and not all my elements in my declared array will be displayed.
Here is my data structure:
typedef struct{
    int arr[MAX];
    int last;
 }Heap;

Here is my sample main function where I called initHeap() and insert():
int main()
{
    int elems[] = {10, 20, 5, 3, 9, 16, 2, 11, 10, 1};
    int x;
    Heap rec;

    initHeap(&rec);

    for(x=0; x<MAX; x++){
       insertToHeap(&rec,elems[x]);
    }

    getch();
    return 0;
    }

Here is my initHeap():
- initHeap() is used to initialize my Priority Queue to prepare for insertion.
void initHeap(Heap *A)
 {
     int x;

      for(x=0; x<MAX; x++){
          A->arr[x]=0;
       }
     A->last = 0;
 }

my insertToHeap():
void insertToHeap(Heap *A, char x)
{
     if(A->last != MAX-1){
         A->arr[A->last] = x;
         A->last+1;
         /*Function call to heapify the POT*/
     }
     else {
          printf("\nHeap is full!\n");
     }
 }

here is my display():
void display(Heap A)
{
     int x;

     printf("Elements inside the heap are: \n");
     for(x=0; x<MAX; x++){
           printf("%d ", A.arr[x]);
     }

     printf("\nLast available cell: %d", A.last);
 }

I did not write yet the heapify function because I want to test my insert function first before I do the heapification. I inserted my elements in the last available space in my heap. My problem here is that whenever I insert an element from an array, the display would only show one element and not all elements I stored in my array.

A: I think your A->last = 0 should be A->last = x.


text:
Q: Pyspark swaps filter and python_udf in optimized plan leading to slowdown and errors I'm having some issue with the spark I'm using
I'm trying to read some parquet file apply a filter and then run some python udf.
spark.read.parquet(...).where(
  col('col_name_a').isNotNull()
).withColumn(
  costly_python_udf("col_name_b").alias("col_b_transform")
)

With just those two steps, the code runs fast (in the sense that I'm action on a partial subset of data given the col_a!=null condition) as I expected. However if I take the dataframe and add more operations to it, processing slows down. It almost feels like the python udf operation and the null check operations got swapped.
I looked at the SQL section in the ApplicationMaster and I see in 'Optimized Logical Plan' that Filter step and BatchEvalPython got swapped.
In the same project, this swap impacted me where I was checking for null string and the loading json and the json load was failing due to the null load error, because guess again, the sequence of filter application and python udf was swapped. Few questions.
I'm currently managing this issue, by inserting cache() step after filter and before the python udf, which seems to be forcing Filter and BatchEvalPython run in the right sequence.

*

*Why does the Filter gets pushed after the BatchEvalPython. I can't think of any scenario where that would be an optimization. If anything, it should be the other way around.

*Is this is known issue? Is this fixed in future versions?

*Is there a better command than cache to force pyspark to not optimize across before and after the cache call?

spark.version = u'2.1.0'


text:
Q: FastAPI: reject a WebSocket connection with HTTP response In a FastAPI based Web app, I have a WebSocket endpoint that should allow connections only if some conditions are met, otherwise it should return an HTTP 404 reply instead of upgrading the connection with HTTP 101.
As far as I understand, this is fully supported by the protocol, But I couldn't find any way to do it with FastAPI or Starlette.
If I have something like:
@router.websocket("/foo")
async def ws_foo(request: WebSocket):
    if _user_is_allowed(request):
        await request.accept()
        _handle_ws_connection(request)
    else:
        raise HTTPException(status_code=404)

The exception isn't converted to a 404 response, as FastAPI's ExceptionMiddleware doesn't seem to handle such cases.
Is there any native / built-in way of supporting this kind of "reject" flow?

A: Once a handshake is completed, the protocol changes from HTTP to WebSocket. If you attempted to raise an HTTP exception inside the websocket endpoint, you would see that this is not possible, or return an HTTP response (e.g., return JSONResponse(...status_code=404)), you would get an internal server error, i.e., ASGI callable returned without sending handshake.
Option 1
Thus, if you would like to have some kind of checking mechanism before the protocol is upgraded, you would need to use a Middleware, as shown below. Inside the middleware, you can't raise an exception, but you can return a response (i.e., Response, JSONResponse, PlainTextResponse, etc), which is actually how FastAPI handles exceptions behind the scenes. As a reference, please have a look at this post, as well as the discussion here.
async def is_user_allowed(request: Request):
    # if conditions are not met, return False
    print(request['headers'])
    print(request.client)
    return False

@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    if not await is_user_allowed(request):
        return JSONResponse(content={"message": "User not allowed"}, status_code=404)
    response = await call_next(request)
    return response

or, if you prefer, you can have is_user_allowed() method raising a custom exception that you need to catch with a try-except block:
class UserException(Exception):
    def __init__(self, message):
        self.message = message
        super().__init__(message)

async def is_user_allowed(request: Request):
    # if conditions are not met, raise UserException
    raise UserException(message="User not allowed.")

@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    try:
        await is_user_allowed(request)
    except UserException as e:
        return JSONResponse(content={"message": f'{e.message}'}, status_code=404)
    response = await call_next(request)
    return response

Option 2
If, however, you need to do that using the websocket instance, you could have the same logic as above, but, instead, pass the websocket instance in is_user_allowed() method, and catch the exception inside the websocket endpoint (inspired by this).
@app.websocket("/ws")
async def websocket_endpoint(ws: WebSocket):
    await ws.accept()
    try:
        await is_user_allowed(ws)
        await handle_conn(ws)
    except UserException as e:
        await ws.send_text(e.message) # optionally send a message to the client before closing the connection
        await ws.close()

In the above, however, you would have to accept the connection first, so that you can call the close() method to terminate the connection, if exception is raised. If you prefer, you could use something like the below. However, that return statement insdie the except block would throw an internal server error (i.e., ASGI callable returned without sending handshake.), as described earlier.
@app.websocket("/ws")
async def websocket_endpoint(ws: WebSocket):
    try:
        await is_user_allowed(ws)
    except UserException as e:
        return
    await ws.accept()
    await handle_conn(ws)


text:
Q: SQL Query - move decimal point I have a table with one column where I need to format the values into a single form.
Results
1258
1248
1.18761801719666
1.1763299703598
1.21516096591949

Values like 1258 are correct. And I need values like 1.18761801719666 to get into similar forms (1188) with the last number being rounded.
When I used:
SELECT CAST(Results as DECIMAL(18,4)) as Results
FROM [Table]

So I get halfway to the desired result, but then I don't know.
SAMPLE DATA:
1258
1248
1.18761801719666
1.1763299703598
1.21516096591949

What I expect:
1258
1248
1187
1177
1215

A: 1.188 and 1188 are different numbers, not just different formats of the same number. So you need some actual mathematical operation here, not just formatting.
For instance, if the rules is "if the number is less than 10, multiply it by 1000", then you could write CASE WHEN Results < 10 THEN Results * 1000 ELSE Results END
You could then cast it to an integer to lose the rest of the decimal places:
SELECT CAST(CASE WHEN Results < 10 THEN Results * 1000 ELSE Results END as INT)


text:
Q: WAL log files fill up quickly - how to prevent this? currently the logs in the folder "/engine-rocksdb/journals" are running full (WAL logs).
When does ArangoDB do a cleaning run of these logs and delete them automatically and how to trigger this cleaning run earlier? My ArangoDB 3.10 runs in single mode and in a virtual environment (cloud with a network storage).
The logfile are increasing very fast for me because there are many writes to the DB. What is the best way, any idea?
What I have done so far:
If I set the value "rocksdb.wal-archive-size-limit" it does delete the logs when the set limit is reached, but it shows errors in the logfile:
2022-09-27T17:53:04Z [898948] WARNING [d9793] {engines} forcing removal of RocksDB WAL file '/archive/813371.log' with start sequence 5387062892 because of overflowing archive. configured maximum archive size is 1073741824, actual archive size is: 75401520
However, I still don't understand the meaning of the logfile output: "configured maximum archive size is 1073741824, actual archive size is: 75401520`". The "actual archive size" is smaller?
But what are the consequences of lowering the "wal-archive-size-limit" value? Is it possible to switch off the wal-archive completely. What exactly is it for? As I understand it, ArangoDb need it for transaction security (i.e. in case of power loss), right?
In general, yes, this is a good thing, but how can I get ArangoDb to a) limit this WAL-archive (without error massages) and b) do a cleaning run faster?
thx :-)

A:
When does ArangoDB do a cleaning run of these logs and delete them automatically and how to trigger this cleaning run earlier?

ArangoDB uses RocksDB underneath, and RocksDB will move WAL file (.log files) into its archive as soon as possible. In order to do so all data from the WAL file needs to be safely stored in the column families' .sst files and have been flushed to disk.
ArangoDB will delete files from the WAL archive (and only from there) once it can assure that an archived WAL file is not used anymore. It will not remove files for the archive that are or may be in current use.
There are a few reasons why ArangoDB may keep archived WAL files for some time:

*

*when server-to-server replication is used: while a follower replicates data, it may read from the leader's WAL. Deleting the WAL file on the leader may make the replication fail

*when arangodump is used to create a database dump, it will create a snapshot of data on the server, and the WAL files for that snapshot will be kept around until the snapshot isn't needed anymore (i.e. arangodump finishes).

*the first 180 seconds after server start, all WAL files are intentionally kept, for forensic reasons, and to allow followers to replay events from a leader's WAL when it is restarted. The value of 180 seconds can be changed by adjusting the startup option --rocksdb.wal-file-timeout-initial.

*there can be some background processing of changes that may refer to data from WAL files. For example, each insert into a collection will need to increase the collection's count() value by 1. To save an extra write into RocksDB on each insert, the count() value is only written to the storage engine by a background thread, ideally only once every X insert operations. However, this may lead to WAL files being around for a bit longer, especially if the background thread cannot keep up with the insert workload.

There is the startup option --rocksdb.wal-archive-size-limit to put a hard limit on the cumulated size of the WAL files in the archive. From your question, it appears that you are currently using ArangoDB version 3.10.
From the warning message you posted, it seems that the WAL archive cleanup somehow applies the wrong limit values.
It turns out that there has been a recent bugfix, released in ArangoDB version 3.10.1, 3.9.4, and 3.8.8, that should rectify this behavior. So upgrading to one of these or later versions may actually help when using the WAL archive size limit.

A: Shared your question in the Speedb hive, on Discord, and here is what we got for you:
"By default, ArangoDB set the max_wal_size to 1G the value of rocksdb.wal-archive-size-limit must be set to at least twice this number (otherwise you may end up with a single WAL file and the delete will fail)."
Hope this help, if it doesn't or you have follow up questions, please join the Speedb Discord and we will be happy to help.


text:
Q: Find most readable colour of text that is drawn on a coloured surface I'm not sure how to ask this but here goes.
I draw a filled coloured rectangle on screen.  The colour is in form of R,G,B
I then want to draw text on top of the rectangle, however the colour of the text has to be such that it provides the best contrast, meaning it's readable.
Example:
If I draw a black rectangle, the obvious colour for text would be white.
What I tried right now is this.  I pass this function the colour of the rectangle and it returns an inverted colour that I then use for my text.
It works, but it's not the best way.
Any suggestions?
// eg. usage: Color textColor = GetInverseLuminance(rectColor);
private Color GetInverseLuminance(Color color)
{
    int greyscale = (int)(255 - ((color.R * 0.30f) + (color.G * 0.59f) + (color.B * 0.11f)));

    return Color.FromArgb(greyscale, greyscale, greyscale);
}

A: One simple approach that is guaranteed to give a significantly different color is to toggle the top bit of each component of the RGB triple.
Color inverse(Color c)
{
    return new Color(c.R ^ 0x80, c.G ^ 0x80, c.B ^ 0x80);
}

If the original color was #1AF283, the "inverse" will be #9A7203.
The contrast will be significant. I make no guarantees about the aesthetics.
Update, 2009/4/3: I experimented with this and other schemes. Results at my blog.

A: The most readable color is going to be either white or black. The most 'soothing' color will be something that is not white nor black, it will be a color that lightly contrasts your background color. There is no way to programmatically do this because it is subjective. You will not find the most readable color for everyone because everyone sees things differently.

A: Some tips about color, particularly concerning foreground and background juxtaposition, such as with text.
The human eye is essentially a simple lens, and therefore can only effectively focus on one color at a time.  The lenses used in most modern cameras work around this problem by using multiple lenses of different refractive indexes (chromatic lenses) so that all colors are in focus at one time, but the human eye is not that advanced.
For that reason, your users should only have to focus on one color at a time to read the text.  This means that either the foreground is in color, or the background, but never both.  This leads to a condition typically called vibration, in which the eye rapidly shifts focus between foreground and background colors, trying to resolve the shape, but it never resolves, the shape is never in focus, and it leads to eyestrain.

A: Your function won't work if you supply it with RGB(127,127,127), because it will return the exact same colour. (modifying your function to return either black or white would slightly improve things)
The best way to always have things readable is to have white text with black around it, or the other way around.
It's oftenly achieved by first drawing black text at (x-1,y-1),(x+1,y-1),(x+1,y-1),(x+1,x+1), and then white text at (x,y).
Alternatively, you could first draw a semi-transparent black block, and then non-transparent white text over it. That ensures that there will always be a certain amount of contrast between your background and your text.

A: why grey?  either black or white would be best.  white on dark colors, black on light colors.  just see if luminance is above a threshold and pick one or the other
(you don't need the .net, c# or asp.net tags, by the way)

A: You need to study some color theory. A program called "Color Wheel Pro" is fun to play around with and will give you the general idea.
Essentially, you're looking for complimentary colors for a given color.
That said, I think you will find that while color theory helps, you still need a human eye to fine tune.


text:
Q: Using functional application ID could not create object for WScript.CreateObject("Excel.Application")
*

*Maestro runs with functional application ID and calls a Powershell script file

*

*The PS script file calls a batch file - Run.bat

*

*The batch file calls a Windows Script file (cscript.exe ...xxx.wsf)

*

*The WSF runs a VBS program

*

*It calls an Excel macro.

But the VBS program fails in the step where it tries to create Excel object and fails with the message "Could not create an object named excel.Application".
This script is working when user manually executes run.bat file.
Maestro also is working when functional application id credentials were used to login the server while maestro runs Run.batch file.
Please help why maestro could not create excel object in non-interactive mode i.e. user who runs the process is not actively logged in to the server.
Code in run.bat file:
cscript.exe ..\..\run.wsf

Code in run.wsf file:
<script language="vbscript" src="..\Run.vbs"></script>

Code in run.vbs file:
Dim xlApp, xlBook
Set xlApp = WScript.CreateObject("Excel.Application") -- Program fails here
Set xlBook = xlApp.Workbooks.Open(fnGetAbsolutePath(xlsFile))

A: I found the problem. Excel dcom-identity settings had been set as  "interactive user" in that server which caused non-interactive excel requests run using interactive user's id. When I changed the setting below, it worked.
1: start->run and type 'DCOMCNFG'
2: Open 'DCOM Config' and locate 'Microsoft Excel Application'
3: Set its identity to 'The Launching User'.


text:
Q: Including scripts in QueryBank / Saved Export queries? Can I incorporate scripts setting variables and while loops, etc. in the "QB Query" of the Query Bank?
I have a SQL Server script that works perfectly in my local dev DB but it doesnt play nice with Volusion.
I don't know if I should spend more time figuring it out or just stop because it isn't even possible.

A: You can't do it in the Custom Queries / Query Bank area.  I believe their system will stop executing the script when it encounters certain keywords or punctuation.  A work around is to create a .sql file that contains your script and place it in your vspfiles/schema/Generic folder.  You'll also need an .xsd file with the same name.  The contents of the xsd file aren't very important - you can reuse the contents from an existing one (search their support pages for Developer Resources to find examples).  Once the sql and xsd files are in place, you can execute the SQL in the .sql file by using the URL/API method, like this...
http://www.MYWEBSITE.com/net/WebService.aspx?Login=USER@MYWEBSITE.com&EncryptedPassword=XXXXXXXXXXXXXXXXX&EDI_Name=Generic\FILENAME (<-- minus the .sql extension)
you'll need to replace several things above of course.  But this works well for us.  One thing to note, if you automate the creation and execution of these files, it's slow/inefficient on their system and could slow your site down, depending on how often you do it.


text:
Q: How do i go off this warning Warning: Invalid argument supplied for foreach() in my code below i want to alter each result according to  $b  quantity  example
for($i = 0; $i<3; $i++)
  1 $pins[$b] 1234
  2 $pins[$b] 5678
  3 $pins[$b] uncompleted

This is my code:
$pin = "12345678910";
# split string in pieces with 4 characters
$disp = str_split($pin, 4);
for($i = 0; $i<3; $i++){
    # loop on all pin
    foreach($disp[$i] as $pins)     {
        # length is not 4
        if(strlen($pins) != 4)     {
            echo "uncompleted";
        } else {
            echo "$pin[$i] ";
        }
    }
}

I am getting a warning:

Invalid argument supplied for foreach()

How do resolve it?

A: $disp is not multi-dimensional so you don't need the for($i.
$pin = "12345678910";
# split string in pieces with 4 characters
$disp = str_split($pin, 4);
foreach($disp as $pin)     {
    # length is not 4
    if(strlen($pin) != 4)     {
        echo "uncompleted";
    } else {
        echo $pin;
    }
}

The foreach($disp[$i] is/was trying to iterate over an array or object but $disp[$i] is a string.
Demo: https://3v4l.org/O2osD

A: Check this, If you are using for loop then do not need to add foreach also, str_split splits a string into parts of array and then we have to go through loop to check which array of object has length of string is 4.
$pin = "12345678910";
$disp = str_split($pin, 4);
$count = count($disp);

for($i = 0; $i < $count; $i++){
  if(strlen($disp[$i]) != 4)     {
    echo "uncompleted";
  } else {
    echo $disp[$i];
  }
}

Thanks i hope it helps someone.


text:
Q: How to allow temporary tables to accept null values If you create temp tables using "insert into" in SQL Server it uses the first insert to determine whether a column accepts null value or not. if the first insert has null value the column become nullable otherwise it will be non-nullable.
Is there a way to create temp tables using "insert into" to accept null values?
Example
This works without any problem
Select 'one' as a , null as b
into #temp

insert into #temp
Select 'two' as a , 500 as b

However this throws "Cannot insert the value NULL into column 'b'"
Select 'one' as a , 500 as b
into #temp

insert into #temp
Select 'two' as a , null as b

I know I could do create Table or alter column statement but I want to do it without rewriting hundreds of the existing queries.

A: How about this?
Select CONVERT(varchar(100), 'one') as a , CONVERT(int, 500) as b
into #temp

insert into #temp
Select 'two' as a , null as b

select * from #temp order by 1

A: I would workaround this by explicitly creating temporary table before first insert.
create table #temp (a varchar(10) not null, b int null)

A: (Un)fortunately, this question is too popular and appears at the top for Sybase ASE 15.7 as well, so just adding my answer for Sybase here.
For me neither of cast, convert or coalesce worked, but a case statement did (which is what coalesce is, but eh...)
select
    a = case when 1 = 0 then null else 'one' end,
    b = case when 1 = 0 null else 500 end
into #temp

A: This is an old question but I had a similar issue where I UNION NULLs to the initial query which may have helped the OP.
Select 'one' as a , 500 as b
into #temp
UNION
SELECT NULL, NULL

insert into #temp
Select 'two' as a , NULL as b

Putting it here so the next time I need to do this and forget how...


text:
Q: How long can memory leaks persist in RPGLE programs? I'm putting into production some RPGLE code which uses %alloc and dealloc to allocate memory.  Programmers should be able to ensure there are no resulting memory leaks but I'm worried about what happens if they don't.
My question is:  if programmers mess up and there are memory leaks then when will this memory be reclaimed?  Is it when the program leaves memory or when the job finishes?

A: From the ILE RPG Programmer's Reference Guide:

Storage is implicitly freed when the
  activation group ends. Setting LR on
  will not free any heap storage
  allocated by the module, but any
  pointers to heap storage will be lost.

If your RPG program is in its own activation group, then the memory will be freed when the program ends.  Of course, when your job ends, so does your activation group.  So ending the job will always clean up any memory allocated.

A: It sounds like you are approaching RPG from a C/C++ background. I've been programming in RPG for about 8 years now and only a handful of times ever had to use the %alloc() BIF.
That being said if you are using a new activation group, you should be fine. If you are using a named activation group and you do not issue the RCLACTGRP command or you are using the default activation group you could run into issues.

A: Indeed, you have to study the mechanism of activation groups. Memory leaks may happen, but will not do any damage to the machine (I love the as400). But you can harm the other programs within your iSeries job (remark: if you are not from a as400 background, you have to read about the as400 job mechanism).
If you start with managing the activationgroups within your job yourself (in the program that is ofcourse), you can create separate, sort of memory area's. It requires some overhead (you have to name the groups) but then you have a safe environment where you can powerfull stuff.

A: I am not familiar with those built-in-functions, but normally everything is cleaned up when the job ends (or user logs off if interactive). If you can't find an answer, I can point you to another community were your answer may be known.

A: Just happen to see this blogs now, way late but who knows others out there might still find this useful.
%alloc, dealloc uses job's default heap so it will be cleaned up when job ends.
There is another type of heaps, which you can use programmatically via CEE APIs, and it uses user defined heaps -- this is the one i think that you need to manage or clean up programmatically coz if not i think it might cause memory leakage.


text:
Q: Resizing of ArrayDeque Quote: Default initial capacity of ArrayDeque is 16. It will increase at a power of 2 (24, 25, 26 and so on) when size exceeds capacity.
Does this mean it behaves similar to ArrayList? Each time size exceeds capacity there is new array where older elements are copied to? Can I say internal implementation of ArrayDequeue and ArrayList is array (as their name says)? Just the resizing differs?

A: Yes ArrayDeque behaves similarly to ArrayList: Internally it uses an Object array. If the capacity is not enough, it creates a new, larger array, and copies items from the old array to the new.
The Java API specification does not require any particular resizing behavior. In fact the current implementation in OpenJDK doubles the size of the array if it's small (64), otherwise it grows by 50%:
    // Double capacity if small; else grow by 50%
    int jump = (oldCapacity < 64) ? (oldCapacity + 2) : (oldCapacity >> 1);

It seems that the"doubling" behavior is approximate: thanks to the "+2" after the first resize the capacity is 16+16+2 = 34. After the second resize it's 34+34+2 = 70. After that the array increases by 50% in every resize.


text:
Q: Overlapping in S3 bucket NotificationConfiguration I have s3 bucket that has NotificationConfiguration with LambdaConfigurations.
I want to add QueueConfigurations.
I get this error:
Configuration is ambiguously defined. Cannot have overlapping suffixes in two rules if the prefixes are overlapping for the same event type.
I don't know how to change prefix or suffix there.
  NotificationConfiguration:
    LambdaConfigurations:
      - Event: s3:ObjectCreated:*
        Filter:
          S3Key:
            Rules:
              - Name: prefix
                Value: !Sub ${User}/
              - Name: suffix
                Value: .csv
        Function: !Sub arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:DatafeedRenamer-${Environment}-Py
    QueueConfigurations:
      - Event: 's3:ObjectCreated:*'
        Filter:
          S3Key:
            Rules:
              - Name: prefix
                Value: !Sub ${User}/
              - Name: suffix
                Value: .csv
        Queue: !GetAtt StandardQueue.Arn


text:
Q: How to programatically create a touch/tap on screen in Android In desktop, We can simulate automatic mouse click with given coordinates. is this possible with Android? Can I simulate automatic touch/tap on scree.

A: Generally speaking, you can't.
You are welcome to write an AccessibilityService. However, this has only limited ability to manipulate other apps, and it requires users to not only install your app but agree to allow your app to have wide access to all their existing app's UIs.


text:
Q: Subclass constructor I created a superclass (Person) & a subclass (Student)
public class Person{
private String name;
private Date birthdate;
//0-arg constructor
public Person() {
    birthdate = new Date("January", 1, 1000);
    name = "unknown name";
}
//2-arg constructor
public Person(String newName, Date newBirthdate){
    this.name = newName;
    this.birthdate = newBirthdate;
}

//Subclass
public class Student extends Person{

    public Student(){
        super(name, birthdate)
}

I get the error: cannor reference name & birthdate before supertype cosntructor has been called.
I tried:
public Student(){
    super()
}

but my course tester says I should use super(name, birthdate);

A: If your default constructor for Student needs to use the two-argument constructor of Person, you'll have to define your subclass like this:
public class Student extends Person{

    public Student() {
        super("unknown name", "new Date("January", 1, 1000));
    }

    public Student(String name, Date birthdate) {
        super(name, birthdate);
    }
}

Note also that Person.name and Person.birthdate are not visible in subclasses because they are declared private.

A: You'll need to create a Student constructor that takes the name and birthday as parameters.
The example you've provided won't work unless the Student is already instantiated.

A: Looks like there are a few misconceptions here:
When you create Student, there isn't a separate Person object--there's just a Student which has all the properties of a Person.
The constructor is what builds the Student, so inside the constructor there is no other Student/Person whose fields you could reference. Once you call super you've initialized the Person portion of the object, and the fields from the Person are accessible, but since it's a new object they can't have been set to anything unless you do it in the constructor.
Your options are either to :
1) use the defaults as set up in Person:
public Student() {
   super(); // this line can be omitted as it's done by default
}

2) Take values as parameters and pass them to the Person constructor:
public Student(String newName, Date newBirthdate) {
    super(newName, newBirthdate);
}

3) Provide new defaults:
public Student() {
    super("Bob", new Date("January", 1, 1990));
}

A: You need to get the name and birthdate parameters  for student somehow. How about:
public Student(String name, Date birthdate){
    super(name, birthdate)
}

you can also do:
public Student(){
    super("unknown name", new Date("January", 1, 1000));
}


text:
Q: MongoDB query speed: pymongo In my python program, I have a mongo query to select items which uses an index. I'm using mongo Atlas. when I run the query in the DB, i get the results within the DB, results come almost instantaneously. Here are some stats and the query:
db.properties.find({Address: /^208 S/},{FullAddress:1, Key:1, PropertyLatitude:1, PropertyLongitude:1} ).limit(10)

inputStage: {
          stage: 'FETCH',
          nReturned: 10,
          executionTimeMillisEstimate: 0,
          works: 10,
          advanced: 10,
          needTime: 0,
          needYield: 0,
          saveState: 0,
          restoreState: 0,
          isEOF: 0,
          docsExamined: 10,
          alreadyHasObj: 0,
          inputStage: {
            stage: 'IXSCAN',
            nReturned: 10,
            executionTimeMillisEstimate: 0,

I implemented the query in pymongo and deployed the system in Azure. DB connection setup is done at the program startup:
client = MongoClient(application.config['DB_URL'])
db = client[application.config['MONGODB_DB']]

When did the first search it takes around 1500ms to return the result, but the subsequent queries takes around 300ms. I do understand when the query runs for the first time, the query planner has to do an analysis, select the best plan to do the execution, and the subsequent queries will be faster as the plan is already selected. My question is, this time difference is significant to the user, in terms of UX.
Is there a way to fix this (not doing a secret first search of course) meaning either:

*

*reduce the execution time difference between the first and the second queries

*speedup the first query


text:
Q: Problema al imprimir figura de asteriscos Mi código me imprime lo que hay en el siguiente ejemplo:
   *
  **
 ***
****

Pero yo lo que quiero es que haya un espacio en medio de cada asterisco pero aun no he podido lograrlo, lo mas lógico seria colocarle al print de la ultima linea un espacio antes del asterisco que quede asi= " *" pero al hacer eso me imprime una figura totalmente diferente (un triangulo) podrían ayudarme
cantidad=int(input("Digite el numero de renglones de asteriscos: "))

for b in range(cantidad+1):
    espacios=cantidad-b   #En esta variable se almacena la cantidad de espacios que habra en cada iteracion del for
    print(" "*espacios+"*"*b)

A: Si no te importa tener un espacio final a la derecha, puedes hacer lo que comentas, usar "* ". Para evitar que la figura de "deforme" solo debes tener en cuenta que para compensar los espacios entre los asteriscos debes añadir el doble al inicio (en vez de espacios debe ser espacios * 2):
cantidad = int(input("Digite el numero de renglones de asteriscos: "))

for b in range(cantidad + 1):
    espacios = (cantidad - b) * 2
    print(" " * espacios + "* " * b)

si quieres evitar agregar el espacio final (aunque visualmente no tiene impacto) puedes usar str.join para añadir los espacios intermedios, por ejemplo:
cantidad = int(input("Digite el numero de renglones de asteriscos: "))

for b in range(cantidad + 1):
    espacios = cantidad - b
    print(" ".join(" " * espacios + "*" * b))

Digite el numero de renglones de asteriscos: 20

                                      *
                                    * *
                                  * * *
                                * * * *
                              * * * * *
                            * * * * * *
                          * * * * * * *
                        * * * * * * * *
                      * * * * * * * * *
                    * * * * * * * * * *
                  * * * * * * * * * * *
                * * * * * * * * * * * *
              * * * * * * * * * * * * *
            * * * * * * * * * * * * * *
          * * * * * * * * * * * * * * *
        * * * * * * * * * * * * * * * *
      * * * * * * * * * * * * * * * * *
    * * * * * * * * * * * * * * * * * *
  * * * * * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * *


text:
Q: wpf inkcanvas stroke erase by pixel I'm developing drawing tool control using inkcanvs in wpf.
When i draw rectangle, this is original image.
Original Image
And i set that editing mode is erase by point. When i erase rectangle, this is image after working.
Erased Image
I want that erase function works as well as default drawing tool in windows. It would be worked by pixel. Erase shape by pixel.
Part of Source Codes
public class Label : Stroke
{
protected override void DrawCore(DrawingContext drawingContext, DrawingAttributes drawingAttributes)

Rect rect = new Rect((Point)this.StylusPoints[0], (Point)this.StylusPoints[1]);

drawingContext.DrawRectangle(...)

A: This is not possible with the standard API.
Only by translating an ink image (strokes, which are enhanced vectors) to a bitmap image (which contains pixels) individual pixels can be manipulated but the stroke information will be lost.
With quite some effort an application could be created that keeps track of all its user's actions (draw some strokes, add a pixel, remove a pixel) and replays them all every time the UI needs a redraw, injecting the transformation from vector to bitmap where needed.
This is a nice exercise but might prove to be too slow and/or complex.


text:
Q: How to add a user defined function in QDB Library? QDB is a database provided by QNX Neutrino package. I went through the QDB documentation to add a user defined SQL function: http://www.qnx.com/developers/docs/6.5.0/topic/com.qnx.doc.qdb_en_dev_guide/writing_functions.html?cp=2_0_8
I created a source file which had my user define SQL function written in C and qdb_function structure definition. I built it with a make file to create libudf.so.
As suggested by QDB I added Function = udftag@libudf.so in the qdb.cfg. But while running the qdb in the shell prompt, it is giving the error (in bold):
qdb -I basic -V -R set -v -c /etc/sql/qdb.cfg -s de_DE@cldr -o tempstore=/fs/tmpfs
QDB: No script registered for handling corrupt database.
qdb: processing [TempMainAddressBook]Function - Can't access shared library
and qdb is getting exited immediately.
I have tried following things:

*

*made sure sqlite3 library is added in the make file

*source code is in strictly in C by using directive : extern "C" to avoid name mangling as the file extension is .cpp. I also tried with .c extension.

*given the absolute path of the libudf.so in qdb.cfg as : Function = udftag@/usr/lib/libudf.so

*qdb_funcion struct is properly defined in library's source code only.

*tried without using the static declaration of function(mentioned in the qdb docs)
After trying all hits and trials also, I am getting the same error every time which is Can't access shared library
If any one has any idea to resolve this error please share.

A: Suggestion 1: run qdb by setting LD_DEBUG=1, like in:
LD_DEBUG=1 qdb command line options

This will output a lot of debug information from the dynamic loader as it attempts to locate and then load the .so files.  Check what is the path that it output before the "Can't access" message is displayed.
Suggestion 2: obvious but make sure that the permissions are OK for the .so file.  Do you have the execution permission set?
Suggestion 3: check if the error message is identical if you completely remove the .so file from the system
Suggestion 4: increase the number of lower-case 'v'-s.  QDB likely supports more, with progressively more verbose information provided as you increase the numbers (6 should be enough for full verbosity)


text:
Q: Can all verbs ending in "-ise" be written with the suffix "ize"? Are there any "-ise" (or "-yse") words which cannot be (or are never) written using "-ize"?
I searched for prior questions, and came across:

*

*https://english.stackexchange.com/questions/47785/correct-use-of-ise-vs-ize-at-the-end-of-words

*https://english.stackexchange.com/questions/47785/correct-use-of-ise-vs-ize-at-the-end-of-words

*Are the endings "-zation" and "-sation" interchangeable?
But I have seen no mention of the rule I was taught at school, which is that while verbs derived from Greek may receive the "-ize" suffix, verbs derived from Latin may not. All the answers to the questions above simply focus on the fact that Americans prefer the "-ize" form and the British tend to use "-ise" for words with those endings.
Has usage changed in the 21st Century? Can we spell all the following verbs with "ize"?

*

*advertise

*advise

*paralyse

*analyse

*despise

*exercise

*revise

*supervise

*surprise

*compromise

If we can use either ending for some of the words, but not others, what is the governing rule?

A: No, you cannot just blindly change all ‑ise words into ‑ize words.
Beyond those you mention (which I notice includes ‑yse words, too, which can never be written ‑ize), there are also verbs like all these below which must always end in ‑ise, never in ‑ize.
I've conveniently sorted these right to left for you so that etymological hints pop out.
        precise
     circumcise
         incise
      subincise
      supercise
     eclaircise
        abscise
         excise
       paradise
     imparadise
     unparadise
    merchandise
           gise
      franchise
    affranchise
    effranchise
    enfranchise
 disenfranchise
   disfranchise
        coalise
           mise
         demise
       redemise
         remise
        premise
        promise
      unpromise
        surmise
   interdespise
           rise
          arise
        rearise
      hypocrise
        reprise
       comprise
        apprise
     enterprise
       forprise
     resurprise
         uprise
       decatise
       practise
     unpractise
         cotise
    readvertise
        mortise
       chastise
       readvise
      preadvise
      disadvise
      misadvise
         devise
       televise
        previse
      improvise
           wise


text:
Q: Eclipse custom template parameterized based on trigger keyword I want to create a custom template with substitution default values based on the trigger keyword.  For example for100 should give output
for (int i = 0; i < 100; i++) {

}

Is there any way to parse ${word} to get 100 and substitute it into the generated code?
The best I am able to do is:
for (int ${index} = 0; ${index} < ${cursor}; ${index}++) {

}

But this does not do modify the code based on the keyword.


text:
Q: Missing configuration for Application File(s) I'm new to ServiceNow and have been following the Learning Path on the Developers site. I created a Jakarta Instance and have been making my way through the tutorials. However, I have been consistently running into problems where I am missing configuration options when creating application files. I can't properly set up UI Policies, Events, Notifications, etc. because I'm missing specific options like being able to write scripts and more. I have switched to the "Advanced View" in the "Related Links" but to no avail. The account is an Administrator account and has not been modified at all since the creation of the Instance. Is there something I am missing? Other developers following this track with me currently do not have the same problems so I'm wondering if its account specific or something with configurations. I've attached my Notification file; even in Advanced View, it is missing "Send When" and "Advanced Condition" script.
An example of options not loading: Notification Application File Example

A: Double check that you are under the Advanced view for these sections.
These should be there for you, Send when and Advanced condition are under the When to send tab within the Advanced view.
If you don't see these under the Advanced view, you should be able to manually add the fields using the Form Designer.
Take a look at the documentation at Form design.
In short

*

*Go to your instance and go to Settings Gear > Developer and change Application to Global

*

*Right click the header and go to Configure > Form Design.

*

*Verify you've selected the Advanced view

*

*Drag the missing fields to the form.

*

*Click Save

*Change the Application back to the one you are working with


text:
Q: Search for all `.xls` files on Ubuntu from command-line? How would you search for all .xls files in the current directory and in all of the subdirectories below the current directory in Ubuntu from the command line?

A:
find . -type f -name '*.xls'


text:
Q: How to avoid the second view ( presentation of my app ) after login for the second time and go to the menu? I created three view controller :

*

*log In

*presentation of my app

*menu

I want the user go to the menu after log in for the second time in my app instead of seeing again the presentation of my app
I came up with this solution : when the user press a button (anyone) on menu, it's mean second time in my app

*

*I created a segue identifier : secondTimeLogin between log in and menu

*in my first view controller (login) I created this code :

if let user = user {

                    if let pressMenu = user["userClickedInMenu"] {

                        self.performSegueWithIdentifier("secondTimeLogin", sender: self)

                    } else {

                    self.performSegueWithIdentifier("presentationScreen", sender: self)
                    }

It's doesn't work for me
Thanks for your help

A: *

*Create 2 segues with the identifiers: "loginToPresentation" and "loginToMenu". As their names suggest, "loginToPresentation" segues from login view to presentation view, and "loginToMenu" segues from login view to menu view. Those are in addition to the segue from presentation view to menu view.

*Save a bool in NSUserDefaults like "previouslyLoggedIn" and set it to TRUE the first time the user logs in. You'll know whether or not it is the first time by querying NSUserDefaults every time at login. If you get FALSE for your boolean, then this is the first time the user logs in so you need to 1. set your boolean to TRUE and 2. self.performSegueWithIdentifier("loginToPresentation", sender: self). If you get TRUE for your boolean, then this isn't the first time the user logs in so you just go straight to menu view self.performSegueWithIdentifier("loginToMenu", sender: self).
Here's how your code from step 2 should look like:
let defaults = NSUserDefaults.standardUserDefaults()
if defaults.boolForKey("previouslyLoggedIn")
{
    self.performSegueWithIdentifier("loginToMenu", sender: self)
}
else
{
    self.performSegueWithIdentifier("loginToPresentation", sender: self)
    defaults.setBool(true, forKey: "previouslyLoggedIn")
}

This should be part of your handling of a successful login.

A: After the first presentation with success, save something in a file (or in some defaultettings) just to remember to skip the presentation page at the second time. Every time you run the application you should read the file (or default settings) to see if is necessary to skip or not the presetantion page or not. In this case you can save in a file the username of the user and the date time so you can control a sort of "timeout" session for the user. I think this can help you. You can apply also the same system to avoid the login for the same user in a small period.