text:
Q: Storing numbers between two numbers in an array as you can read from the title I'm trying to store all the numbers between two numbers in an array.
For example store the numbers between 21 and 43 (22,23,24,25,26,27,28,29...) in an array.

This is the code, I don't know why but it prints only the higher number minus one.

class Program
{

    static void Main(string[] args)
    {

        int higher = 43;
        int lower = 21;
        int[] numbers = new int[22]; //the numbers between 21 and 43 are 22

        for (int i = lower; i < higher;i++)
        {
            for (int a = 0; a < 22; a++)
            {
                numbers[a] = i;
            }
        }
        for (int c = 0; c < 22; c++)
        {
            Console.WriteLine(numbers[c]);
        }
        Console.ReadLine();

    }
}

A: For everytime you loop through i, you put that number in every slot of the array. The inner loop is what is causing your issue. A better solution would be:
int higher = 43;
int lower = 21;
int[] numbers = new int[21];

int index = 0;
for (int i = lower + 1; i < higher; i++) // if you want to store everything
                                         // between 21 and 43, you need to
                                         // start with 22, thus lower + 1
{
    numbers[index] = i;
    index++;
}
for (int c = 0; c < 21; c++)
{
    Console.WriteLine(numbers[c]);
}
Console.ReadLine();

A:
This is the code, I don't know why but it prints only the higher number minus one.

This question will attract answers giving you a half dozen solutions you can cut and paste to do your assignment.
I note you did not ask a question in your question -- next time, please format your question in the form of a question.  The right question to ask here is how do I learn how to spot mistakes in code I've written? because that is the vital skill you lack. Answers that give you the code will not answer that question.
I already gave you a link to a recent answer where I explain that in detail, so study that.
In particular, in your case you have to read the program you wrote as though you had not written it.  As though you were coming fresh to the program that someone else wrote and trying to figure out what it does.
The first thing I would do is look at the inner loop and say to myself "what does this do, in words?"
        for (int a = 0; a < 22; a++)
        {
            numbers[a] = i;
        }

That is "put the value i in every slot of the array.  Now look at the outer loop:
    for (int i = lower; i < higher;i++)
    {
        put the value i in every slot of the array
    }

Now the technique to use here is to logically "unroll" the loop. A loop just does something multiple times so write that out. It starts with lower, it goes to higher-1, so that loop does this:
        put the value lower in every slot of the array
        put the value lower+1 in every slot of the array
        …
        put the value higher-1 in every slot of the array

What does the third loop do?
        print every item in the array

And now you know why it prints the highest number minus one multiple times.  Because that's what the program does. We just reasoned it out.

Incidentally the answers posted so far are correct, but some are not the best.
You have a technique that you understand for "do something to every member of an array, and that is:
loop an indexer from 0 to the array size minus one
    do something to the array slot at the indexer

But the solutions the other answers are proposing are the opposite:
loop an indexer from the lower to the higher value
    compute an index
    do something to the array slot at that index

It's important to understand that both are correct, but my feeling is that for the beginner you should stick with the pattern you know.  How would we
loop an indexer from 0 to the array size minus one
    do something to the array slot at the indexer

for your problem?  Let's start with giving you a much better technique for looping the indexer:
for (int i = 0; i < numbers.Length; ++i)

That's a better technique because when you change the size of the array, you don't have to change the loop!  And also you are guaranteed that every slot in the array is covered.  Design your loops so that they are robust to changes and have good invariants.
Now you have to work out what the right loop body is:
{
    int number = i + lower;
    numbers[i] = number;
}

Now you know that your loop invariant is "when the loop is done, the array is full of consecutive numbers starting at lower".

A: Replace a with a direct translation of i
for (int i = lower; i < higher;i++)
{
  numbers[i-lower] = i;
}

A: Use below
        int higher = 43;
        int lower = 21;
        int[] numbers = new int[22]; //the numbers between 21 and 43 are 22

        for (int i = lower+1; i < higher; i++)
        {

                numbers[i-lower] = i;

        }
        for (int c = 1; c < 21; c++)
        {
            Console.WriteLine(numbers[c]);
        }
        Console.ReadLine();

A:
I think higher & lower are variables so following will give you output
  for any higher and lower numbers

class Program
{
    static void Main(string[] args)
    {
        int higher = 43;
        int lower = 21;
        int numDiff = higher - lower - 1;
        int[] numbers = new int[numDiff]; //the numbers between 21 and 43 are 22
        for(int i = 0; i<numbers.Length; i++)
        {
            numbers[i] = numDiff + i + 1;
        }
        for(int b = 0; b<numbers.Length; b++)
        {
            Console.WriteLine(numbers[b]);
        }
        Console.ReadLine();
    }
}


text: Q: Resemble data structure to understand under the hood of promise I have been trying to understand promise under the hood. There is lot of source code online. I tried but could not understand the chaining part. I understand the recursion is used for chaining but still, is there any resemble data structure or algorithm which i can head around and then trying promise under the hood.

redpajama_set_name: RedPajamaStackExchange


text: Q: RESTful java, проблема с ссылками Всем привет! Есть построенный Web Service на jax-rs 2.0. Проблема заключается в том, что не могу поставить правильно ссылку в Html странице на css стили. Кто может помочь с проблемой?


text:
Q: how to select unique attribute of div in cypress How do I select the unique attribute of div in Cypress? In my case, I want to get data-testid
<div id="Dropdown78"
     class="ms-Dropdown-title"
     data-testid= "busnum_drop">
</div>

A: You can use this:
cy.get('#Dropdown78').click()
cy.get('[data-testid="busnum_drop"]').click()


text:
Q: Image Server Performance I have read many questions/comments regarding saving the image in DB or file system on server side. However i'm still confused. For now I allow user to upload image (limit to 10MB) and I save the image in the server folder and serve the image via apache context path configuration pointed to that location. However, due to the numbers of image and high load. We want to provide load balancing and fail over functionality. So I have 2 options.

*

*Add code to replicate the uploaded image to all servers or using rsync to do that.

*Using CouchDB or MongoDB and save the image as attachment of an document. So I have out of the box replicate functionality.

Can anyone show me the pros/cons of these approach. Can CouchDB/MongoDB have the same read performance compared to file system ?

A: You can also store files in distributed file system. The benefit over DB supported image server is you do not have to alter the application. Obviously, storing all the data the same way, including images, may be a benefit for you, but changing architecture for already working system may also be problematic.
For example, GlusterFS may be installed on top of "normal" file system to give you distributed features minimizing changes to the system itself. It is supposed to support via its plugins (translators) all the feature you would potentially expect from cloud system: replication, load balancing, stripping of files into relocated parts and fail-over.

A:
Can CouchDB/MongoDB have the same read performance compared to file system ?

No, there will be lag between file system timers and database timers, this is an unfortunately reality.
I have no idea of your current setup, load and performance so I cannot really advise on what to do, however, Apache isn't really a good image server anyway.
Your best bet might be to look into a CDN cache for your images.


text:
Q: UIImageView masks and bottom alignment I am working on an app that has TableViewCells with varying heights. I am placing a UIImageView into them and each will use the same size image (the same size of the largest cell), however I need to mask the excess in the smaller cells (keeping the bottom, not the top).
To be more specific, I have 3 different cell heights, 112, 104 and 88. The images will all be 112 tall and I want the images to have the tops cut off on the smaller cells. Im pretty sure the answer lies within the bounds, frame and center attributes of a UIImageView, but I cant figure out exactly what I should be doing.

A: You will need to set the frame of your image view such that the bottom of the image view is aligned with the bottom of your cell.
You will also need to ensure the contentview of you cell is clipping content to its bounds (setClipToBounds to yes).
If I had to do this I would subclass the UITabelViewCell class and implement the layoutSubviews method. In your implementation don't forget to call super first so the content view has the right size (also if you go in editing mode). Then use the content view bounds and place your content accordingly.

A: When you add the image view to the cell, it should automatically cut off the top part, as long as you have the UIImageView bottom positioned within the frame, it should be what you wanted.


text:
Q: Firestore Flutter How Sort Data using int fields Hello i have a firestore db with structure
Root
.....Oder
.........Xyz1
______T:1
.........Xyz1
______T:1
when i get the data i want it to sort automatically in  desending oder using the int value stored in 'T'
T is unique for every document
child: StreamBuilder(
            stream: Firestore.instance.collection("Oder").snapshots(),
            builder: (BuildContext context,
                AsyncSnapshot<QuerySnapshot> snapshot) {
              if (!snapshot.hasData) {
                return new Text('Loading...');
              }
              return new ListView(
                reverse: true,
                children: snapshot.data.documents.map((document) {
                  return new ListTile(
                    title: new Text(document['T'].toString()),
                  );
                }).toList(),
              );
            },
          ),

This is my code here
I also have the same value of T as String as each document name so sorting with that gave me 1,10,11,2,3...
So i need to get sorted with the int value stored in T

A: This is
You can get the data with this line:
 CollectionReference collectionReference = Firestore.instance.collection("data-collection");

But , you can get the ordered data with:
Query collectionReference = Firestore.instance.collection("data-collection").orderBy('field');

orderBy should returns a Query, you can no longer store it as a CollectionReference.


text:
Q: WinForms компиляция NuGet Для подключения к sql server  использовал готовый DataConnectionDialog из пакета
 Microsoft Data Connection Dialog.
Вроде сделал все как надо, но при компиляции вылетает исключение:

Дополнительные сведения:
Не удалось найти ресурсы, соответствующие
  указанной культуре или нейтральной культуре.  Проверьте правильность
  внедрения или связывания
  "Microsoft.Data.ConnectionUI.Resources.resources" со сборкой
  "BandivanKatUser" во время компиляции, или убедитесь, что все
  необходимые сопутствующие сборки полностью подписаны и могут быть
  загружены.

Это код, где вылетает исключение:
public static DataProvider SqlCeDataProvider
{
    get
    {
        if (_sqlCeDataProvider == null)
        {
            Dictionary<string, string> descriptions = new Dictionary<string, string>();
            descriptions.Add(SqlCeDataSource.Name,
                Resources.DataProvider_SqlEverywhere_Description);

            Dictionary<string, Type> uiControls = new Dictionary<string, Type>();
            uiControls.Add(String.Empty, typeof(SqlCeConnectionUIControl));

            _sqlCeDataProvider = new DataProvider(
                "System.Data.SqlCeClient",
                Resources.DataProvider_SqlEverywhere,
                "SqlCeClient",
                Resources.DataProvider_SqlEverywhere_Description,
                typeof(System.Data.SqlServerCe.SqlCeConnection),
                descriptions,
                uiControls,
                typeof(SqlCeConnectionProperties));
        }
        return _sqlCeDataProvider;
    }
}

А именно вот на этой строке:
descriptions.Add(SqlCeDataSource.Name, Resources.DataProvider_SqlEverywhere_Description);

A: #r "Microsoft.Data.ConnectionUI"
#r "Microsoft.Data.ConnectionUI.Dialog"

using Microsoft.Data.ConnectionUI;

static private string GetConnectionString() {
    DataConnectionDialog dcd = new DataConnectionDialog();
    DataSource.AddStandardDataSources(dcd);
    return DataConnectionDialog.Show(dcd) == DialogResult.OK ? dcd.ConnectionString : null;
}

var f = new Form();
new Button() { Text="Connect", Parent = f }.Click += (s, e) => {
    var cs = GetConnectionString();
    // ...
};
f.ShowDialog();


text:
Q: Get a particular URL in Node JS other ways I have a REST API of Reddit. I am trying to parse the JSON output to get the URL of the responses. When I try to send the request, I get multiple outputs, but I am not sure how to do it as it's a random response.
https
  .get("https://www.reddit.com/r/cute/random.json", resp => {
    let data = "";

    resp.on("data", chunk => {
      data += chunk;
    });

    const obj = JSON.parse(data);
    resp.on("end", () => {
      console.log(obj.url);
    });
  })
  .on("error", err => {
    console.log("Error: " + err.message);
  });

This is the code I have got. I used the default Node's http library and I don't think it worked. I have never used any Node Libraries, so it will be helpful if you can suggest them too. And also let me know if what I have done is right.

A: I understand that http is a core library of Node JS, but I strongly suggest you to use something like node-fetch. Make sure you run the following command on your terminal (or cmd) where your package.json file exists:
$ npm install node-fetch

This will install the node-fetch library, which acts similarly to how the Web based fetch works.
const fetch = require("node-fetch");
const main = async () => {
  const json = await fetch("https://www.reddit.com/r/cute/random.json").then(
    res => res.json()
  );
  console.log(
    json
      .map(entry => entry.data.children.map(child => child.data.url))
      .flat()
      .filter(Boolean)
  );
};
main();

The URLs that you are looking for, I could find in the data.children[0].data.url so I did a map there. I hope this is something that might help you.
I get multiple output for the same code, run multiple times, because the URL you have used is a Random Article Fetching URL. From their wiki:

/r/random takes you to a random subreddit. You can find a link to /r/random in the header above. Reddit gold members have access to /r/myrandom, which is right next to the random button. Myrandom takes you to any of your subscribed subreddits randomly. /r/randnsfw takes you to a random NSFW (over 18) subreddit.

The output for me is like this:
[ 'https://i.redd.it/pjom447yp8271.jpg' ]   // First run
[ 'https://i.redd.it/h9b00p6y4g271.jpg' ]   // Second run
[ 'https://v.redd.it/lcejh8z6zp271' ]       // Third run

Since it has only one URL, I changed the code to get the first one:
const fetch = require("node-fetch");
const main = async () => {
  const json = await fetch("https://www.reddit.com/r/cute/random.json").then(
    res => res.json()
  );
  console.log(
    json
      .map(entry => entry.data.children.map(child => child.data.url))
      .flat()
      .filter(Boolean)[0]
  );
};
main();

Now it gives me:
'https://i.redd.it/pjom447yp8271.jpg'   // First run
'https://i.redd.it/h9b00p6y4g271.jpg'   // Second run
'https://v.redd.it/lcejh8z6zp271'       // Third run
'https://i.redd.it/b46rf6zben171.jpg'   // Fourth run

Preview

I hope this helps you. Feel free to ask me if you need more help. Other alternatives include axios, but I am not sure if this can be used on backend.


text:
Q: Can an JS generated Image HTML element throw an exception? I've found this code from Facebook where there is a try catch which I don't understand.
fb_param is a JS object where the only required property is pixel_id, but that requirement is checked by an if clause.
Can anyone tell me how this code can throw an exception?
/*1375267557,179355677,JIT Construction: v893363,en_US*/

/**
 * Copyright Facebook Inc.
 *
 * Licensed under the Apache License, Version 2.0
 * http://www.apache.org/licenses/LICENSE-2.0
 */
try {
  (function() {
    if (typeof fb_param != 'undefined' && fb_param.pixel_id) {
      var a = 'https://www.facebook.com/offsite_event.php',
        b = a + '?id=' + fb_param.pixel_id;
      if (fb_param.value) b += '&value=' + encodeURIComponent(fb_param.value);
      if (fb_param.currency) b += '&currency=' + encodeURIComponent(fb_param.currency);
      var c = new Image();
      c.src = b;
    }
  })();
} catch (e) {
  new Image().src = "http:\/\/www.facebook.com\/" + 'common/scribe_endpoint.php?c=jssdk_error&m=' + encodeURIComponent('{"error":"LOAD", "extra": {"name":"' + e.name + '","line":"' + (e.lineNumber || e.line) + '","script":"' + (e.fileName || e.sourceURL || e.script) + '","stack":"' + (e.stackTrace || e.stack) + '","message":"' + e.message + '"}}');
}


text:
Q: Populate textarea based on which dropdown has been changed My issue is I am trying to update a textarea's text based on which dropdown was changed.
So if dropdown 1 is changed the textarea updates, but if dropdown 2 is changed it would update the textarea again. My current code is below:

Dropdown 1

    <select id="thingama" onClick="responseText(thingama); ">
      <option></option>
      <option value="test 1">1</option>
      <option value="test 2">2</option>
    </select>

Dropdown 2

    <select id="thingama1" onClick="responseText(thingama1); ">
      <option></option>
      <option value="test 3">3</option>
      <option value="test 4">4</option>
    </select>

  <textarea id="resptext" style=" width: 600px;  height: 400px;"></textarea>
  <button onClick="CopyToClipboard()">Copy</button>

I believe my issue is in how I am trying to pass the variable, but I am missing something that I believe will be super simple. Any help is appreciated.

A: you have few issues on your code, first you should use onchange, then you should use this instead of name

<!html>

Dropdown 1

<select id="thingama" onchange="responseText(this); ">
<option></option>
<option value="test 1">1</option>
<option value="test 2">2</option>
</select>

Dropdown 2

<select id="thingama1" onchange="responseText(this); ">
<option></option>
<option value="test 3">3</option>
<option value="test 4">4</option>
</select>

<textarea id="resptext" style=" width: 600px;  height: 400px;"></textarea>

<button onClick="CopyToClipboard()">Copy</button>


text:
Q: Facebook Javascript SDK: FB.login() doesn't work on Firefox/IE I'm building a very simple facebook application that just fetches a user's notifications from Facebook and also allows them to login. The URL is: http://widget.sidepage.co/_jump_frame.html
This works perfectly on Chrome - where the user is allowed to log in and authorize the app through a standard Facebook popup and once the app is authorized, it works well.
The problem is, on Firefox, clicking on the Facebook icon on the widget only opens a blank tab. There are no popup blocker warnings or JS errors thrown at the console.
Any pointers on how to fix this?

A: oh dude easy fix this is a Defining document compatibility issue...
and for what exactley you will need i suggest doing exactly what I did  to find out what your issue was run your app in firefox 16 and request to view the page source and observe the mark up as it is rendered to firefox and then do a little research on what it is that firefox 16 needs as far as a compatible input to run your code. It shouldn't be too bad. Best to you.. A few other sources. On this topic and legacy compatibility.
helpful link
helpful link
hope that helps dude :)


text:
Q: Split time value from json using java I want to split the value 08:41:19 from below json response. How to split the value?
{
  "parameters": [
    {
      "name": "CurrentLocalTime",
      "value": "2019-05-29 08:41:19",
      "dataType": 4,
      "parameterCount": 1,
      "message": "Success"
    }
  ],
  "statusCode": 200
}

A: Try this,
 JSONArray jSONArray = inputJSON.getJSONArray("parameters");
 int length = jSONArray.length();
  for (int i = 0; i < length; i++) {
        JSONObject jSONObject= jSONArray.getJSONObject(i);
        System.out.println(jSONObject.get("value").split("\\s")[1]);
    }


text:
Q: (Apple) GameplayKit State Machine implementation with SKScene I've read up on the GameplayKit State Machine and the documentation  explicitly mention Game UI as an example of usage. Im fully understanding the concept but I am unsure how to implement it while using SpriteKit.
Lets say I want 3 states. Menu, Gameplay and Game Over - All which display content to the SKScene.
GameScene class extends SKScene. So it's impossible to turn GameScene into a state machine since we only can extend one class.
Should GameScene have a variable for a state machine with a reference to the SKScene, or is there a better solution? Earlier I've used protocols for state machines which makes it easy, but I'd like to try the functionality of GameplayKit.

A: You're on the right track. Add the state machine variable in GameScene and initialise its starting state.
import SpriteKit
import GameplayKit

class GameScene: SKScene {
    var stateMachine: GKStateMachine!

    override func didMove(to view: SKView) {
        self.stateMachine = GKStateMachine(states: [
            StartState(scene: self),
            PlayingState(scene: self),
            PausedState(scene: self),
        GameOverState(scene: self)
        ])

        self.stateMachine.enter(StartState.self)
    }

    override func update(_ currentTime: TimeInterval) {
        self.stateMachine.update(deltaTime: currentTime)
    }
}

Then initialise the states so they accept GameScene as input parameter.
import SpriteKit
import GameplayKit

class StartState: GKState {
    var scene: GameScene!

    init(scene: GameScene){
        super.init()

        self.scene = scene
    }

    override func isValidNextState(_ stateClass: Swift.AnyClass) -> Bool {
        return stateClass == PlayingState.self
    }

    override func updateWithDeltaTime(seconds: TimeInterval) {
        self.stateMachine?.enterState(PlayingState.self)
    }
}


text:
Q: Apache NiFi Text Replacement what's the best way to replace strings within the [] (including the brackets) with values from attributes?
{
  "VoiceMessageTemplateEnglish" : "Hello, this is [LocationName] calling to confirm an appointment for [Name] on [AppointmentDate] at [AppointmentTime] with [Name]. Please press 1 To confirm, Press 2 To Cancel",
}
I tried using ExecuteScript processor with JS but did not have any luck.
Thanks!

A:
processor ExecuteGroovyScript in nifi  1.5.0
def ff = session.get()
if(!ff)return

def attr = ff.getAttributes()
def text = ff.read().getText("UTF-8")
text = text.replaceAll( /\[(\w+)\]/ ) {  attr[it[1]] ?: "noValue" }

ff.write("UTF-8", text)

REL_SUCCESS << ff

A: I ended up using JS to solve the problem:
thanks @daggett for pointing me in the right direction
var flowFile = session.get();
if (flowFile != null) {
var lclAppointmentDate = flowFile.getAttribute("AppointmentDate");
var lclAppointmentStartTime = flowFile.getAttribute("AppointmentStartTime");
var lclName = flowFile.getAttribute("Name");
var lclVoiceMailTemplate = flowFile.getAttribute("VoiceMailTemplate");

if (lclVoiceMailTemplate != null){
    lclVoiceMailTemplate  = lclVoiceMailTemplate
                       .replace('[Name]', lclName)
                       .replace('[AppointmentDate]', lclAppointmentDate)
                       .replace('[AppointmentTime]', lclAppointmentStartTime);
    flowFile = session.putAttribute(flowFile, "FinalVoiceMailTemplate", lclVoiceMailTemplate);
}
session.transfer(flowFile, REL_SUCCESS);
session.commit();

}


text:
Q: distinction of naming convention between "value" and "val"? I saw one script using "value" in class constructor's parameter
BUT "val" as function parameter.
constructor(value){}

push(val){}

Is it a personal preference, or convention?

A: Its normal to use val in place of value as a short version.There are no such conventions. When it comes to Jquery or some other languages, val is used as a built in function name.


text:
Q: Jquery Css Move Div Up Down into another Div on Scroll hi i want to scroll small button inside each division when the division are viable or in view port. i tried using scrollTop() but its scrolling all div
i want to create similar effect they are using on download button
https://www.template.net/web-templates/bootstrap/bootstrap-gallery-template/

here is my code
$(document).ready(function () {
  var el = $('.spicbo');
var elpos_original = el.offset().top;
$(window).scroll(function(){
    var elpos = el.offset().top;
    var windowpos = $(window).scrollTop();
    var finaldestination = windowpos;
    if(windowpos<elpos_original) {
        finaldestination = elpos_original;
        el.stop().css({'top':5});
    } else {
        el.stop().animate({'top':finaldestination-elpos_original+10},400);
    }
});

thank you in advance

A: I have created a working example based on what I seen in the prototype webpage you have provided in CODEPEN. In this example, when mouse pointer moves inside of container div, button moves smoothly around with the pointer.
HTML
<div class="container">
  <button type="submit">download</button>
</div>

CSS
.container {
   position: relative;
   margin-top: 20px;
   width: 300px;
   height: 100px;
   background: #ccc;
 }

 button {
   position: absolute;
   opacity: 0;
   top: 0;
   right: 0;
   margin: 5px;
   transition: opacity 0.1s ease-in-out;
 }

JS
$(document).ready(function() {

   var currentMousePos = { x: -1, y: -1 };

   $(".container").mousemove(function(event) {
     if ((event.pageY + $("button").outerHeight(true) - 20) < $(".container").height()) {
         currentMousePos.y = event.pageY - 20;
      }

      $("button").css({opacity:1});
      $("button").stop(true,true).animate({
          top: currentMousePos.y
      }, 200)
   });

   $(".container").mouseleave(function() {
     $("button").css({opacity:0});
   });

});
In the mousemove event, we track mouse pointer when it is inside of container div. If the mouse pointer is down the div so that it pushes the button out of the div, we do not update currentMousePos.y so that button will always stay inside of container. Then we change the opacity to 1 and use animate to move the button around accordingly. On the mouseleave event, we return button to invisible state.


text:
Q: Width constraint change with UIView animation I have width constraint which I update through SnapKit. Expanding animation:
self.snp.updateConstraints({(make) in
    make.width.equalTo(150.0)
})

Collapsing animation:
self.snp.updateConstraints({(make) in
    make.width.equalTo(150.0)
})

When I animate this through:
UIView.animate(withDuration: 0.5,animations: {
    self.layoutIfNeeded()
}, completion: nil)

My view change width by expanding first jumping to left, and then expanding from left to right   because my "animated" view trailing anchor equal to superview trailing anchor.
slider.snp.makeConstraints({(make) in
    make.trailing.equalToSuperview()
    make.centerY.equalToSuperview()
    make.height.equalTo(slider.getContentHeight())
    make.width.equalTo(slider.labels.first?.intrinsicContentSize.width ?? 30.0)
})

So i would like to animation be expanding from right to left

A: I achieved desired result by changing view.center.x . I tried to change leading constraint and width but it didn't work out. I also happen to change width of my view but it happens without animation and before/after for expand/collapse respectively. So here is my code:
self.snp.updateConstraints({(make) in
    make.width.equalTo(150.0)
})

UIView.animate(withDuration: 0.2,
    animations: {
        self.center.x -= 90
        self.layoutIfNeeded()
    }, completion: nil)

And reverse :
UIView.animate(withDuration: 0.2,
    animations: {
        self.center.x += 90
        self.layoutIfNeeded()
    }, completion: nil)

self.snp.updateConstraints({(make) in
    make.width.equalTo(30.0)
})

Animation is a bit rough when it comes to collapsing but works just fine for expanding. Still appreciate any suggestion.


text:
Q: Integrate cognito and dynamoDB table Basically this is the scenario i use a aws cognito service as the id server of a aplicattion and i have some dynamo tables that save some of those users.
I need to delete a user on those dynamoDB tables when i delete the same user on a cognito pool
this is the work flow.

*

*User is deleted on cognito.

*Lambda or any apropriate service listen to the event trigger.

*Lambda or any apropriate service delete user from the dynamoDB tables.

i was reading the docs from aws and other peoples questions on stackoverflow, Triggering a Lambda function upon deleting a user on AWS Cognito User Pool, Amazon Cognito Delete account and  i realized that cognito dont have a specific trigger for delete event.
How can i achieve that described workflow ?
thanks in advance.

A: Unfortunately this is not supported out-of-the-box by Amazon Cognito. You will have to write your own solution with a combination of other Amazon services.
There are a lot of ways to implement this, but one thing we've done in our applications:
First, create your own API endpoint such as: DELETE /user. You can do it with API Gateway
Second, connect your API endpoint to a Lambda function, or host your code elsewhere, but you need to call the Cognito user pool API with your code and delete it like that. Here is a snippet of how that can be done in NodeJS
const AWS = require('aws-sdk');
AWS.config.update({
  accessKeyId: 'access key id',
  secretAccessKey: 'secret access key',
  region: 'region',
});
const cognito = new AWS.CognitoIdentityServiceProvider();

await cognito.adminDeleteUser({
  UserPoolId: 'pool id',
  Username: 'username',
}).promise();

(For the full answer on how to delete a user with code, check this stack overflow question out)


text:
Q: Apollo UseMutation: TypeError: Cannot read property 'data' of undefined Error:
Unhandled Runtime Error
TypeError: Cannot read property 'data' of undefined

Call Stack
MutationData.onMutationCompleted

Following Apollo Docs and just don't see where I went wrong. One of useMutation hooks variables are dependent on the initial useQuery hook. I have confirmed that the data from useQuery successfully returns data.
The useMutation should return a url that I need use in router.push(dataU.url) but the mutation won't work in the first place. Not sure if router tasks in absolute url or only relative url.
This is 3rd party GraphQL API so its not like a backend issue.
createUser.js
import { gql } from "@apollo/client";

const CREATE_USER = gql`
  mutation($url: String!, $plan: String!) {
    createUser(name: $plan, returnUrl: $url) {
      url
    }
  }
`;

export default CREATE_USER;

index.js
import { useQuery, useMutation } from "@apollo/client";
import Router, { useRouter } from "next/router";

import GET_USER from "./getUser";
import CREATE_USER from "./createUser";

const Index = () => {
  // 1. Initialize router
  const router = useRouter();

  // 2. useQuery Hook
  const { loading, error, data } = useQuery(GET_USER);

  // 3. useMutation Hook
  const [
    createUser,
    {
      data: dataU,
      loading: loadingU,
      error: errorU,
    },
  ] = useMutation(CREATE_USER);

  if (loading || loadingU) return
Loading
;
  if (error || errorU) return
{error.message}
;

  const user = data.user;

  const handler = () => {
    createUser({
      variables: {
        url: `https://mywebsite.com/${user}`,
        plan: "Cool",
      },
    });
    router.push(dataU.url)
  };

  return (
    <Button onClick={handler}></Button>
  );
};

export default Index;


text:
Q: Querying oracle clob column I have a table with a clob column. Searching based on the clob column content needs to be performed. However
select * from aTable where aClobColumn = 'value';
fails but
select * from aTable where aClobColumn like 'value';

seems to workfine. How does oracle handle filtering on a clob column. Does it support only the  'like' clause and not the =,!= etc. Is it the same with other databases like mysql, postgres etc
Also how is this scenario handled in frameworks that implement JPA like hibernate ?

A: Yes, it's not allowed (this restriction does not affect CLOBs comparison in PL/SQL)
to use comparison operators like =, !=, <> and so on in SQL statements, when trying
to compare two CLOB columns or CLOB column and a character literal, like you do. To be
able to do such comparison in SQL statements, dbms_lob.compare() function can be used.
  select *
    from aTable
   where dbms_lob.compare(aClobColumn, 'value') = 0

In the above query, the 'value' literal will be implicitly converted to the CLOB data type.
To avoid implicit conversion, the 'value' literal can be explicitly converted to the CLOB
data type using TO_CLOB() function and then pass in to the compare() function:
  select *
    from aTable
   where dbms_lob.compare(aClobColumn, to_clob('value')) = 0

A: how about
select * from table_name where to_char(clob_column) ="test_string"

A: Clob's are large datatypes that can store massive data and hence many operators that support varchar operations will not work on Clob, but in PL/SQL some of them do like mentioned here: http://docs.oracle.com/cd/B19306_01/appdev.102/b14249/adlob_sql_semantics.htm#g1016221
As you can see in the table Like is supported in both Sql and pl/sql for clobs, but = is not supported in SQL, but is in pl/sql
If you really need to you could convert to varchar in sql and compare like Tom Kyte mentions here like this:
http://sqlfiddle.com/#!4/1878f6/1
select * from aTable where dbms_lob.substr( aClobColumn , length(aClobColumn), 1 )='value';

A: So do not. Because if you want to compare the data - then it may be a situation where one value: NULL and the second EMPTY_CLOB
And it is for this method different matter!
It returns -1, although in terms of data - both values should not contain.
Would be correct:
dbms_lob.compare (NVL (AUDIT_PAYLOAD_TEXT_DEC, Empty_Clob ()),  NVL (AUDIT_PAYLOAD_TEXT, Empty_Clob ()))


text:
Q: Rust build error: failed to run custom build command for `glib-sys v0.8.0` I am trying to build a Rust program on Windows 10. When trying to compile a Rust file with I keep getting the following error messages.
cargo run
   Compiling glib-sys v0.8.0
   Compiling const_fn v0.4.9
   Compiling quote v1.0.21
   Compiling socket2 v0.4.4
   Compiling net2 v0.2.37
   Compiling winreg v0.7.0
error: failed to run custom build command for `glib-sys v0.8.0`

They are caused by:
Caused by:
  process didn't exit successfully: `C:\Users\artem\zabotay\backend\target\debug\build\glib-sys-b1ba74e042d8283d\build-script-build` (exit code: 1)
  --- stdout
  cargo:rerun-if-env-changed=GLIB_2.0_NO_PKG_CONFIG
  cargo:rerun-if-env-changed=PKG_CONFIG_x86_64-pc-windows-msvc
  cargo:rerun-if-env-changed=PKG_CONFIG_x86_64_pc_windows_msvc
  cargo:rerun-if-env-changed=HOST_PKG_CONFIG
  cargo:rerun-if-env-changed=PKG_CONFIG
  cargo:rerun-if-env-changed=GLIB_2.0_STATIC
  cargo:rerun-if-env-changed=GLIB_2.0_DYNAMIC
  cargo:rerun-if-env-changed=PKG_CONFIG_ALL_STATIC
  cargo:rerun-if-env-changed=PKG_CONFIG_ALL_DYNAMIC
  cargo:rerun-if-env-changed=PKG_CONFIG_PATH_x86_64-pc-windows-msvc
  cargo:rerun-if-env-changed=PKG_CONFIG_PATH_x86_64_pc_windows_msvc
  cargo:rerun-if-env-changed=HOST_PKG_CONFIG_PATH
  cargo:rerun-if-env-changed=PKG_CONFIG_PATH
  cargo:rerun-if-env-changed=PKG_CONFIG_LIBDIR_x86_64-pc-windows-msvc
  cargo:rerun-if-env-changed=PKG_CONFIG_LIBDIR_x86_64_pc_windows_msvc
  cargo:rerun-if-env-changed=HOST_PKG_CONFIG_LIBDIR
  cargo:rerun-if-env-changed=PKG_CONFIG_LIBDIR
  cargo:rerun-if-env-changed=PKG_CONFIG_SYSROOT_DIR_x86_64-pc-windows-msvc
  cargo:rerun-if-env-changed=PKG_CONFIG_SYSROOT_DIR_x86_64_pc_windows_msvc
  cargo:rerun-if-env-changed=HOST_PKG_CONFIG_SYSROOT_DIR
  cargo:rerun-if-env-changed=PKG_CONFIG_SYSROOT_DIR

  --- stderr
  `"pkg-config" "--libs" "--cflags" "glib-2.0" "glib-2.0 >= 2.42"` did not exit successfully: exit code: 1
  error: could not find system library 'glib-2.0' required by the 'glib-sys' crate

I look through other questions, but found no answer about glib2.0 fix
--- stderr
Package glib-2.0 was not found in the pkg-config search path.
Perhaps you should add the directory containing glib-2.0.pc' to the PKG_CONFIG_PATH environment variable No package 'glib-2.0' found Package glib-2.0 was not found in the pkg-config search path. Perhaps you should add the directory containing glib-2.0.pc'
to the PKG_CONFIG_PATH environment variable
No package 'glib-2.0' found
warning: build failed, waiting for other jobs to finish...

How to fix this error?


text:
Q: conditional expression in one line if statment self.values is optional parameter (List) in my class.
I have the following code:
self.values.append(area) if self.values else self.values = [area]

This produce
SyntaxError: can't assign to conditional expression

I know I can fix this by doing:
 if self.values:
    self.values.append(area)
 else:
    self.values = [area]

But isn't there a shorter way to set it?

A: You can do the following, using the fact as it the list is None or empty, it's evaluated as false and the other operand of the OR expression will be used
self.values = (self.values or []) + [area]


text:
Q: Windows server event log has several thousand print errors I'm managing a Windows 2012R2 Server, and when I looked in the event log, I saw about 30,000 errors.
They look like this:
Process: PrinterDCA.Service
Level: Error
Process ID: 1196
Thread ID: 20

The source is the PrintFleet Enterprise.
How can I find out what's causing the errors? Note that I'm not necessarily looking for the solution, just pointing me in the direction of solving this problem would be helpful as well.
(if I click on Event Log Online Help, it gives me a Microsoft Surface ad)


text:
Q: FireFox Always Prompts to Open Local File When I open a local file of type .mng (custom file type), FireFox always asks which application to open the .mng file - it uses the Windows File Associations and knows that the .mng file extension is associated with my program. However, the box is greyed out that says, "Always do this for files of this type.". I looked in Tools > Options > Applications and I don't see the MNG file type in the list. Is there a reason that FireFox will not let me select "Always do this.." in the confirmation box, so I am not prompted every time?
EDIT: FYI; I also want to "download" this file locally using the "file://" prompt!
Using FireFox 17.0.3 ESR

A: If you need to perform a default action on a local "download" file, i.e.,if you are using "file://",  I would suggest that you manually edit the mimetypes.rdf file and add the particular extension that is causing you such pain.
For web page use and working with MIMETYPES read the below:
From the Firefox/Seamonkey KB on File types and download actions
You may not be able to set an automatic download action. This can occur when a misconfigured web server assigns an incorrect MIME type, such as "application/octet-stream" (shown here in SeaMonkey 1.x)

or if the server assigns "Content-Disposition: attachment" to the file download (as shown here in SeaMonkey 1.x).

When this happens, the option to always perform the same action will either be "grayed-out" or, in Firefox, selecting the "Do this automatically" option will not seem to have an effect and you will again be asked what to do when you next encounter that file type (see below for related bug reports). There is little you can do in these cases because the problem is at the server end.
Note: the MIME type of a downloaded file, and whether it should be handled as an attachment, is only shown in the SeaMonkey 1.x "Opening" dialog. This information does not appear in Firefox or in SeaMonkey 2.
Why are correct MIME types important?
Example of an incorrect MIME type result If the web server or application reports an incorrect MIME type for content, a web browser has no way, according to the HTTP specification, of knowing that the author actually intended the content to be processed and displayed in a way different from that implied by the reported MIME type.
Some other web browsers, such as Microsoft Internet Explorer, try to allow for misconfigured web servers and applications by guessing what the correct MIME type should be. This has sheltered many web administrators from their own errors, since Internet Explorer will continue to process content as expected even though the web server is misconfigured, e.g. displays an image which is reported to be plain text.
Serving content using the correct MIME type can also be important for security reasons; it's possible for malicious content to affect the user's computer by pretending to be a safe type of document when it is in fact not.


text:
Q: What is the proper way of updating this Redux store state in React app I have a React app which uses Redux for state management. The initial structure of the store is as follows:
const initialState = fromJS({
  visitorRecords: [],
  approvedBookingId: null,
});

At some point my visitorRecords becomes something similar to this:
[
   Map {
      "id":"1556008644569",
      "expectedArrival":"Thu, 25 Apr 2019 08:31:00 GMT",
      "lastName":"Vath",
      "notes":"",
      "actualDeparture":"",
      "actualArrival":"",
      "visitor":"Sven Vath",
      "status":2,
      "cardNumber":2,
      "employeeBeingVisited":"John Doe",
      "firstName":"Sven",
      "expectedDeparture":"Fri, 26 Apr 2019 08:31:00 GMT",
      "verbalStatus":"Visitor returned pass",
      "company":"Disney"
   },
   Map {
      "id":"1555586876781",
      "expectedArrival":"Thu, 18 Apr 2019 06:30:00 GMT",
      "lastName":"A.",
      "notes":"",
      "actualDeparture":"",
      "actualArrival":"",
      "visitor":"Christoph.",
      "status":0,
      "cardNumber":1,
      "employeeBeingVisited":"Jean Pier",
      "firstName":"Pablo",
      "expectedDeparture":"Sat, 20 Apr 2019 15:30:00 GMT",
      "verbalStatus":"Waiting for visitor arrival",
      "company":"Disney"
   }
]

What I want to do in my reducer is to update a specific record by its id. I have the id and the values for the edit fields coming from my action but I don't know how to handle them following the best practices for update.
This is what my reducer looks like:
export default (state = initialState, action) => {
  switch (action.type) {
    case ON_VISITOR_RECORDS_FETCHED:
      return state.merge({
        visitorRecords: fromJS(action.visitorRecords),
      });
    case ON_RETURN_APPROVED:
      return state.merge({
        approvedBookingId: action.approvedBookingId,
      });
    case ON_VISITOR_RECORD_UPDATED:
      console.log(JSON.stringify(state.get("visitorRecords")));
      // console.log('action.bookingBeingUpdated: ' + action.bookingBeingUpdated)
      // console.log('JSON.stringify(action.updatedTextFields)' + JSON.stringify(action.updatedTextFields))
      // console.log('updatedExpectedArrival: ' + action.updatedExpectedArrival)
      // console.log('updatedExpectedDeparture: ' + action.updatedExpectedDeparture)
      // console.log('updatedStatus: ' + action.updatedStatus)
      return state;
    default:
      return state;
  }
};

From here, I want to use action.bookingBeingUpdated, then find the corresponding record in visitorRecords and update it with the new action.updatedTextFields, action.updatedExpectedArrival, action.updatedExpectedDeparture, action.updatedStatus
I was reading this article but I don't quite understand how the update happens there. Plus, the structure of the container there is different.
EDIT: Type of the elements inside visitorRecords ins not an anonymous object but a Map

A: You would generally use map on your array of vistorRecords, and pass the id and fields to update in the action, so for example it would look like this:
case ON_VISITOR_RECORD_UPDATED:
     console.log(JSON.stringify(state.get("visitorRecords")));
     const updatedRecords = state.visitorRecords.map(record => {
         if (record.id === action.bookingBeingUpdated) {
             return new Map({
                 ...record,
                 expectedArrival: action.updatedExpectedArrival
                 // other fields...
             });
         }
         return record;
     });
return state.merge({
    state,
    fromJS({visitorRecords: updatedRecords})
});

A: Here's how you will do using immutablejs
case ON_VISITOR_RECORD_UPDATED:
    const newRecordsCollection = visitorRecords.map(record => {
        if (record.get('id') === action.bookingBeingUpdated) {
            return record.merge({
                updatedTextFields: action.updatedTextFields,
                updatedExpectedArrival: action.updatedExpectedArrival,
                updatedExpectedDeparture: action.updatedExpectedDeparture,
                updatedStatus: action.updatedStatus
            });
        }
        return record;
    });

    return state.merge({
        visitorRecords: newRecordsCollection
    });

A: You can update your record something like this:
case ON_VISITOR_RECORD_UPDATED:
  return {
      ...state,
      visitorRecords: state.visitorRecords.map(record => {
        if(record.id.toString===action.bookingBeingUpdated.toString()){
          return {
            ...record,
            updatedExpectedArrival: action.updatedExpectedArrival,
            updatedExpectedDeparture: action.updatedExpectedDeparture,
            updatedStatus: action.updatedStatus
          }
        } else {
          return record
        }
      })
    }

A: Best practice is to actually map() the existing state and return a new one that includes the updated item-values that you desire.
Let's say you dispatch an action and a payload that includes the id and new values you want to use:
dispatch({
   type: "ON_VISITOR_RECORD_UPDATED"
   payload: newRecordData
})

Now in your reducer:
export default (state = initialState, action) => {
  switch (action.type) {
    case ON_VISITOR_RECORDS_FETCHED:
      return state.merge({
        visitorRecords: fromJS(action.visitorRecords),
      });
    case ON_RETURN_APPROVED:
      return state.merge({
        approvedBookingId: action.approvedBookingId,
      });
    case ON_VISITOR_RECORD_UPDATED:
      return {
      ...state,
      visitorRecords: state.visitorRecords.map((record) => {
          if(record.id == action.payload.id){
             return{
                ...record,
                ...action.payload
             }
          }
      })
      }
    default:
      return state;
  }
};

This ensures that you have a completely new state-value for your reducer

A: Please don't use state.merge you can use
```return {
       ...state,
       visitorRecords: [...state.visitorRecords,action.visitorRecords]

}```
Please send Id from action after and compare this id in ON_VISITOR_RECORD_UPDATED type like
```visitorRecords: {
       ...state.visitorRecords,
       data: state.visitorRecords.data.map((items) => {
            if (items.id=== action.id) {
               return { ...items, name: "updated name" };
             }
              return items;
            })
     }```


text:
Q: Sacar por cada división el empleado con más beneficio (SQL) ahora sigo con el quebradero de cabeza...
Tengo estas dos tablas todavía:
Departamento

Ventas

El caso es, necesito  sacar por cada división, el empleado que más gana, suma de salario+comisión.
Estoy atascado aquí, ya que logro sacar el empleado que más gana pero solo de Galicia.
select top 1 SUM(p.salario+p.comision) as SalarioTotal, D.DIVISION
from DPTO D
INNER JOIN PERSONAL P ON P.DPTO = D.NUMDPTO
group by P.ID, D.DIVISION
order by SalarioTotal desc

A: Creo que estabas cerca. Primero de todo advertir que hay datos de comisión en null, y la suma de un número más null es null, por lo que hay que tratarlo.
Por otro lado con el group by es suficiente
select  D.DIVISION, SUM(p.salario + ISNULL(p.comision, 0) as SalarioTotal
from DPTO D
INNER JOIN PERSONAL P ON P.DPTO = D.NUMDPTO
group by P.ID, D.DIVISION
order by SalarioTotal desc

A: He conseguido sacar el resultado pero con top4, no filtrando por cada división, qué empleado gana más...

select top 4 P.ID, D.DIVISION, SUM(p.salario+p.comision) as SalarioTotal
from DPTO D
INNER JOIN PERSONAL P ON P.DPTO = D.NUMDPTO
group by D.DIVISION, P.ID
order by SalarioTotal desc


text:
Q: how to create nodes in neo4j using python, only with unique edges/relations while doing bulk insert from .data file? My data looks like this: (it's a .data file)
emp_id          cus_id
bckshfow2424       dsf31
bckshfow2424       dsf31
bckshfow2424       dsf31
bckshdw2424        dsbd1
bckshdw2424        dsbd1
bckshdw2424        dsf31

for the above set of combination, I would want to create the nodes having unique relations expecting a resulting dataset of:
emp_id   cus_id
bckshfow2424    dsf31
bckshdw2424     dsbd1
bckshdw2424      dsf31

like this have a bunch of records in the data file with some of the dups.
I am using the following command to load the data. However, I am not able to load the unique combination nodes:
with open("file_path") as f:
next(f)
with driver.session() as session:
    for line in f:
        a = line.split('\t')
        print a
        result = session.run(
            "MERGE (e:Empid {id:'" + a[1] + "' }) MERGE  (c:Custid { id: '" + a[2] + "'})  CREATE UNIQUE (e)-[m:HAS]->(c) ;")
        print a

After loading the data..when I run:
    MATCH (e:Empid) RETURN COUNT (e);
I get 2.
And the query to get count of existing relationship gives me result as 5 which is the original dataset with dups.
    MATCH (e:Empid) -[m:HAS]->(c:Custid)
    With type(m) as count_m
    Return count_m;

A: Firstly, you should use parameter in your queries, instead of creating a dynamic string query. It will be faster.
Otherwise, you should not use CREATE UNIQUE, it's deprecated. Can you replace it by a MERGE and test it ?


text:
Q: unable to access terminal alias/ shortcuts in .zshrc file or .bashrc in terminal, File/folder permission issue On mac, it used to work file but recently it doesnt allow me to use the alias /shortcuts in the terminal
I have created the alias for git add .   =  a .
git checkout -b  = co -b
But now unless I specify sudo and full git add .  command i can't run the command.
Also for any command I always have to use sudo which wasn't the case before.
projectFolder/.git: Permission denied

Unless I do sudo and full git iniit  command it doesnt work.

A: Since you have access to sudo, you should be able to chown your all tree back to your account:
sudo chown -R jay /Users/jay

As long as you see root as a user in your tree (with ls -alrth), you would need sudo indeed.


text:
Q: Library Dependency I'm making a C++ based library with Visual Studio 2015. I have my work based on curl-7.51.0, OpenSSL-1.0.2j, and ZLib-1.2.8.

When I was using curl library (which was statically linked with openssl and zlib) I wasn't needed to add Include/Library paths of openssl and zlib (except for compiling). But when I use my library, Visual Studio gets the LNK1104 error that he can't find the libcurl_a.lib.

Why does this happen? how can I statically/fully include curl library in my custom library?


text:
Q: Running flask automatically after boot I'm trying to run flask when my raspberry pi turns on.
I created a service for my flask API, this is the service file:
[Unit]
Description= Flask API
After=network.target

[Service]
WorkingDirectory=/home/pi/bucketlist/
ExecStart=flask run --host=0.0.0.0
Restart=Always

[Install]
WantedBy=multi-user.target

But when I try sudo systemctl start flask then sudo systemctl status flask I get this error.
Jun 10 09:56:40 raspberrypi flask[4769]: Usage: flask run [OPTIONS]
Jun 10 09:56:40 raspberrypi flask[4769]: Error: While importing "app", an ImportError was raised:
Jun 10 09:56:40 raspberrypi flask[4769]: Traceback (most recent call last):
Jun 10 09:56:40 raspberrypi flask[4769]:   File "/usr/lib/python3/dist-packages/flask/cli.py", line 235, in locate_app
Jun 10 09:56:40 raspberrypi flask[4769]:     __import__(module_name)
Jun 10 09:56:40 raspberrypi flask[4769]:   File "/home/pi/bucketlist/app/__init__.py", line 5, in <module>
Jun 10 09:56:40 raspberrypi flask[4769]:     from flask_api import FlaskAPI
Jun 10 09:56:40 raspberrypi flask[4769]: ModuleNotFoundError: No module named 'flask_api'
Jun 10 09:56:40 raspberrypi systemd[1]: flask_api.service: Main process exited, code=exited, status=2/INVALIDARGUMENT
Jun 10 09:56:40 raspberrypi systemd[1]: flask_api.service: Failed with result 'exit-code'.

When I type flask run --host=0.0.0.0 manually it works fine, I don't know why the service gives this error.
More info:
I also tried python /home/pi/bucketlist/run.py instead of  flask run --host=0.0.0.0 in ExecStart.
I have a virtual environment set-up in the bucketlist directory.
Python 2.7.16
Flask 1.1.4
Werkzeug 1.0.1


text:
Q: Same CPU players are always winning at Mario Kart 8 Deluxe After some time playing at Mario Kart 8 Deluxe, I realized that always (not sometimes or usually, it's always) the two CPU players that obtain the best positions are Toad and Donkey Kong. Although this is not important for playing the game, it's a little frustrating, because I would like to battle for the first place against other players too. I'm tired of Toads and DKs.
I wanted to see if this thing only happens in my game or if it happens in other players games. And if there is any setup where I could change it.

A: Finallly I discovered the solution here. The fastest CPU players are not selected at random. They depend on the player you choose. If I choose always Yoshi, then I will always face Toad and DK. So the solution is to choose other players.

A: I play Mario Kart 8 but not the Deluxe version, but I can say that every time I start a Grand Prix, or any VS Race with multiple tracks, that always two or three CPUs are always better than the rest, and some that are worse.
I think it's just how it's randomized when you start a new Grand Prix or a VS Race. Whenever I start a new Grand Prix race, different characters are in first and second.
I don't know in your case when you say always, whether that is every race in a Grand Prix cup, or in every race, you do no matter what.


text:
Q: How to count the number of occurrences in a variable using python I imported a csv file with the variable "HEIGHT" which has 10 values.
HEIGHT
62
58
72
63
66
62
63
62
62
67

I want to use numpy and numpy only to count the number of times the value '62' does not occur. The answer should be 6.
import numpy
import csv
with open('measurements.csv'),'r') as f:
rows=f.readline()
rows=f.split(',')
rows=numpy.array([rows[2:4]])
print(rows)

I'm a beginner python learner practicing numpy, so I am not quite sure how to approach this problem.

A: Using numpy you can do:
data = np.array([62, 58, 72, 63, 66, 62, 63, 62, 62, 67])

(data != 62).sum()

That is, data != 62 will make a numpy Boolean array, and sum will add these up, with True as 1, giving the total count.

A: If you want to use numpy and numpy only,
Load the file using numpy:
dataset = np.loadtxt('measurements.csv', delimiter=',')

Seems like the height variable is in the 3rd column (index 2). When you use loadtxt, you'll get a 2D array that looks like a table. You need the column with index 2, and you can then use @tom10's solution:
(dataset[:, 2] != 62).sum()

And you have a complete numpy workflow.
Note: Read docs to understand functions used better.

*

*numpy.loadtxt

*Comparisons in numpy arrays (Tutorial - opinionated!)

*Official docs on indexing


text:
Q: Pine Script entries exit on next bar even if TP/SL reached I cannot understand why Pine Script is exiting my position on next bar when I set SL/TP.
This is my simple example code:
if entryConditionsAreMet
    strategy.entry("short", strategy.short)

// let's assume 5% TP and 2% SL
takeProfitShort = strategy.position_avg_price * (1 - (5 / 100))
stopLossShort = strategy.position_avg_price * (1 + (2 / 100))

strategy.exit("exitShort", "short", limit=takeProfitShort, stop=stopLossShort)

It opens and closes positions correctly, however the TP/SL always occur on the next bar.
Look at the picture below to understand (the green line is the TP and the orange one is the SL):
I'd expect the position closes on the same bar, not in the next one!
As you can see, the position closes not when the TP is reached but on the next opening bar.
Why does this happen? How to avoid it?

A: Try this:
if entryConditionsAreMet
    strategy.entry("short", strategy.short)

// let's assume 5% TP and 2% SL
takeProfitShort = strategy.position_avg_price * (1 - (5.0 / 100))
stopLossShort = strategy.position_avg_price * (1 + (2.0 / 100))

strategy.exit("exitShort", "short", limit=takeProfitShort, stop=stopLossShort)


text:
Q: How to change list of booleans to incremental numbers Is there a way to change boolean values in a list to incremental values based on certain conditions?
I have these two variables:
answers = [True, True, False, True, True, False, False]
p = 2

This is my code:
[x-p if x == False else x+x for x in answers]

This is the output (which is incorrect):
[2, 2, -2, 2, 2, -2, -2]

This is the desired output:
[1, 2, -2, 4, 5, -2, -2]

I know why this is happening as True == 1 in integer terms so essentially it sees 1+1, but I don't know how to make it add incrementally.

A: This line gives you the right output :
[i+1 if answers[i] == True else -2 for i in range(len(answers))]

A: How about this:
answers = [True, True, False, True, True, False, False]
output = [i if answer else -2 for i, answer in enumerate(answers, 1)]
print(output) # [1, 2, -2, 4, 5, -2, -2]

A: Shortest:
[i+1 if x else -2 for i,x in enumerate(answers) ]

A: This is what you might be looking for. With your given set of variables
 answers = [True, True, False, True, True, False, False]
 p = 2

 retval = []
 temp = 0

 for item in answers:
     if item:
        item += temp
        retval.append(item)
     else:
        retval.append(item-2)
     temp += 1

# retval is the output list with [1, 2, -2, 4, 5, -2, -2]

Let me know in case you have any questions regarding the above.


text:
Q: Javascript Array/JSON Library Basically I need some sort of library/set of functions that will allow me to perform advanced functions on arrays.
For example:
var jsondata = "SearchResponse":{ "Version":"2.0","Query":{
"SearchTerms":"sushi"},"Web":{ "Total":15000000,"Offset":0,"Results":[
{ "Title":"Sushi - Wikipedia, the free encyclopedia","Description":"In
Japanese cuisine, sushi (寿司, 鮨, 鮓, sushi?) is vinegared rice, usually
topped with other ingredients, including fish (cooked or uncooked) and
vegetables.","Url":"http:\/\/en.wikipedia.org\/wiki\/Sushi","DisplayUrl
":"http:\/\/en.wikipedia.org\/wiki\/Sushi","DateTime":"2008-06-
09T06:42:34Z"}]}} /* pageview_candidate */}

var filterdata = filter(jsondata, {"Title":"Sushi - Wikipedia, the free encyclopedia"});

And then filterdata will contain all results in jsondata that have the Title Sushi - Wikipedia, the free encyclopedia

A: Take a look at underscore.js. You probably won't be able to write code exactly as in your question, but it comes near to it:
_.filter(jsondata.Web.Results, function (val) {
    return val.Title === "Sushi - Wikipedia, the free encyclopedia";
});

A: Look at PHP.js. It brings PHP power to JavaScript.

A: Well, first of all, jsondata is an Object, not an Array; however the jsondata.Web.Results property is an Array.  With that in mind, you could make use of the JavaScript Array.filter method.
var results = jsondata.Web.Results.filter(function (value) {
    // Return true if you want this 'value' object to appear in the 'results' Array.
    return (value.Title === "Sushi - Wikipedia, the free encyclopedia");
});

If you want to do more serious work with Arrays then it would be sensible to include a Collections Framework; the most popular one for JavaScript is underscore.js.  A solid understanding of Collections will pay off dividends in the future for your programming career.


text:
Q: Object property is filled when shown but undefined when accessed. Nodejs Sequelize I am performing this raw sql query
SELECT postId, users.id as userId,users.firstName,users.lastName,users.avatar,COUNT(postId) as
numOfLikes,body
FROM posts
INNER JOIN likes ON likes.postId = posts.id
INNER JOIN users ON users.id = posts.userId
GROUP BY postId
ORDER BY postId DESC

through nodeJs sequelize ORM
 Posts.findAll({
                attributes: ['id','body','createdAt', [db.fn('count', db.col('likes.postId')), 'numOfLikes']],
                include: [{ attributes: [], model: Likes,required:true, },{model:Users,required:true}],
                group: ['id'],
                order: [['id', 'DESC']]
            })

I receive everything as it should be but cannot access numOfLikes object property (undefined)
{
 "id": 18,
  "body": "This show was organized.",
  "createdAt": "2021-03-06T23:55:44.000Z",
  "numOfLikes": 5,
  "user": {
  "id": 73,
  "firstName": "Paolo",
  "lastName": "Jovovic",
  "email": "dzonnna@gmail.com",
  "email_verified": "1",
  "password": "$2b$10$6fLwPfuLP8Jfp7em0iqBm.YhznDut8AWOmUPynqecfd9YMvZBMaXq",
  "google_id": null,
  "avatar": "1_aZF6_EToO4T3ZeHXfgF-Vg.png",
  "role": "0",
  "createdAt": "2021-02-28T22:30:42.000Z",
  "updatedAt": "2021-03-01T23:59:21.000Z"
  }
  }

A: I had this same issue - I was selecting certain attributes and the query was working correctly.
const books = await Book.findAll({
  where: {status_id: [status[0].id, status[1].id]},
  attributes: ["id", "cover", "title", "status_id", "created_at"],
  order: [["_id", "DESC"]],
})

the object showed the value but when i tried to access it, it was always undefined.
dataValues: {
    id: '9beb341c-a0fa-489d-8a32-c9ec28f0ab16',
    cover: 'cover_500.jpg',
    title: 'birth',
    status_id: '8a5b8c46-b5ac-477a-b1c5-ca2210399e6c',
    created_at: 2022-10-16T02:10:32.000Z
},

I should point out here that i've changed the name of createAt in the model
createdAt: {
    field: "created_at",
    type: Sequelize.DATE,
},

when trying to access the value with book.create_at or book.createAt both come back as undefined even though they are clearly on the object.  this is a very strange behavior.  since they are in the datavalues they should be accessible.
when I remove the attributes selection column and just return everything for the row, it magically works.
so the issue is either,

*

*I changed the name in the model and there is some kind of issue / error in sequalize

*There is just some kind of issue / error with sequalize access the datavalue
either way, you can grab the whole row and only return / build your object out of the columns you desire.
I switched the attributes to
attributes: ["id", "cover", "title", "status_id", "createdAt"],

and it is now letting me access the field with createdAt but still not created_at so the issue appears to be the renaming of the field along with the selection of attributes.
hope this helps someone until they can fix this.

A:         Posts.findAll({
            attributes: ['id', 'body', 'createdAt', [db.fn('count', db.col('likes.postId')), 'numOfLikes']],
            include: [{ attributes: [], model: Likes, required: true, }, { model: Users, required: true }],
            group: ['id'],
            order: [['id', 'DESC']]
        }).then(postList => {
            postList = JSON.parse(JSON.stringify(postList)) // This is important
            postList.forEach(post => {
                // access post
                console.log(post, post.users)
            });
        })


text:
Q: Are major domainname registrars requiring glue records unnecessarily? I have somedomain.com registered with Namecheap, and have successfully set up A records for ns1.somedomain.com and ns2.somedomain.com to be used as nameservers for other domains.
I have otherdomain.me registered with Godaddy. When I go into Godaddy's interface and tell otherdomain.me that its nameservers are going to be ns1.somedomain.com and ns2.somedomain.com, Godaddy's interface complains that those nameservers are not registered.
And indeed, if I go back to namecheap's "Nameserver registration" section and give it the IP addresses of ns1.somedomain.com and ns2.somedomain.com, Godaddy will then allow me to assign those nameservers to otherdomain.me without issue.
So I guess my question is twofold:

*

*Amy I correct in assuming that "Nameserver registration" is simply the friendlier term for creating glue records?

*If so, and given that glue records are supposed to be used to resolve circular dependencies (which I do not have), have major registrars perverted the purpose of glue records - turning them into a global database of "permitted" nameservers?

A: Point 1 - Yes it is just another term, which merely adds unecessary confusion.
Point 2 - In addition to the A records each nameserver also needs to have a glue record. Seems like you simply missed that step until prompted to do so by the GoDaddy system. This comes under the heading of expected behaviour.

A:
Amy I correct in assuming that
"Nameserver registration" is simply
the friendlier term for creating glue
records?

Indirectly, yes.  You're really creating a host object in the registry which may or may not be used to create a glue record.
The EPP protocol does not strictly require an IP address when creating a host, but follows with:

"Hosts    provisioned as name servers
might be subject to server-operator
policies that require or prohibit
specification of IP addresses,
depending on the name of the host and
the namespace in which the    server
will be used as a name server."

However, to your point about not requiring IPs if glue is not necessary:

When provisioned for use as a    name
server, IP addresses are REQUIRED only
as needed to produce DNS    glue
records.  For example, if the server
is authoritative for the    "com"
namespace and the name of the server
is "ns1.example.net", the    server is
not required to produce DNS glue
records for the name    server, and IP
addresses for the server are not
required by the DNS.

For resolution it is not strictly necessary for the .me registry to require IPs for out-of-bailiwick nameservers, such as those in .com.  I'm not clear on whether "server-operator policies" supersede that.
Whether or not the IP you provide for the host object creation is used as glue may also be determined by the nameserver software the registry is running.  For example, BIND 8 will provide out-of-bailiwick glue while BIND 9 will not.
It may also be possible that the registry wants the IP by default but will not include out-of-bailiwick host records in the zone.  Or that the registrar (godaddy) requires the IP address but only submits it to the registry as needed; this may be the case since godaddy deals with multiple registries, and it's just easier to always ask for the IPs.  I don't really see that as a perversion.  Maybe they're just trying to keep things simple on their side.
So, yeah, to answer your title question: A registrar asking for IPs to create out-of-bailiwick nameservers is not strictly necessary, but it may not be their fault.

A: The point of the glue record in this case is to allow the response for your domain (foo.me IN NS ns1.foo.com) to also include an additional record (ns1.foo.com IN A 1.2.3.4).  Otherwise, you'd require at least one extra DNS transaction of every client (and realistically at least two on a client without any cache), which gets to be expensive.  Depending on the policies of the TLD in question, glue records even for out-of-TLD domains may or may not therefore be required, just to reduce load on the TLD NSes.  GoDaddy probably figured it was easier to just always require them, since it both prevents a situation where they violate a registrar agreement if the TLD's policy changes, and it also tends to speed access to customer sites.
Win-win, until you came along and complained.  ;)

A: *

*No, Name Registration is the Registrar creating an NS record for your domain in the TDL. For exmaple.com, they would create the "example" NS record in the COM domain. An NS record must point to another DNS server, if that DNS server is within the scope of the new domain, then it would create a circular dependancy (looking up example.com would point to example.com). To break this pattern Glue Records were introduced which allow TDLs to resolve name servers; the NS record for example.com would point to something like ns1.example.com, which the COM domain knows by a glue record points to IP 1.2.3.4 (all just examples).
By extension, if your name servers exist in a domain other than the one you are registering then you don't need glue records. For instance, if domain.com was hosting the DNS for example.com then the NS for example.com would point to ns1.domain.com. The glue records for domain.com would then be used and you would not need additional records for example.com

*No, and you're venturing off into conspiracy theorist nut-job land. GoDaddy (and all domain registers I know of) will allow you to add as many glue records as you reasonably want (free too). I personally use GoDaddy, I have registered glue records with them, free, and it's not terribly complicate (although they do not call them glue records for whatever reason).


text:
Q: Geofence pending intent firing too late when device is in deep sleep (doze) mode I need to notify user when he is near by given place. I use Geofencing API for this. When i test app on Android emulator with mock location everything works fine. Same for real device with Mock Location. But when I walk and my phone is in deep sleep mode Geofence fires after 5 - 10 min. If i am inside geofences radius and I unlock my phone, open any app which use location my geofence triggers immediately. (Android 5.1, Motorolla moto G 1-st generation)
Below is the way, how I registered my geofence:
  public void registerLocation(RegisterAlarmRequestModel data) {
    if (isLocationDetectionAllowed() && isConnected) {
        GeofencingRequest geofencingRequest = prepareGeofencingRequest(prepareGeofence(data));
        PendingIntent pendingIntent = prepareIntent(data.getId());
        PendingResult<Status> result = GeofencingApi.addGeofences(
                googleApiClient, geofencingRequest, pendingIntent);
        Status status = result.await();
        if (status.isSuccess())
            Log.d("Location", "Geofence " + data.getId() + " has been registered");
    }
}

//preparing Geofence Pending Intent which will be triggered
private PendingIntent prepareIntent(int alarmId) {
    Intent intent = new Intent(context, LocationRingingService.class);
    intent.putExtra(LocationRingingService.KEY_ALARM_ID, alarmId);
    return PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}

private GeofencingRequest prepareGeofencingRequest(Geofence geofence) {
    GeofencingRequest.Builder builder = new GeofencingRequest.Builder()
            .setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER)
            .addGeofence(geofence);
    return builder.build();
}

private Geofence prepareGeofence(RegisterAlarmRequestModel data) {
    Geofence geofence = new Geofence.Builder()
            .setRequestId(String.valueOf(data.getId()))
            .setCircularRegion(data.getLatitude(), data.getLongitude(), data.getRadius())
            .setLoiteringDelay(100)
            .setExpirationDuration(Geofence.NEVER_EXPIRE)
            .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER)
            .build();
    return geofence;
}

For receiving intent I am using IntentService:
@Override
protected void onHandleIntent(Intent intent) {
    Log.d("Location", "accepted intent: " + intent.toString());
    //database request
}

This is how i have registered my service in manifest:
<service
        android:name=".plugin.delivery.ringing.location.service.LocationRingingService"
        android:enabled="true"
        android:exported="true" />

Update: I need catch the moment when user just entered into geofence as accurate as possible. I have one idea: register geofence with radius greater than need (for example if need 100m radius, register geofence with 200-300m radius). And when user enters into Geophence with larger radius -  start service with location udating to improve geofencing precision. And when user just entered - disable location service.

A: The problem is that when your phone is in deep sleep it is not updating the location accurately. The most accurate way to update location is GPS, and this is also the most battery-intensive. Other ways to update your location, such as using the cellular network, will consume less battery but are also less accurate. By default, geofences want to be really sure you are in the geofence before sending the intent. It is hard to get this sort of accuracy when in deep sleep because the phone is not getting accurate location data.
The reason why the geofence triggers immediately when you unlock your phone and use a location-aware app, is that the app updates the LastLocation, which your geofence sees and then sends the intent. While your phone is in deep sleep the location is not being updated.
With geofences there are also a few settings you can tweak to improve responsiveness. I see you're already using setLoiteringDelay, try playing around with different values , maybe try very small values and see what happens. You could also set a value for setNotificationResponsiveness, which works in a similar way. Doing that should make your fence more responsive, but it may cost more battery life. Also read the API Reference for setLoiteringDelay and setNotificationResponsiveness. Also read the geofence troubleshooting section if you haven't.
You could also increase the size of the geofence, try doubling it and then test. Since your location accuracy is low while in deep sleep, this will make it easier for your phone to be sure that it is inside the geofence, and once it's sure it is inside the geofence it will send the intent.
I hope this helps!

A: To improve it, Let's perform some checks
1) Use broadcast receiver to get it triggered easily instead of service. And set priority with intent-filter.
For e.g
    <receiver
        android:name=".youpackage.GeoReceiver"
        android:exported="true">
        <intent-filter android:priority="999">
            <action android:name="yourpackage.ACTION_RECEIVE_GEOFENCE" />
        </intent-filter>
    </receiver>

And your pending intent will be :
Intent intent = new Intent("yourpackage.ACTION_RECEIVE_GEOFENCE");
PendingIntent pendingIntent = PendingIntent.getBroadcast(
                youractivity,
                0,
                intent,
                PendingIntent.FLAG_UPDATE_CURRENT);

2) As your GPS goes in sleep mode, we need to wake it up while creating Geofence. Once you create your geofence, you can start pinging your GPS until you will get ENTER transition. This would must help to get triggering it.
public class GPSService extends Service implements GoogleApiClient.ConnectionCallbacks,    GoogleApiClient.OnConnectionFailedListener, LocationListener {

    GoogleApiClient mGoogleApiClient;
    LocationRequest locationRequest;

    public GPSService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
     // TODO: Return the communication channel to the service.
     throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public void onCreate() {
      super.onCreate();

     mGoogleApiClient = new GoogleApiClient.Builder(this)
        .addApi(LocationServices.API)
        .addConnectionCallbacks(this)
        .addOnConnectionFailedListener(this)
        .build();

     mGoogleApiClient.connect();
  }

   @Override
   public void onLocationChanged(Location location) {

     Utility.ReadAndWriteData(this, Utility.readFileName(this), "Still Geofence is not triggered!!!");

    }

    @Override
    public void onConnected(Bundle bundle) {

        locationRequest = LocationRequest.create();
      locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setFastestInterval(1000);
        locationRequest.setInterval(2000);
    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,locationRequest,this);

    }

   @Override
   public void onConnectionFailed(ConnectionResult connectionResult)   {

  }

     @Override
     public void onConnectionSuspended(int i) {

     }

     @Override
     public void onDestroy() {
       super.onDestroy();

        if(mGoogleApiClient.isConnected()) {

     LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);

       }
 }

And don't forgot to stop this service immediately when you get ENTER transition or It cause drain battery. This service is only to wake GPS up from sleep mode.


text:
Q: cordova-2.9.1.jar Breaks My App I have a PhoneGap App and I am trying to add DroidGap:
import org.apache.cordova.DroidGap;
public class RestartAppActivity extends DroidGap {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.loadUrl("file:///android_asset/www/index.html");
    }
}

I also added cordova-2.9.1.jar to the libs folder. But now when I run the app MainActivity will not start. The error is
L java.lang.NoSuchFieldError: No field launchUrl of type Ljava/lang/String
MainActivity:
public class MainActivity extends CordovaActivity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        loadUrl(launchUrl);
    }
}

Thanks!


text:
Q: Jqgrid - hidden columns does not work My colmodel definition looks like follows:
<c name='NewShippingAddressCity' index='NewShippingAddressCity' align='left' sortable='false' hidden='true' width='150'></c>

but I don't know why this column is still visible. What should I change to hide it?
I use jqgrid 4.4.0
EDIT 1
It looks like from some reaseon hidden attribute becomes 'undefined' so te javascript sets it to false instead of true.

A: No by default value of hidden is false. try to give it with out quotes and as i can not check your entire code, follow this link  there are plenty of methods in answers which can provide you the functionality.
Alternatively, you can use hideCol property of jqgrid. See the documentation


text:
Q: Change GRUB default start option (SO) Is it possible to change the default start option from the GRUB command line?
I have 2 options Fedora and Other. Currently the Fedora is the default. Is it possible to change it to Other from the GRUB command line, and make it permanent?
thanks.

A: in /boot/grub/menu.lst is option default, you should set it for another value, for exmaple - 0 - feodra, 1, other


text:
Q: Yii2 get access only using pretty URLs I'm using URL manager like the following:
'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'rules' => [
                'verses/view/<id:\d+>' => 'verses/view',
            ],
        ],

It works fine to make access using mysite.com/verses/view/158. The problem is, it is still possible to access the same content using non pretty URL i.e using plain get parameter such as mysite.com/verses/view?id=158. I need any way to restrict the access using the pretty URL.
I have tried the following couples of rules separately, but nothing I have gotten:

*

*'verses/view<?id=>' => 'Error404',

*'verses/view?id=<\d+>' => 'Error404',

A: What is the point of such restriction?
Anyway, one way to do it is something like this:
public function actionView($id)
{
    if (strpos(\Yii::$app->request->getUrl(), '?') !== false) {
        throw new \yii\web\BadRequestHttpException;
    }
    // ... the rest of action
}

No changes in UrlManager needed.

A: Try using UrlManager parameter enableStrictParsing = true.
What happens. UrlManager checks all rulls and they all do not match the request. Thus, by default it checks all default rules. Among default rules it finds the rule with ?id= and preforms routing to that one.
So, in order to avoid that route, you need to list all possible routes in the UrlManger rules and make enableStrictParsing = true. The routes not listed in the config rules parameter will be ignored.


text:
Q: Combined ConcurrentQueue and ConcurrentStack I'm looking for a concurrent collection which can be accessed from both sides. I want to achieve the following:

*

*Some producers add items

*The client shall be able to display the last n produced items

*The collection shall only contain elements produced within the last x hours

So I need to access the top of the list (FIFO) for displaying the last n items, but I also need to access the end of the list (LIFO) to prune elements older than x hours continuously.

A: Another approach is to use MemoryCache class, which is thread-safe and provide built-in functionality for removing "expired" items.
I have created a class for keeping saved value and timestamp
public class SavedItem<T>
{
    public DateTime Timestamp { get; set; }

    public T Value { get; set; }
}

Collection class will have two methods: one for adding and one for retrieving N-amount of last items
public class ExpiredCollection
{
    private readonly MemoryCache _cache;

    private readonly int _hoursLimit;

    public ExpiredCollection(int hoursLimit)
    {
        _cache = new MemoryCache("sample");
        _hoursLimit = hoursLimit;
    }

    public void Add<T>(T value)
    {
        var item = CreateCacheItem(value);
        var policy = CreateItemPolicy();

        _cache.Add(item, policy);
    }

    private CacheItem CreateCacheItem<T>(T value)
    {
        var addedValue = new SavedItem<T>
        {
            Timestamp = DateTime.Now,
            Value = value
        };
        // Create unique key to satisfy MemoryCache contract
        var uniqueKey = Guid.NewGuid().ToString();

        return new CacheItem(uniqueKey, addedValue);
    }

    private CacheItemPolicy CreateItemPolicy()
    {
        // This will set a time when item will be removed from the cache
        var expirationTime = DateTime.Now.AddHours(_hoursLimit);
        var offset = new DateTimeOffset(expirationTime);

        return new CacheItemPolicy
        {
            AbsoluteExpiration = offset
        };
    }

    public IEnumerable<T> GetLast<T>(int amount)
    {
        return _cache.Select(pair => (SavedItem<T>)pair.Value)
                     .OrderBy(item => item.Timestamp)
                     .Select(item => item.Value)
                     .Take(amount);
    }
}

A:
The client shall be able to display the last n produced items

That is not about removing items. I assume you want them to stay in there after having been displayed.
So you don't really want the  LIFO part.
When the number of items isn't too big you can use a ConcurrentQueue and ToArray() to get a snapshot (and use only the first n items).


text:
Q: How can I select ip range? I have src_ip(varchar2) column. I need to select ip range like this:
100.64.0.0/10 --> 100.64.0.0 - 100.127.255.255
I tried encode to ip address but it's not working for me. How can I do this?

A: Some time ago I created a package with function related to IP-Addresses (IPv4 only). With this package you should be able to write your query.
CREATE OR REPLACE PACKAGE BODY IP_Utils AS

BASE_BIN CONSTANT INTEGER := 2;
BASE_OCT CONSTANT INTEGER := 8;
BASE_DEC CONSTANT INTEGER := 10;
BASE_HEX CONSTANT INTEGER := 16;

/**
* Convert a decimal nubmer into a binary/octal/hex string
* @param DecN Integer decimal number
* @param Base The binary base (BASE_BIN, BASE_OCT, BASE_HEX)
* @return The binary/octal/hex string
*/
FUNCTION Dec2Base(
        DecN IN INTEGER,
        Base IN PLS_INTEGER DEFAULT BASE_HEX)
    RETURN VARCHAR2 DETERMINISTIC IS

    HexString CONSTANT CHAR(16) := '0123456789ABCDEF';
    DecNumber INTEGER := DecN;
    BaseString VARCHAR2(128) := NULL;

BEGIN
    IF DecN IS NULL THEN
        RETURN NULL;
    END IF;
    IF Base > 16 THEN
        RAISE NUMERIC_OVERFLOW;
    END IF;

    LOOP
        BaseString := SUBSTR(HexString, MOD(DecNumber, Base) + 1, 1 ) || BaseString;
        DecNumber := TRUNC(DecNumber / Base);
        EXIT WHEN DecNumber = 0;
    END LOOP;
    RETURN BaseString;

END Dec2Base;

/**
* Convert a binary/octal/hex number into a decimal value
* @param BaseString The binary/octal/hex string
* @param Base The binary base (BASE_BIN, BASE_OCT, BASE_HEX)
* @return The decimal number
*/
FUNCTION Base2Dec(
        BaseString IN VARCHAR2,
        Base IN PLS_INTEGER DEFAULT BASE_HEX)
    RETURN INTEGER DETERMINISTIC IS

    BaseNumber INTEGER := 0;
    HexString CONSTANT CHAR(16) := '0123456789ABCDEF';

BEGIN
    IF Base > 16 THEN
        RAISE NUMERIC_OVERFLOW;
    END IF;

    IF BaseString IS NULL THEN
        RETURN NULL;
    END IF;
    FOR i IN 1..LENGTH(BaseString) LOOP
        BaseNumber := BaseNumber * Base + INSTR(HexString, UPPER(SUBSTR(BaseString, i, 1))) - 1;
    END LOOP;

    RETURN BaseNumber;
END Base2Dec;

/**
* Convert a IPv4 AP-Address into decimal value
* @param IP The IP-Address, e. g. '10.151.20.224'
* @return The decimal equivalent
*/
FUNCTION Ip2Decimal(IP IN VARCHAR2) RETURN INTEGER DETERMINISTIC IS
    DecimalIp NUMBER := 0;
BEGIN

    IF Ip IS NULL THEN
        RETURN NULL;
    END IF;

    FOR i IN 1..4 LOOP
        DecimalIp := DecimalIp + REGEXP_SUBSTR(IP, '\d+', 1, i) * 256**(4-i);
    END LOOP;
    RETURN DecimalIp;

END Ip2Decimal;

/**
* Convert an IP-Address from decimal value into IPv4 format
* @param IpDecimal Decimal IP-Address, 0..4294967295
* @return The IP in IPv4 format
*/
FUNCTION Decimal2Ip(IpDecimal IN INTEGER) RETURN VARCHAR2 DETERMINISTIC IS

    IP VARCHAR2(16);
    Octet INTEGER;
    v_IpDecimal INTEGER := IpDecimal;

BEGIN
    IF IpDecimal IS NULL THEN
        RETURN NULL;
    END IF;

    IF IpDecimal > 2**32 -1 THEN
        RAISE NUMERIC_OVERFLOW;
    END IF;

    FOR i IN 1..4 LOOP
        Octet := TRUNC(v_IpDecimal/256**(4-i));
        v_IpDecimal := v_IpDecimal - Octet * 256**(4-i);
        IP := IP ||'.'||Octet;
    END LOOP;
    RETURN SUBSTR(IP, 2);

END Decimal2Ip;

/**
* Determines Subnet and Broadcast-Ip of given Ip Address
* @param Ip IP-Address, e.g. 10.152.10.17
* @param SubnetMask The SubnetMask, e.g. 255.255.255.240
* @param Subnet Subnet-IP: e.g. 10.152.10.16
* @param BroadcastIp Broadcast-IP: e.g. 10.152.10.31
*/
PROCEDURE GetIpSubnet(Ip IN VARCHAR2, SubnetMask IN VARCHAR2, Subnet OUT VARCHAR2, BroadcastIp OUT VARCHAR2) IS
    CIDR INTEGER;
    SubnetDec INTEGER;
BEGIN

    IF SubnetMask IS NULL OR Ip IS NULL THEN
        RETURN;
    END IF;

    FOR i IN 1..4 LOOP
        Subnet := Subnet ||'.'||BITAND(REGEXP_SUBSTR(Ip, '\d+', 1, i), REGEXP_SUBSTR(SubnetMask, '\d+', 1, i));
    END LOOP;
    Subnet := SUBSTR(Subnet, 2);

    CIDR := SubnetMask2CIDR(SubnetMask);
    SubnetDec := Ip2Decimal(Subnet);
    FOR i IN CIDR..31 LOOP
        SubnetDec := SubnetDec + 2**(31-i);
    END LOOP;
    BroadcastIp := Decimal2Ip(SubnetDec);

END GetIpSubnet;

/**
* Returns SubnetMask of given IP-Address
* @param Ip IP-Address with CIDR, e.g. 10.152.10.17/27
* @return SubnetMask, e.g. 255.255.255.224
*/
FUNCTION GetSubnetMask(Ip IN VARCHAR2) RETURN VARCHAR2 DETERMINISTIC IS
BEGIN
    IF Ip IS NULL OR NOT REGEXP_LIKE(Ip, '/\d{1,2}$') THEN
        RETURN NULL;
    END IF;
    RETURN CIDR2SubnetMask(REGEXP_SUBSTR(Ip, '\d{1,2}$'));
END GetSubnetMask;

/**
* Returns Subnet of given IP-Address
* @param Ip IP-Address, e.g. 10.152.10.17
* @param SubnetMask SubnetMask in IPv4 Format, e.g. 255.255.0.0
* @return Subnet in IPv4 Format, e.g. 10.152.0.0
*/
FUNCTION GetSubnetIp(Ip IN VARCHAR2, SubnetMask IN VARCHAR2) RETURN VARCHAR2 DETERMINISTIC IS
    Subnet VARCHAR2(16);
    BroadcastIp VARCHAR2(16);
BEGIN
    GetIpSubnet(Ip, SubnetMask, Subnet, BroadcastIp);
    RETURN Subnet;
END GetSubnetIp;

/**
* Returns Broadcast of given IP-Address
* @param Ip IP-Address, e.g. 10.152.10.17
* @param SubnetMask SubnetMask, e.g. 255.255.0.0
* @return Broadcast in IPv4 Format, e.g. 10.152.255.255
*/
FUNCTION GetBroadcastIp(Ip IN VARCHAR2, SubnetMask IN VARCHAR2) RETURN VARCHAR2 DETERMINISTIC IS
    Subnet VARCHAR2(16);
    BroadcastIp VARCHAR2(16);
BEGIN
    GetIpSubnet(Ip, SubnetMask, Subnet, BroadcastIp);
    RETURN BroadcastIp;
END GetBroadcastIp;

/**
* Returns Subnet of given IP-Address
* @param Ip IP-Address with CIDR, e.g. 10.152.10.17/16
* @return Subnet in IPv4 Format, e.g. 10.152.0.0
*/
FUNCTION GetSubnetIp(Ip IN VARCHAR2) RETURN VARCHAR2 DETERMINISTIC IS
    Subnet VARCHAR2(16);
    BroadcastIp VARCHAR2(16);
    SubnetMask VARCHAR2(16);
BEGIN
    SubnetMask := GetSubnetMask(Ip);
    GetIpSubnet(REGEXP_REPLACE(Ip,'/.+$'), SubnetMask, Subnet, BroadcastIp);
    RETURN Subnet;
END GetSubnetIp;

/**
* Returns Broadcast of given IP-Address
* @param Ip IP-Address with CIDR, e.g. 10.152.10.17/16
* @return Broadcast in IPv4 Format, e.g. 10.152.255.255
*/
FUNCTION GetBroadcastIp(Ip IN VARCHAR2) RETURN VARCHAR2 DETERMINISTIC IS

    Subnet VARCHAR2(16);
    BroadcastIp VARCHAR2(16);
    SubnetMask VARCHAR2(16);
BEGIN
    SubnetMask := GetSubnetMask(Ip);
    GetIpSubnet(REGEXP_REPLACE(Ip,'/.+$'), SubnetMask, Subnet, BroadcastIp);
    RETURN BroadcastIp;
END GetBroadcastIp;

/**
* Translate SubnetMask to CIDR
* @param SubnetMask SubnetMask in IPv4 Format, e.g. 255.255.255.240
* @return CIDR value, e.g. 26
*/
FUNCTION SubnetMask2CIDR(SubnetMask VARCHAR2) RETURN INTEGER DETERMINISTIC IS
    IpBin CHAR(32);
BEGIN
    IF SubnetMask IS NULL THEN
        RETURN NULL;
    END IF;
    IpBin := Dec2Base(Ip2Decimal(SubnetMask), BASE_BIN);
    IF REGEXP_LIKE(IpBin, '^1+0+$') THEN
        RETURN REGEXP_INSTR(IpBin, '0')-1;
    ELSIF REGEXP_LIKE(IpBin, '^1{32}$') THEN
        RETURN 32;
    ELSE
        RAISE VALUE_ERROR;
    END IF;
END SubnetMask2CIDR;

/**
* Translate CIDR to SubnetMask
* @param CIDR Subnet, e.g. 26
* @return SubnetMask in IPv4 Format, e.g  255.255.255.240
*/
FUNCTION CIDR2SubnetMask(CIDR IN INTEGER) RETURN VARCHAR2 DETERMINISTIC IS
BEGIN
    IF CIDR IS NULL THEN
        RETURN NULL;
    END IF;
    IF CIDR NOT BETWEEN 1 AND 32 THEN
        RAISE VALUE_ERROR;
    END IF;

    RETURN Decimal2Ip(Base2Dec(RPAD(LPAD('0', CIDR+1, '1'), 32, '0'), BASE_BIN));
END CIDR2SubnetMask;

END IP_Utils;
/


text:
Q: C# DataGridView use Rows and Columns as Headers I am connected to a Database. I created an DataViewGrid which uses Databinding from that Database.
I want to use Rows and Columns as Headers, right now somehow there are just Columns as Headers.
I am using Visual Studio 15 and want to use the Designer.
Does anyone ever did that? Or know an better Windows.Form for creating Table, which are connected to the Database and have Headers at the Row and Column side?
Thx in advance

A: Your requirements are not very clear but I guess you want to customize the row and column headers. The dataGridView is probably one of the best controls to view data in Windows Forms. I will show how to do the following typical requirements would be;

*

*To show column headers in Title Case or UPPER Case

*Customize the column headers specific names

*Show row numbers on row headers

Code below is in C#
//Show Columns in Title, Lower(textInfo.ToLowerCase) or Upper case textInfo.ToUpperCase
    System.Globalization.TextInfo textInfo = new System.Globalization.CultureInfo("en-US", false).TextInfo;
    foreach (DataGridViewColumn col in dataGridView.Columns)
    {
        col.HeaderText = textInfo.ToTitleCase(col.HeaderText);
    }

//Customize specific column headers, using name or column index
    dataGridView.Columns["number"].HeaderText = "No.";
    dataGridView.Columns["quantity"].HeaderText = "Product Quantity";
    dataGridView.Columns[0].HeaderText = "Code";

//Set Row headers with numbers
    int rowNumber = 1;
    foreach (DataGridViewRow row in dataGridView.Rows)
    {
        if (row.IsNewRow) continue;
        row.HeaderCell.Value = "Row " + rowNumber;
        rowNumber = rowNumber + 1;
    }
    dataGridView.AutoResizeRowHeadersWidth(
    DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders);

Reference

A: Thirdparty Grids like DevExpress PivotGrid allow you do to sth. like this. The basic dataGridView is not able to present RowHeader as far as i know. You could create a custom column to your DataSource, which holds RowHeader information and show this as first column. If you modify the first columns layout a bit it looks like RowHeader maybe. Would be the only trick i know with basic dataGridView.


text:
Q: How to set length of file write function call in lua? I'm using an embedded lua which provides an interface to access some data in C.
Specifically it gets an image blob in raw bytes.  I know the size of the raw data and I'm wanting to write this blob to disk.
However, I can't figure out from the lua io package how to write data of a set length.  How do I set the number of bytes that the write call will consume?

A: The write functions of the io library expect a string or a number as input which both have a known length.
It's not like in C where you migh give a pointer and a number of bytes to be written.


text:
Q: Label disappearing after attributting it a parent I have a Microsoft Visual Studio 2017 Project. I have 2 picture boxes and I want to have 2 transparent labels over them to attribute an onclick event.
label1.Parent = pictureBox1;
label1.BackColor = Color.Transparent;
label2.Parent = pictureBox2;
label2.BackColor = Color.Transparent;`

The problem is that the first label works fine, becomes transparent and can be clicked, but the second one disappears when I give it a new parent.


text:
Q: Checkout Form submission using ajax I want to submit my form using ajax, My script code does not have any errors also my php but when i click the submit button nothing happens, just form will empty otherwise nothing happened, the data does not store in the database. I don't know what the error is. I don't Know how to find it, Can anyone please help me to fix this?

CHECKOUT FORM

                <form id="checkout_form">

                              Name:
                              <input type="text" class="form-control" id="name" name="name">

                              Email:
                              <input type="text" class="form-control" id="email" name="email">

                              Address:
                              <input type="text" class="form-control" id="address" name="address">

                              City:
                              <input type="text" class="form-control" id="city" name="city">

                              State:
                              <input type="text" class="form-control" id="state" name="state">

                              Card Name:
                              <input type="text" class="form-control" id="card_name" name="card_name">

                              CVV:
                              <input type="text" class="form-control" id="cvv" name="cvv">

                              Card Number:
                              <input type="text" class="form-control" id="card_number" name="card_number">

                              Expire Month:
                              <input type="text" class="form-control" id="expired_month" name="expired_month">

                              Zip Code:
                              <input type="text" class="form-control" id="zip_code" name="zip_code">

                            <input type="submit" name="submit" class="btn btn-success" value="CHECKOUT" action = "checkout" id="submit">

                </form>

script code

action1.php
<?php

include('database_connection.php');

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

        $data = array(
            ':name' => $_POST['name'],
            ':email' => $_POST['email'],
            ':address' => $_POST ['address'],
            ':city' => $_POST['city'],
            ':state' => $_POST['state'],
            ':card_name' => $_POST ['card_name'],
            ':cvv' => $_POST['cvv'],
            ':card_number' => $_POST['card_number'],
            ':expired_month' => $_POST['expired_month'],
            ':zip_code'=> $_POST['zip_code']
        );

        $query = "INSERT INTO checkout (name,email,address,city,state,card_name,cvv,card_number,expired_month,zip_code) VALUES (:name,:email,:address,:city,:state,:card_name,:cvv,:card_number,:expired_month,:zip_code)";

        $statement = $connect ->prepare($query);

        if($statement->execute($data))
        {
            echo "form submitted";
        }
}
?>

A: Your form page is refreshing when submit is clicked. Do this:
$('#submit').click(function(e){
     e.preventDefault;

As stated in the comments, also:
echo $query;
exit; //This exit is causing the query not to run because the script stops running.

You have semi-colons in front of your field names. Remove them:
$data = array(
            'name' => $_POST['name'],
            'email' => $_POST['email'],
            'address' => $_POST ['address'],
            'city' => $_POST['city'],
            'state' => $_POST['state'],
            'card_name' => $_POST ['card_name'],
            'cvv' => $_POST['cvv'],
            'card_number' => $_POST['card_number'],
            'expired_month' => $_POST['expired_month'],
            'zip_code'=> $_POST['zip_code']
        );

A: Welcome to the Stackoverflow @prabhu-msd
Add e.preventDefault; as the first line under this code:
$('#submit').click(function(){

It prevents the page to be refreshed and run your Ajax. Under success add location.reload(); after this line $('#message').val("form submitted"); to refresh the page once your data is submitted (If you want to refresh the page) otherwise do what ever you want.
In your PHP File, you are using exit which prevents the execution of your query. Kindly, remove that exit.