text:
Q: Always show date input calendar that takes up whole div I'm using ASP.NET Core 2.2 MVC and I have a page containing a date input. When the page loads, I would like it to have the calendar always kept open by default without needing to click the little arrow:

If that's possible, can the arrow be removed as well? I'd still want the text box to be there for manual input.
I also want the calendar always take up the height and width of its parent div. If the div's height is relative, the calendar would stretch as it needs to.
The solution I'm looking for doesn't need to be solved exactly this way, and I'm open to plug-ins. I've tried JQuery UI datepicker but I haven't gotten it to work the way I want to. One thing to note is that I have asp-for attribute on the input tag.
HTML:

    <input asp-for="@Model.DatePicked" type="date" required />

CSS:
#wrapper {
   height: 20vh;
   width: 20vw;
}

A: If you want to use JQuery UI datepicker:

I would like it to have the calendar always kept open by default without needing to click the little arrow

You can use inline mode, it display the datepicker embedded in the page instead of in an overlay. Simply call .datepicker() on a div instead of an input.
$("#datepicker").datepicker();

Because you call datepicker in div it always keep it open as you wish

.

If that's possible, can the arrow be removed as well? I'd still want the text box to be there for manual input.

With inline mode there is not any arrow and if you want to show date in textbox:
<input type="text" id="alternate">

$("#datepicker").datepicker({
  altField: "#alternate"
});


text:
Q: How do I change color dynamically in a Vue Routes app? I am trying to create a Vue-Routes application in which it should be possible to change colors of two divs in index.html by writing the name of the selected colors in two input fields. This is a bit complicated since this is a routes app. How do I accomplish this task?
The finished application should have this functionality: Codepen.
index.js (Routes)
import ColorPage from '../components/colorPage.js'

const routes = [
    {path: '/', component: ColorPage},
];
const router = new VueRouter({
    routes

});

var vm = new Vue({
    el: '.container',
    router,
});

ColorPage.js
const ColorPage = {
    props:
        ['bga', 'bgb'],
    data() {
        bga: {
            backgroundColor: ''
        },
        bgb: {
            backgroundColor: ''
        }
    },
    template: `

'Change Colors By Typing Their Names:'

    <input type="text" class="colorInput" v-on:input="bga.backgroundColor = $event.target.value" placeholder="here...">

    <input type="text" class="colorInput"  v-on:input="bgb.backgroundColor = $event.target.value" placeholder="... and here!">

`,
};

export default ColorPage

Index.html

Vue routing

                    <router-link to="/">Color</router-link>
                    <router-link to="/main">Main</router-link>
                    <router-link to="/settings">Settings</router-link>
                    <router-link to="/vue">Vue</router-link>

        <router-view></router-view>

A: You need to define bga and bgb in parent also

const ColorPage = {
    props:['bga','bgb'],
    template: `

Change Colors By Typing Their Names:

    <input type="text" class="colorInput" v-model="$parent.bga" placeholder="here...">

    <input type="text" class="colorInput" v-model="$parent.bgb" placeholder="... and here!">

`
};

const routes = [
    {path: '/', component: ColorPage}
];
const router = new VueRouter({
    routes

});

var vm = new Vue({
    el: '.container',
    router,
    data:{
        bga:'',
        bgb:''
    }
});

Vue routing

                    <router-link to="/">Color</router-link>
                    <router-link to="/main">Main</router-link>
                    <router-link to="/settings">Settings</router-link>
                    <router-link to="/vue">Vue</router-link>

        <router-view></router-view>

Another way is by $parent

const ColorPage = {
    data:function(){
      return {
          bga: this.$parent.bga,
          bgb: this.$parent.bgb,
        }
    },
    methods:{
      changeBgaColor:function(){
        this.$parent.bga = this.bga;
      },
      changeBgbColor:function(){
        this.$parent.bgb = this.bgb;
      }
    },
    template: `

Change Colors By Typing Their Names:

    <input type="text" class="colorInput" v-on:keyup="changeBgaColor" v-model="bga" placeholder="here...">

    <input type="text" class="colorInput" v-on:keyup="changeBgbColor" v-model="bgb" placeholder="... and here!">

`
};

const routes = [
    {path: '/', component: ColorPage}
];
const router = new VueRouter({
    routes

});

var vm = new Vue({
    el: '.container',
    router,
    data:{
        bga:'',
        bgb:''
    }
});

Vue routing

                    <router-link to="/">Color</router-link>
                    <router-link to="/main">Main</router-link>
                    <router-link to="/settings">Settings</router-link>
                    <router-link to="/vue">Vue</router-link>

        <router-view></router-view>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using session tickets (RFC 5077) on a custom client I have an HTTPS server, serving custom clients written in C++ (using POCO::Net and OpenSSL). Do I need to do something actively to enable session tickets on the client, or will it respond properly just by the fact I am using the latest OpenSSL?

A: You need to ensure that the client is, in fact, using TLS session tickets. It is quite possible to turn off ticket-based session resumption in custom clients using OpenSSL APIs. For instance, SSL_CTX_set_options supports the following option:

SSL_OP_NO_TICKET
Normally clients and servers will, where possible, transparently make use of RFC4507bis tickets for stateless session
  resumption.
  If this option is set, this functionality is disabled and tickets will
  not be used by clients or servers.

If the client has explicitly turned off ticket-based resumption using the above-quoted option, it will not support TLS tickets.


text:
Q: Editing and removing value in json using jquery I have this JSON,
{"items":[{"Code":"c101","Desc":"Car"},{"Code":"c341","Desc":"House"}]}

How can I edit the Desc of the item that have a code of c341?
How can I delete the item that have a code of c101?
I tried this code but not working,
delete obj.items.Code="c101"

A: For deleting the item with specific id use Array.prototype.findIndex() and splice(),
obj.items.splice(obj.items.findIndex(v => v.Code == "c101"), 1)

For editing use Array.prototype.find(),
var edit = obj.items.find(v => v.Code == "c341")
edit.Code = "asd" //This will affect the item's code in the original array
                  //since `find()` will return the reference not a copy.

A: There are probably more efficient solutions out there, but this is the basic idea of what you want to do.
$.each(obj.items, function (index, element){
  if (element.Code === "c101") {
    obj.items.splice(index, 1);
    return false;
  }
});

A: Before you have to find the item by its code and then edit it
var obj = {"items":[{"Code":"c101","Desc":"Car"},{"Code":"c341","Desc":"House"}]};

function getItemByCode(code){

    for(var i in obj.items){
        var item = obj.items[i];
        if(item.Code === code){
            return item;
        };
    };
}

var item = getItemByCode('c341');

item.Desc = "new desc"

This solution works with IE9+ and others browsers

A: Have you tried:

var json_string = '{"items":[{"Code":"c101","Desc":"Car"},{"Code":"c341","Desc":"House"}]}';
var json = JSON.parse(json_string);

if (json && json.items) {
 json.items = json.items.filter((element, i) => {
  if (element.Code) {
   return element.Code != 'c101';
  }
  return true;
 });
}


text:
Q: what does an item without namespace mean in style <style name="Widget.Styled.ActionBar" parent="Widget.Sherlock.Light.ActionBar.Solid.Inverse">
    <item name="background">@drawable/bg_action_bar</item>
    <item name="android:background">@drawable/bg_action_bar</item>
    <item name="android:textColor">@color/my_red</item>
</style>

<style name="My_Style" parent="style/Theme.Sherlock.Light">
    <item name="android:actionBarStyle">@style/ActionBar</item>
    <item name="android:homeAsUpIndicator">@drawable/ic_action_back</item>
    <item name="homeAsUpIndicator">@drawable/ic_action_back</item>
</style>

What is the difference between 'homeAsUpIndicator' and 'android:homeAsUpIndicator' or 'background' and 'android:background' ?
I wonder if I need to set them both? I just found these examples, but could not find what you are setting when you don't use the 'android' namespace...

A:
Due to limitations in Android's theming system any theme
  customizations must be declared in two attributes. The normal
  android-prefixed attributes apply the theme to the native action bar
  and the unprefixed attributes are for the custom implementation. Since
  both theming APIs are exactly the same you need only reference your
  customizations twice rather than having to implement them twice.

The easiest way to convey exactly what this entails is with an example. The following is the full theme from the "Styled" example mentioned above:
<style name="Theme.Styled" parent="Theme.Sherlock.Light.DarkActionBar">
    <item name="actionBarStyle">@style/Widget.Styled.ActionBar</item>
    <item name="android:actionBarStyle">@style/Widget.Styled.ActionBar</item>
</style>

Read more about ActionbarSherlock's Mirrored Attributes


text:
Q: querying posts by custom taxonomy terms right from a querystring based URL The following URL seems to work for cats and tags only.
yoursite.com?cat=2&tag=bread1+bread2
what if you wanted to get into custom taxonomy and terms and do something similar?
is there an equivalent to something like the following?
yoursite.com?taxonomy=food&tag=bread1+bread2

A: This should work :
  yoursite.com/taxonomyname/bread1,bread2

So for example, on my site, I actually use :
 mysite.com/location/barcelona,paris

And I get a list of all posts tagged with Barcelona or Paris


text:
Q: IntelliJ introductory examples gives compile errors I am following IntelliJ IDEA's introduction to Android (using v 12.1.6):
http://confluence.jetbrains.com/display/IntelliJIDEA/Make+the+application+interactive
In section 3 it asks you to use add the following event handler:
private void InitializeApp()
{
message = (TextView) findViewById(R.id.message);
droid = (ImageView) findViewById(R.id.imageView);

// Define and attach listeners
droidTapListener = new View.OnClickListener()  {
    public void onClick(View v) {
       TapDroid();
    }
};
droid.setOnClickListener(droidTapListener);
}

but this just leads to these compile errors:
java: cannot find symbol
 symbol:   variable droidTapListener
 location: class com.example.app2.MyActivity
java: cannot find symbol
symbol: method TapDroid()
  java: cannot find symbol
  symbol:   variable droidTapListener
  location: class com.example.app2.MyActivity

I suspect the documentation is out of date, but can someone explain how to fix this?
Thanks,
Mark

A: You missed the two lines just before:
private View.OnClickListener droidTapListener;

You add this member to the class MyActivity and initialize it in the InitializeAppmethod


text:
Q: Post from my app appears on the page's wall, but the users who liked that page can't see in their newsfeed I have a facebook app to post on my fan page, it works perfectly.
My problem is when I post on my fan page with my app, the new post appears on the page's wall, but the users who liked that page can't see in their newsfeed...
Is there a new Graph API restriction or something like that?
I wrote my app with the facebook's PHP sdk.
Thanks a lot.

A: Well, I think I found the problem...
When a facebook's user press the "like" button in your fan page automatically is checked the "Show in news feed"  option and then the user is able to receive the new posts from your facebook page in his wall. In my case (I don't know why) the "Show in news feed"  option is not automatically checked, the user needs to mark manually the option to recieve my new post from my fan page.
Here is some articles about this topic:
http://antoniocalero.com/2012/08/24/show-in-news-feed-myth/
http://alwaysupward.com/blog/fb-fans-arent-seeing-your-posts-and-how-to-fix-it/comment-page-2/
I hope this helps someone.
And I'm sorry for my bad English.


text:
Q: Как правильно обработать данную строку? Есть строка:
asdasd@asd.ru:sdfjsf\r\nasdasdasd@asdasd.ru:jsdgj\r\nasdashsdfh@asdasd.ru\r\nfhksdfjhsdfjh@asd.ru:djhsdfj

Ее нужно обработать с помощью js, чтобы после обработки она была в виде массива, где будут лежать данные для каждой строки в таком виде:
[
    {'email' : '1email', 'password' : 'adgshs'},
    {'email' : '1email', 'password' : 'adgshs'}
]

Как это сделать?
Понимаю, что это, скорее всего, нужно делать с помощью split, но не понимаю, как :(

A: как-то вот так:

var str = 'asdasd@asd.ru:sdfjsf\r\nasdasdasd@asdasd.ru:jsdgj\r\nasdashsdfh@asdasd.ru\r\nfhksdfjhsdfjh@asd.ru:djhsdfj';
var object = str.split('\r\n').map(function (val) {
    var obj = val.split(':');
    return {email: obj[0], password: obj[1]};
});
console.log(object);


text:
Q: "Not found" returned when creating RabbitMQ queue using rabbitmqadmin I need to create a RabbitMQ queue from command line.

*

*I have a RabbitMQ setup in kubernetes.

*I login into a RabbitMQ pod and fetch the rabbitmqadmin for my version 3.8.14

*I run this:

./rabbitmqadmin -u user1 -p password1 -N rabbit@rabbitmq-0.rabbitmq.default.svc.cluster.local declare queue name=CompName.Player1
But instead of adding the queue I get:
**Not found: /api/queues/%2F/CompName.Player1
I tried these but had no success, also the rabbitmq log shows no events when running these rabbitmqadmin commands:
 ./rabbitmqadmin declare queue name=Test1
./rabbitmqadmin -u user1 -p password1 declare queue name=CompName.Player1
curl -i -u user1:password1 -H "content-type:application/json" -XPUT -d'{"durable":true}' http://localhost:15672/api/queues/%2f/CompName.Player1
Adding the queue manually via management web UI works but it's not an option for a kubernetes solution.

A: I got it. I think at some point the API endpoint got updated so all calls must go to http://localhost:15672/rabbitmq/api. Here's the configuration line that was added that caused the issues:
management.path_prefix = /rabbitmq

Here are the working examples:
./rabbitmqadmin -u user1 -p password1 --path-prefix=http://localhost:15672/rabbitmq declare queue name=CompName.Player1
curl -i -u user1:password1 -H "content-type:application/json" -XPUT -d'{"durable":true}' http://localhost:15672/rabbitmq/api/queues/%2f/CompName.Player1
Also this worked:
import pika
import sys
connection = pika.BlockingConnection(
    pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.queue_declare(queue='CompName.Player1', durable=True)
connection.close()```


text:
Q: Api Maps Offline Boa noite pessoal, tudo bem?
Gostaria de saber se teria como meu aplicativo abrir o mapa quando o usuário estiver sem internet ?

A: Olá! Sim, tem como fazer usando o maps api, criando seus próprios tiles e usando o TileProvider para manipulá-los.
Mas o próprio Google não encoraja muito a fazer isto em seus termos de serviço. "No caching or storage."
Uma solução open source é utilizar o OpenStreetMaps com tiles de mapa.
Aqui tem as ferramentas para usar o OSM no Android:
https://github.com/osmdroid/osmdroid
E aqui a ferramenta para você baixar os tiles:
http://mobac.sourceforge.net/
É isto. ;)


text:
Q: Get previous props value with React Hooks I am using usePreviousValue custom hook to get previous props value from my component:
const usePreviousValue = value => {
  const ref = useRef();
  useEffect(() => {
    ref.current = value;
  });
  return ref.current;
};

const MyComponent = ({ count }) => {
   const prevCount = usePreviousValue(count)

   return (
 {count} | {prevCount}
)
}

But in this case, in prevCount I always have only the first count prop value when a component was rendered, and the next updated prop value is never assigned to it. Are there any ways to properly compare nextProp and prevProp with functional React components?

A: Your code sample seems to be working just fine. How exactly are you using the component? Try to run the snippet below:

const { useEffect, useRef, useState } = React;

const usePreviousValue = value => {
  const ref = useRef();
  useEffect(() => {
    ref.current = value;
  });
  return ref.current;
};

const MyComponent = ({ count }) => {
   const prevCount = usePreviousValue(count);

   return (
 {count} | {prevCount}
);
}

function App() {
  const [count, setCount] = useState(0);

  return (

      <MyComponent count={count} />
      <button
        onClick={() => setCount((prevCount) => prevCount + 1)}
      >
        Count++
      </button>

  );
}

ReactDOM.render(<App />, document.body);

A: As previously answered, the easiest way to do it is using a custom hook:

import isEqual from "lodash/isEqual";
import { useEffect, useRef } from "react";

const useComponentDidUpdate = (callback, data, checkIfIsEqual) => {
    const prevData = useRef(data);

    useEffect(() => {
        const isTheSame = checkIfIsEqual ? isEqual(data, prevData) : undefined;
        callback(prevData.current, isTheSame);
        prevData.current = data;
    }, [data]);

    return null;
};

export default useComponentDidUpdate;

Then in your component:

const Component = ({age})=>{
const [state, setState] = useState({name: 'John', age})

useComponentDidUpdate(prevStateAndProps=>{
if(prevStateAndProps.age !== age || prevStateAndProps.state.name !== state.name){
   // do something
}

}, {state, age})

...
}


text:
Q: Camera properties for 3d using specular reflection Could any one help in clarifying the following description taken from the article "Local Shape from Mirror Reflection" by Savarese, Chen and Perona.
"Let c be the center of projection of the camera. The image plane is positioned l distance units in front of c, perpendicular to the view direction v. Given a scene point p let q be the image of p observed on the image plane through a specular reflection on the mirror surface at r."

*

*To my understanding both c, v and l are properties of the camera, so how can I find them?

*As p moves along the scene plain q and r shift respectively are c,v and l constant or should a new center of projection, image plane and view direction be calibrated separately for each point?

Image for the setup of the system:

A: C and v are not intrinsic properties of the camera, they are just its location and orientation. However, l is the focal length, which is an intrinsic parameter. Both intrinsic and extrinsic parameters can be recovered through a calibration procedure. If you like matlab, google for Jean-Yves Bouguet's camera calibration toolkit. It has also been ported to OpenCV since forever, if you'd rather C or C++.
The extrinsic parameters change only if the camera is moved relative to the scene. The intrinsic ones change if anything in the lens is changed, e.g. by refocusing or changing the aperture (the f-stop). Neither change with the exposure time (it only affects how many photons reach the sensor).
Note that with today's lens mounts (screw, bayonet) and sensor sizes and resolutions (a few tens of mm and several megapixels across) it's very easy to "move" the camera: just touching the lens is often enough to move its center by a few pixels and its axis by a few minutes of arc. If repeatability is paramount you may want to look into getting a special/custom lens mounts and very rigid camera stand/support. In any case your software will need to be robust with respect to small camera motions


text:
Q: Routing a get request to a module controller I what to route a request
/cart

to a controller in a module
Customer::CartController

after looking in the rails documentation the line of code in the routes.rb should be
get "cart" => "cart#index", :module => "customer", :as => :cart

but for some reason is not working. It keeps showing uninitialized constant CartController
Any idea how can i do this ?

A: :module => 'customer' should go to the scope call:
scope :module => "customer" do
  get "cart" => "cart#index", :as => :cart
end

A: Also
get "cart" => "customer/cart#index", :as => :cart


text:
Q: django/drf: many-to-many, serializer, duplicates I have M2M relationship between models Combo and ComboLinks.
User should be able to provide ComboLinks that are gathered by the backend into a one Combo.
This is done with through DRF serializer and it works but with an issue: if a user provides a list of ComboLinks that has one or more ComboLinks already present in the database - duplicate is created.
How can I avoid creating those duplicates and use already present ComboLinks to point to new Combo object?
django model structure:
class Combo(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='searches')
    updated = models.DateTimeField(auto_now = True)

class ComboLink(models.Model):
    combo = models.ManyToManyField('Combo', blank=True, related_name='links')
    title = models.CharField(max_length = 64, null=True, blank=True)

django view:
@api_view(['GET', 'POST', 'PUT', 'DELETE'])
def getCombo(request, pk=None):
    user = request.user
    # for all paths besides create new search
    if (pk != 'new') and (pk != None):
        combo = Combo.objects.get(id=int(pk))
        if user != combo.user:
            return Response('Not valid user for a search', status=status.HTTP_401_UNAUTHORIZED)

    # handle different request methods
    if request.method == 'GET':
        serializer = ComboSerializer(combo, many=False)
        return Response(serializer.data, status=status.HTTP_200_OK)
    if request.method == 'POST':
        data = request.data
        data['user'] = user.id
        combo = Combo.objects.create(user= User.objects.get(id=user.id))

        serializer = ComboSerializer(instance = combo, data = data)

        if serializer.is_valid():
            print('updateSearch: combo serializer IS valid')
            serializer.save()
            combo.save()
        else:
            print('updateSearch: combo serializer NOT valid, failing to save')
            print(serializer.errors)
        return Response(serializer.data, status=status.HTTP_200_OK)

serializers (writeable):
from rest_framework.serializers import ModelSerializer, HyperlinkedRelatedField
from drf_writable_nested.serializers import WritableNestedModelSerializer
from .models import ComboLink, Combo

class ComboLinkSerializer(ModelSerializer):
    class Meta:
        model = ComboLink
        fields = ['title']

class ComboSerializer(WritableNestedModelSerializer):
    links = ComboLinkSerializer(many=True, read_only=False)
    class Meta:
        model = Combo
        fields = ['user', 'id', 'updated','links']

A: I had to abandon saving through DRF serializer because if I link manually existing ComboLinks but pass to serializer.save only new ones then only new ones will be saved since it overwrites data:/
So, only use serializer to verify format and save manually everything
        def check_links(request, combo=None):
        """ if provided link was already present in the db just use it instead of creating a duplicate """
        data = request.data.copy()
        data['user'] = user.id
        if not combo:
            combo = Combo.objects.create(user=request.user)

        for indx, i in enumerate(data['links']):
            if ComboLink.objects.filter(link=i['link']).exists():
                cl = ComboLink.objects.get(link=i['link'])
            else:
                cl = ComboLink.objects.create(title=i['title'], link=i['link'], img=i['img'])
            combo.links.add(cl)

        serializer = ComboSerializer(instance = combo, data = data)
        if serializer.is_valid():
            print('updateSearch: combo serializer IS valid')
            combo.save()
        else:
            print('updateSearch: combo serializer NOT valid, failing to save')
            print(serializer.errors)
        return serializer.data


text:
Q: How to deploy ASP.NET project with Angular 13 frontend to IIS? I am trying to setup the solution for a web application which uses ASP.NET with .NET Framework 4.8 for the backend and Angular 13 for the frontend (we cannot use .NET Core or any newer version because some of the libraries we need to use are only available for .NET Framework).
In the solution, the angular project is in the same folder as the backend project (where the sln file is also located). Now, I created a publish profile for the backend project but it is not yet linked to the angular project in any way, so the output folder only contains the files for the backend. In addition to that, I built the angular frontend via ng build which generated all of the files I need for the frontend in the dist folder.
How can I deploy this to an IIS webserver so users can see and work with the angular frontend and all http requests to the backend are routed to the appropriate controller and action in my ASP.NET application? Are there any tutorials or instructions for this? So far, I was not able to find what I am looking for and I am very confused how I am supposed to make this work in IIS.


text:
Q: Canonical way to checksum downloads in a Dockerfile? I'm creating a Dockerfile that downloads, builds, installs node.js from source.  I'd like to checksum the download before building it, and stop or exit the Dockerfile if the checksum fails:
# officially supported ubuntu
FROM ubuntu:12.04

# SETUP
RUN cd /tmp
RUN apt-get update -y
RUN apt-get install wget build-essential automake -y
RUN wget http://nodejs.org/dist/latest/node-v0.10.26.tar.gz
RUN wget http://nodejs.org/dist/latest/SHASUMS256.txt

# RUN checksum: exit on fail, continue on success
??? how ???

# INSTALL
RUN tar -xvf node-v0.10.26.tar.gz && cd node-v0.10.26
RUN ./configure && make && make install

# CLEANUP
apt-get autoremove --purge wget build-essential automake -y

Has the Docker community settled on a 'best practices' way of doing this?

A: I have set the checksum as a variable
ARG CHECKSUMKUBECTL="51f5679a0cb11a65f25c3479bbfdfd21c4d0acd8814d3cbaf5aaeea7682178a3820c3555b17ea6ee24470ac67ebfd0f78cc98513e5b526436494350be64bda69"

The following throws an exit code when they do not match, and an Ok if they match.
RUN echo "${CHECKSUMKUBECTL}  $BIN_DIR/kubectl" | sha512sum --check

A: If any of the RUN commands return a non-zero code, the build will fail.
FROM fedora
RUN false

In the Dockerfile above, I'm just doing a quick test by running false. false is a linux utility that just sets a non-zero return code, handy for testing. As you can see, when I build that Dockerfile, it complains and fails out.
$ docker build .
Uploading context 12.29 kB
Uploading context
Step 0 : FROM fedora
 ---> 58394af37342
Step 1 : RUN false
 ---> Running in a5b9a4b37e25
2014/04/22 09:41:19 The command [/bin/sh -c false] returned a non-zero code: 1

Now that we know this, if we have the file and checksums in the image (which you appear to have via wget), we can test that they match up. Here is a quick and dirty version of this below, in which I generate a file and calculate its checksum before verifying it. In your example, you would obviously not be doing that, I just do it to show you how this works.
FROM fedora

# Create the text file
RUN echo ThisIsATest > echo.txt

# Calculate the checksum
RUN sha1sum echo.txt > sha1sums.txt

# Validate the checksum (this should pass)
RUN sha1sum -c sha1sums.txt

# Alter the text
RUN echo ThisShouldFail > echo.txt

# Validate the checksum (this should now fail)
RUN sha1sum -c sha1sums.txt

And if we run this...
$ docker build -no-cache .
Warning: '-no-cache' is deprecated, it will be removed soon. See usage.
Uploading context  12.8 kB
Uploading context
Step 0 : FROM fedora
 ---> 58394af37342
Step 1 : RUN echo ThisIsATest > echo.txt
 ---> Running in cd158d4e6d91
 ---> 4088b1b4945f
Step 2 : RUN sha1sum echo.txt > sha1sums.txt
 ---> Running in 5d028d901d94
 ---> c97b1d31a720
Step 3 : RUN sha1sum -c sha1sums.txt
 ---> Running in 44d119897164
echo.txt: OK
 ---> ca01d590cadd
Step 4 : RUN echo ThisShouldFail > echo.txt
 ---> Running in 87b575ac4052
 ---> 36bb5d8cf6d1
Step 5 : RUN sha1sum -c sha1sums.txt
 ---> Running in e20b7ac0c924
echo.txt: FAILED
WARNING: 1 computed checksum did NOT match
2014/04/22 10:29:07 The command [/bin/sh -c sha1sum -c sha1sums.txt] returned a non-zero code: 1

A: 1- Download your file and put it where you need it, then run:
sha256sum /path/to/file

Output:
255d...334  /path/to/file

2- copy the output and put it in your Dockerfile like this: (be careful about spaces between brackets)
RUN [ "255d...334  /path/to/file" = "$(sha256sum /usr/local/bin/confd)" ]

As @Todd mentioned, if the command responds non-zero the build will fail.
you can use sha1sum or sha512sum aswell.


text:
Q: How to rearrange array using spaces? I'm struggling with rearranging my array. I have used from single to multiple loops trying to put spaces (white characters) between two pairs of characters, but I was constantly rewriting the original input. So there is always an input of even length, for example ABCDEFGH. And my task would be to extend the size of the array by putting spaces after every 2 chars (except the last one).
So the output would be:
AB CD EF GH

So the size of output (if I'm correct) will be (2*input_len)-1
Thanks.
EDIT:
This is my code so far
// output = "ABCDEFGHIJKL
char c1;
  char c2;
  char c3;
  int o_len = strlen(output);
  for(int i = 2; i < o_len + olen/2; i = i + 3){
    if(i == 2){
      c1 = output[i];
      c2 = output[i+1];
      c3 = output[i+2];
      output[i] = ' ';
      output[i+1] = c1;
      output[i+2] = c2;
    }
    else{
      c1 = output[i];
      c2 = output[i+1];
      output[i] = ' ';
      output[i+1] = c3;
      output[i+2] = c1;
      c3 = c2;
    }
  }

So the first 3 pairs are printed correctly, then it is all a mess.

A: Presuming you need to store the space separate result, probably the easiest way to go about inserting the spaces is simply to use a pair of pointers (one to your input string and one to your output string) and then just loop continually writing a pair to your output string, increment both pointers by 2, check whether you are out of characters in your input string (if so break; and nul-terminate your output string), otherwise write a space to your output string and repeat.
You can do it fairly simply using memcpy (or you can just copy 2-chars to the current pointer and pointer + 1, your choice, but since you already include string.h for strlen() -- make it easy on yourself) You can do something similar to:
#include <stdio.h>
#include <string.h>

#define ARRSZ 128   /* constant for no. of chars in output string */

int main (int argc, char **argv) {

    char *instr = argc > 1 ? argv[1] : "ABCDEFGH",  /* in string */
        outstr[ARRSZ] = "",                         /* out string */
        *ip = instr, *op = outstr;                  /* pointers to each */
    size_t len = strlen (instr);                    /* len of instr */

    if (len < 4) {  /* validate at least 2-pairs worth of input provided */
        fputs ("error: less than two-pairs to separate.\n", stderr);
        return 1;
    }
    if (len & 1) {  /* validate even number of characters */
        fputs ("error: odd number of characters in instr.\n", stderr);
        return 1;
    }
    if (ARRSZ < len + len / 2) {  /* validate sufficient storage in outstr */
        fputs ("error: insufficient storage in outstr.\n", stderr);
        return 1;
    }

    for (;;) {  /* loop continually */
        memcpy (op, ip, 2);             /* copy pair to op */
        ip += 2;                        /* increment ip by 2 for next pair */
        op += 2;                        /* increment op by 2 for next pair */
        if (!*ip)                       /* check if last pair written */
            break;
        *op++ = ' ';                    /* write space between pairs in op */
    }
    *op = 0;                            /* nul-terminate outstr */

    printf ("instr  : %s\noutstr : %s\n", instr, outstr);
}

Example Use/Output
$ ./bin/strspaceseppairs
instr  : ABCDEFGH
outstr : AB CD EF GH

$ ./bin/strspaceseppairs ABCDEFGHIJLMNOPQ
instr  : ABCDEFGHIJLMNOPQ
outstr : AB CD EF GH IJ LM NO PQ

Odd number of chars:
$ ./bin/strspaceseppairs ABCDEFGHIJLMNOP
error: odd number of characters in instr.

Or short string:
$ ./bin/strspaceseppairs AB
error: less than two-pairs to separate.

Look things over and let me know if you have further questions.

Edit To Simply Output Single-Pair or Empty-String
Based upon the comment by @chqrlie it may make more sense rather than issuing a diagnostic for a short string, just to output it unchanged. Up to you. You can modify the first conditional and move it after the odd character check in that case, e.g.
    if (len & 1) {  /* validate even number of characters */
        fputs ("error: odd number of characters in instr.\n", stderr);
        return 1;
    }
    if (len < 4) {  /* validate at least 2-pairs worth of input provided */
        puts(instr);   /* (otherwise output unchanged and exit) */
        return 0;
    }

You can decide how you want to handle any aspect of your program and make the changes accordingly.

A: I think you are looking for a piece of code like the one below:
This function returns the output splitted array, as you requested to save it.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>

char* split_by_space(char* str, size_t length, size_t step) {
    size_t i = 0, j = 0, spaces = (length  / step);
    char* splitted = malloc(length + spaces + 1);

    for (i = 0, j = 0; i < length; ++i, ++j) {
        if (i % step == 0 && i != 0) {
            splitted[j] = ' ';
            ++j;
        }
        splitted[j] = str[i];
    }
    splitted[j] = '\0';
    return splitted;
}

int main(void) {
    // Use size_t instead of int.
    size_t step = 2; // Also works with odd numbers.
    char str[] = "ABCDEFGH";
    char* new_str;
    // Works with odd and even steps.
    new_str = split_by_space(str, strlen(str), step);
    printf("New splitted string is [%s]", new_str);
    // Don't forget to clean the memory that the function allocated.
    free(new_str);
    return 0;
}

When run with a step value of 2, the above code, outputs:
New splitted string is [AB CD EF GH]

A: Try this,
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

void rearrange(char *str)
{
    int len=strlen(str),n=0,i;
    char *word=malloc((len+(int)(len/2)));

    if(word==NULL)
    {
       printf("Memory Error");
       exit(1);
    }

    for(i=0;i<len;i++)
    {
        if( i % 2 == 0 && i != 0)
        {
            word[n]=' ';
            n++;
            word[n]=str[i];
            n++;
        }
        else
        {
            word[n]=str[i];
            n++;
        }
    }

    word[n]='\0';
    strcpy(str,word);
    free(word);
    return;
}

int main()
{
     char word[40];

     printf("Enter word:");
     scanf("%s",word);

     rearrange(word);

     printf("\n%s",word);

     return 0;
 }

See Below:
The rearrange function saves the letters in str into word. if the current position is divisible by 2 i.e i%2 it saves one space and letter into str, otherwise it saves letter only.

A: Inserting characters inside the array is cumbersome and cannot be done unless you know the array is large enough to accommodate the new string.
You probably want to allocate a new array and create the modified string there.
The length of the new string is not (2 * input_len) - 1, you insert a space every 2 characters, except the last 2: if the string has 2 or fewer characters, its length is unmodified, otherwise it increases by (input_len - 2) / 2. And in case the length is off, you should round this value to the next integer, which is done in integer arithmetics this way: (input_len - 2 + 1) / 2.
Here is an example:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char *reformat_with_spaces(const char *str) {
    size_t len = strlen(str);
    size_t newlen = len > 2 ? len + (len - 2 + 1) / 2 : len;
    char *out = malloc(newlen + 1);

    if (out) {
        for (size_t i = 0, j = 0; i < len; i++) {
            if (i > 0 && i % 2 == 0) {
                out[j++] = ' ';
            }
            out[j++] = str[i];
        }
        out[j] = '\0';
    }
    return out;
}

int main(void) {
    char buf[256];
    char *p;
    while (fgets(buf, sizeof buf, stdin)) {
        buf[strcspn(buf, "\n")] = '\0';  // strip the newline if any
        p = reformat_with_spaces(buf);
        if (p == NULL) {
            fprintf(stderr, "out of memory\n");
            return 1;
        }
        puts(p);
        free(p);
    }
    return 0;
}


text:
Q: Update all rows in MySQL where DATETIME has passed What I'm trying to achieve is a scheduled release for articles. I need to write a PHP script that changes a (MySQL) field on every row where a DATETIME column value has passed.
For example: I have a column named release that is the type of DATETIME. Say the release on row X is 2017-03-10 21:48:52. The time now is 2017-03-10 22:01:34. That means the time on the field release on row X has passed. That means I wish to update a field on this row.
How can I create a WHERE statement that finds every row with a passed time.
I think this should be very simple but after a while of searching I couldn't find an answer that would work for me.

A: Use a simple comparison operator and NOW() function:
// releases is your table name
// release_date is your field
UPDATE releases WHERE release_date < NOW()

It will update all fields that have release_date less than (before) current date and time.


text:
Q: how to generate sql query for the summation of specific column and then rank it i have a table mark_summery, Here is my table structure

now i just want to sum the "obt_marks" and "total_marks" of specific student with multiple exams (maximum four). "multiple exams mean summation of four exams " how can i sql it. any idea.?

A: Try using this code
select s.StudentID, s.name, sum(marks)
from tbl_marks m inner join tbl_student s
on m.studentid=s.studentid
group by s.studentid
having sum(marks)=
(
select max(tbl.totalmarks) from
(select studentid, sum(marks) as totalmarks from tbl_marks group by studentid) tbl
)

Try using this code

A: You could use sum group by on a subqyery for the number of exam for each student
select student_id, sum(obt_marks), sum(total_marks)
from my_table
inner join (
    select student_id, count(exam_id) num_exam
    from my_table
    group by student_id
 ) t on t.student = my_table.student_id and t.num_exam <= 4
 group by student_id

A: You could create a metod which fetches the data and into you're controller you could sum it with a foreach
    $user = $this->User_model->total_activity($id);
    $sum = 0;

    foreach ($user as $key) {
         if ($key['db_field'] !== null) {
            $sum += $key['db_field']);
         }
    }
    return $sum;


text:
Q: WIX and removing .InstallState file I have written my first setup program using WIX (version 3.6). When uninstalling the application, an .InstallState file gets left behind in the app folder. Is this supposed to be removed, and if so, what do I need to add to my script to remove it?
I've searched extensively but haven't really come up with anything.

A: If this file is installed with your application, it should be removed automatically on uninstall.
If this file is created later, then you should add RemoveFile element with On="uninstall" into a corresponding component.


text:
Q: Laravel one to many relationship insert data I have two tables notification and alerFrequency. they have a one to many relationships respectively. the notification_id is a foreign key in the alerFrequency table. Both tables have models. now what I am trying to do is, to automatically  insert data into the alertFrequency table if website is add in the notification table. this is the notification table
<?php
namespace App;
use App\Status;
use App\Notification;
use App\AlertFrequency;

use Illuminate\Database\Eloquent\Model;

class Notification extends Model
{
    protected $fillable = ['id','website_url','email','slack_channel','check_frequency','alert_frequency','speed_frequency','active'];
    public function statuses(){
        return $this->belongsToMany('App\Status')->withPivot('values')->withTimestamps();
    }
    public function alertFrequencies(){
        return $this->hasMany('App\AlertFrequency');
    }
    public  function alert(){
        $alert_timestamp = AlertFrequency::with('notification')->orderBy('created_at','desc')->select('created_at')->first();
        $alert_timestamp=$alert_timestamp->created_at->toDateTimeString();
        if($alert_timestamp==null){
            return false;
        }
            return $alert_timestamp;    }

and in the guzzle controller, I am using 3 functions: the add function to add a new alertFrequency into the table (which is not working at all) and the I called it in the sendnotification function, so that if it is time to send notification, it will add a new created_at in the alerFrequency table. Here is the guzzle controller
<?php
namespace App\Http\Controllers;

use \GuzzleHttp\Client;
use App\Utilities\Reporter;
use GuzzleHttp\Exception\ClientException;
use App\Notification;
use App\Status;
use App\Setting;
use Carbon;
use App\AlertFrequency;
class GuzzleController extends Controller
{
    private $default_check_frequency;

    protected $client;

    protected $reporter;

    public function __construct()
    {
        $this->client = new Client();

        $this->reporter = new Reporter;

        $this->default_check_frequency = Setting::defaultCheckFrequency();
    }

    private function addStatusToNotification(Notification $notification, Status $status, $resCode)
    {
        $notification->statuses()->attach($status, [
            'values' => strval($resCode)
        ]);
    }
    /*function to add new time stamp into the alertFrequency table*/
    private function add(Notification $notification, AlertFrequency $alert){
        $notification->alertFrequency()->save();
    }

    private function report(Notification $notification, $resCode)
    {
        if(empty($resCode)){
            $resCode = "no response found";
        }

        $status = Notification::health($resCode);
        $this->reporter->slack($notification->website_url . ':' . '  is '. $status . ' this is the status code!' . ' @- ' .$resCode, $notification->slack_channel);
        $this->reporter->mail($notification->email,$notification->website_url.' is '. $status . ' this is the status Code: '. $resCode);
    }

    private function sendNotification(Notification $notification, $status_health, $alert_frequency, $resCode,$alert)
    {
        echo "elpse time alert";
        var_dump(\Carbon\Carbon::parse($alert)->diffInMinutes());
        // If this is the first time we check, OR if the status changed from up to down and vice versa, notify!!!
        if (empty($status_health['timestamp']) || Notification::health($resCode) <> Notification::health($status_health['value'])){
            $this->report($notification,$resCode);
            return;
        }

        // If the website is (still) down and the alert frequency is exceeded, notify!!!
        if(Notification::health($resCode) === 'down' && \Carbon\Carbon::parse($alert)->diffInMinutes() >= $alert_frequency){
            $this->report($notification,$resCode);
            $this->add($notification,$alert);
        }
    }

    public function status()
    {
        $notifications = Notification::where('active', 1)->get();
        //$alert = AlertFrequency::
        $status = Status::where('name', 'health')->first();

        foreach ($notifications as $notification) {
             $frequency = $this->updateStatus($notification, $status);
        if (!empty($frequency)) {
            $notification->alertFrequencies()->create([
                'notification_id' => $frequency
            ]);
        }
        }
    }

    private function updateStatus(Notification $notification, Status $status)
    {
        $status_health = $notification->status('health');
        $check = empty($status_health['timestamp']);
        $elapsed_time = $check ? 10000 : \Carbon\Carbon::parse($status_health['timestamp'])->diffInMinutes();

        $check_frequency = $this->getCheckFrequency($notification);

        /* create an attachemtn in to the alerFrequenct table*/
        $alert = $notification->alert();
        var_dump($alert);

        if ($check || $elapsed_time >= $check_frequency) {
            $resCode = $this->getStatusCode($notification->website_url);

            $this->addStatusToNotification($notification, $status, $resCode);

            $this->sendNotification(
                $notification,
                $status_health,
                $this->getAlertFrequency($notification),
                $resCode,
                $alert
            );

        }
    }
    private function getCheckFrequency(Notification $notification)
    {
        return isset($notification->check_frequency)
        ? intval($notification->check_frequency)
        : $this->default_check_frequency;
    }
     private function getAlertFrequency(Notification $notification)
    {
        return isset($notification->alert_frequency)
        ? intval($notification->alert_frequency)
        : $this->default_check_frequency;
    }

    private function getStatusCode($url)
    {
        try {
            $response = $this->client->get($url, [
                'http_errors' => false
            ]);
            return $response->getStatusCode();
        } catch (\GuzzleHttp\Exception\ConnectException $e) {

        }
    }
}


text:
Q: Linux Grant Android Studio (AVD) permissions /dev/kvm (Permissions Denied) I'm confused with how to give permissions to Android Studio to install Virtual Devices through AVD manager.
I tired to add permissions to the folder and relogged-in without success. I'm also confused with commands regarding group and username; am I suppose to substitute username with name of user.
Currently if I do theses commands I get
ls -al /dev/kvm
crw-rw---- 1 root root 10, 232 May  7 20:23 /dev/kvm

grep kvm /etc/group
I get nothing printed

So, I know there is no group. I don't want to give privilages to root just the user name for example "blade".
I also checked with the device supports KVM
egrep -c '(vmx|svm)' /proc/cpuinfo
8
kvm-ok
8

Thanks!

A: First, you'll need to install the qemu-kvm package. For Debian/Ubuntu:
sudo apt install qemu-kvm

Next, add your user to the kvm group:
sudo adduser <username_here> kvm

Finally, log out and log back in or reboot your computer for the changes to take effect.
See complete tutorial at https://www.linuxslaves.com/2018/10/fix-android-studio-devkvm-device-permission-denied-ubuntu.html

A: Update VT from Bios Setting

*

*Power on the system and press[delete] key to enter BIOS [EZ Mode]

*Press [F7] key to enter BIOS [Advance Mode] as below picture:
(If press [delete] key to enter [Advanced Mode] directly and then no need to press [F7] key any more)

*Select  [Advanced] page and click [CPU Configuration] item

*Select [Intel(VMX) Virtualization Technology] item and set to [Enabled]

*Press [F10] key and click [OK] ,the system will auto reboot


text:
Q: Plot abscissa points I have been instructed to plot abscissa points. This is new to me, even the concept is alien to me. I have a set of data, where S is the x-axis and res the y-axis. The goal is to plot a figure where the y-values are abscissa points with step size 1. I hope I make myself clear as this is new vocabulary for me. This picture below show what I want, but for the case of 3 different results.

My data is
S   res
0.0609  6.7704
0.2329  6.2444
0.2450  6.2129
0.3614  5.9381
0.3695  5.9208
0.3874  5.8832
0.5407  5.5962
0.6937  5.3617
0.8068  5.2139
0.8800  5.1277
0.9417  5.0601
1.0426  4.9583
1.0596  4.9421
1.3909  4.6730
1.7260  4.4673
1.7819  4.4379
1.8029  4.4271
2.3595  4.1906
3.5557  3.8780
3.8134  3.8310
3.9931  3.8011
4.1521  3.7764
4.2312  3.7646
4.3542  3.7471
4.8955  3.6785
5.0500  3.6612
5.3198  3.6329
5.4694  3.6183
5.5042  3.6150
5.6136  3.6048
5.9022  3.5795
5.9254  3.5776
6.2234  3.5538
6.5877  3.5272
6.7547  3.5158
6.8985  3.5064
6.9526  3.5030
7.3203  3.4808
7.3491  3.4791
7.6427  3.4628
7.8028  3.4544
7.8861  3.4501
8.2681  3.4316
8.6863  3.4130
8.8786  3.4049
9.1432  3.3944
9.3339  3.3871
9.4376  3.3832
9.6991  3.3739
10.1324 3.3593
10.3367 3.3528
10.3872 3.3513
10.4576 3.3491
10.8189 3.3384
10.9081 3.3359
11.2106 3.3276
11.3095 3.3250
11.3511 3.3239
11.4378 3.3216
11.6254 3.3168
11.6436 3.3164
12.0040 3.3076
12.0999 3.3053
12.7600 3.2907
12.9767 3.2862
12.9839 3.2860
13.2933 3.2799
13.5121 3.2756
13.7759 3.2707
14.1185 3.2646
14.9172 3.2513
15.2656 3.2459
15.3575 3.2445
15.8158 3.2379
15.9012 3.2367
15.9566 3.2359
16.4394 3.2294
16.8287 3.2244
17.0825 3.2212
17.5011 3.2162
17.5183 3.2160
17.8230 3.2125
18.0421 3.2101
18.2244 3.2081
18.2769 3.2075
18.5387 3.2047
19.0181 3.1998
19.2317 3.1977
19.3171 3.1969
19.3596 3.1965
19.7607 3.1927
20.2166 3.1885
20.5085 3.1860
21.6216 3.1768
21.8692 3.1749
22.1848 3.1725
22.2096 3.1723
22.3483 3.1713
23.6573 3.1622
24.2929 3.1581
25.0191 3.1537
25.0860 3.1533
25.4832 3.1510
26.0507 3.1479
26.4090 3.1459
27.0138 3.1428
27.1195 3.1423
27.3474 3.1411
27.6732 3.1395
27.9499 3.1382
27.9999 3.1379
28.3672 3.1362
28.6554 3.1349
29.0878 3.1329
30.0215 3.1289


text:
Q: Convert string fraction into float We're trying to convert in PostgreSQL something like this:
select '1/2'::float;

ERROR:  invalid input syntax for type double precision: "1/2"
LINE 1: select '1/2'::float;

And actually this works:
select 1/2::float;
  ?column?
----------
    0.5

Are we missing something? We have tried to_number... The only solution we came threw was to use split...

A:
Are we missing something?

Yes, you are.
1/2::float means "the value 1 divided by the value 2 cast as a float".
'1/2'::float means: cast the string '1/2' to a float value - but the / character is invalid for a number constant.
A valid number in SQL consists of the digit 0-9 a dot . for the decimal separator and optionally an e to indicate exponential values (e.g. 1e6 for "one million"). So '1/2'::float is wrong in the same way as '1(2'::float or '1 divided by 2'::float

And before you ask for a function to do that for you, see the following questions for a generic "eval()" function:

*

*Eval Calculation-string: "2 * 3 + 4 * 5" in Postgresql

*Are there any way to execute a query inside the string value (like eval) in PostgreSQL?

*How to evaluate expression in select statement in Postgres

A: Try this:
(Borrowing from https://xzilla.net/blog/2006/Dec/sql-servers-charindex-function-in-postgresql.html and Ross Pressor's answer at Convert fractional string to decimal for SQL Server)
create or replace function charindex(text, text, integer) returns integer as $$
begin
    return
        case
        when strpos(substr($2, $3 + 1), $1) = 0
        then 0
        else strpos(substr($2, $3+1), $1) + $3
        end;
end;
$$ language plpgsql;

create or replace function fraction_to_decimal ( frac varchar(100) ) returns decimal as $$
begin
    return case
        when frac like '% %/%'
            then cast(left(frac, charindex(' ', frac, 1) -1) as decimal) +
                ( cast(substring(frac, charindex(' ', frac, 1) + 1, charindex('/', frac, 1)-charindex(' ',frac,1)-1) as decimal)
                / cast(right(frac, length(frac) - charindex('/', frac, 1)) as decimal) )
        when frac like '%/%'
            then cast(left(frac, charindex('/', frac, 1) - 1) as decimal) / cast(right(frac, length(frac) - charindex('/', frac, 1)) as decimal)
        else
            cast(frac as decimal)
        end;
end;
$$ language plpgsql;

Then: SELECT fraction_to_decimal('1/2');
Also works fine for nulls: SELECT fraction_to_decimal(null);


text:
Q: Phone list c# (Reading from a file)
This is a pretty simple program. It IS a homework project. The program should start, read a .txt file, populate the name list and when you click on the name, the phone number is displayed. I have it coded, no errors, no warnings. It will not read the .txt file and I can't figure out why. I've been scouring my book, youtube, even here, but can't pin it down. Any help would be appreciated. Here is my current code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

namespace Phonebook
{
    struct PhoneBookEntry
    {
        public string name;
        public string phone;
    }
    public partial class Form1 : Form
    {
        // FIeld to hold a list of PhoneBookEntry objects.
       private List<PhoneBookEntry> phoneList = new List<PhoneBookEntry>();

        public Form1()
        {
            InitializeComponent();
       }

        // The ReadFile method reads the contents of the
        //PhoneList.txt file and tores it as PhoneBokeEntry
        // objects in the phoneList.
        private void ReadFile()
        {
            try
            {
                StreamReader inputFile;  // To read the file
                string line;             // To hold a line from the file

                // Create an instance of the PhoneBookEntry structure.
                PhoneBookEntry entry = new PhoneBookEntry();

                // Create a delimiter array.
                char[] delim = { ',' };

                // Open the PhoneList file.
                inputFile = File.OpenText("PhoneList.txt");

                // Read the lines from the file.
                while (!inputFile.EndOfStream)
                {

                    // Read a line from the file.
                    line = inputFile.ReadLine();

                    // Tokenize the line
                    string[] tokens = line.Split(delim);

                   // Store the tokens in the entry object.
                    entry.name = tokens[0];
                    entry.phone = tokens[1];

                // Add the entry object to the List.
                phoneList.Add(entry);
                }
            }
            catch (Exception ex)
            {
              // Display an error message.
               MessageBox.Show(ex.Message);
            }
        }
        // The DisplayNames method displays the list of names
        // in the namesListBox conrol.
        private void DisplayNames()
        {
            foreach (PhoneBookEntry entry in phoneList)
        {
            nameListBox.Items.Add(entry.name);
            }
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            // Read the PhoneList.txt file.
            ReadFile();

            // DIsplay the names.
            DisplayNames();
        }

        private void nameListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Get the index of the selected item.
            int index = nameListBox.SelectedIndex;

            // Display the corresponding phone number.
            phoneLabel.Text = phoneList[index].phone;
        }

         private void exitButton_Click(object sender, EventArgs e)
        {
            // close the form.
            this.Close();
        }

    private void Form1_Load_1(object sender, EventArgs e)
    {

    }
}

}


text:
Q: Why is the message of the shutdown pop-up cut off? I am working on a prank Program that randomly reboots your pc while also doing other stuff.
Anyways, I am currently working on the reboot part and I came up with this command:
shutdown -g -t 30 -d p:2:18 -c "Dieser Computer wurde von einer externen Quelle übernommen und wird momentan infiziert mit dem WannaCry Virus. Um nicht-autorisierten Zugriff auf anderen Computern in diesem Netzwerk zu vermeiden starten wir nun Ihr Gerät neu." -f

My Problem is that the text is being cut off because of no particular reason. This is what the pop-up looks like:
The Pop-Up
I did some research on why this could happen, but I see no reason.
/c "comment":   This command option allows you to leave a comment describing the reason for the shutdown or restart. You must include quotes around the comment. The maximum length of the comment is 512 characters.
Source: https://www.lifewire.com/shutdown-command-2618100
Does anyone know why this could happen?
Thanks in advance
TRG

A: Interesting, I can reproduce using an even shorter message like "nicht-auto" or "n-a". Perhaps it interprets "-a" like a new parameter, despite being quoted. If you remove the dash "-", it works. Looks like a bug to me.
A workaround is to replace the dash by an alternative Unicode character:
shutdown -g -t 30 -d p:2:18 -c "nicht$([char]0x2010)autorisierten" -f


text:
Q: How to deserialize a XMLSerializer object with ByteArrayOutputStream as Output I have a code like this to make a serialize xml file:
private byte[] bytes;
...
OutputStream byteArrayOutputStream = new ByteArrayOutputStream();
XmlSerializer newSerializer = Xml.newSerializer();
newSerializer.setOutput(byteArrayOutputStream, "utf-8");
newSerializer.startDocument("utf-8", null);
newSerializer.startTag(null, "playlist");
newSerializer.attribute(null, "version", "1.0");
...
put all my XML tags
...

newSerializer.endTag(null, "playlist");
newSerializer.endDocument();
this.bytes= byteArrayOutputStream.toByteArray();

What i need to do: convert this byte Array into a XML file again and i don´t know how to do it!

A:
You can change your existing serialisation and deserialisation as follows:

try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream os = new ObjectOutputStream(baos);
        os.writeObject(newSerializer);
        ObjectInputStream oin = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
        return (XmlSerializer) oin.readObject();
    } catch (Exception e) {
        throw new Exception("Exception occurred:" + e.getMessage(), e);
    }


text:
Q: How to check if a value exists in table or not in Java? Can anyone suggest me that how can I check if value entered by user is exist in some specific table or not through javaCode?

A: I'm guessing you need the JDBC tutorial first of all. That will enable you to run SQL against your DB from Java such as:
if EXISTS (select *
    from authors
    where name = 'Dan Brown')


text:
Q: How do I move a row from a table in one database to another? So in my program, I have two database.
One is 'CurrentCargo', the other is 'PastOrders'
What I wanted to do is that when the tick box in "CurrentCargo"'s table had been ticked, it will take the variables in the row and move it into the "PastOrders"'s Table.
As shown in the image below:
 Tick in tick box triggers a movement of row values
So this is what I typed for my code:
private void CurrentCargoTable_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        if (e.ColumnIndex == 9 && e.RowIndex >= 0)
        {
            bool Check = Convert.ToBoolean(CurrentCargoTable.Rows[e.RowIndex].Cells[e.ColumnIndex].Value);

            int Index = 0;

            int Code;
            DateTime ImportDate;
            DateTime ExportDate;
            string From;
            string To;
            string TransportMode;
            string Supplier;
            Decimal Cost;
            bool Payed;
            bool Delivered;

            if (Check == true)
            {
                Index = CurrentCargoTable.CurrentCell.RowIndex;

                Code = (int)CurrentCargoTable.Rows[Index].Cells[1].Value;
                ImportDate = (DateTime)CurrentCargoTable.Rows[Index].Cells[2].Value;
                ExportDate = (DateTime)CurrentCargoTable.Rows[Index].Cells[3].Value;
                From = (String)CurrentCargoTable.Rows[Index].Cells[4].Value;
                To = (String)CurrentCargoTable.Rows[Index].Cells[5].Value;
                TransportMode = (String)CurrentCargoTable.Rows[Index].Cells[6].Value;
                Supplier = (String)CurrentCargoTable.Rows[Index].Cells[7].Value;
                Cost = (Decimal)CurrentCargoTable.Rows[Index].Cells[8].Value;
                Payed = false;
                Delivered = false;

                string sql = string.Format("insert into dataGridView1 (Code, Import_Date, Export_Date, From, To, TransportMode, Supplier, Cost, Payed, Delivered) values ('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}');", Code, ImportDate, ExportDate, From, To, TransportMode, Supplier, Cost, Payed, Delivered);
                this.tableTableAdapter1.Insert(sql);
                this.tableAdapterManager1.UpdateAll(this.pastOrdersDataSet);
                dataGridView1.Update();

But it still doesn't work. I tried to use a message box to see if the variables are storing the right values. And every single one is holding the value I wanted. So I kind of get the part of "reading", but I don't get the part of "writing".
Please help me if anyone knows, thank you.

A: The following will will work if there is no previous data (may be you need to check for this before executing)
string sql = string.Format(@"Select * into CurrentCargo  from PastOrders Where
PastOrders.Code = '{0}'", Code);


text:
Q: Count number of elements in a column greater than x but smaller than y I am trying to count the number of elements in column 'xyz' which are smaller than x but larger than y.
a= df['xyz']
df[1/3 < a < 2/3].count()

However, this gives me:

ValueError: The truth value of a Series is ambiguous. Use a.empty,
  a.bool(), a.item(), a.any() or a.all().

A: Subsetting your dataframe is not necessary. Just sum a Boolean series:
res = df['xyz'].between(1/3, 2/3, inclusive=False).sum()

Chained comparisons such as x < a < y work with regular Python scalars, not with Pandas objects, which require vectorised operations.

A: this will give you the df where it's true:
mask = (df['xyz'] > min) & (df['xyz'] <= max)
df = df[mask]

then:
len(df) or df.count() or df.shape[0]

or just:
  sum(mask)

A: a= df['xyz']
df[(a < 2/3) & (a > 1/3)].count()


text:
Q: How to refer dynamic range from another sheet to active sheet cell through VBA I am not getting dynamic range work sheet name in formula. Can anyone assist on this? I get the active sheet range in the formula as =COUNTIF(I3:I31,A3)
Sub Test_DaySumm()

Dim Rg As Range
wksMain.Select
Dim ws1 As Worksheet
Set ws1 = wksMain

If ws1.FilterMode = True Then ws1.ShowAllData
LastRow = ws1.Cells(Rows.Count, "I").End(xlUp).Row
Set MyRange = ws1.Range(Cells(3, 9), Cells(LastRow, 9))

wksDaySummary.Select
xRow = 3
Do Until wksDaySummary.Cells(xRow, 1) = ""
    Set Rg = wksDaySummary.Cells(xRow, 2)
    Rg.Formula = "=COUNTIF( " & MyRange.Address(0, 0) & "," & Rg.Offset(0, -1).Address(0, 0) & ")"
    Rg.Value = Rg.Value
    xRow = xRow + 1
DoEvents
Loop

End Sub

A: Have a look at the Range.Address Property documentary

.Address(RowAbsolute, ColumnAbsolute, ReferenceStyle, External, RelativeTo)

and use the External:=True parameter get get the worksheet name in the address too:
MyRange.Address(RowAbsolute:=False, ColumnAbsolute:=False, External:=True)

So instead of eg I3:I31 the result would be like 'Main Sheet'!I3:I31


text:
Q: How do I go about using a users location when they are in a certain place? The place would trigger an action based on location I'm trying to create an app for android with little experience programming. I want to use a phones gps to determine a place on google maps then cause an action to happen. The action would be based on the location and I'd also like to have the user designate locations to cause an action.
If there are any resources or websites you can point me to I would really appreciate it.
I'm currently only using android studio, is there anything else I need?

A: first, you need the current user location. You can follow the steps offered here to obtain it. The locationmanager provides a method onLocationChanged(Location loc) which then is triggered automatically when the location changes. You can implement your "actions" here. Im not quite sure if I have understood what the designation of locations by the user would have to trigger.
If you want to trigger a specific "action", you can implement the method onMapClicked(Location loc) by setting an onMapClickListener to your map.
Depending on how your "predefined places" are built, you have different possibilities.
1) Are those places points? --> you can calculate the euclidian (or spherical) distances, and related to that distance decide if you want to trigger something or not.
2) are those places 2d rectangles? --> use LatLngBounds and its contains(LatLng point) method to decide if the userlocation or user-designated-location is inside
3) are those places any polygons? here  is a good example on how to create such a place. there is also a contains() method.
4) Are your places not predefined? We need more information on what you want to do in this case.
 edit based upon ur comment :
so you there are 2 things your app should do:
1) do some action (just like popping up a message), when the user is entering a "place" or comming near to a "place"
2) give the user the possibily to create such a place by himself.
secondary can be done by adding a onMapClickListener to your map.
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
        @Override
        public void onMapClick(LatLng latLng) {
            // latLng is the lcoation, tapped by the user on the map. lets save it
            chosen_location = new LatLng(latLng.latitude, latLng.longitude);
        }
    });
}

This will save the single points, tabbed by a user on a map. If you wanna go further later for polygons, you can add this point to an ArrayList of points. However, you probably want the user to add more information about that point. Make use of EditText to let the user e.g. enter a description of that point (or later polygon), and finally, when clicking a button to "save that entered place", you can add it to an ArrayList. You probably also gonna have a server-backend in order to update and retrieve a list of places created by multiple people from anywhere.
but for now, lets go on and check if the user came nearTo such a point or entered such a polygon:
    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 35000, 10, new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            // the users location changed (e.g. he moved some meters)
            current_location = new LatLng(location.getLatitude(), location.getLongitude());
            // somehow get all the places ( i guess a server backend is recommended )
            // for now, lets say all the places are already obtained into an Arraylist called places:
            ArrayList<LatLng> places = new ArrayList<LatLng>;

            // Go check for each of the places, if the users current location is near to such a point
            for (LatLng place : places) {
                if (distance(place,current_location)<100) {
                    LatLng near_place = place;
                    // here we are! near_place is near the users current location, lets do some action
                    Log.d("app","Users location (" + current_location.latitude +","+current_location.longitude+") is near to a place with coordinates "+near_place.latitude+","+near_place.longitude+").");
                }
            }
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    });
}

and here is a method to calculate (spherical) distance in meters between to LatLng objects:
 /**
 * method calculate distance between two LatLng points in meter
 */
public float distance(double lat_a, double lng_a, double lat_b, double lng_b) {
    double earthRadius = 3958.75;
    double latDiff = Math.toRadians(lat_b - lat_a);
    double lngDiff = Math.toRadians(lng_b - lng_a);
    double a = Math.sin(latDiff / 2) * Math.sin(latDiff / 2) +
            Math.cos(Math.toRadians(lat_a)) * Math.cos(Math.toRadians(lat_b)) *
                    Math.sin(lngDiff / 2) * Math.sin(lngDiff / 2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    double distance = earthRadius * c;

    int meterConversion = 1609;

    return new Double(distance * meterConversion).floatValue();
}


text:
Q: open corrupt tar file with python I am downloading tar files from a ftp server with the help of python. However, now I am facing problems and getting the error "ReadError: unexpected end of data". I assume my file got corrupted. I can open the files outside python with the comment 'wget' inside the terminal, however I would like to only stick to python. This is my code:
os.chdir(aod_ipng)
[urlretrieve('%s%s'%(url_ipng,x),'%s'%(x)) for x in ari]

for i in range(len(ari)):
    fileName = '%s'%(ari[i])
    ind = save_ipng[i].index('IVAOT')
    h5f = save_ipng[i][ind:]
    tfile = tarfile.open(fileName,'r|')
    for t in tfile:
        if t.name == '%s'%h5f:
            f = tfile.extract(t)

*

*ari is a string array that holds several names of tar files that needs to be downloaded.

*h5f is the name of the specific h5.gz file that needs to be extracted from the tar file
Let me know if you need more information regarding my code!

A: Reliable downloads of large files over bad connections is not easy. If http range requests are supported then you can resume the download on broken connections.
A good start is to use the requests library and read the remote file as a stream.
However disconnects and resumes might still have to be handled by you.
See this question for how to use that API
But please make sure that the file is indeed a tar. You can use libmagic for file format detection.
That file extension suggests a gzip not a tar.
import gzip
f = gzip.open('h5.gz', 'rb')
file_content = f.read()
f.close()

A: "ReadError: unexpected end of data"
This means that your file is shorter than expected, so it is not fully downloaded.
wget does not open tar files, it downloads files.


text:
Q: Multiple where condition in query MyTable
ID | Name | Type
---+------+-----
1  | asd  | A
2  | zxc  | B
3  | qwe  | A

First query
select ID, TypeA_Name from MyTable Where Type = 'A'

Gives
ID | TypeA_Name
---+-----------
1  | asd
3  | qwe

Second Query
select ID, TypeB_Name MyTable Where Type = 'B'

Gives
ID | TypeB_Name
---+-----------
2  | zxc

I wand TypeA_Name and TypeB_Name in single query a below
select ID, TypeA_Name, TypeB_Name from MyTable

Should Give
ID | TypeA_Name | TypeB_Name
---+------------+-----------
1  | asd        | ---
2  | ---        | zxc
3  | qwe        | ---

Then how can I frame where clause ?  Thanks

A: Try this:
select
    ID,
    case when Type='A' then Name else null end as TypeA_Name,
    case when Type='B' then Name else null end as TypeB_Name
from MyTable

you can use your WHEREs normally eg Where Type = 'A'


text:
Q: Installation of postgresql-15 seems to fail Apologies in advance if this is a stupid question - I am a developer not a sysadmin.
Since running apt-get update/upgrade on my ubuntu VM (Oracle VirtualBox) I cannot seem to get my postgresql database online.  I believe this is may be because postgresql-15 has been upgraded from beta-3 to beta-4.
This is a real nuisance for me because it has trashed our development environment. (I am assuming when we are ready to release 15 will be fully available and I would really like to be able to use merge statements in my code)
I wiped postgresql from the host and am now attempting a fresh install following these instructions.
At Step 3. sudo -u postgres psql  I receive the follwing error : psql: error: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory Is the server running locally and accepting connections on that socket?
which, essentially, is the problem I was faced with after the failed upgrade (despite having run systemctl start postgresql)
Can anyone advise what it is I need to do to get postgres-15 (preferably beta-4) up and running?

hugh@ububtuvm:~$ systemctl status postgresql
● postgresql.service - PostgreSQL RDBMS
     Loaded: loaded (/lib/systemd/system/postgresql.service; disabled; vendor p>
     Active: active (exited) since Sun 2022-09-18 10:47:19 UTC; 31min ago
    Process: 2349 ExecStart=/bin/true (code=exited, status=0/SUCCESS)
   Main PID: 2349 (code=exited, status=0/SUCCESS)
        CPU: 905us

Sep 18 10:47:19 ububtuvm systemd[1]: Starting PostgreSQL RDBMS...
Sep 18 10:47:19 ububtuvm systemd[1]: Finished PostgreSQL RDBMS.

hugh@ububtuvm:~$ journalctl -xeu postgresql.service
░░ Subject: A stop job for unit postgresql.service has begun execution
░░ Defined-By: systemd
░░ Support: http://www.ubuntu.com/support
░░
░░ A stop job for unit postgresql.service has begun execution.
░░
░░ The job identifier is 1675.
Sep 18 10:47:19 ububtuvm systemd[1]: Starting PostgreSQL RDBMS...
░░ Subject: A start job for unit postgresql.service has begun execution
░░ Defined-By: systemd
░░ Support: http://www.ubuntu.com/support
░░
░░ A start job for unit postgresql.service has begun execution.
░░
░░ The job identifier is 1675.
Sep 18 10:47:19 ububtuvm systemd[1]: Finished PostgreSQL RDBMS.
░░ Subject: A start job for unit postgresql.service has finished successfully
░░ Defined-By: systemd
░░ Support: http://www.ubuntu.com/support
░░
░░ A start job for unit postgresql.service has finished successfully.
░░
░░ The job identifier is 1675.

root@ubuntuvm:/home/hugh# cat /usr/lib/systemd/system/postgresql.service
# postgresql.service is the meta unit for managing all PostgreSQL clusters on
# the system at once. Conceptually, this unit is more like a systemd target,
# but we are using a service since targets cannot be reloaded.
#
# The unit actually managing PostgreSQL clusters is postgresql@.service,
# instantiated as postgresql@15-main.service for individual clusters.

[Unit]
Description=PostgreSQL RDBMS

[Service]
Type=oneshot
ExecStart=/bin/true
ExecReload=/bin/true
RemainAfterExit=on

[Install]
WantedBy=multi-user.target

(installed by apt install)

I found this which contains the following paragraphs.

After updating from an alpha or beta release I get an error about
CATALOG_VERSION After upgrading from an alpha or beta package, I get
an error like:
The database cluster was initialized with CATALOG_VERSION_NO X, but
the server was compiled with CATALOG_VERSION_NO Y. This is because the
PostgreSQL data format can change between alpha releases - and
occasionally even between beta releases if there's a really pressing
need.
If you need to access the old data, you will need to use the package
version you were running before, and use pg_dump or pg_upgrade. The
necessary binaries should have been saved in /var/tmp/postgresql*.
Alternatively, look for the old packages in your
/var/cache/apt/archives.

I am still struggling, though - I have not found the previous version anywhere yet.

A: Ubuntu has some clever support for running multiple postgres instances. The postgresql.service unit is just a dummy unit: it does nothing but run /bin/true. This may seem useless, but it's not! The key is that it is the dependencies of this unit that are important, and those are generated dynamically at boot time by /lib/systemd/system-generators/postgresql-generator.
This looks at all the /etc/postgresql/*/*/postgresql.conf files on your system and uses these to generate instances of the postgresql@.service template unit.
When you install the postgresql-15 package, this should:

*

*Provide the file /etc/postgresql/15/main/postgresql.conf (and other files in that directory), and

*Automatically start the postgresql@15-main.service unit.

I've reproduced this on an Ubuntu 22.04 system, where I started with postgresql-14, then installed postgresql-15 following the link in your question, and now I have:
root@ubuntu:~# systemctl list-units postgresql\*
  UNIT                       LOAD   ACTIVE SUB     DESCRIPTION
  postgresql.service         loaded active exited  PostgreSQL RDBMS
  postgresql@14-main.service loaded active running PostgreSQL Cluster 14-main
  postgresql@15-main.service loaded active running PostgreSQL Cluster 15-main

I can successfully connect to the database, but since here I'm running two different postgres instances I need to specify an explicit port. Looking at the config files in /etc/postgresql/..., I see that my postgres 15 instance is using port 5433, so I run:
root@ubuntu:/# sudo -u postgres psql -p 5433
psql (15beta4 (Ubuntu 15~beta4-1.pgdg22.04+1))
Type "help" for help.

postgres=#

If the Postgresql 15 service fails to start, to see the service status I would run:
systemctl status postgresql@15-main.service

And to see the logs I would run:
journalctl -u postgresql@15-main.service


text:
Q: How to check if a PDF file is corrupted or not in android? I am working on an application where I need to download multiple PDF files from the server and save them and on the print all command in my application I will merge all the PDFs and show print preview.
But the issue is while merging I am facing few files that are corrupted due to not saving correctly or are corrupted in general.
How can I check if the saved file is corrupt or not?


text:
Q: using method of interface in golang from different file I've method which I want to provide some interface to make it more easier to test
This is the function
File A
func readFile(s source) ([]byte, error) {
        p := fs.GetPath()
        file, err := ioutil.ReadFile(p + "/" + s.path + "/" + "rts.yaml")
        if err != nil {
            return yamlFile, fmt.Errorf("erro reading file : %s", err.Error())
        }
        return file, err
    }

Now I add for it struct
type source struct{
    path string
}

And the interface that the readFile is implementing
type fileReader interface {
    readFile(path string) ([]byte, error)
}

And now I need to call this function from another file but Im getting error while doing this
File B
type source struct {
    path string
}

a := source{}

yamlFile, err := readFile(a)

what am I missing here ?

A: Import the package containing the source struct in File A and then use that struct to initialize the variable after that pass the variable to the readFile function.
File B
import A
a := A.Source{}

Because source struct in File A is different from source struct in File B. And source struct of File A is implementing the interface that's why you need to import the source struct and then pass it into the function.
One this should be noticed that to make any struct or function exportable you should start the struct or fucntion name with upper case letter.
File A
// make struct exportable
type Source struct{
    path string
}

implemented the interface which is different from
File B
type source struct{
    path string
}

which does not implemented the interface.
Edited
File A
package main

import (
    "fmt"
    "io/ioutil"
    "os"
)

type Source struct {
    Path string
}

type fileReader interface {
    readOneFile() ([]byte, error)
}

func(s Source) readOneFile() ([]byte, error) {
    cwd, err := os.Getwd()
    file, err := ioutil.ReadFile(fmt.Sprintf("%s/file.txt", cwd))
    if err != nil {
        return nil, fmt.Errorf("erro reading file : %s", err.Error())
    }
    return file, err
}

File B
package main

import (
    "fmt"
)

func main() {
    s := Source{}
    data, err := s.readOneFile()
    if err != nil {
        fmt.Errorf("Error in reading the file")
    }
    fmt.Println(string(data))
}


text:
Q: How does Facebook app handle layout changes when keyboard appears? Facebook app is just amazingly handling UI changes at login screen. Check it out.
No keyboard

With keyboard (notice how need help? and English Change views disappear)

Yes, I do know about the adjustPan and adjustResize settings, but how does Facebook set exactly which views will be visible when keyboard is present?

A: Seems like they are showing/hiding specific text (such as need help or English in example above), when Soft keyboard becomes visible.
Now, in Android, there is No direct way to detect if soft keyboard is visible or not.
Why?
Below is the Answer from Android framework Engineer.

The IME being shown has little meaning, since exactly how the IME
behaves is up to it -- it may be a transparent overlay and not impact
the application, a small strip, or all other kinds of things.
Due to this, the main way you interact with the IME is by setting your
softInputMode to be resizeable so when the IME says it wants to
occlude part of the screen your app's UI will get resized to take that
into account if needed.

But, there are different ways/methods/workarounds by using which Apps (like Facebook) could potentially detect if Soft keyboard is visible or not and based on the outcome, app could show/hide texts/widgets in it's UI.
Method 1:
InputMethodManager imm = (InputMethodManager) getActivity()
            .getSystemService(Context.INPUT_METHOD_SERVICE);

    if (imm.isAcceptingText()) {
        //soft keyboard is shown, so hide "need help" text, for example
    } else {
        //Software Keyboard was not shown;
    }

Method 2:
final View activityRootView = findViewById(R.id.activityRoot);
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(
        new OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                int heightView = activityRootView.getHeight();
                int widthView = activityRootView.getWidth();
                if (1.0 * widthView / heightView > 3) {
                    //Make changes for Keyboard not visible
                } else {
                    //Make changes for keyboard visible
                }
            }
        });

Now both Above mentioned methods does not necessarily works 100% in every situations (as one can expect from non-supported operation way out of SDK)
Facebook may be using any of the above method or who knows, they may have implemented it in different way!

A: editText.setOnFocusChangeListener(new OnFocusChangeListener() {

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        // view/hide whatever you want depending on the hasFocus value
        // hasFocus == true -> keyboard shown
    }
});

A: edittext.post(new Runnable() {
        public void run() {
            edittext.requestFocusFromTouch();
            InputMethodManager lManager = (InputMethodManager) activity
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            lManager.showSoftInput(edittext, 0);
        }
    });


text:
Q: R boxplot how is this manual fill wrong I would like to colour my boxplot variables differently. I looked here and tried the following but the plot boxes are all the standard white colour (i have 6 factors in Type). What should i change?
library(ggplot2)
ggplot(PGcounts, aes(Type, Word)) +
            geom_boxplot() +
            coord_trans(y = "log10") +
            scale_fill_manual(values = c("white","white","white","red","blue","white"))

A: What has to change is
geom_boxplot() +

to
geom_boxplot(fill = c("white","white","white","red","blue","white")) +

and remove
scale_fill_manual(values = c("white","white","white","red","blue","white"))

A: Also you can just change from geom_boxplot() to geom_boxplot(aes(fill=Type)) in you original codes.
ex:
ggplot(PGcounts, aes(Type, Word)) +
        geom_boxplot(aes(fill=Type)) +
        coord_trans(y = "log10") +
        scale_fill_manual(values = c("white","white","white","red","blue","white"))


text:
Q: Selenium table search not returning correct text I'm currently learning how to use selenium in python, I have a table, and I want to retrieve the element but currently facing some trouble.

..

..

      ..

           I want to get the text here

      ..

           I want to get the text here as well

Inside this table, I want to access the text in the bold tag but my program isn't returning the correct number of tr, in fact I'm not even sure if its searching the correct stuff.
I have backtracked my problem from the end text and found that the errors started appearing from the line with comment. (I think the code afterwards is wrong as well but I'm focusing on getting the correct table row first)
My code is:
search_table = driver.find_element_by_id("SearchTable")
search_table_body = search_table.find_element(By.TAG_NAME, "tbody")

trs = search_table_body.find_elements(By.TAG_NAME, "tr")
print(trs) # this does not return correct number of tr)
for tr in trs:
  tds = tr.find_elements(By.TAG_NAME, "td")
  for td in tds:
    href = td.find_element_by_class_name("qtooltip")
    print(href.get_attribute("innerHtml"))

I'm supposed to get the correct number of tr count so I can return the text in the anchor tag but I am stuck. Any help is appreciated. Thanks!

A: You can get all  tags which are children of  tag having class attribute of qtooltip and living inside a table cell using a single XPath selector
//table/descendant::a[@class='qtooltip']/b

Example code:
elements = driver.find_elements_by_xpath("//table/descendant::a[@class='qtooltip']/b")
for element in elements:
    print(element.text)

Demo:

References:

*

*XPath Tutorial

*XPath Axes

*XPath Operators & Functions


text:
Q: html doesn't read my ASP start tag I have .html file with asp code inside.
<html>
<body>
<%
Request.write("hello")
%>
</body>
</html>

and this prints
    <% Request.write("hello") %>
I believe ASP is activated because it works when I renamed it to test.asp.
But What I'm trying to do is to encapsulate the asp code inside of html file.

A:
I believe ASP is activated because it works when I renamed it to test.asp.

Then rename the file to test.asp.
By default server-side code is processed in .asp files, not .html (or any other) files.  Ideally, you don't want to change that as it adds a lot of unnecessary overhead to the web server.  You can configure the web server (depending on the web server) to also process other file types, but again it's not recommended.
Additionally, I believe you meant this:
Response.write("hello")

Writing to the request doesn't really make much sense.


text:
Q: Promises function Use in Nodejs Can't able to understand the promise function, how to deal with it can anyone explain it through a simple example. Tried it through different sites but got confused in it

A: A Promise is a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers to an asynchronous action's eventual success value or failure reason. This lets asynchronous methods return values like synchronous methods: instead of the final value, the asynchronous method returns a promise for the value at some point in the future.
In simple words "A promise is a word taken for some action, the other party who gave the promise might fulfill it or deny it". In the case of fulfilling, the promise gets resolved, and in another case, it gets rejected.
We can create a promise in JavaScript and use it as an upcoming fact to describe few actions. Promises are kind of design patterns to remove the usage of unintuitive callbacks.

A: You can understand it with this example:
 const request = require("request")

function doSomething(url){
   //return promise from here
   return new Promise(function(resolve, reject) {
    request.get(url, function(error, resp, body) {
        if (error) {
            reject(error);
        } else {
            resolve(JSON.parse(body));
        }
    })
  })
 }

function callDoSomething(){
//initialising a promise
let prom = doSomething(url)
//consume it
prom.then(function(res) {
 console.log(res)
})
.catch(function(e){
 console.log(e.message)
})
}

callDoSomething()

You can also go for Promise.all to deal with multiple promise:
let prom1 = doSomething(url1)
let prom2 = doSomething(url2)
let prom3 = doSomething(url3)

Promise.all([prom1,prom2,prom3])
.then(res =>{
   //expected output array
   console.log(res)
 })
.catch(e =>{
  console.log(e.message)
 })


text:
Q: How do I handle special characters in a Perl regex? I'm using a Perl program to extract text from a file. I have an array of strings which I use as delimiters for the text, e.g:
$pat = $arr[1] . '(.*?)' . $arr[2];

if ( $src =~ /$pat/ ) {
   print $1;
}

However, two of the strings in the array are $450 and (Buy now). The problem with these is that the symbols in the strings represent end-of-string and capture group in Perl regular expressions, so the text doesn't parse as I intend.
Is there a way around this?

A: Use quotemeta:
$pat = quotemeta($arr[1]) . '(.*?)' . quotemeta($arr[2]);
if ($src =~ $pat)
    print $1;

A: Try Perl's quotemeta function. Alternatively, use \Q and \E in your regex to turn off interpolation of values in the regex. See perlretut for more on \Q and \E - they may not be what you're looking for.

A: quotemeta escapes meta-characters so they are interpreted as literals.  As a shortcut, you can use \Q...\E in double-quotish context to surround stuff that should be quoted:
$pat = quotemeta($arr[1]).'(.*?)'.quotemeta($arr[2]);
if($src=~$pat) { print $1 }

or
$pat = "\Q$arr[1]\E(.*?)\Q$arr[2]";  # \E not necessary at the end
if($src=~$pat) { print $1 }

or just
if ( $src =~ /\Q$arr[1]\E(.*?)\Q$arr[2]/ ) { print $1 }

Note that this isn't limited to interpolated variables; literal characters are affected too:
perl -wle'print "\Q.+?"'
\.\+\?

though obviously it happens after variable interpolation, so "\Q$foo" doesn't become '\$foo'.


text:
Q: How do I create the following macro
How do I create this where {a}{b}{c} are variables for a possible math formula?

A: How about this?
\documentclass{article}
\usepackage{amsmath} % for \text
\newcommand\test[3]{\text{voor }\left( \begin{array}{@{}c@{\,}} #1 \\ #2 \end{array}\middle|\ \ #3 \right)}
\begin{document}
\[
\test{a}{b}{c}
\]
\end{document}

A: I suggest using the amsmath command \genfrac which will resize as follows:

\documentclass{article}

\usepackage{amsmath}

\newcommand{\test}[3]{\left( \genfrac{}{}{0pt}{}{#1}{#2}\,\middle\vert\, #3\right)}

\begin{document}

\begin{equation*}
  \test a b c
  \quad \scriptstyle \test{a}{b}{c}
  \quad \scriptscriptstyle \test{a}{b}{c}
\end{equation*}
\( \test a b c \)

\end{document}

\genfrac takes six arguments, the first two are delimiters around the "fraction", then next is the thickness of the horizontal dividing line, set to 0pt here to make it invisible, and the last two are the numerator and denominator of the fraction.
If you want to have good control over the enclosing brackets (...) then an alternative definition can be given using the mathtools package:

\documentclass{article}

\usepackage{mathtools}

\DeclarePairedDelimiterX{\test}[3]{(}{)}{\genfrac{}{}{0pt}{}{#1}{#2}\,\delimsize\vert\, #3}

\begin{document}

\begin{equation*}
  \test* a b c\quad \scriptstyle \test* a b c\quad
  \scriptscriptstyle \test* a b c
\end{equation*}
\( \test a b c \)

\begin{equation*}
  \test*{a^X}{b_Y}{c_Z} \quad \test[\Bigg]{a^X}{b_Y}{c_Z}
  \quad \test[\bigg]{a^X}{b_Y}{c_Z}
  \quad \test[\Big]{a^X}{b_Y}{c_Z}
  \quad \test[\big]{a^X}{b_Y}{c_Z}
  \quad \test{a^X}{b_Y}{c_Z}
\end{equation*}

\end{document}

This time you have use \test* for the version with automatic sizing of brackets, \test just gives you ordinary brackets, but you also get the possiblities \test[\big], \test[\Big] etc. where the brackets sizes are explicitly specified.


text:
Q: Load Picker View options from online JSON file I am using Alamofire to grab a JSON file from the internet that would basically look like this but may have more or less values in the future:
["Item 1","Item 2","Item 3"]

My question is, rather than specifying an array of what to use in the UIPicker, how can I have the options from the JSON file loaded in?

A: Grab all the elements to form an array and use that array to fill the picker view and reload it as
    [contentPickerView reloadAllComponents];
    [contentPickerView selectRow:0 inComponent:0 animated:YES];


text:
Q: How to troubleshoot odd Google Analytics data that possibly includes Googlebot? We are a natural foods grocery chain located in Seattle, WA. Our store location pages are among the most viewed pages on our website, including the locations index page that serves as a store locator where you can enter your zip code to find the nearest stores.
Beginning with stats for Tuesday, February 3, 2015, I began seeing suspicious behavior that peaked on Friday, February 6 and continues today and appears to only be affecting our store locator page for our "www." hostname (versus our "m." hostname). Specifically, I observed an unusually high number of views where the source was "(direct)". For the vast majority of these direct views, many of the standard dimensions, such as browser, operating system, region, etc, have a value of "(not set)". So far there have been almost 2,800 page views that match this criteria, with about 260 of them being unique (also odd).
When I looked at the Apache access log, I discovered that there were no where near enough requests for the page in question -- even if I included requests where the user agent is identified as Googlebot, bingbot or Yahoo! Slurp.
Thus far, these anomalies have concerned the page without any query parameters. However, as I was reviewing, I discovered another mystery that also began on February 3. There were a lot of requests with the zip code query parameter set to zip codes outside our market area. Again, the standard dimensions were logged as "(not set)". This time when I looked at the server logs, I did find an equivalent number of requests, but the very surprising thing was the majority were from Googlebot! My first thought was that someone was spoofing Googlebot, but by following Google's documented steps for validating, these seemed legit.
For example, On February 6, there were two requests in the server log for "/locations/index.php?zip=66758&radius=5" (this is the zip for Neosho Falls, KS). The user agent for both was logged as "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)". One request was from 66.249.67.61 and the other from 66.249.67.77.
host 66.249.67.77
77.67.249.66.in-addr.arpa domain name pointer crawl-66-249-67-77.googlebot.com.

host crawl-66-249-67-77.googlebot.com
crawl-66-249-67-77.googlebot.com has address 66.249.67.77

host 66.249.67.61
61.67.249.66.in-addr.arpa domain name pointer crawl-66-249-67-61.googlebot.com.

host crawl-66-249-67-61.googlebot.com
crawl-66-249-67-61.googlebot.com has address 66.249.67.61

And in Google Analytics, there were exactly 2 pages views reported (1 unique) at the same time.
Also odd is that all of these zip code based requests were reporting zero for the number of "Entrances". I then later discovered that these zip code based requests were often the landing pages for the aforementioned suspicious page views with no query parameters.
On February 6, there were only a total of 472 of these zip code requests in Google Analytics, but the server had logged almost 2,000 with Googlebot as the user agent. It appears the bot was running through a long list of zip codes.
I keep thinking to myself there is something obvious I'm missing since Googlebot activity should be excluded from Google Analytics reports. I've posted to the Google Analytics product forum with no replies yet.
I should also add that we're using the classic version of the tracking code, which hasn't been edited recently.


text:
Q: Recursive function call fails to recurse in AWS Lambda - Python3 Im trying to replace python dictionary key with a different key name recursively for which i am using aws lambda with a api endpoint to trigger.
Suprisingly the recursion part fails for weird reason. The same code works fine in local.
Checked cloudwatch logs. No error message get displayed there. Let me know if im missing anything here
EDIT: Related to Unable to invoke a recursive function with AWS Lambda and recursive lambda function never seems to run
### function that is called inside lambda_handler

def replace_recursive(data,mapping):
    for dict1 in data:
        for k,v in dict1.copy().items():
            if isinstance(v,dict):
                dict1[k] = replace_recursive([v], mapping)
            try:
                dict1[mapping['value'][mapping['key'].index(k)]] = dict1.pop(mapping['key'][mapping['key'].index(k)])
            except KeyError:
                continue
    return data

## lambda handler

def lambda_handler(events,_):
    resp = {'statusCode': 200}
    parsed_events = json.loads(events['body'])
    if parsed_events:
        op = replace_recursive(parsed_events,schema)
        resp['body'] = json.dumps(op)
    return resp

Input I pass:
{
  "name": "michael",
  "age": 35,
  "family": {
    "name": "john",
    "relation": "father"
  }
}

In the output, keys in the nested dictionary are not getting updated. Only outer keys get modified

A: Since you're ingesting JSON, you can do the key replacement right in the parse phase for a faster and simpler experience using the object_pairs_hook argument to json.loads.
import json

key_mapping = {
    "name": "noot",
    "age": "doot",
    "relation": "root",
}

def lambda_handler(events, _):
    replaced_events = json.loads(
        events["body"],
        object_pairs_hook=lambda pairs: dict(
            (key_mapping.get(k, k), v) for k, v in pairs
        ),
    )
    return {
        "statusCode": 200,
        "body": json.dumps(replaced_events),
    }

body = {
    "name": "michael",
    "age": 35,
    "family": {"name": "john", "relation": "father"},
}
print(
    lambda_handler(
        {
            "body": json.dumps(body),
        },
        None,
    )
)

prints out
{'statusCode': 200, 'body': '{"noot": "michael", "doot": 35, "family": {"noot": "john", "root": "father"}}'}