text:
Q: How to restrict the visibility/accessibility of a method to sub-package in java 8? I'm trying to understand if we have any option in Java 8 to restrict the visibility/accessibility of a method to sub-package?
For example, if I've a method print() of class A in a package abc. Now, how can i restrict that method to be accessible only in abc's sub-packages like abc.def or abc.def.ijk etc.

A: There is no such feature in the language. One option to achieve this, is to encapsulate the action into a public type and carefully publish it to the intended package. E.g.
package abc;

import java.util.function.Consumer;

import abc.def.B;
import java.lang.Objects;

public class A {
    public static Consumer<A> getPrintAccess(B.AccessToken token) {
        Objects.requireNonNull(token);
        return A::print;
    }

    private void print() {
        System.out.println("privileged action");
    }
}

package abc.def;

import abc.A;

public class B {
    public static class AccessToken {
        /* non-public */ AccessToken() {}
    }

    void someMethod(A object) {
        A.getPrintAccess(new AccessToken()).accept(object);
    }
}

While the method getPrintAccess is publicly visible, it will grant access only to code capable of instantiating abc.def.B.AccessToken. Since its constructor is package-private, only code in package abc.def can do that. Of course, code in that package must not hand out an instance of AccessToken to untrusted code.


text:
Q: basic bit field C I don't know why this code works. it supposed to print out every student which follows chem. but why does a number for instance 21&4(student 123001) evaluate to true while a number like 49&4(123008) doesn't?

A: I think it is due to bit operation AND.
In binary
49 is 110001
 4 is 000100
 & =  000000

So it evaluates to false
wheras
21 is 10101
 4 is 00100
 & =  00100

So you get a non-zero result which is true.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Multi-dimentional array how to get the nested value without foreach loop I got output from one of the WordPress table cells. The following value is displayed.
$allcoinkey=get_option('_transient_mcw-custom-data');
    var_dump($allcoinkey);

and the output:
 [0]=>
  array(2) {
    ["slug"]=>
    string(7) "bitcoin"
    ["keywords"]=>
    string(30) "بیتکوین,بیت کوین"
  }
  [1]=>
  array(2) {
    ["slug"]=>
    string(8) "ethereum"
    ["keywords"]=>
    string(27) "اتریوم,اتاریوم"
  }
}

How do I access keyword values where slug=bitcoin without foreach?

A: i use this sample code:
<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');

$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array);   // $key = 1;
?>

A: You can do it like this:
<?php
$allcoinkey = [
    [
        'slug' => 'bitcoin',
        'keywords' => 'بیتکوین,بیت کوین',
    ],
    [
        'slug' => 'ethereum',
        'keywords' => 'اتریوم,اتاریوم',
    ],
];
$bitcoinKeywords = current(array_filter($allcoinkey, static function (array $cryptoCurrency) {
    return $cryptoCurrency['slug'] === 'bitcoin';
}))['keywords'];

echo $bitcoinKeywords;


text:
Q: Comment Migration Resurrects the Dead If an answer had a comment that was deleted, and a ♦ converts the answer with its comments to a comment, the deleted comment reappears.
Interestingly, the checkbox only appears if there is at least one live comment.

A: Will be fixed in the next deploy.


text:
Q: Wcf 3.5 - Different endpoints with different bindings and SOAP I have a problem... I explored whole internet and I don't know what I'm doing wrong.
Problem: WCF web service, .Net Framework 3.5, 2 different type of clients (Handheld device and usual computer)
What I'm trying to do is to create 2 diferent endpoints, one with basicBinding (For SOAP request) and other with wsBinding (for usual computers)
So I go thru web.config and I created 2 different bindings, related with 2 different endpoints:
<bindings>
  <basicHttpBinding>
    <binding name="BasicBinding" openTimeout="00:10:00" receiveTimeout="23:59:00"
      sendTimeout="23:59:00" messageEncoding="Text" />
  </basicHttpBinding>
  <wsHttpBinding>
    <binding name="DefaultBinding" openTimeout="00:10:00" receiveTimeout="23:59:59"
      sendTimeout="23:59:59">
      <reliableSession inactivityTimeout="01:00:00" />
      <security mode="None">
        <transport clientCredentialType="None" />
        <message clientCredentialType="None" />
      </security>
    </binding>
  </wsHttpBinding>
</bindings>
<services>
  <service behaviorConfiguration="qtswsdl.QTS_ServiceBehavior"
    name="qtswsdl.QTS_Service">
    <endpoint address="http://host.com/service.svc/ForHh"
      binding="basicHttpBinding" bindingConfiguration="BasicBinding"
      name="handHeldEndPoint" contract="qtswsdl.QTSPort" />
    <endpoint address="http://host.com/service.svc/ForCp"
      binding="wsHttpBinding" bindingConfiguration="DefaultBinding"
      name="coProcessorEndPoint" contract="qtswsdl.QTSPort" />
  </service>
</services>
<behaviors>
  <serviceBehaviors>
    <behavior name="qtswsdl.QTS_ServiceBehavior">
      <serviceMetadata httpGetEnabled="true" />
      <serviceDebug includeExceptionDetailInFaults="true" />
      <dataContractSerializer maxItemsInObjectGraph="2147483647" />
      <serviceThrottling maxConcurrentCalls="2147483647"maxConcurrentSessions="2147483647"
        maxConcurrentInstances="2147483647" />
    </behavior>
  </serviceBehaviors>
</behaviors>

So when I try to send SOAP messages to "http://host.com/service.svc/ForHh" Im getting a "HTTP 400 - Bad Request" (the /ForCp is also not working)
I tried with custom clients, with WcfTestClient.exe and I was not able to fin what is happening
Any tip or suggestion?
Thanks for your time
EDIT:
After enable Svc trace I got a couple of exceptions:
<Message>The message with Action 'http://Host.com/Service.svc/ForHh' cannot be processed at the receiver, due to a ContractFilter mismatch at the EndpointDispatcher. This may be because of either a contract mismatch (mismatched Actions between sender and receiver) or a binding/security mismatch between the sender and the receiver.  Check that sender and receiver have the same contract and the same binding (including security requirements, e.g. Message, Transport, None).</Message>

Funny thing is that I'm sending the SOAP request programatically. It's my understanding that if I'm sending SOAP request programatically i don't need to define any contract because it is being send using SOAP 1.1 by default.
Code that sends the request is the following code:
private string SendRequestAndGetAnswerFromWebService(string methodName, string requestXml){

     StringBuilder soapRequest = new StringBuilder("<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"");
                soapRequest.Append(" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" ");
                soapRequest.Append("xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\"><soap:Body>");
                soapRequest.Append(requestXml);//Body
                soapRequest.Append("</soap:Body></soap:Envelope>");

                   WebRequest webRequest = WebRequest.Create(@"http://Host.com/Service.svc/" + methodName);
                   HttpWebRequest httpRequest = (HttpWebRequest)webRequest;
                   httpRequest.Method = "POST";
                   httpRequest.ContentType = "text/xml; charset=ascii";
                   httpRequest.Headers.Add("SOAPAction: " + @"http://Host.com/Service.svc/Service.svc/" + methodName);
                   httpRequest.ProtocolVersion = HttpVersion.Version11;
                   httpRequest.Credentials = CredentialCache.DefaultCredentials;
                   httpRequest.Timeout = 7000;
                   httpRequest.ContentLength = System.Text.Encoding.ASCII.GetByteCount(soapRequest.ToString());
                   Stream requestStream = httpRequest.GetRequestStream();

                   //Create Stream and send Request
                   StreamWriter streamWriter = new StreamWriter(requestStream, Encoding.ASCII);
                   streamWriter.Write(soapRequest.ToString());
                   //Send the request
                   streamWriter.Close();

                   //Get the Response
                   HttpWebResponse wr = (HttpWebResponse)httpRequest.GetResponse();
                   StreamReader srd = new StreamReader(wr.GetResponseStream());
                   string resulXmlFromWebService = srd.ReadToEnd();
                   return resulXmlFromWebService;
}

Maybe my assumption about contract and soap messages sent programatically are wrong...

A: Generally, this is very bad practice -- you should NOT be manually authoring SOAP requests to WCF services this way. It is better if you were to take advantage of the out-of-the-box WCF request/reply paradigms instead of resorting to setting up headers manually.
What I would recommend is to create an alternative example where you DO achieve the same thing out-of-the-box (with perhaps DataContracts, OperationContracts, and ServiceContracts on the client-end, perhaps taking advantage of WebHttpBehavior and WebHttpBinding). Examine the exact messages that are sent and received in that scenario, and closely examine, character by character, how those messages are different from the ones you're sending here.
Also, it's hard to tell what else you could be doing wrong from just the detail you've provided.
Here is what I suggest:

*

*Enable tracing on the service side, generate tracing logs, and analyze with SvcTraceViewer. To do this, follow the instructions at this MSDN article on using the service trace viewer. Notice what's different between the first and second time.

*Turn on debug exceptions. This is done by turning in includeExceptionDetailInFaults, which you can do by following the instructions here. Notice what's different between the first and second time.

*Use Fiddler to monitor the wire traffic on both the client side and the service side.
Generally, once you do this, you should plenty of more info on what's going funky at the service side and can diagnose the issue pretty quickly. Try it, and please report back! :)


text:
Q: Why does this Haskell expression compile? Here are some definitions I wrote, to avoid mixing currencies
{-# LANGUAGE GeneralizedNewtypeDeriving #-}

data EUR
data USD

newtype Amount a = Amount Double deriving (Fractional, Num, Show)

eur :: Double -> Amount EUR
eur = Amount

usd :: Double -> Amount USD
usd = Amount

*

*usd 34 + usd 3 type checks as expected

*usd 33 + eur 33 is a compilation error as expected

*I'm surprised but usd 33 + 3 is OK according to the compiler. Something I wanted to avoid, and don't understand. I suspect it is because Num instance, but then what is the difference with the second case?

Can you explain why usd 33 + 3 compiles and if it is possible to make the type-checker reject this expression.

A: When GHC derives the Num class, it provides an implementation for the
fromInteger function. Integer literals like 3 actually have the type Num a => a.
ghci> :t (34)
(34) :: Num a => a

When the type checker sees that you are trying to add a value of type
Amount USD to 3, it determines 3 :: Amount USD, which is valid since
it is a member of the Num typeclass.

A: Numbers in Haskell have lots of implicitness. Mentally, you ought to replace every number literal like 3 with fromInteger 3. Since Amount uses GeneralizedNewtypeDeriving to be part of the Num typeclass, it inherits a fromInteger instance. So the compiler is doing this
usd 33 + 3
===                                      [implicit fromInteger & expand usd]
(Amount 33 :: Amount USD) +
  fromInteger 3
===                                      [fromInteger :: Num a => a -> Amount a]
(Amount 33 :: Amount USD) +
  (Amount 3 :: Amount a)
===                                      [unify a]
(Amount 33 :: Amount USD) +
  (Amount 3 :: Amount USD)


text:
Q: Cant boot from USB drive. Cant access GRUB. No graphical interface I started an upgrade to 12.04 but stalled during install. Now, the system boots directly into command window where I must sign in. I tried creating a bootable USB (no CD drive installed) with unetbootin and Universal USB Installer, but the system do not boot to USB first - goes directly to hard drive. I tried accessing the grub menu with all suggested commands (ex holding shift, F1, Esc, F10, F12 etc etc etc) but none worked. How can I install the new version 12.04 LTS from USB? Is there any way to install from command line? Or how can I access GRUB settings from command?
Please please please help!
PS. I am not very familiar with Linux-type systems, so step-by-step guidance would be appreciated!!!

A: Make sure that your machine will boot first in its USB. You can do this by setting its Boot Priority/Sequence in BIOS.

*

*Restart your machine

*Press F2 or the key that will let you access the setup for BIOS

*Under Boot Priority/Boot Sequence tab, make the USB as the first priority to boot

*Then try restarting your machine again. It must now boot in your USB

Hope this can help.


text:
Q: Changing Notification RemoteViews Background Color I've a problem changing my Background-Color with the Application-Theme.
NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(this);

TypedValue typedValue = new TypedValue();

getTheme().resolveAttribute(R.attr.colorPrimary, typedValue, true);

int iPrimaryColor = typedValue.data;

getTheme().resolveAttribute(R.attr.colorPrimaryDark, typedValue, true);

int iPrimaryDarkColor = typedValue.data;

Intent notIntent = new Intent(getApplicationContext(), MainActivity.class);
notIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

PendingIntent notOpenOnClick = PendingIntent.getActivity(getApplicationContext(), 0, notIntent, PendingIntent.FLAG_UPDATE_CURRENT);

RemoteViews smallContentView = new RemoteViews(getPackageName(), R.layout.notification_small);
RemoteViews bigContentView = new RemoteViews(getPackageName(), R.layout.notification_expanded);

nBuilder.setSmallIcon(R.drawable.not_icon)
    .setOngoing(true)
    .setContentTitle(getCurrentSong().getTitle())
    .setContentIntent(notOpenOnClick);

Notification not = nBuilder.build();

smallContentView.setInt(R.id.not_linLayout, "setBackgroundColor", iPrimaryColor);
smallContentView.setInt(R.id.not_imvDivider, "setBackgroundColor", iPrimaryDarkColor);

bigContentView.setInt(R.id.not_linLayout, "setBackgroundColor", iPrimaryColor);
bigContentView.setInt(R.id.not_imvDivider, "setBackgroundColor", iPrimaryDarkColor);

setListeners(smallContentView);
setListeners(bigContentView);

not.contentView = smallContentView;
not.bigContentView = bigContentView;

if (isPlaying()) {
    not.contentView.setImageViewResource(R.id.not_btnPlayPause, R.drawable.ic_pause_48dp);
    not.bigContentView.setImageViewResource(R.id.not_btnPlayPause, R.drawable.ic_pause_48dp);
}
else {
    not.contentView.setImageViewResource(R.id.not_btnPlayPause, R.drawable.ic_play_48dp);
    not.bigContentView.setImageViewResource(R.id.not_btnPlayPause, R.drawable.ic_play_48dp);
}

I already tried this, but the Background of my Notification is still white.
The ID's are correct, the View linLayout is a LinearLayout.
Please keep in mind: The whole codes is invoked in a Service!
Thanks!

A: Much of this can be easier done by taking advantage of NotificationCompat.MediaStyle. It pulls the background color from the setColor() call on pre-API 24 devices (and uses that color as an accent on API 24+ devices). This also means you don't need to write any custom RemoteViews code anymore as it relies solely on the actions you add to your notification for media controls:
NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(this);
nBuilder.setSmallIcon(R.drawable.not_icon)
  .setContentTitle(getCurrentSong().getTitle())
  .setContentIntent(notOpenOnClick);
// This is what sets the background color on <N devices
// It is an accent color on N+ devices
nBuilder.setColor(getResources().getColor(R.color.colorPrimary));
// Add actions via nBuilder.addAction()
// Set the style, setShowActionsInCompactView(0) means the first
// action you've added will be shown the non-expanded view
nBuilder.setStyle(new NotificationCompat.MediaStyle()
  .setShowActionsInCompactView(0));

You should definitely read over all of the methods available for MediaStyle and reivew the Best Practices in media playback I/O 2016 talk for example code and best practices around using notifications. Specifically at 30 minutes into the talk

A: the setColorized documentation says:

Set whether this notification should be colorized. When set, the color set with setColor(int) will be used as the background color of this notification.
This should only be used for high priority ongoing tasks like navigation, an ongoing call, or other similarly high-priority events for the user.
For most styles, the coloring will only be applied if the notification is for a foreground service notification.
However, for MediaStyle and DecoratedMediaCustomViewStyle notifications that have a media session attached there is no such requirement.
Calling this method on any version prior to O will not have an effect on the notification and it won't be colorized.

Kotlin code:
import android.support.v4.media.session.MediaSessionCompat
import android.support.v4.media.session.PlaybackStateCompat
import androidx.core.app.NotificationCompat
import androidx.media.app.NotificationCompat.DecoratedMediaCustomViewStyle

// create a MediaSession so that we can create a DecoratedMediaCustomViewStyle
val mediaSession = MediaSessionCompat(applicationContext,"tag")
mediaSession.setFlags(0)
mediaSession.setPlaybackState(PlaybackStateCompat.Builder()
        .setState(PlaybackStateCompat.STATE_NONE,0,0f)
        .build())

// create & display the colorized notification
notificationManager.notify(
        0,
        NotificationCompat
                .Builder(this,notificationChannel)
                .setStyle(DecoratedMediaCustomViewStyle()
                        .setMediaSession(mediaSession.sessionToken))
                .setSmallIcon(R.drawable.ic_app_foreground)
                .setColor(getColor(android.R.color.black))
                .setColorized(true)
                .setContentText("Hello, World!")
                .build())

....

// cleanup upon dismissing the notification
mediaSession.release()


text:
Q: React Native picker selected value keeps a deleted item On a screen I delete an object based on a value, and when the item gets deleted and I want to select a new one, the 'selectedValue' prop keeps the value of the item that whas deleted, thus triggering an error.
Let's say I have this list:
[{ profit: '2300', month: 'February', year: '2021' },
{ profit: '2600', month: 'January', year: '2021' },
{ profit: '3100', month: 'March', year: '2021' },
{ profit: '1900', month: 'January', year: '2020' },
{ profit: '2400', month: 'April', year: '2021' }]

And on one of the Picker components I display the months of the year that was selected. For example, if I choose the year 2021 the month array should be ['January', 'February', 'March', 'April'].
Then, I delete the values for February. The values get deleted and the array for 2021 changes to ['January', 'March', 'April'].
However, on the Picker 'currentItem', the value is set to February, no matter if the value is not on the ItemList anymore.
Here's my code of the screen where the Picker is:
<ItemPicker
   visible={monthModalVisible} // <- The item picker is a Modal, thus it's not visible until the press of a button
   itemList={userMonths} // <- The array with the months of the selected year
   defaultItem={userMonths[0]}
   onSelectItem={m => {
     setMonthModalVisible(false);
     saveInState({ month: m });
     toggleProfit(m); // <- Function that retrieves the object on the list based on the selected month
     setMonthSelected(m);
   }}
 />

And this is my code for the ItemPicker component:
import { Picker } from '@react-native-community/picker';

export default function CustomDatePicker(props) {
  const {
    visible,
    itemList,
    defaultItem,
    btnText,
    onSelectItem
  } = props;
  const [currentItem, setCurrentItem] = useState(defaultItem);
  const { shadow, flexCenter, modal, button, picker } = styles;

  useEffect(() => {
    setCurrentItem(defaultItem);
  }, [defaultItem]);

  return (
    <Modal
      animationType="slide"
      transparent
      visible={visible}
    >
      <View style={flexCenter}>
        <View style={[shadow, modal]}>
          <Picker
            selectedValue={currentItem}
            onValueChange={value => setCurrentItem(value)}
            style={picker}
          >
            {itemList.map(item => (
              <Picker.Item value={item} label={item} key={item} />
            ))}
          </Picker>
          <Button
            text={btnText}
            style={button}
            onPress={() => { setCurrentItem(currentItem); onSelectItem(currentItem); }}
          />
        </View>
      </View>
    </Modal>
  );
}

What I want to do is make the Picker component "forget" the value that was selected (and deleted, i.e. If I choose February and it's object gets deleted, then February shouldn't be the Picker's currentItem anymore)

A: The useEffect hook is not working.
  useEffect(() => {
    setCurrentItem(defaultItem);
  }, [defaultItem]);

Just use this
import { Picker } from '@react-native-community/picker';

export default function CustomDatePicker(props) {
  const {
    visible,
    itemList,
    defaultItem,
    btnText,
    onSelectItem
  } = props;
  const [currentItem, setCurrentItem] = useState(null);
  const { shadow, flexCenter, modal, button, picker } = styles;

  return (
    <Modal
      animationType="slide"
      transparent
      visible={visible}
    >
      <View style={flexCenter}>
        <View style={[shadow, modal]}>
          <Picker
            selectedValue={currentItem || defaultItem}
            onValueChange={value => setCurrentItem(value)}
            style={picker}
          >
            {itemList.map(item => (
              <Picker.Item value={item} label={item} key={item} />
            ))}
          </Picker>
          <Button
            text={btnText}
            style={button}
            onPress={() => { setCurrentItem(null); onSelectItem(currentItem || defaultItem); }}
          />
        </View>
      </View>
    </Modal>
  );
}


text:
Q: QwtPlot how to select point(s) curve I have a QwtPlot that contains some curves and I would like to be able to get the selected point(s) (and curve pointer) from these curves : select a point by clicking and select points by dragging a rect.
I use the following code:
// Picker with click point machine to provide point selection
QwtPlotPicker* clickPicker = new QwtPlotPicker(this->canvas());
clickPicker->setStateMachine(new QwtPickerClickPointMachine);
clickPicker->setMousePattern(0,Qt::LeftButton,Qt::SHIFT);
connect(clickPicker, SIGNAL(appended(QPointF)),
        this, SLOT(pointSelected(QPointF)));

// Picker with drag rect machine to provide multiple points selection
QwtPlotPicker* rectPicker = new QwtPlotPicker(
            this->xBottom, this->yLeft, QwtPicker::RectRubberBand,
            QwtPicker::AlwaysOff, this->canvas());
QwtPickerDragRectMachine* test = new QwtPickerDragRectMachine();
test->setState(QwtPickerMachine::RectSelection);
rectPicker->setStateMachine(test);
connect(rectPicker, SIGNAL(selected(QRectF)),
        this, SLOT(pointsSelected(QRectF)));

but the pointSelected slot is called every time I click on the QwtPlot and not only on a curve
BTW, I also try to connect a slot to the signal QwtPlotPicker::selected(const QVector &pa) but it is never emitting ...

A: I think it is more convenient to use the CanvasPicker as it comes with the examples and can be extended easily.
Please have a look at the event_filter which comes with Qwt. You should use the class CanvasPicker (it is not part of the Qwt API, but you'll find the code in the examples).
You can instantiate it in your class using
    picker = new CanvasPicker(plot); // plot is a pointer to your instance of QwtPlot

You'll see that the event filter is installed in the constructor of CanvasPicker.
Now have a look at CanvasPicker::eventFilter(QObject *object, QEvent *e) which is called when an event occurs in the event loop of QwtPlot. Implement your application logic in the switch construct, f.i. change case QEvent::MouseMove:.


text:
Q: Rspec: Stack level too deep whatever the test I am trying to build a test suite using Rspec and I have always a "Stack Level too deep" failure message, whatever the test that I try to run.
I am using Rails 3.0.5 and Rspec 2.0.1
To make it very simple, I just made a simple test:
it "should show home page" do
  visit root_path
  response.should be_success
end

Testing ONLY this test file using:
rspec ./spec/requests/simple_test.rb

gives me the "Stack level too deep" error.
The root path is for now just a simple home page that says "this is the home page" and it works fine in a browser. Moreover, the test.log file shows that the request has been processed and gave a 200 OK answer ... still the test fails "visit root_path: stack level too deep...
Anyone knows what is happening? I have searched the web and found many answers for which there was an infinite recursion but here ??? ...
A last precision: a few months ago, I did not have this problem .. since then, I installed devise (version 1.5.3) ... but here, I do not make any call to neither devise, nor user controllers, so what could cause this behaviour ?
Many thanks in advance for any clue... I don't know how to tackle or debug this.

A: The problem is a bug in webrat:
Webrat 0.7.3 or 0.7.2 causes "Stack level too deep" error when used with Rspec 2.0.1.
Downgrading to webrat 0.7.1 fixed the issue
More explanations there: http://www.backdrifter.com/2010/11/07/stack-level-too-deep-with-rspec-2-and-webrat/


text:
Q: May I have a real life example where a non-static member function not accessing the object being called via a null pointer causes observable problems?
Possible Duplicate:
When does invoking a member function on a null instance result in undefined behavior?

Anything like this:
class Class {
public:
    void Method()
    {
       //empty;
    }
};

Class* object = 0;
object->Method();

is undefined behavior in C++ because calling non-static member functions via null pointers is formally illegal. See this answer for a detailed explanation full of quotes from the C++ Standard. I'm well aware of the theoretical part and this question is not about theory and so it's not a duplicate of that question.
In all implementations I'm aware of the code above or some equivalent thereof doesn't cause any observable problems - since the member function doesn't access the object the method will be called just fine.
May I have any real-life example in which the same setup causes practical observable problems?

A: Simple:
struct Object { void foo(); std::string s; };

void print(Object* o) {
  o->foo();
  if (o) { std::cout << o->x << "\n"; }
}

Let us say that foo does not access any non-static attribute of Object (ie, x).
The problem is that because formally o->foo() is undefined behavior if o is null, then it is obvious that o is not null. Therefore the check is redundant.
The function is thus optimized:
void print(Object* o) {
  o->foo();
  std::cout << o->x << "\n";
}

Reversing the order does not change anything:
void print(Object* o) {
  if (o) { std::cout << o->x << "\n"; }
  o->foo();
}

is still optimized:
void print(Object* o) {
  std::cout << o->x << "\n";
  o->foo();
}

Sometimes referred to as the Time Travel Clause of Undefined Behavior by some SO members.
For more information, check out Chris Lattner's serie on Undefined Behavior:

*

*What Every C Programmar Should Know About Undefined Behavior 1/3

*What Every C Programmar Should Know About Undefined Behavior 2/3

*What Every C Programmar Should Know About Undefined Behavior 3/3
Your specific concern is addressed in 2/3.
Whether this actually fails depend on the compiler you use, the optimization passes you specify and the order in which they run.
Do you really want to depend on all that :x ?
Of course, one would argue that's it is pointless to have a function member that does not access any state of the object... so the question itself is of little value in practice (but interesting for its theoretical aspects).

A: This is UB, so what would constitute a "problem"? To be a problem, the code would have to do something other than what the standards say it should do or what we expect it to do, otherwise it's not a problem. The standards give us no idea what the code should or will do, so whatever it does isn't a problem.
You say it doesn't cause any "observable problems". Well, of course not. Whatever it did would be fine. It could fault, and that wouldn't be a "problem" because that's what the standard tells us can happen.

A: It is unlikely that this code produces any problems on any platform I'm aware of. It is still undefined behavior, primarily because it is an irrelevant corner case: it could be defined that under certain conditions calling a member function on a null pointer would be OK. However, what is the point? If you don't access any of the members, why make the function a non-static member function? There is no loss in leaving this undefined as there is no conceivable need to define this case and it would thus unnecessarily complicate the language.


text:
Q: Save the background image of a rectangle using file dialog in javafx I have two rectangles in my scene .Then I set a background in those rectangles using setFill() and make some changes.How do I save those images to disk using saveDialog ? Here is my save function -
  FileChooser fileChooser = new FileChooser();
  fileChooser.getExtensionFilters().add(new ExtensionFilter("Image Files", "*.png", "*.jpg", "*.gif"));
  fileChooser.setTitle("Save Image");
  File file = fileChooser.showSaveDialog(window);
  rect2.getFill();
  SaveFile(file);

A: You can create a javafx.scene.image.Image from any node by calling snapshot(...) on the node:
Image img = rect2.snapshot(null, null);

The javax.imageio.ImageIO class has methods for saving images in standard formats, but only works with AWT images, so you need to convert it first:
BufferedImage bImg = SwingFXUtils.fromFXImage(img, null);
String format = file.getName().substring(file.getName().lastIndexOf(".")+1);
ImageIO.write(bImg, format, file);


text:
Q: "SAWarning: No driver name specified; this is expected by PyODBC when using DSN engine = sa.create_engine(SQLALCHEMY_DATABASE_URL)" Having issues connecting to my sql-server using pyodbc after several checks.
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
import pyodbc
SQLALCHEMY_DATABASE_URL = f"mssql+pyodbc://user_one:secret@DESKTOP-6T5DDMB\mypassword/Billy+Driver=SQL+Server+Native+Client+11.0',echo=True"
engine = create_engine(SQLALCHEMY_DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

A: So after a thorough research from stackoverflow i discovered i was missing some syntax from my code using a wrong connecting string.
wrong: f"mssql+pyodbc://user_one:secret@DESKTOP-6T5DDMB\mypassword/Billy+Driver=SQL+Server+Native+Client+11.0',echo=True"
Right:
import pyodbc
import sqlalchemy as
mssql+pyodbc://DESKTOP-6T5DDMB\mypassword/Billy?driver=SQL+Server+Native+Client+11.0
engine = sa.create_engine(SQLALCHEMY_DATABASE_URL)
And this is applicable when using Windows Authentication.


text:
Q: How to save hyperlink Dynamically to a sharepoint calendar list? I have a calendar list called "learning Calendar" and it has the following fields.
Location,Start Time,Start Time,Employee Name,Manage Name,Program Name,Status,HyperLink.
I am able to add the data into it sucessfully.
But i would like to save current URl into HyperLink field in the list dynamically. How can i achive this? Here is the saved Date
Location     - AAA
Start Time   -2/14/2012  7:00:00 PM
Start Time   -2/14/2012  8:00:00 PM
Employee Name-BBBB
Manage Name  -CCCC
Program Name -DDDD
Status       -Approved
HyperLink    - ? how do i save dynamically URl here ? (Statically i am able to add)
Please Help.


text:
Q: Delete all SQLite rows NOT IN specific rows I have a database for my leaderboard. Currently, I insert all scores into my leaderboard, and select the 5 highest scores to show on my app. I think it would take up too much room to never delete the other scores, so I would like to delete them. How can I do this?
Here's how I select the top 5 scores, ranked first by score and second by time if score is equal:
    public  Cursor gethmLeaderboard(SQLiteDatabase db){

    String[] columns = {TableInfo.LB_RANK, TableInfo.LB_SCORE, TableInfo.LB_TIME};

    Cursor c = db.query(TableInfo.TABLE_HM, null, null, null, null, null, TableInfo.LB_SCORE + " DESC, " + TableInfo.LB_TIME + " ASC", "5");
    return c;

}

Here's how I create my table:
public String CREATE_HMQUERY = "CREATE TABLE " + TableInfo.TABLE_HM + "("
        + TableInfo.LB_RANK + " INTEGER PRIMARY KEY AUTOINCREMENT DEFAULT 1 ," + TableInfo.LB_SCORE +
        " INT,"+ TableInfo.LB_TIME + " VARCHAR );";

I want to delete all rows NOT IN that query. How can I do that?
What I've tried:
public String DEL_ALLBUTES = "DELETE FROM " +
        TableInfo.TABLE_HM + " WHERE " +
        TableInfo.LB_RANK + " NOT IN (SELECT " +
        TableInfo.LB_RANK + " FROM " +
        TableInfo.TABLE_HM + " ORDER BY " +
        TableInfo.LB_SCORE + " DESC, " +
        TableInfo.LB_TIME + " ASC LIMIT 5);";

In this format:
db.rawQuery(DEL_ALLBUTES, null);

But when I check the database there are still tons of rows so it doesn't work.

A: Use execSQL() for commands (everything which is not a SELECT).
And rawQuery() for queries (SELECT).


text:
Q: REST Heartbeat for checking service availability I need to implement a heartbeat to check whether my rest server is up and running, I was thinking about a service called "heartbeat" or "echo" together with my other services, that just perform a read from database to response with some value, eg: a version number o whatever, or just saying Hello. And then use curl to send request periodically (eg: every 20 seconds), so far so good. Now I need to develop some scripting for using curl periodically and if there are continuous error response (eg: 3 errors one after the other) I send an alert by email.
I was wondering whether there is any non-comercial (or not-paid) solution "out-of-the-box" to implement the last part (the script sending periodic request and sending alert emails), or if not, how would it the easiest way to get it done.
Thank you !

A: You can, and probably should use monit (or other equivalent tools) to achieve this. Monit can check HTTP services, and take some action (restart service, alert) when request fails


text:
Q: How can i change UI of my page after async call? I am having async call on my page,
This takes about 1 minute.
I need to change UI after call completes.
Sample code is give below.
 protected void Unnamed1_Click(object sender, EventArgs e)
{

    apicasystemWPMCheckStatsService.CheckStatsServiceClient obj = new apicasystemWPMCheckStatsService.CheckStatsServiceClient();
    string xmlOptionForGetCheckStats = "<options><mostrecent count='1'/><dataformat>xml</dataformat><timeformat>tz</timeformat></options>";
    string checkId = "";

    TextBox1.Text = TextBox1.Text + "test" + "\r\n";
    obj.BeginGetCheckStats("admin@azuremonitoring", "Cu4snfPSGr8=", "PD6B685A0-006A-4405-951E-B24BB51E7966",
                                       checkId, xmlOptionForGetCheckStats, new AsyncCallback(ONEndGetCheckStats), null);

    TextBox1.Text = TextBox1.Text + "testdone" + "\r\n";

}

public void ONEndGetCheckStats(IAsyncResult asyncResult)
{

    System.Threading.Thread.Sleep(3000);
    TextBox1.Text = TextBox1.Text + "testcomplete" + "\r\n";

}

The question is that how can i get "testcomplete" in my textbox. as my page is not getting posted back after this async call....
My current O/P :
test
testdone
Expected:
test
testdone
testcomplet

A: Simple answer: You can not do it like that. Because once the ASPX page is sent to the client there is no somple way for the server to communicate with that page.
You can do this however with AJAX. In your Unnamed1_Click set up a "flag" in Session that signals that an async operation is pending. In your ONEndGetCheckStats set that "flag" to signal that the operation has completed.
Add an ASP.NET page method (Quick Tutorial) to your code-behind that:

*

*Checks whether the operation is pending and returns null wehen it is

*When operation is finished removes everything from Session and returns the text that you need

On your ASPX page wire up a client-side event on the Unamed1 (a poor name for a button btw) button that starts a client-side loop checking the status using that PageMethod. When status is not null anymore Javascript to change the TextBox1 text.


text:
Q: Finding Duplicates using Salesforce API from external tool Could any one guide us the best approach to find the duplicates using with own filters not salesforce Duplicate Rules.
We have pushing leads to Salesforce from external tool.We want restrict the duplicates with own filters before push to SF.
Presently, we follow the below approach.
1)Filter set up
example : (Company AND Phone)
2)Check duplicates using above filter using SOQL through REST API
Select id,name,company from Lead where company ='Salesforce.com' AND phone='1235645698';
In Our tool,We pushing bulk leads also .In this case,one API call consume for each lead to check the duplicates.
Is there any alternative approach to find the duplicates using self filters not Salesforce native duplicate management.

A: If you can't do this on Salesforce (or just don't want to) you can query using the IN keyword. So if you have, for example, three leads from different companies, you can fire the following query:
SELECT Id, Name, Company, Phone
FROM Lead
WHERE Company IN ('Company A', 'Company B', 'Company C')
AND Phone IN ('99999', '99998', '99997')

This way, you can retrieve multiple records and then flag which leads you have that you do not need to send to Salesforce.
This isn't a good approach because you will be facing two limits:

*

*Number of characters allowed on the request URI;

*Number of records retrieved by the API;

*Number of queries issued by your application.

So, instead of doing this filtering outside Salesforce, you should consider using Duplicate Rules on the Lead object (on Setup > Duplicate Management > Duplicate Rules), and then uploading all the unfiltered data you have (unfiltered for duplicates, that is).


text:
Q: Collection Navigation property not Refreshed (reload) after Edit I use a function to load data for a datagrid, Each row in the grid show items from a collection navigation property, But when I edit the collection and reload data for datagrid the added or removed entries not showing it shows only old ones:
Here is a part of LoadData() function I use for refreshing datagrid data, I call this after editing collection (Note the collection is correctly saved to DB):
count = query.Count();

var resumes0 = query.Skip(args.Skip.Value).Take(args.Top.Value).ToList<Resume>();
resumes0.ForEach(r =>
{
    context.Entry(r).Navigation("ResumeSkills").IsLoaded = false;
    context.Entry(r).Collection(r => r.ResumeSkills).IsLoaded = false;
    context.Entry(r).Collection(r => r.ResumeSkills).Load();
});
resumes = resumes0;

A: AsNoTracking() here:
var query = context.Resumes.Include(r => r.AcceptedResumes).Include(r => r.ResumeSkills).ThenInclude(rs => rs.Skill).AsNoTracking().AsQueryable();

solved my problem, But I need tracking entities. But it seems this is the only way to solve this problem.


text:
Q: (C#, Unity)Как заблокировать управление? Вот у меня есть код(Без смеха):
    void Start()
{
    rb = GetComponent<Rigidbody2D>();
    fill = 0.5f;
}

// Update is called once per frame
void Update()
{
    bar.fillAmount = fill;
}

void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject.name == "dieCollider")
{
    if (transform.position.x > 9.93f)
    {
        rb.AddForce(new Vector2(+5.0f, 0),ForceMode2D.Impulse);

    }
    if (transform.position.x < 9.92f)
    {
        rb.AddForce(new Vector2(-5.0f, 0),ForceMode2D.Impulse);
    }
    fill = fill - 0.1f;
}

if (fill <= 0)
{
    Destroy(gameObject);
    Debug.Log("Print");
    Application.LoadLevel (Application.loadedLevel);
}
}

void OnTriggerStay2D(Collider2D col)
{
    fill = fill - 0.01f;
    if (fill <= 0)
{
    Destroy(gameObject);
    Debug.Log("Print");
    Application.LoadLevel (Application.loadedLevel);
}
}

И
void Start()
{
    rb = GetComponent<Rigidbody2D>();
}

// Update is called once per frame
void FixedUpdate()
{
    if (Input.GetKey(KeyCode.A))
    {
        speedX = -horizontalSpeed;
    }
    else if (Input.GetKey(KeyCode.D))
    {
        speedX = horizontalSpeed;
    }
    if (Input.GetKeyDown(KeyCode.Space) && isGrounded)
    {
        rb.AddForce(new Vector2(0, verticalImpulse), ForceMode2D.Impulse);
    }
    if (transform.position.y <= -4.57f)
    {
        Destroy(gameObject);
    }
    transform.Translate(speedX, 0, 0);
    speedX = 0;
}
private void OnCollisionEnter2D(Collision2D collision)
{
    if (collision.gameObject.tag == "Ground")
      isGrounded = true;

}
private void OnCollisionExit2D(Collision2D collision)
{
    if (collision.gameObject.tag == "Ground")
     isGrounded = false;
}

Как сделать так,чтобы когда персонаж заходил в триггер,и на пару секунд у него блокировалось управление.

A: Можете попробовать изучить и реализовать паттерн "Состояние". Если коротко - у вас, например, есть отдельный абстрактный класс, отвечающий за обработку ввода (например BaseInputController). От него наследуются, например DefaultInputController и StunInputController, первый имеет стандартную логику передвижения, а второй игнорирует весь ввод (а там уже меняйте, как хотите). Реализация будет какая-нибудь такая (абсолютно случайный пример из головы):
using System;
using System.Collections;
using UnityEngine;

public class Test : MonoBehaviour
{
    BaseInputController _currentController;

    private void Start()
    {
        _currentController = new DefaultInputController();
    }

    private void FixedUpdate()
    {
        _currentController.UpdateControll();
    }

    public void DoStun(float duration)
    {
        _currentController = new StunInputController();
        StartCoroutine(DelayedActionRoutine(duration, () => _currentController = new DefaultInputController()));
    }

    IEnumerator DelayedActionRoutine(float delay, Action action)
    {
        yield return new WaitForSeconds(delay);
        action?.Invoke();
    }

    abstract class BaseInputController
    {
        public abstract void UpdateControll();
    }

    class DefaultInputController : BaseInputController
    {
        public DefaultInputController() { }

        public override void UpdateControll()
        {
            //Здесь будет обработка управления вашим персонажем. Можете передавать его параметры в конструктор класса и управлять ими здесь
        }
    }

    class StunInputController : BaseInputController
    {
        public override void UpdateControll()
        {
            //Можно, например, показывать всплывающее сообщение над персонажем при попытке его сдвинуть
        }
    }
}

Таким образом можно клепать сколько угодно "особых" состояний-типов-управления и переходить между ними через какие-то условия верхнего класса. Параметры, которые требуется обрабатывать конкретному типу управления можно передавать в его конструктор (например, для базового - можете передавать базовую скорость и прочие параметры)

A: Сам недавно начал изучать. Я бы сделал так:
Получи объект к которому прикреплен скрипт и выключи его
object.GetComponent<NameScript>().enabled = false;

Создай метод в котором включай обратно скрипт спустя пару сек
Invoke("NameMethod", 2f)


text:
Q: Net force affecting a simple pendulum What is the net force affecting a simple gravity pendulum?
I know the restoring force equals to:
$$
\vec{F}_s= -mg\cdot\sin{\varphi(t)}\cdot\hat{\theta}
$$
And then there is the centripetal force (?):
$$
\vec{F}_c = \frac{mv^2}{L}\cdot-\hat{r}
$$
$$
= \hat{r}(mg\cdot\cos{\varphi(t)}-T)
$$
I am guessing that the net force equals to the vectoral sum of the forces I have highlighted:
$$
\vec{F}_{net} = \vec{F}_s+\vec{F}_c
$$
But I honestly am confused about the centripetal force and don't quite understand how it equals to $\frac{mv^2}{L}$.

A: Since we know our pendulum is not getting any longer, we know that the net force in the radial direction must be zero. And so the net force acting on the pendulum is in the direction of $\hat{\theta}$ as you mentioned. This force is obviously going to be $( -mg \sin{\theta} )\hat{\theta} $ , which of course gives us:
$$m\vec{a}=( -mg \sin{\theta} )\hat{\theta} $$
And since $a$ is in th rotational direction, we can say $\vec{a}=(l \frac{\mathrm{d}^2}{\mathrm{d} t^2}\theta) \hat{\theta}$
Plugging that back in we obtain:
$$\frac{\mathrm{d}^2}{\mathrm{d} t^2}\theta = -\frac{g}{l}\sin{\theta}$$
This differential equation tells you everything about the pendulum, and you can use a small angle approximation to obtain a Harmonic Oscillator, but if you are interested in centripetal force it will be a little more subtle since we are now dealing with non-uniform circular motion, and so the velocity vector is not so nice to deal with. This is because in uniform circular motion $v$ is just a number, however in the case of a pendulum its a time varying vector.
But to understand why in general $a_c=\frac{v^2}{r} \rightarrow F_c=ma_c=\frac{mv^2}{r}$ consider the following:

Triangles ABC and PQR are similar and therefore:
$$\frac{\Delta v}{v}=\frac{\Delta s}{r}\rightarrow a:=\frac{\Delta v}{\Delta t}=\frac{v}{r}\frac{\Delta s}{\Delta t}= \frac{v^2}{r}$$
And so we obtain $a_c=\frac{v^2}{r}$


text:
Q: Retrieve all morphedBy relations An Order have many ordered items
An Order's ordered items can either be a User or Product
What I am looking for is a way to retrieve all morphed objects to an Order. Instead of $order->users or $order->products I would like to do $order->items.
My progress
My progress so far involves a Many To Many Polymorphic Relationship.
My tables:
orders
    id - integer

orderables (the order items)
    order_id - integer
    orderable_id - integer
    orderable_type - string

    quantity - integer
    price - double

-----------

users
    id - integer
    name - string

products
    id - integer
    name - string

Example on how orderables table look

This is how I create an order and add a user and a product:
/**
 * Order
 * @var Order
 */

    $order = new App\Order;
    $order->save();

/**
 * Add user to order
 * @var [type]
 */

    $user = \App\User::find(1);

    $order->users()->sync([
        $user->id => [
            'quantity' => 1,
            'price' => $user->price()
        ]
    ]);

/**
 * Add product to order
 * @var [type]
 */

    $product = \App\product::find(1);

    $order->products()->sync([
        $product->id => [
            'quantity' => 1,
            'price' => $product->price()
        ]
    ]);

Order.php
/**
 * Ordered users
 * @return [type] [description]
 */

    public function users() {
        return $this->morphedByMany('Athliit\User', 'orderable');
    }

/**
 * Ordered products
 */

    public function products() {
        return $this->morphedByMany('Athliit\Product', 'orderable');
    }

Currently I can do
foreach($order->users as $user) {
    echo $user->id;
}

Or..
foreach($order->products as $product) {
    echo $product->id;
}

But I would like to be able to do something along the lines of...
foreach($order->items as $item) {
    // $item is either User or Product class
}

I have found this question, which was the closest I could find to what I am trying to do, but I can't make it work in regards to my needs, it is outdated, and also seems like a very hacky solution.
Have a different approach?
If you have a different approach than Polymorphic relationships, please let me know.

A: Personally, my Order models have many OrderItems, and it is the OrderItems that have the polymorphic relation. That way, I can fetch all items of an order, no matter what type of model they are:
class Order extends Model
{
    public function items()
    {
        return $this->hasMany(OrderItem::class);
    }

    public function addItem(Orderable $item, $quantity)
    {
        if (!is_int($quantity)) {
            throw new InvalidArgumentException('Quantity must be an integer');
        }

        $item = OrderItem::createFromOrderable($item);
        $item->quantity = $quantity;

        $this->items()->save($item);
    }
}

class OrderItem extends Model
{
    public static function createFromOrderable(Orderable $item)
    {
        $this->orderable()->associate($item);
    }

    public function order()
    {
        return $this->belongsTo(Order::class);
    }

    public function orderable()
    {
        return $this->morphTo('orderable');
    }
}

I'll then create an interface and trait that I can apply to Eloquent models that makes them "orderable":
interface Orderable
{
    public function getPrice();
}

trait Orderable
{
    public function orderable()
    {
        return $this->morphMany(OrderItem::class, 'orderable');
    }
}

use App\Contracts\Orderable as OrderableContract; // interface
use App\Orderable; // trait

class Product extends Model implements OrderableContract
{
    use Orderable;
}

class EventTicket extends Model implements OrderableContract
{
    use Orderable;
}

As you can see, my OrderItem instance could be either a Product, EventTicket, or any other model that implements the Orderable interface. You can then fetch all of your order's items like this:
$orderItem = Order::find($orderId)->items;

And it doesn't matter what type the OrderItem instances are morphed to.

EDIT: To add items to your orders:
// Create an order instance
$order = new Order;

// Add an item to the order
$order->addItem(User::find($userId), $quantity);

A: I think your solution is fine. I'd just add this helper method:
Order.php
public function items() {
    return collect($this->products)->merge($this->users);
}

Then you can loop through the items with:
foreach ($order->items() as $item) {


text:
Q: JSF logout page - best practices: is it correct to use one common bean? Is it correct/ a best practice to have a commonBean for operations that are common to the application? In my case this would be a logout function that clears the logged value of a session bean.
One of my coworkers told me that only one controller bean should be used per view, however it seems like a waste to have the same method replicated in multiple beans.

A: Your colleague is referring to the seperation of View and Controller as a loosely defined principle in a pure MVC pattern.  The Managed Bean in a JSF application lends itself well to the role of a Controller, however this should not be considered a hard and fast rule for the very reasons that you have stated.
I quote Martin Fowler from Patterns of Enterprise Application Architecture:

As I said, the value of MVC lies in its two separations.  Of these are
  the separation of presentation and model is one of the most important
  design principles in software, and the only time you shouldn't follow
  it is in very simple systems where the model has no real behavior in
  it anyway.  As soon as you get some nonvisual logic you should apply
  the separation.  Unfortunately, a lot of UI frameworks make it
  difficult, and those that don't are often taught without a separation.
The separation of view and controller is less important, so I'd only
  recommend doing it when it is really helpful.  For rich-client
  systems, that ends up being hardly ever, although it is common in Web
  front ends where the controller is separated out.  Most of the
  patterns on Web design here are based on that principle.

Essentially Fowler states that binding view to controller is not as important as binding model to view, so utilizing controllers across views or multiple controllers per view is certainly acceptable if it is helpful to do so.


text:
Q: Tomcat with 1-way and 2-way SSL I have a service A that uses 1-way SSL and also 2-way SSL to make secure requests to service B. 1-way SSL is specified by Tomcat config, I provide keystoreFile, keystorePass, enable SSL, etc. 2-way SSL is implemented using JSSE on the client (service A). I know this could be done similarly in Tomcat server.xml too (example is here: http://blog1.vorburger.ch/2006/08/setting-up-two-way-mutual-ssl-with.html).
Part of my 1-way SSL Tomcat configuration:
<Connector port="securePort"
           scheme="https"
           secure="true"
           clientAuth="false"
           sslProtocol="TLS"
           SSLEnabled="true"
           keystoreFile="keystoreFile"
           keystorePass="keystorePass"
           keystoreType="keystoreType"
           ...
/>

Is there a way to specify both 1-way and 2-way (client side) SSL for the same service in Tomcat though. The challenge here is that I'm using 2 certificates (server and client one) on the same IP. Any hints?

A: When service A makes SSL requests with client-authentication to service B, it's not a server, it's a client. This has nothing to do with configuring client authentication on your Tomcat server where service A is running.
How your service A picks up its keystore settings (which it uses as a client) depends on how it's implemented and which libraries it uses to make these connections. It's not particularly different from any standalone client.
It's likely that it will at least pick up the default settings via the system properties. You can set the javax.net.ssl.keyStore (and related) system properties in the container (e.g. via JAVA_OPTS in catalina.sh or .bat). These settings will however be usable by all the webapps running within your container (but these settings won't be used by your <Connector/> configuration, if you've configured a different keystore there). Affecting all the webapps in your container like this may not always be desirable.
You could also have your keystore file where your client code can load it (e.g. somewhere under WEB-INF) and load this keystore as a resource stream to initialise the SSLContext used by your client library (if your client application can use such settings). Another possible way is to pass the keystore via JNDI. All this depends on how you want to configure the deployment of your service and how its code expects to be configured.

A: I hope this is your scenario
Service A ---> 1 way SSL request to an endpoint
Service B ---> 2 way SSL request to an endpoint
Tomcat connector configured with 2 way SSL
Since tomcat connector is configured with 2 way SSL all incoming connections will be validated for handshake; this means if there is no key for 1 way ssl endpoint, handshake will fail. To overcome this you need to import 1 way ssl endpoint certificate into truststore
Now both 1 way and 2 way SSL will work


text:
Q: How to used deckgl in "Bing Map" We succeeded in displaying nearly 10 million pieces of data on a map using the Google Map API and Deck GL library.
However, I don't like the price and license policy of the Google Map API, so I'm going to change it to Bing Map.
It is difficult to find examples or examples of using Bing Map and Deckgl together on the Internet.
I understand that Deckgl can be used interworking with any base map if it meets a specific condition, but I'm not sure what the specific condition is.
What I want to know is as follows.

*

*Can I use it with deckgl?

*Which map do you prefer if you use Deckgl between OSM and BingMap?

*Can you handle the map on BingMap? (getCenter, setCenter, etc.)

*Is there a Map Event? (Clicked Event, Dragged Event, etc.)

*Is 3D building or setTilt possible like MapBox?

A: There is no example for this currently, but this could be achieved by adding a canvas to the map as a custom layer. Here is an example: https://bingmapsv8samples.azurewebsites.net/#Canvas%20Layer
Alternatively, consider using Azure Maps. The Azure Maps web SDK wraps MapLibre (open source community fork of Mapbox), Deck.gl was originally writen for Mapbox, so it's not too difficult to access the underlying API in the Azure Maps web SDK and get deck.gl working. I've experimented with this a bit in the past. Here is a quick example:
<!DOCTYPE html>

    <title></title>

    <meta charset="utf-8" />
    <meta http-equiv="x-ua-compatible" content="IE=Edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />

    <link rel="stylesheet" href="https://atlas.microsoft.com/sdk/javascript/mapcontrol/2/atlas.min.css" type="text/css" />

Here is what the above code generates:


text:
Q: Unable to cancel a Servicestack Facebook authentication proccess When accessing "/api/auth/facebook" i'm redirected to facebook ouath dialog, but when trying to cancel, i keep getting redirected to the same facebook ouath dialog.
This means i cannot cancel this process.
Is this a bug?

A: I fixed this issue a little while back.
https://github.com/ServiceStack/ServiceStack/pull/850


text:
Q: Does the physical separation of wormhole mouths in real space affect transit time through the throat? So I've somehow built my wormhole. I've stuffed the thing with negative energy so it's stable and traversable. I've got one end in orbit around Earth and the other in orbit around Mars.
My question is how long does it take to travel from one end of the wormhole to the other? The two ends are constantly changing position relative to each other in real space as the Earth and Mars move around the Sun but is the length of the wormhole changing too?
If I moved the Mars end of the wormhole to a distant star system, would the transit time through the wormhole be instantaneous or would it take longer than when it was in orbit around Mars? If so how long?

A: The separation between the two mouthes of the wormhole on the "outside" is technically independant from the separation of the throat. There may be some subtleties involves (it's hard to really discuss exact realistic solutions), but a simple example is to consider the thin-shell wormhole in Minkowski space. In there, the throat distance is always zero, and the distance between the two wormholes is arbitrary, as well as the matter distribution being completely independant from the distance.
In the case where the distance is large enough, I don't think it should have much influence at all even in a more realistic case, as the space around the two mouthes will be roughly Minkowski and as such the local matter distribution will not depend (much) on the distance between them. Slight caveat if the wormhole is near time machine formation (ie, the time shift between the two mouthes is almost equal to the distance between them), in which case quantum effects will probably have some influence on the whole affair.


text:
Q: Linked error/Makefile I am sure this is stupid but i get this linker error
undefined reference to insert_record ,which is a function declared in Operations.hpp,implemented in Operations.cpp and used in main, and i can't find what is wrong in this makefile.
Maybe a pair of rested eyes can spot the problem.
It seems that operations isn't linked although the object is being created.
OBJS = main.o Operations.o CDR.o TBucketList.o RBucketList.o  DateTime.o HashTable.o
CC = g++
CXXFLAGS = -W -Wall -Wno-unused -pedantic  -c -g
LDFLAGS = -W -Wall -Wno-unused -pedantic  -g

werhaus: $(OBJS)
    $(CC) $(LDFLAGS) $(OBJS) -o werhaus

main.o : CDR.hpp Operations.hpp HashTable.hpp
    $(CC) $(CXXFLAGS) main.cpp

Operations.o : Operations.hpp HashTable.hpp
    $(CC) $(CXXFLAGS) Operations.cpp

TBucketList.o : TBucketList.hpp RBucketList.hpp
    $(CC) $(CXXFLAGS) TBucketList.cpp

RBucketList.o : RBucketList.hpp
    $(CC) $(CXXFLAGS) RBucketList.cpp

HashTable.o : HashTable.hpp TBucketList.hpp
    $(CC) $(CXXFLAGS) HashTable.cpp

CDR.o : CDR.hpp DateTime.hpp
    $(CC) $(CXXFLAGS) CDR.cpp

DateTime.o : DateTime.hpp
    $(CC) $(CXXFLAGS) DateTime.cpp

    clean:
    \rm *.o  werhaus

Update:
main.cpp :
insert_record(originator_number, aCDR, destination_number, hashtable1, hashtable2, BucketSize);

Operations.hpp:
void insert_record(const char*, CDR*, const char*, const Hashtable*, const Hashtable*, int);

Operations.cpp:
void insert_record(const char* originator_number, CDR* aCDR, const char* destination_number, Hashtable* hashtable1, Hashtable* hashtable2, int Bsize)

All seem fine in main..

A: There does not seem to be an error in your Makefile. As @G.M. noted, the dependencies of .o to corresponding .cpp are missing, these need to be added.
It can be that insert_record declaration in Operations.hpp does not match the definition in Operations.cpp and you end up with two functions insert_record. Check that the function declaration and definitions match: same return type and argument types, both in the same namespace.

A: I think you should better use something like this:
NAME=   werhaus

CXX=          g++ # Use CXX for C++
CXXFLAGS=     -W -Wall -Wno-unused -pedantic -g
LDFLAGS=      -g # No need for warning flags at linking

SRC=    main.cpp          \
        Operations.cpp    \
        CDR.cpp           \
        TBucketList.cpp   \
        RBucketList.cpp   \
        DateTime.cpp      \
        HashTable.cpp

OBJS=   $(SRC:.cpp=.o)

$(NAME): $(OBJS)
        $(CXX) $(LDFLAGS) $(OBJS) -o $(NAME)

all:    $(NAME)

%.o:    %.cpp
        $(CXX) -o $@ -c $< $(CXXFLAGS)

clean:
        rm -f $(OBJ)

fclean: clean
        rm -f $(NAME)

re:     fclean all

.PHONY: all clean fclean re

This type of makefile will avoid you a lot of errors.
Also, you don't need to put hpp files as dependencies.
Good luck.

A: In Operations.hpp you have a declaration with signature:
void insert_record(
    const char*, CDR*,
    const char*,
    const Hashtable*,
    const Hashtable*,
    int)

In Operations.cpp you define a function with the different signature:
void insert_record(
    const char* CDR*,
    const char*,
    Hashtable*,
    Hashtable*,
    int)

So the declaration in Operations.hpp is not in fact implemented in Operations.cpp
and is undefined.


text:
Q: Sum up tables results from multiple sheets into one table in R I am reading through excel file that has multiple sheets.
 file_to_read <- "./file_name.xlsx"

 # Get all names of sheets in the file
 sheet_names <- readxl::excel_sheets(file_to_read)

 # Loop through sheets
 L <- lapply(sheet_names, function(x) {
 all_cells <-
 tidyxl::xlsx_cells(file_to_read, sheets = x)
})

L here has all the sheets. Now, I need to get the data from each sheet to combine all the columns and rows into one file. To be exact, I want to sum the matching columns and rows in the data into one file.
I will put simple example to make it clear.
For example, this table in one sheet,
df1 <- data.frame(x = 1:5, y = 2:6, z = 3:7)
rownames(df1) <- LETTERS[1:5]
df1
M x y z
A 1 2 3
B 2 3 4
C 3 4 5
D 4 5 6
E 5 6 7

The second table in the next sheet,
df2 <- data.frame(x = 1:5, y = 2:6, z = 3:7, w = 8:12)
rownames(df2) <- LETTERS[3:7]
df2
M x y z  w
C 1 2 3  8
D 2 3 4  9
E 3 4 5 10
F 4 5 6 11
G 5 6 7 12

My goal is to combine (sum) the matched records in all 100 tables from one excel file to get one big tables that has the total sum of each value.
The final table should be like this:
M x y  z   w
A 1 2  3   0
B 2 3  4   0
C 4 6  8   8
D 6 8  10  9
E 8 10 12 10
F 4 5  6  11
G 5 6  7  12

Is there a way to achieve this in R? I am not an expert in R, but I wish if I could know how to read all sheets and do the sum Then save the output to a file.
Thank you

A: As you have stated that you have hundreds of sheets it is suggested that you should import all of these in one single list say my.list in R (as per this link or this readxl documentation suggested) and follow this strategy instead of binding every two dfs one by one
df1 <- read.table(text = 'M x y z
A 1 2 3
B 2 3 4
C 3 4 5
D 4 5 6
E 5 6 7', header = T)
df2 <- read.table(text = 'M x y z  w
C 1 2 3  8
D 2 3 4  9
E 3 4 5 10
F 4 5 6 11
G 5 6 7 12', header = T)

library(tibble)
library(tidyverse)

my.list <- list(df1, df2)

map_dfr(my.list, ~.x)
#>    M x y z  w
#> 1  A 1 2 3 NA
#> 2  B 2 3 4 NA
#> 3  C 3 4 5 NA
#> 4  D 4 5 6 NA
#> 5  E 5 6 7 NA
#> 6  C 1 2 3  8
#> 7  D 2 3 4  9
#> 8  E 3 4 5 10
#> 9  F 4 5 6 11
#> 10 G 5 6 7 12
map_dfr(my.list , ~ .x) %>%
  group_by(M) %>%
  summarise(across(everything(), sum, na.rm = T))
#> # A tibble: 7 x 5
#>   M         x     y     z     w
#>   <chr> <int> <int> <int> <int>
#> 1 A         1     2     3     0
#> 2 B         2     3     4     0
#> 3 C         4     6     8     8
#> 4 D         6     8    10     9
#> 5 E         8    10    12    10
#> 6 F         4     5     6    11
#> 7 G         5     6     7    12

Created on 2021-05-26 by the reprex package (v2.0.0)

A: One approach that will work is these steps:

*

*read each sheet into a list

*convert each sheet into a long format

*bind into a single data frame

*sum and group by over that long data frame

*cast back to tabular format

That should work for N sheets with any combination of row and column headers in those sheets. E.g.
file <- "D:\\Book1.xlsx"
sheet_names <- readxl::excel_sheets(file)
sheet_data <- lapply(sheet_names, function(sheet_name) {
  readxl::read_xlsx(path = file, sheet = sheet_name)
})

# use pivot_longer on each sheet to make long data
long_sheet_data <- lapply(sheet_data, function(data) {
  long <- tidyr::pivot_longer(
    data = data,
    cols = !M,
    names_to = "col",
    values_to = "val"
  )
})

# combine into a single tibble
long_data = dplyr::bind_rows(long_sheet_data)

# sum up matching pairs of `M` and `col`
summarised <- long_data %>%
  group_by(M, col) %>%
  dplyr::summarise(agg = sum(val))

# convert to a tabular format
tabular <- summarised %>%
  tidyr::pivot_wider(
    names_from = col,
    values_from = agg,
    values_fill = 0
  )

tabular

I get this output with a spreadsheet using your initial inputs:
> tabular
# A tibble: 7 x 5
# Groups:   M [7]
  M         x     y     z     w
  <chr> <dbl> <dbl> <dbl> <dbl>
1 A         1     2     3     0
2 B         2     3     4     0
3 C         4     6     8     8
4 D         6     8    10     9
5 E         8    10    12    10
6 F         4     5     6    11
7 G         5     6     7    12

A: You could use dplyr and tidyr to get your desired result:
Let be
df <- data.frame(subject=c(rep("Mother", 2), rep("Child", 2)), modifier=c("chart2", "child", "tech", "unkn"), mother_chart2=1:4, mother_child=5:8, child_tech=9:12, child_unkn=13:16)
> df
  subject modifier mother_chart2 mother_child child_tech child_unkn
1  Mother   chart2             1            5          9         13
2  Mother    child             2            6         10         14
3   Child     tech             3            7         11         15
4   Child     unkn             4            8         12         16

and
df2 <- data.frame(subject=c(rep("Mother", 2), rep("Child", 2)), modifier=c("chart", "child", "tech", "unkn"), mother_chart=101:104, mother_child=105:108, child_tech=109:112, child_unkn=113:116)

> df2
  subject modifier mother_chart mother_child child_tech child_unkn
1  Mother    chart          101          105        109        113
2  Mother    child          102          106        110        114
3   Child     tech          103          107        111        115
4   Child     unkn          104          108        112        116

Then
library(dplyr)
library(tidyr)

df2_tmp <- df2 %>%
  pivot_longer(col=-c("subject", "modifier"))

df %>%
  pivot_longer(col=-c("subject", "modifier")) %>%
  full_join(df2_tmp, by=c("subject", "modifier", "name")) %>%
  mutate(across(starts_with("value"), ~ replace_na(., 0)),
         sum = value.x + value.y) %>%
  select(-value.x, -value.y) %>%
  pivot_wider(names_from=name, values_from=sum, values_fill=0)

returns
# A tibble: 5 x 7
  subject modifier mother_chart2 mother_child child_tech child_unkn mother_chart
  <chr>   <chr>            <dbl>        <dbl>      <dbl>      <dbl>        <dbl>
1 Mother  chart2               1            5          9         13            0
2 Mother  child                2          112        120        128          102
3 Child   tech                 3          114        122        130          103
4 Child   unkn                 4          116        124        132          104
5 Mother  chart                0          105        109        113          101


text:
Q: How can I access functions defined in Google Script Editor outside of it? If I have a function written in Google Spreadsheets script editor that retrieves the data in the spreadsheet in JSON format, how can I access that function outside of the script editor in my own code? I want to access that JSON and manipulate it in my own code. Is there a way to do that using the Spreadsheets API? I format it in a specific way inside script editor so I can't just use the json-in-script provided. In the call (http://spreadsheets.google.com/feeds/feed/key/worksheet/public/basic?alt=json-in-script&callback=myFunc) there's a callback function for myFunc. Can I use the function I defined in the script editor to replace myFunc?

A: Following your comment that brings some details on your use case, there is a Google-Apps-Script feature specially designed to give access to some functions you wrote from within another script : is is called libraries and is fully described in the documentation.

EDIT, following 2cond comment:
Calling a GS function from a javascript (or any other language) script that is not a Google Script (GS) is not possible if you consider using it as a function...
but
what you can eventually do - depending on the data this function must handle - is to deploy a script as a webApp running as a service and call this service from your external app using the equivalent of an urlFetch (that's the service doing that in GS).
The service will have an url to which you can add parameters and it will return a result that you can use in your local app.
Of course this workflow has a few limitations and might quickly become complex but in many cases it is fully workable.
Note that the url you will have to use in the "versioned" one ending with .exec (Not sure this word is correct but I mean the published url that corresponds to a version of your script and not the ".dev" one that one can use to test a script in GS).
You'll find details about that in the documentation and on many other ressources, including SO. The url is typically something like this :
https://script.google.com/macros/s/AKfycbyw-2WtmF7wsd__________azjImbMWm5YrxB8/exec?someParameter=someValue&otherParam=otherVal // etc...


text:
Q: Cannot access Apache web server from Wan side I am running apache 2.4.46 on parrot linux, I modified the default /var/www/html/index.html using html for educational purpose. I can access this server on LAN but I want to access this apache server on WAN, following some tutorials I port forwarded to inet 192.168.0.104 and port 80, I also used no-ip website to get a free dns and succesfully added it to my router. When I try to connect to this dns I get a 404 error. Can somebody help me to understand what I am missing.
ps ~ I after that removed the apache service and added ssh service on port 22 to check whether it was a dns mistake but I was successfully able to ssh into my computer over WAN

A: If you are receiving a 404 then you know your Apache server is visible to the outside world. A 404 means the server received the request but can't find a file. If the server were not accessible, you would see a timeout.
The most common cause of this issue is an incomplete Apache configuration. Check that you have a ServerAlias line in your /etc/apache2/sites-enabled/000-default.conf file (or whichever site config file is your target). The line can contain multiple routing targets for the Apache installation. For example:
ServerAlias example.com *.example.com

Generally what I do with these is have a catch all *.* thrown on the end so that any unexpected request routes, such as an IP address or bare CNAME address, gets handled without returning a 404 or 500 error.


text:
Q: transforming XML having column wise data into row wise table form using XSLT I have below XML which is coming from client side , I need to transform that into table using XSLT. The data is coming Column wise and I need create a table by selecting first Column Data of every Column element and then second Column Data of every Column element and put that in
.

Note : Element Columnn contains First , second , third column data
Nested Element ColumnData contains row 1 .. row N data for each column.
<?xml version="1.0" encoding="utf-8"?>
<ColumnSet> /* This is group of all columns*/
  <Columnn value="ColumnName1" > /*This contains first column's rows*/
    <ColumnData value="R1C1"/> /*This is Row 1 of Column 1 */
    <ColumnData value="R2C1"/>
  </Columnn>
  <Columnn value="ColumnName2" > /*This element has second column's all rows*/
    <ColumnData value="R1C2"/>
    <ColumnData value="R2C2"/>
  </Columnn>
</ColumnSet>

I want to see the result in below form
ColumnName1      ColumnaName2
R1C1                 R1C2
R2C1                 R2C2

How do I accomplish this ?

A: Try it this way:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" omit-xml-declaration="yes" version="1.0" encoding="utf-8" indent="yes"/>

<xsl:template match="/ColumnSet">
    <xsl:variable name="cols" select="Columnn"/>
    <xsl:variable name="rows" select="Columnn[1]/ColumnData"/>

            <xsl:for-each select="$cols">
                <xsl:value-of select="@value"/>
             </xsl:for-each>

        <xsl:for-each select="$rows">
            <xsl:variable name="i" select="position()"/>

                <xsl:for-each select="$cols">
                    <xsl:value-of select="ColumnData[$i]/@value"/>
                </xsl:for-each>

        </xsl:for-each>

</xsl:template>

</xsl:stylesheet>


text:
Q: React hooks: Can't update state inside function component I'm new to React and am trying to figure out how to make a phonebook. I've gotten quite far but I'm having an issue I can't solve. I'm using React Hooks.
Everything works fine, except for when I call the setNewNumber('') and setNewName('') functions at the end of addPerson(), just before the filteredEntries const.
I want to reset the input fields in the form to empty strings ('') once the other code inside addPerson() is done running, but it seems like the two functions are never called since the value for newName and newNumber don't change to '' (instead they keep the values the user added). However, my other useState functions (setPersons() and setFilteredPersons()) work inside addPerson()...
I've tried reading the documentation and asking around but haven't found a solution. I'd be very grateful for any clues/help!
import React, { useState } from 'react'
import Person from './components/Person'

const App = () => {
  const [ persons, setPersons ] = useState([
    { name: 'Cat', number: '111' },
    { name: 'Dog', number: '222' },
    { name: 'Horse', number: '333' },
    { name: 'Owl', number: '444' }
  ])
  const [filteredPersons, setFilteredPersons] = useState([...persons])
  const [ newName, setNewName ] = useState('')
  const [ newNumber, setNewNumber ] = useState('')

  const addPerson = (event) => {
    event.preventDefault()

    const createPerson = () => {
      const personObject = {
        name: newName,
        number: newNumber,
      }
      setPersons([...persons, personObject])
      setFilteredPersons([...persons, personObject]) //varför går det inte att bara köra [...persons?]
    }

    const upperCaseNewName = newName.toUpperCase()
    let doubleName
    persons.map(person => {
      const upperCasePerson = person.name.toUpperCase()
      if(upperCaseNewName === upperCasePerson) {
        doubleName = upperCasePerson
      }
      return doubleName
    })

    if (doubleName === undefined) {
      createPerson()
    } else if(doubleName === upperCaseNewName) {
      alert(`${newName} is already in the phonebook`)
    }

    setNewName('')
    setNewNumber('')
  }

  const filterEntries = event => {
      let filtered = persons.filter(person => {
        return person.name.toUpperCase().indexOf(event.target.value.toUpperCase()) !== -1
      })
    setFilteredPersons(filtered)
  }

  const renderPersons = () => filteredPersons.map(person =>
    <Person key={person.name} name={person.name} number={person.number}/>
  )

  return (

Phonebook

Filter entries:
 <input onChange={(event) => filterEntries(event)}/>
      <form>

          name: <input onChange={(event) => setNewName(event.target.value)}/>

          phone: <input onChange={(event) => setNewNumber(event.target.value)}/>

          <button type="submit" onClick={addPerson}>add</button>

      </form>

Numbers

      {renderPersons()}

  )
}

export default App

The person component at the top just contains this code:
import React from 'react'

const Person = (props) => {
    return(
        <>

{props.name} {props.number}

        </>
    )
}

export default Person

A: Your components are not actually tied to your state values. You need them to be "controlled." Check out the docs for more examples :)
https://reactjs.org/docs/forms.html#controlled-components
<input value={newName} onChange={event => setNewName(event.target.value)} />

A: The reset is working correctly. What you forgot to do is add the value to each input. Without the value attribute the input is considered an uncontrolled component. By the sounds of it, you're looking to control the value via code.
Change

  name: <input onChange={event => setNewName(event.target.value)} />

  phone: <input onChange={event => setNewNumber(event.target.value)} />

to

  name: <input value={newName} onChange={event => setNewName(event.target.value)} />

  phone: <input value={newNumber} onChange={event => setNewNumber(event.target.value)} />

Codesandbox Demo

A: You have missed adding value attribute to input and thus your component is not the "Controlled" component.
You can read more here.
Changes needed
<input
   value={newName}
   onChange={event => setNewName(event.target.value)}
/>

phone:
<input
   value={newNumber}
   onChange={event => setNewNumber(event.target.value)}
/>

Codesandbox Link: https://codesandbox.io/s/crimson-frog-ecp98
Hope this Helps!


text:
Q: Windows 7 user cannot connect to mapped drives over VPN I have a user that when connected to domain using the windows 7 VPN client, cannot access any of her mapped network drives.
I know it is not a DNS issue because I can ping the servers the drives are located on by hostname, and the drives are mapped by I.P. addresses anyway.
I tried uninstalling the users firewall and connecting to the mapped drives, but no dice.
The only error message I get is "unexpected network error occurred" or no error at all, it just times out.
I tried using the same domain account to connect to the VPN on another machine, and I can access the shared drives just fine.
What could be causing this issue?

A: I'd guess VPN settings are blocking traffic from the entry point being used to the network shares. That behavior is what I would expect to see in that instance. If the other PC you accessed the network with was setup on a different VPN entry point, that would explain the issue.


text:
Q: Why onPurchasesUpdated isn't being called after launchBillingFlow I'm in the process of implementing in app billing for Android and have got to the point where I can retrieve a list of products from the store. And can activate the Google purchase dialog via calling the launchBillingFlow() method. The documentation indicates that once this has been called, the onPurchasesUpdated is then called with the result. However this isn't happening for me.
The logging confirms that the purchase is requested (from within my method: startPurchaseFlow()). My onPurchasesUpdated() is also called when the activity first runs and provides a OK result (0) to confirm connection set up.
But why isn't it being called after launchBillingFlow()?
Class that holds purchase mechanics:
public class BillingManager implements PurchasesUpdatedListener {
    private final BillingClient mBillingClient; // Billing client used to interface with Google Play
    private final Store mActivity; // Referenced in constructor

   // Structure to hold the details of SKUs returned from querying store
    private static final HashMap<String, List<String>> SKUS;
    static
    {
        SKUS = new HashMap<>();
        SKUS.put(BillingClient.SkuType.INAPP, Arrays.asList("com.identifier.unlock")); // Strings for in app permanent products
    }

    public List<String> getSkus(@BillingClient.SkuType String type) {
        return SKUS.get(type);
    }

    // Constructor
    public BillingManager(Store activity) {
        mActivity = activity;
        mBillingClient = BillingClient.newBuilder(mActivity).setListener(this).build(); // Initialise billing client and set listener
        mBillingClient.startConnection(new BillingClientStateListener() { // Start connection via billing client
            @Override
            public void onBillingSetupFinished(@BillingClient.BillingResponse int billingResponse) { // Actions to complete when connection is set up
                if (billingResponse == BillingClient.BillingResponse.OK) {
                    Log.i("dev", "onBillingSetupFinished() response: " + billingResponse);
                    mActivity.getProducts();
                } else {
                    Log.w("dev", "onBillingSetupFinished() error code: " + billingResponse);
                }
            }
            @Override
            public void onBillingServiceDisconnected() { // Called when the connection is disconnected
                Log.w("dev", "onBillingServiceDisconnected()");
            }
        });
    }

    // Receives callbacks on updates regarding future purchases
    @Override
    public void onPurchasesUpdated(@BillingClient.BillingResponse int responseCode,
                                   List<Purchase> purchases) {
        Log.d(TAG, "onPurchasesUpdated() response: " + responseCode);
        if (responseCode == 0 && !purchases.isEmpty()) {
            String purchaseToken;
            for (Purchase element : purchases) {
                purchaseToken = element.getPurchaseToken();
                mBillingClient.consumeAsync(purchaseToken, null); // Test to 'undo' the purchase TEST
            }
        }
    }

    // Used to query store and get details of products args include products to query including type and list of SKUs and a listener for response
    public void querySkuDetailsAsync(@BillingClient.SkuType final String itemType,
                                     final List<String> skuList, final SkuDetailsResponseListener listener) {
        // Create a SkuDetailsParams instance containing args
        SkuDetailsParams skuDetailsParams = SkuDetailsParams.newBuilder()
                .setSkusList(skuList).setType(itemType).build();
        //Query the billing client using the SkuDetailsParams object as an arg
        mBillingClient.querySkuDetailsAsync(skuDetailsParams,
                new SkuDetailsResponseListener() {

            // Override the response to use the listener provided originally in args
            @Override
                    public void onSkuDetailsResponse(int responseCode,
                                                     List<SkuDetails> skuDetailsList) {
                        listener.onSkuDetailsResponse(responseCode, skuDetailsList);
                    }
                });
    }

    // Start purchase flow with retry option
    public void startPurchaseFlow(final String skuId, final String billingType) {
        Log.i("dev", "Starting purchaseflow...");

        // Specify a runnable to start when connection to Billing client is established
        Runnable executeOnConnectedService = new Runnable() {
            @Override
            public void run() {
                BillingFlowParams billingFlowParams = BillingFlowParams.newBuilder()
                        .setType(billingType)
                        .setSku(skuId)
                        .build();
                mBillingClient.launchBillingFlow(mActivity, billingFlowParams);
                Log.i("dev", "Just called launchBillingFlow..." + skuId);

            }
        };

        // If Billing client was disconnected, we retry 1 time
        // and if success, execute the query
        startServiceConnectionIfNeeded(executeOnConnectedService);
    }
    // Starts connection with reconnect try
    private void startServiceConnectionIfNeeded(final Runnable executeOnSuccess) {
        if (mBillingClient.isReady()) {
            if (executeOnSuccess != null) {
                executeOnSuccess.run();
            }
        } else {
            mBillingClient.startConnection(new BillingClientStateListener() {
                @Override
                public void onBillingSetupFinished(@BillingClient.BillingResponse int billingResponse) {
                    if (billingResponse == BillingClient.BillingResponse.OK) {
                        Log.i(TAG, "onBillingSetupFinished() response: " + billingResponse);
                        if (executeOnSuccess != null) {
                            executeOnSuccess.run();
                        }
                    } else {
                        Log.w(TAG, "onBillingSetupFinished() error code: " + billingResponse);
                    }
                }
                @Override
                public void onBillingServiceDisconnected() {
                    Log.w(TAG, "onBillingServiceDisconnected()");
                }
            });
        }
    }

} // End of class

Class that implements interface and initiates request for purchases and displays product information:
public class Store extends AppCompatActivity {
    SharedPreferences prefs; // used to access and update the pro value
    BillingManager billingManager; // Used to process purchases

    // Following are used to store local details about unlock product from the play store
    String productSku = "Loading"; // Holds SKU details
    String productBillingType = "Loading";
    String productTitle = "Loading"; // Will be used to display product title in the store activity
    String productPrice = "Loading"; // Used to display product price
    String productDescription = "Loading"; // Used to display the product description

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_store);

        // Set up toolbar
        Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
        setSupportActionBar(myToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        // Create billing manager instance
        billingManager = new BillingManager(this);
        // Set up the shared preferences variable
        prefs = this.getSharedPreferences(
                "com.identifier", Context.MODE_PRIVATE); // Initiate the preferences

        // set up buttons
        final Button btnBuy = findViewById(R.id.btnBuy);
        btnBuy.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                billingManager.startPurchaseFlow(/*productSku*/ "android.test.purchased", productBillingType); // Amended for TEST
            }
        });
        final Button btnPro = findViewById(R.id.btnPro);
        btnPro.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                getProducts();
            }
        });
        getProducts();
        updateDisplay();
    } // End of onCreate

    // Used to unlock the app
    public void unlock() {
        Log.d("dev", "in unlock(),  about to set to true");

        prefs.edit().putBoolean("pro", true).apply();
        MainActivity.pro = true;

    }

    // Go back if back/home pressed
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {

            // Respond to the action bar's Up/Home button
            case android.R.id.home:
             NavUtils.navigateUpFromSameTask(this);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
// Used to request details of products from the store from this class
    public void getProducts() {
        List<String> inAppSkus = billingManager.getSkus(BillingClient.SkuType.INAPP); // Create local list of Skus for query
        billingManager.querySkuDetailsAsync(BillingClient.SkuType.INAPP, inAppSkus, new SkuDetailsResponseListener() {
            @Override
            public void onSkuDetailsResponse(int responseCode, List<SkuDetails> skuDetailsList) {
                if (responseCode == BillingClient.BillingResponse.OK && skuDetailsList != null) {
                    for (SkuDetails details : skuDetailsList) {
                        productSku = details.getSku();
                        productTitle = details.getTitle();
                        productDescription = details.getDescription();
                        productPrice = details.getPrice();
                        productBillingType = details.getType();
                    }
                    updateDisplay();
                }
            }
        });
    }
// Helper method to update the display with strings
    private void updateDisplay() {
        final TextView titleText = findViewById(R.id.txtTitle);
        final TextView descriptionText = findViewById(R.id.txtDescription);
        final TextView priceText = findViewById(R.id.txtPrice);
        titleText.setText(productTitle);
        descriptionText.setText(productDescription);
        priceText.setText(productPrice);
    }
}

A: Ok, so this (replacing the onPurchasesUpdated method above) is now working/responding as expected. Why, I don't know, but it is.
 @Override
 public void onPurchasesUpdated(@BillingClient.BillingResponse int responseCode,
                         List<Purchase> purchases) {
     if (responseCode == BillingClient.BillingResponse.OK
             && purchases != null) {
         for (Purchase purchase : purchases) {
             Log.d(TAG, "onPurchasesUpdated() response: " + responseCode);
             Log.i("dev", "successful purchase...");
             String purchasedSku = purchase.getSku();
             Log.i("dev", "Purchased SKU: " + purchasedSku);
             String purchaseToken = purchase.getPurchaseToken();
             mBillingClient.consumeAsync(purchaseToken, null); // Test to 'undo' the purchase TEST
             mActivity.unlock();
         }
     } else if (responseCode == BillingClient.BillingResponse.USER_CANCELED) {
         // Handle an error caused by a user cancelling the purchase flow.
         Log.d(TAG, "onPurchasesUpdated() response: User cancelled" + responseCode);
     } else {
         // Handle any other error codes.
     }
 }


text:
Q: Open Stack Log Format I am trying to analyze the OpenStack log file having the following format:
nova-api.log.1.2017-05-16_13:53:08    16-05-17    00:00.3 25746   INFO    nova.osapi_compute.wsgi.server  [req-9bc36dd9-91c5-4314-898a-47625eb93b09   113d3a99c3da401fbd62cc2caa5b96d2    54fadb412c4e40cdbaed9335e4c35a9e    -   -   -]  10.11.10.1  GET /v2/54fadb412c4e40cdbaed9335e4c35a9e/servers/detail HTTP/1.1    status: 200 len:    1893    time:   0.2577181
Looking for a help to know the headers of every session in the above Log...Sorry, I am new to this area any suggestions will be really a great help...


text:
Q: Load Unpacked Chrome Extension not working I'm getting started on my first extension using the Chrome tutorial and got tripped up almost immediately. Says to click Load Unpacked and then select the file path to the manifest file. However, when I click Load Unpacked nothing shows up; no file explorer or even an error message. There's no change to the screen. Any understanding on why this might be happening?

A: Regedit:
Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome\ExtensionInstallBlocklist
Then remove * from 1
Restart chrome.
Bingo, can add Extensions...

A: Go to chrome://policy/ and check if the ExtensionInstallBlacklist policy has been set.
If it is, then ask your friendly admin if they can please update the policy.
[Update] Open Dev Tools (F12) and check under console. If you see a policy error, then you know the culprit.

A: strace may be of value here. First, pstree -p to find the root PID of chrome or chromium. Then strace -f -s256 -v -p $CHROMEPID -o/tmp/chrome.strace.log, where CHROMEPID is the PID you found in the first step.
I was having a similar problem, however I did get a file explorer and was able to navigate to the extension directory, but then I couldn't figure out how to actually enable it; nothing showed up in the directory itself to click on. On the bottom was only "Select Folder". But then I tried maximizing the window (in the fluxbox taskbar, right-clicked the name of the window and selected Maximize), then I found the "Cancel" and "Open" buttons below "Select Folder". Clicking Open on the folder from one level up did the trick.
I know this won't likely help the OP but maybe it will help somebody.

A: Make sure you don't have an extension with the exact same name installed from the Web Store.
In the past, you could have two versions of the same extension installed side by side, one from the store and one loaded unpacked. In the past few months, that changed.


text:
Q: Is it possible to construct an actual light-clock, with a single photon bouncing between two parallel mirrors? And the clock would be connected to a recording apparatus, thus taking the concept of a light-clock from thought-experiment to reality?  Could that photon bounce "indefinitely"?

A:
Is it possible to construct an actual light-clock, with a single photon bouncing between two parallel mirrors?

The short answer is no
1)The short reason is that a photon is an elementary particle and exists in the quantum mechanical framework. Any interactions with other particles, as the ones in the mirrors, will have a probability of Compton scattering and and  loosing energy and eventually its original energy will be completely absorbed .
2)In order to be used as a clock, it must interact with some recording set up and this interaction, to register will take some of the energy of the photon, see 1).


text:
Q: how to represent metadata in a data warehouse I am working on to create a data warehouse. I have made a database which will be the data warehouse and will consist of dimension and fact tables. I know that other than dimension and fact table a data warehouse should also consist of a meta data, now my question is what should be the structure of metadata and all the information it should have?

A: What about having Azure Data Catalog capture the table and column names and let developers and business users collaborate on the definitions in a UI? This would be a great data dictionary.
http://azure.microsoft.com/en-us/services/data-catalog/
Or if you want to roll your own with extended properties you might do the following:
https://www.mssqltips.com/sqlservertip/1637/script-to-build-a-sql-server-data-dictionary-and-report-with-microsoft-excel/


text:
Q: How to get accurate position from GPS periodically In application I need to get geo position of phone every x minutes (for now it's 5min and 50m), in such a way that phone doesn't discharge during day. The accuracy of position must be at least 40m. By now I have listeners for gps and network. The problem lies in the fact that the data I can receive sometimes is totally wrong (depends on phone) - new position can be even 200m from my real position and with 40m accuracy; next point can be the same but in opposite direction. For my app it's fatally.
So the question is next: Is there any way to get more accuracy data but not very often?
Update 1: to show the problem in action:

(The phone is lying in the fixed position)

A: To get more accurate location make sure you're using the    ACCESS_FINE_LOCATION permission in your manifest. To prevent higher battery usage, you can use setInterval and setFastestInterval on your LocationRequest object. Longer intervals mean less battery usage by your app.

A: You should not be accessing the gps and network directly, you should be using LocationManager and using ACCURACY_FINE in your Criteria. This will help conserve battery life, and avoid issues with phones where the gps may have been disabled. There's more detail on that here.
As far as the accuracy of your location, you can use Location's getAccuracy method to get Android's estimate of how accurate a measurement is. If it doesn't fit your criteria, discard it and poll again.


text:
Q: How to create 'terms & conditions check box' in django?
I want to make a registration form like this, where user would type username,email,password,confirm password and check the terms and condition box to register his/herself. But i dont know how to create a model row for check box so that according to its input i would allow or disallow user to register.
models.py
class registeration(models.Model):
    username = models.CharField(max_length=100)
    email = models.EmailField()
    password = models.CharField(max_length=100)
    confirm_pasword = models.CharField(max_length=100)

    def __str__(self):
        return self.username

A: You can use BooleanField for this:
terms_confirmed = models.BooleanField()