text:
Q: iOS 13.1 doesn't receive silent CKQuerySubscription notifications My app uses CloudKit Query subscriptions and notifications as part of a CloudKit-based synchronization solution. This works perfectly with iOS 12, macOS 10.14 and even macOS 10.15 beta, but NOT with iOS 13.0, iOS 13.1, iPadOS 13.1 and tvOS 13.0.
Removing and recreating the subscriptions doesn't solve this.
Is this a known problem?
According to the documentation, nothing has changed with CloudKit subscriptions. Or did I miss something?

A: To receive silent CKQuerySubscription notifications in iOS 13.x and tvOS 13.x, the soundName and alertBody parameters of the NotificationInfo of your CKQuerySubscription must not be set.
In the past we have learned to use an empty string for said parameters, to make the whole CloudKit subscription thing working, but that's now history. Apparently Apple has fixed an old bug, causing problems with apps that used this 'workaround'.
I have tested this on iOS 12.4.2, iOS 13.1.2, tvOS 13.0, macOS 10.14.6 and macOS 10.15 GM.
let info = CKSubscription.NotificationInfo()
info.shouldSendContentAvailable = true
// info.soundName = "" // Don't set this property
// info.alertBody = "" // And also leave this this property alone
let subscription = CKQuerySubscription(recordType: "yourRecordType", predicate: NSPredicate(value: true), subscriptionID: "yourSubscription", options: [CKQuerySubscription.Options.firesOnRecordUpdate, CKQuerySubscription.Options.firesOnRecordDeletion])
subscription.notificationInfo = info

// You must first delete the old subscription to change the sound name
let deleteOperation = CKModifySubscriptionsOperation(subscriptionsToSave: nil, subscriptionIDsToDelete: ["yourSubscription"])
yourContainer.privateCloudDatabase.add(deleteOperation)

let createOperation = CKModifySubscriptionsOperation(subscriptionsToSave: [subscription], subscriptionIDsToDelete: nil)
createOperation.addDependency(deleteOperation)
yourContainer.privateCloudDatabase.add(createOperation)

A: Silent Notifications stopped working for my app as well in iOS 13.

*

*On my iOS 12 devices and MacBook, silent notifications kept working correctly.

*Recreated subscriptions multiple times without success.

*Checked all steps in
https://developer.apple.com/library/archive/qa/qa1917/_index.html
When I saw Ely's answer, I immediately went to check if I had a soundName set for the notification. Though I did not have any, I saw the alertBody empty string and decided to try it without it. After recreating the subscription, silent notifications started working again in iOS 13. When reading the documentation, it seems obvious that you do not want an alert message on a silent notification. However, I do remember adding it at some point to make it work on another iOS version.
In my case, I was creating a RecordZoneSubscription like this:
CKSubscription * subscription = [[CKRecordZoneSubscription alloc] initWithZoneID:self.dataZone.zoneID subscriptionID:[self mainPrivateSubscriptionID]];

CKNotificationInfo *notificationInfo = [CKNotificationInfo new];
notificationInfo.shouldBadge = false;
notificationInfo.alertBody = @""; // THE CULPRIT
notificationInfo.shouldSendContentAvailable = true;
subscription.notificationInfo = notificationInfo;

Solution:
CKSubscription * subscription = [[CKRecordZoneSubscription alloc] initWithZoneID:self.dataZone.zoneID subscriptionID:[self mainPrivateSubscriptionID]];

CKNotificationInfo *notificationInfo = [CKNotificationInfo new];
notificationInfo.shouldBadge = false;
notificationInfo.shouldSendContentAvailable = true;
subscription.notificationInfo = notificationInfo;


text:
Q: WebApi 2.0 - ApiControllers em outro Assembly não sofrem mapeamento se runAllManagedModulesForAllRequests="false" Eu tenho uma aplicação WebApi2 que implementa alguns ApiControllers.
Esta mesma aplicação referencia um Assembly que implementa alguns mais.
Todos estes controllers utilizam Attribute Routing, como no exemplo a seguir:
[RoutePrefix("sample1.endpoint")]
public class SampleController : ApiController
{
    [Route("")]
    [HttpGet]
    public HttpResponseMessage WebApiTest()

Se defino runAllManagedModulesForAllRequests="true" no web.config, a aplicação funciona perfeitamente - mas eu quero desligar este atributo (que pode ser bastante custoso em produção).
Porém, se eu ajustar o valor de runAllManagedModulesForAllRequests para false, apenas os ApiControllers locais são corretamente mapeados; chamadas para os outros geram um 404.
Qual parte, provavelmente óbvia, eu não implementei?
(cross-post: https://stackoverflow.com/questions/29376376/webapi-2-0-apicontrollers-in-another-assembly-fail-to-map-if-runallmanagedmodu)

A: Segundo a resposta nesta questão no SOEN, o problema é que o módulo não está sendo carregado. Para isso basta chamar um método qualquer do módulo para poder garantir que o mesmo foi carregado, antes de chamar o MapHttpAttributeRoutes.
A resposta sugere que você crie o seguinte método na sua biblioteca externa:
public static class MyApiConfig {
  public static void Register(HttpConfiguration config) {
      config.MapHttpAttributeRoutes();
  }
}

E que se chame este método para registrar o módulo.
Você terá problemas caso existam vários módulos, pois ai o método MapHttpAttributeRoutes seria chamado várias vezes.
Se esse for o caso, pode criar um método que não receba nada, chamado LoadModule, cuja única operação vai ser algo que o compilador não possa resolver eliminar o método:
public static class MyApiConfig {
  public static Type LoadModule() {
      return typeof(MyApiConfig);
  }
}

Você deve chamar esse método, de cada módulo, antes de chamar o MapHttpAttributeRoutes.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a limit to the number of naturally-spawned wolves you can have? I was wondering if there was a limit to the amount of wolves you can have in Minecraft. I have seen a lot of videos of people with a lot of wolves. Just wondering how because there is a limit to the number of mobs that can spawn around you. I would like to know if everything written here can be done legit.

A: There is no limit to the amount of wolves you can have at a time tamed. However, there is a limit of about 6 wolves that can be naturally spawned in a about 30 block radius untamed. This also applies to hostile mobs.  Passive mobs (like cows, sheep, etc.) have a different spawn limit. For more information, see "Spawning" on the "Wolf" page at Minecraft Wiki.


text:
Q: How to display redis data in humanfriendly from in javascript I run the following command in redis to set hash and decrement amount of this hash
127.0.0.1:6379> hset test:key amount 133243112
(integer) 1
127.0.0.1:6379> hincrbyfloat test:key amount -18978839
"114264273"
127.0.0.1:6379> hincrbyfloat test:key amount -102099438.3
"12164834.69999999999708962"
127.0.0.1:6379> hincrbyfloat test:key amount -12164834.7
"-0.00000000000272848"

And when I try to get value in javascript I have got the string "-0.00000000000272848". How can I convert this string to humanfriendly value "0"


text:
Q: How could I split a list based on first character of word and put them in a dictionary without using modules? I'm trying to split the following list according to the starting character of each word:
word_list = ['be','have','do','say','get','make','go','know','take','see','come','think',
     'look','want','give','use','find','tell','ask','work','seem','feel','leave','call']

and put them in a dictionary without using modules.
This is what I tried:
word_list = ['be','have','do','say','get','make','go','know','take','see','come','think',
     'look','want','give','use','find','tell','ask','work','seem','feel','leave','call']
n = 'a'
x = []

dictionary = dict()

for c in range(97, 123):
        x.append(chr(c))
print(x)
print()

for i in x:
    for j in word_list:
        if i in dictionary.keys():
            if j.startswith(i):
                dictionary[i].append(j)
            else:
                dictionary = [j]
print(dictionary)

The expected results:
dictionary = {'a':['ask'],'b':['be'],...................}

A: You can use setdefault or defaultdict:
word_list = ['be','have','do','say','get','make','go','know','take','see','come','think',
     'look','want','give','use','find','tell','ask','work','seem','feel','leave','call']

result = {}
for word in word_list:
    result.setdefault(word[0], []).append(word)

# OR

from collections import defaultdict

result = defaultdict(list)
for word in word_list:
    result[word[0]].append(word)

defaultdict has the exact same interface as dict otherwise, so it can be used anywhere you need a dict.

A: Try the code below,
word_list = ['be','have','do','say','get','make','go','know','take','see','come','think',
     'look','want','give','use','find','tell','ask','work','seem','feel','leave','call']

dictionary = dict()
for c in map(chr,range(97, 123)):
    words = [i for i in word_list if i.startswith(c)]
    if words:
        dictionary[c] = words
print(dictionary)

A: The problem with your code is that there are no keys in your dictionary to start with, so if i in dictionary.keys(): is never true because you never execute any code to put a key into the dictionary. Basically you need to add to the dictionary when j starts with i and i is not already a key in the dictionary:
for i in x:
    for j in word_list:
        if i in dictionary.keys():
            if j.startswith(i):
                dictionary[i].append(j)
        elif j.startswith(i):
            dictionary[i] = [j]
print(dictionary)

Output:
{'f': ['find', 'feel'],
 'l': ['look', 'leave'],
 'd': ['do'],
 'g': ['get', 'go', 'give'],
 't': ['take', 'think', 'tell'],
 'h': ['have'],
 'u': ['use'],
 's': ['say', 'see', 'seem'],
 'm': ['make'],
 'b': ['be'],
 'a': ['ask'],
 'w': ['want', 'work'],
 'k': ['know'],
 'c': ['come', 'call']
}

You can achieve the same result with a nested dictionary/list comprehension:
dictionary = { c : [w for w in word_list if w.startswith(c)] for c in [w[:1] for w in word_list] }


text:
Q: Cannot update views on left and right side of view pager I have used viewpager which displays view with an image and radiobutton below. Each swipe screen is not a fragment, they are  layouts which just swipe the same view with different imageview. The problem is that, I am unable to deselect the radio button which is in left and right side of the current view after i select the radio button of the current screen. If I return POSITION_NONE in getItemPosition(), it refresh the screen and radio button also deselected but the view is flickered. If i am able to call instantiateItem(), my problem is solved .  But this method is called only when view is destroyed based on the setOffsetScreenPageLimit(). How can I achieved such requirements, if view pager cannot help?
Fragment:
public class AnswerImageDialogFragment extends DialogFragment implements ViewPager.OnPageChangeListener {
//member declaration

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    String strQuestion = null;

    View rootView = inflater.inflate(R.layout.activity_viewpager_demo, container,
        false);
    getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
    intro_images = (ViewPager) rootView.findViewById(R.id.pager_introduction);
    pager_indicator = (LinearLayout) rootView.findViewById(R.id.viewPagerCountDots);

   //do some stuff

    //set the adapter
    mAdapter = new ViewPagerAdapter(getContext(), map);
    intro_images.setAdapter(mAdapter);
    intro_images.setCurrentItem(clickPosition);
    intro_images.setOnPageChangeListener(this);
    setUiPageViewController();

    bus = EventBus.getDefault();
    bus.register(this);
    return rootView;
}
//other method
}

PagerAdapter:
public class ViewPagerAdapter extends PagerAdapter {
// member declaration
public ViewPagerAdapter(Context mContext, HashMap<String, Object> map) {
//other initialization
}
@Override
public int getCount() {
    return optionImages.size();
}

@Override
public boolean isViewFromObject(View view, Object object) {
    return view == ((LinearLayout) object);
}

@Override
public Object instantiateItem(ViewGroup container, final int position) {
    View itemView = LayoutInflater.from(mContext).inflate(R.layout.pager_item, container, false);

    final ImageView ivOption = (ImageView) itemView.findViewById(R.id.answerId); // this is used as radio button in this case

    /*The code snippet is to select the answer option based on whether answer is choosen or not.
      If choosen, select as default in the pop up answer.
    */
    if (null != ans) {
        Iterator iterator = ans.iterator();
        if (ans.size() > 0) {
            int value = (int) iterator.next();
            if (value == position) {
                ivOption.setImageResource(R.drawable.ic_radio_button_tick);
            } else {
                ivOption.setImageResource(R.drawable.ic_radio_button_nontick);
            }
        }
    }
    p = position;

    /*The code snippet is to change the answer value based on the user selection.
      This means if user choosen another answer then clear the earlier choosen answer
    */
    ivOption.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            //do stuff
        }
    });

    txtQuestion.setText(question);
    txtOption.setText(optionsList.get(position));

    imageView.setParseFile(optionImages.get(position));
    imageView.loadInBackground();
    container.addView(itemView);
    return itemView;
}

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
    LinearLayout ll = (LinearLayout) object;
    /*RelativeLayout ivOption = (RelativeLayout) ll.getChildAt(2);
    ImageView iv = (ImageView) ivOption.getChildAt(1);
    iv.setImageResource(R.drawable.ic_radio_button_tick);*/
    container.removeView(ll);
}
@Override
public int getItemPosition(Object object) {
    return super.getItemPosition(object);
}

public void refresh(ArrayList object) {
    this.object = new ArrayList();
    this.object.addAll(object);
    this.notifyDataSetChanged();
}


text:
Q: Pass arbitrary connection options to Farday I'm trying to convert a project I have from using Excon to Faraday with the Excon adapter, but I'm not having any luck.
The issue is that I need to pass through some arbitrary connection options to Excon as the API I am interfacing with uses client side SSL certs for authentication.
To make the connection with straight Excon I was using this:
@connection = Excon.new("some_url", client_cert: File.expand_path(@some_cert), client_key: File.expand_path(@some_key))

According to the Faraday documention, I should be able to do something like this:s
@connection = Faraday::Connection.new(url: "some_url", client_cert: File.expand_path(@some_cert), client_key: File.expand_path(@some_key)) do |faraday|
  faraday.adapter :excon
end

When I try that (with the 0.9 RC5 from Github), I get an undefined method client_cert= error, which leads me to believe the documentation is out of date.  Does anybody know how to pass arbitrary connection options through to an adapter?

A: You have to pass the SSL options as a hash.  This should work:
ssl_opts = {
  client_cert: File.expand_path(@some_cert),
  client_key: File.expand_path(@some_key)
}
@connection = Faraday::Connection.new(url: "some_url", ssl: ssl_opts) do |faraday|
  faraday.adapter :excon
end

This gist has some more examples for using SSL with Faraday.


text:
Q: Conflicting answers gained from different equations First time posting I hope this is the place.
if someone could help me sort out formatting for the equations that would be nice
"As a result of being hit from behind by a toy truck, a 50g toy car rolls 3.0m across a floor that applies a constant retarding force of 1.2N to it. The car stops 2.0s after being hit. If the truck was in a contact with the ball for 0.15s calculate the impulse given to the car"
I started off this question by calculating the acceleration acting on the ball after the impact
\begin{eqnarray*}
F &=& ma\\
\therefore F/m &=& a\\
\therefore -1.2/0.05 &=& a = -24ms^{-2}\\
\end{eqnarray*}
Now from this I attempted to calculate the initial velocity strait after the impact. This is there the problems began. Using the equasion
\begin{eqnarray*}
v^2 &=& u^2 + 2as\\
0^2 &=& u^2 + 2 * -24 * 3\\
u^2 &=& 144\\
u &=& 12ms^{-1}\\
\end{eqnarray*}
But
\begin{eqnarray*}
(v-u)/t &=& a\\
(0-u)/2 &=& -24\\
-u &=& -48\\
u &=& 48ms^{-1}\\
\end{eqnarray*}
Why do these two equasions yield different results

A: The question is inconsistent. At least one of the numbers (mass, force, stopping distance, or stopping time) is wrong. Your calculation of the acceleration from force and mass is correct, but an acceleration of $24$ m/s$^2$ for $2$ seconds means that the toy car was initially traveling at $48$ m/s. This is over $100$ mph ($160$ kph) and there is no way the car is stopping in only $3$ meters. The actual stopping distance in $2$ seconds is $48$ meters. This isn't necessarily what the question writer had in mind, so we don't know what the real answer should be.


text:
Q: Subcaption label positions - unexpected behaviour with twoside report I need to position subfigure labels on the top left of their respective figures. I can do this fine for a normal report, however if I change to a twosided report the labels are incorrect on even pages. On even pages the labels don't shift into the correct position, and the subfigures become offset (provided they are different sizes). I'm not sure what to do to appraoch this issue from here.
Here's a MWE, any help or insight would be fantastic:
\documentclass[12pt, twoside]{report}

\usepackage{graphicx}
\usepackage{caption}
\usepackage{subcaption}

\usepackage{lipsum}

\captionsetup[subfigure]{
    singlelinecheck = false,
    justification = raggedright,
    margin = {-3ex, 0ex},
}

\begin{document}

%
\begin{figure}[tbp]
    \centering
    \begin{subfigure}[t]{0.4\linewidth}
        \subcaption{}
        \includegraphics[width=\linewidth]{example-image-a}
    \end{subfigure}
    \hspace{3ex}
    \begin{subfigure}[t]{0.28\linewidth}
        \subcaption{}
        \includegraphics[width=\linewidth]{example-image-b}
    \end{subfigure}
    \caption{Labels in correct position.}
\end{figure}
%

\lipsum[1-3]

%
\begin{figure}[tbp]
    \centering
    \begin{subfigure}[t]{0.4\linewidth}
        \subcaption{}
        \includegraphics[width=\linewidth]{example-image-a}
    \end{subfigure}
    \hspace{3ex}
    \begin{subfigure}[t]{0.28\linewidth}
        \subcaption{}
        \includegraphics[width=\linewidth]{example-image-b}
    \end{subfigure}
    \caption{Labels in incorrect position, and figures offset.}
\end{figure}
%

\lipsum[4-5]

%
\begin{figure}[tbp]
    \centering
    \begin{subfigure}[t]{0.4\linewidth}
        \subcaption{}
        \includegraphics[width=\linewidth]{example-image-a}
    \end{subfigure}
    \hspace{3ex}
    \begin{subfigure}[t]{0.28\linewidth}
        \subcaption{}
        \includegraphics[width=\linewidth]{example-image-b}
    \end{subfigure}
    \caption{Labels back in correct position.}
\end{figure}
%

\end{document}

A: According to caption package document Page.11, 'In twoside documents the left and right margin will be swapped on even pages. To prevent this, you can specify the option oneside additionally, e.g. \captionsetup{margin=
{0pt,10pt},oneside}'. So the correct example is:
\documentclass[12pt, twoside]{report}
\usepackage{graphicx}
\usepackage{caption}
\usepackage{subcaption}
\usepackage{lipsum}
\captionsetup[subfigure]{
    singlelinecheck = false,
    justification = raggedright,
    margin = {-3ex, 0ex},
    oneside
}
\usepackage[showframe]{geometry}

\begin{document}
%
\begin{figure}[t]
    \centering
    \begin{subfigure}[t]{0.4\linewidth}
        \subcaption{}
        \includegraphics[width=\linewidth]{example-image-a}
    \end{subfigure}
    \hspace{3ex}
    \begin{subfigure}[t]{0.28\linewidth}
        \subcaption{}
        \includegraphics[width=\linewidth]{example-image-b}
    \end{subfigure}
    \caption{Labels in correct position.}
\end{figure}
%
\lipsum[1-3]
%
\begin{figure}[t]
    \centering
    \begin{subfigure}[t]{0.4\linewidth}
        \subcaption{}
        \includegraphics[width=\linewidth]{example-image-a}
    \end{subfigure}
    \hspace{3ex}
    \begin{subfigure}[t]{0.28\linewidth}
        \subcaption{}
        \includegraphics[width=\linewidth]{example-image-b}
    \end{subfigure}
    \caption{Labels in incorrect position, and figures offset.}
\end{figure}
%
\lipsum[4-5]
%
\begin{figure}[t]
    \centering
    \begin{subfigure}[t]{0.4\linewidth}
        \subcaption{}
        \includegraphics[width=\linewidth]{example-image-a}
    \end{subfigure}
    \hspace{3ex}
    \begin{subfigure}[t]{0.28\linewidth}
        \subcaption{}
        \includegraphics[width=\linewidth]{example-image-b}
    \end{subfigure}
    \caption{Labels back in correct position.}
\end{figure}
%
\end{document}


text:
Q: Java MIDI - getting data from piano? I've inherited a Java project that used an old C++ dll to receive MIDI data from a piano connected to the computer.
Now that Java has built-in support for MIDI devices, I want to get rid of the legacy C++ dll and just use pure Java. Does Java support receiving data from a piano connected to the computer? I've searched Google for examples to no avail.

A: Yes, the JavaSound API can be used to read MIDI data from a MIDI device.
JFugue is a Java API for music programming that uses the JavaSound API, and can help simplify your interaction with JavaSound. In JFugue 5.x, sample code to capture 10 seconds of MIDI data from a MIDI device is as follows:
MidiDevice device = /* specify a MIDI device */
MusicTransmitterToSequence transmitter = new MusicTransmitterToSequence(device);
transmitter.listenForMillis(10000);
Sequence music = transmitter.getSequence();

You can also start and stop listening to a device:
MidiDevice device = /* specify a MIDI device */
MusicTransmitterToSequence transmitter = new MusicTransmitterToSequence(device);
transmitter.startListening();
// Do stuff
transmitter.stopListening();
Sequence music = transmitter.getSequence();

A: If you want to record with just the MIDI api by Java (javax.sound.midi.*) this is done very easily. This is not code to copy and paste, but it should help you to start programming your own MIDI recorder, which is quite easy actually.
The first step is to define your input and output MidiDevice. So first you will have to find a list of IO possibilities and make a GUI in which you can select the input and output device for your MIDI recording and playback.
Info[] infos = MidiSystem.getMidiDeviceInfo();
for(int i=0;i<infos.length;i++)
{
    System.out.println(infos[i].getName() + " - " + infos[i].getDescription());
}

So there is a list of your MIDI devices. Next you want to select a MIDI device, for example you get to choose the indexes in the infos array.
MidiDevice inputDevice = MidiSystem.getMidiDevice(infos[x]);
MidiDevice outputDevice = MidiSystem.getMidiDevice(infos[y]);

You also will want to specify some globals: sequencer, transmitter and receiver.
Sequencer sequencer = MidiSystem.getSequencer();
Transmitter transmitter;
Receiver receiver;

Now there is a record button you want to use.
// Open a connection to your input device
inputDevice.open();
// Open a connection to the default sequencer (as specified by MidiSystem)
sequencer.open();
// Get the transmitter class from your input device
transmitter = inputDevice.getTransmitter();
// Get the receiver class from your sequencer
receiver = sequencer.getReceiver();
// Bind the transmitter to the receiver so the receiver gets input from the transmitter
transmitter.setReceiver(receiver);

// Create a new sequence
Sequence seq = new Sequence(Sequence.PPQ, 24);
// And of course a track to record the input on
Track currentTrack = seq.createTrack();
// Do some sequencer settings
sequencer.setSequence(seq);
sequencer.setTickPosition(0);
sequencer.recordEnable(currentTrack, -1);
// And start recording
sequencer.startRecording();

Beware, this code can throw MidiUnavailableExceptions and you should call the close methods on all the things you've opened in a finally statement.
But this is just the core of what the code should look like. It records everything to the Sequence seq as soon as you call the method sequencer.startRecording().
Then you want to stop the recording, and be able to save the sequence as MIDI to a file, or do a playback. For example this could be code when you press the Stop record button or something.
// Stop recording
if(sequencer.isRecording())
{
    // Tell sequencer to stop recording
    sequencer.stopRecording();

    // Retrieve the sequence containing the stuff you played on the MIDI instrument
    Sequence tmp = sequencer.getSequence();

    // Save to file
    MidiSystem.write(tmp, 0, new File("MyMidiFile.mid"));
}

Also the Track class (a sequence can have multiple tracks) contains the actual input data, which you can easily access by a get method. The Track class consists of MidiEvents. For example the Track is:
MidiEvent 0: The C key is pressed
MidiEvent 1: The D key is pressed
MidiEvent 2: The C key of MidiEvent 0 is released
MidiEvent 3: The sustain pedal is pressed
etc...

And every MidiEvent has a certain timestamp, which is expressed in MIDI Ticks, thus you can easily change the tempo by increasing or decreasing the number of ticks per second.
The hardest problem here is that MidiEvents are expressed in byte code, thus you will have to use a reference byte code sheet which tells you what byte represents what action. This should get you started with that: http://www.onicos.com/staff/iz/formats/midi-event.html


text:
Q: SSRS - Reports not arriving for email groups We have an issue where a 3rd party supplier is generating business critical reports from their SSRS server to distribute into our business via email.  The reports arrive without issue when each recipients individual email address is supplied.  However we now need to widen the audience of these reports and so we have created some query based distribution groups, eg sales@company.com.
I can send an email to this group from my own external email (Gmail) and it arrives fine.  However the reports sent from our supplier do not arrive when using the group emails?  We do not even see them hit our inbound email.
I have found a link which seems to describe the issue:
SSRS Subscription to an email group (distribution list) is not working
And another which details how to setup local SMTP for SSRS:
https://msdn.microsoft.com/en-us/library/ms159155.aspx#bkmk_confiugre_remote_SMTP
However I am concerned that our supplier is not going to make any configuration changes at their end.  A start would be to understand why SSRS will not send to group emails when it has no issue with individual emails?  Has anyone had any experience of this issue?
Thanks
Mark

A: This type of issue usually has nothing to do with SSRS. It is probably generating the email and sending it. Once that is passed to the mail server, it has to have permissions to use those distribution lists, domains, etc. So it comes down to configuration on the mail server. If you can't get them to fix it, you'd have to have it forwarded through an email account that you can control.


text:
Q: Encode JSON string before deserialize I am getting raw JSON format as a string(without encoded) from third party.  So I am getting parse error message when I try to deserialize string because of extra double quotes. Is it possible to serialize string before deserialization on my end or escape any special characters before deserialization? Please let me know.
I tried to do replace with backslash but it didn't work.
{
  "Detail":{
     "date1": "06-JAN-2016",
     "summary": "test """""""""""",
     "city": "TEST"
     }
}

string escapeJson = jsonFile.Replace(@"\", "");

var myJsonObject = JsonConvert.DeserializeObject<RootObject>(escapeJson);

public class RootObject
{
    public Detail detail { get; set; }
}

public class Detail
{
    public DateTime date1{ get; set; }
    public string summary{ get; set; }
    public string city{ get; set; }
}


text:
Q: What's the meaning of "wrestle with one's own conflicting votes on something"
The conservative legal challenge to President Barack Obama's executive
  action on immigration, in line for U.S. Supreme Court review, would
  force the justices to wrestle with their own conflicting votes on when
  states have a legal right to sue the federal government.

What's the meaning of "wrestle with one's own conflicting votes on something"?
I know 'wrestle with' means struggle with or handle something, but I'm not sure what one's own conflicting votes means. Does it mean that the justices have contrasting views on the issue?
Quoted from Reuters http://www.reuters.com/article/2015/11/11/usa-court-immigration-idUSL1N1362KD20151111#pOBIabKLQveaH8sB.99

A: The justices do not always agree, and judges can even be inconsistent in their votes between cases.  For example, a judge may vote in favor of abortion because a woman has a right to choose what she does with her own body based on the right to privacy, but then vote against euthanasia using reasoning that seemingly contradicts their earlier positions.
So, "wrestle with their own conflicting votes" would imply that the court is divided on the issue.  Not only between judges themselves (the conservative-leaning judges vs the liberal-leaning judges), but also with judges who may have voted one way on one case, and a seemingly opposite way on a another similar case.


text:
Q: A confusion about SearchBar and Tableview without searching, when I tapped any cell, alert shows correct surname. However, somehow, when I search a name and tapped its cell, alert shows wrong surname. In every case (I mean, I search whatever) alert always shows Quuen surname. I think because of when I search, the result always becomes first index of my tableview.
My codes:
import UIKit

struct Human {
    var name = String()
    var surname = String()

}

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate {

    @IBOutlet weak var tableView: UITableView!

    @IBOutlet weak var searchBar: UISearchBar!

    var members = [Human]()

    var filteredData = [String]()

    var inSearchMode = false

    var names = ["Oliver","Harold","John","Thea","Felicity"]
    var surnames = ["Queen","Finch","Reese","Queen","Smoak"]

    override func viewDidLoad() {
        super.viewDidLoad()

        for i in 0..<names.count {
            members.append(Human(name: names[i],surname: surnames[i]))
        }

        tableView.delegate = self

        tableView.dataSource = self

        searchBar.delegate = self

        searchBar.returnKeyType = UIReturnKeyType.done
    }

    // MARK: - UITableViewDataSource

    func numberOfSections(in tableView: UITableView) -> Int {

        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        if inSearchMode {

            return filteredData.count
        }

        return members.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        if let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as? DataCell {

            let text: String!

            if inSearchMode {

                text = filteredData[indexPath.row]

            } else {

                text = members[indexPath.row].name
            }

            cell.congigureCell(text: text)

            return cell

        } else {

            return UITableViewCell()
        }
    }

    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {

        if searchBar.text == nil || searchBar.text == "" {

            inSearchMode = false

            view.endEditing(true)

            tableView.reloadData()

        } else {

            inSearchMode = true

            filteredData = names.filter { $0.lowercased().contains(searchBar.text!.lowercased()) }

            tableView.reloadData()

        }
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        showAlert(title: "Surname is...", msg: members[indexPath.row].surname)
    }

}

extension UIViewController {

    func showAlert(title: String, msg: String) {
        let alert = UIAlertController(title: title, message: msg, preferredStyle: .alert)
        let action = UIAlertAction(title: "OK", style: .default, handler: nil)
        alert.addAction(action)
        self.present(alert, animated: true, completion: nil)
    }
}

And screenshots are here:
https://imgur.com/a/aRMNe
Finally, how can I solve this issue?

A: Use like below :
Change filteredData type to Human
var filteredData = [Human]()

Changed in cellForRow, didSelectRowAt and textDidChange.
Added comment for the changed lines.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
     if let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as? DataCell {
        let text: String!
        if inSearchMode {
            text = filteredData[indexPath.row].name // changed this line only
        } else {
            text = members[indexPath.row].name
        }
        cell.textLabel?.text = text
        return cell
    } else {
        return UITableViewCell()
    }
}

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    if searchBar.text == nil || searchBar.text == "" {
        inSearchMode = false
        view.endEditing(true)
        tableView.reloadData()
    } else {
        inSearchMode = true
        filteredData = members.filter { $0.name.lowercased().contains(searchBar.text!.lowercased()) } // changed this line
        tableView.reloadData()
    }
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if inSearchMode {
        showAlert(title: "Surname is...", msg: filteredData[indexPath.row].surname) // added this line
    } else {
        showAlert(title: "Surname is...", msg: members[indexPath.row].surname)
    }
}


text:
Q: jasmine: spyOn(obj, 'method').andCallFake or and.callFake? I want to mock test data in my Jasmine tests. Here are two versions:
// version 1:
spyOn(mBankAccountResource, 'getBankAccountData').and.callFake(fakedFunction);

// version 2:
spyOn(mBankAccountResource, 'getBankAccountData').andCallFake(fakedFunction);

When I execute my tests with a browser (Chrome, Firefox) then the first version works. However, when I run the same test with phantomjs, I have to use the second version. Otherwise, it complains that the function is not defined.
Here are the error messages:
// phantomjs (with version 1)
    TypeError: 'undefined' is not an object (evaluating 'spyOn(mBankAccountResource, 'getBankAccountData').and.callFake')
    at /home/phil/workspaces/world/basket.angular.ui/basket.angular.ui/test/bankaccount/BankAccountCtrlTest.js:65
    at invoke (/home/phil/workspaces/world/basket.angular.ui/bower_components/angular/angular.js:3707)
    at workFn (/home/phil/workspaces/world/basket.angular.ui/bower_components/angular-mocks/angular-mocks.js:2149)
undefined

// Chrome (with version 2)
TypeError: Object function () {
        callTracker.track({
          object: this,
          args: Array.prototype.slice.apply(arguments)
        });
        return spyStrategy.exec.apply(this, arguments);
      } has no method 'andCallFake'
    at Object.<anonymous> (/home/phil/workspaces/world/basket.angular.ui/basket.angular.ui/test/bankaccount/BankAccountCtrlTest.js:65:59)
    at Object.invoke (/home/phil/workspaces/world/basket.angular.ui/bower_components/angular/angular.js:3707:17)
    at Object.workFn (/home/phil/workspaces/world/basket.angular.ui/bower_components/angular-mocks/angular-mocks.js:2149:20)

I searched the Jasmine API but could not find out which version is the correct one. All examples that I found seem to use the second version.
Did the API of Jasmine change recently? How can I write my tests, so it always works?

A: Yes, the spy API changed from Jasmine 1.3.1 to Jasmine 2.0. There's no "correct" version. If you can find the tool support for Jasmine 2.0, I would recommend upgrading.
Jasmine 1.3.1 syntax (documentation [archived link])
spyOn(mBankAccountResource, 'getBankAccountData').andCallFake(fakedFunction);
expect(mBankAccountResource.getBankAccountData.mostRecentCall.args).toEqual(["foo"]);

Jasmine 2.0 syntax (documentation [archived link])
// Methods moved to 'and' property
spyOn(mBankAccountResource, 'getBankAccountData').and.callFake(fakedFunction);

// Call data moved to 'calls' property
expect(mBankAccountResource.getBankAccountData.calls.mostRecent().args).toEqual(["foo"]);

I mention tool support because it seems that's the problem you're having. Jasmine 2.0 has only been out for a couple of months (at the time of writing). Support for Jasmine 2.0 in Karma, by comparison, has been out for a couple of weeks (I'm not sure about other tools).
To solve your issue, investigate which tool(s) you're using to run tests and see if any of them support Jasmine 2.0. If all of them do, then go for the upgrade. Otherwise, downgrade your browser tests to Jasmine 1.3.1 and wait until tool support is better. Just make sure you're consistent across the board.


text:
Q: JFrame wrong location with Ubuntu (Unity ?) It seems that there is a bug with Ubuntu (maybe only unity). The decoration of the JFrame is taken into account for getLocation() and getSize(), but not for setLocation() and setSize(). This leads to weird behaviour. For instance, if you use pack() after the frame is displayed and the dimensions changed, the frame will go down 20 pixels...
To illustrate a concrete case when it becomes really annoying, I made a SSCCE. It's a JFrame with a basic JPanel. If you drag the panel, the JFrame is supposed to move along.
Under Windows, it works as expected. Under Ubuntu, if I do setUndecorated(true) it will also work fine, but if I let the decoration, the JFrame turn crazy !
public class Test {
    private static JFrame mainFrame;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                mainFrame = new JFrame("test");
                mainFrame.setSize(300,20);
                mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                mainFrame.setVisible(true);

                Container pane = mainFrame.getContentPane();
                pane.addMouseMotionListener(new MouseMotionListener() {
                    private int posX = 0, posY = 0;

                    @Override
                    public void mouseDragged(MouseEvent e) {
                        int x = e.getX() - posX + mainFrame.getX();
                        int y = e.getY() - posY + mainFrame.getY();
                        mainFrame.setLocation(x, y);
                    }

                    @Override
                    public void mouseMoved(MouseEvent e) {
                        posX = e.getX();
                        posY = e.getY();
                    }

                });

            }
        });
    }
}

I don't know how I can fix that. How can I get the size of the windows decoration ? And I have no idea about which versions of Ubuntu are concerned. And if it is only a Unity problem, I don't even know how to find out if my user is using Unity...
Any idea for a workaround ?
Edit :
Ok, MadProgrammer did provide a better code, but the bug still occurs sometimes. I edited my MouseListener accordingly to track the bug :
            pane.addMouseMotionListener(new MouseMotionListener() {
                private int posX = 0, posY = 0;

                @Override
                public void mouseDragged(MouseEvent e) {
                    int x = e.getXOnScreen() - posX;
                    int y = e.getYOnScreen() - posY;
                    mainFrame.setLocation(x, y);
                    System.out.println("drag   :  border ignored / border considered : "+(mainFrame.getY()+e.getY())+"   /   "+e.getYOnScreen());
                }

                @Override
                public void mouseMoved(MouseEvent e) {
                    posX = e.getXOnScreen() - mainFrame.getX();
                    posY = e.getYOnScreen() - mainFrame.getY();
                    System.out.println("move  :  border ignored / border considered : "+e.getY()+"   /   "+posY);
                }
            });

Each time that the 2 values are identical, it means that the bug will occur on the next click. Otherwise, the values are different. On other OS, the values are always the same. Actually, they should be or the same always, or always different. I don't understand how they can be sometimes equal and sometimes different...

A: I don't have Ubuntu to test with, but I've used something similar to this on both MacOS and Windows
import java.awt.Container;
import java.awt.Point;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class Test {

    private static JFrame mainFrame;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                mainFrame = new JFrame("test");
                mainFrame.setSize(300, 100);
                mainFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                mainFrame.setVisible(true);

                Container pane = mainFrame.getContentPane();
                MouseAdapter ma = new MouseAdapter() {
                    private Point offset;

                    @Override
                    public void mouseDragged(MouseEvent e) {
                        if (offset != null) {
                            Point pos = e.getLocationOnScreen();

                            int x = pos.x - offset.x;
                            int y = pos.y - offset.y;

                            System.out.println(x + "x" + y);

                            SwingUtilities.getWindowAncestor(e.getComponent()).setLocation(x, y);
                        }
                    }

                    @Override
                    public void mousePressed(MouseEvent e) {

                        Point pos = SwingUtilities.getWindowAncestor(e.getComponent()).getLocation();

//                      Point pos = e.getComponent().getLocationOnScreen();
                        offset = new Point(e.getLocationOnScreen());
                        System.out.println(pos + "/" + offset);
                        offset.x -= pos.x;
                        offset.y -= pos.y;

                        System.out.println(offset);
                    }
                };
                pane.addMouseListener(ma);
                pane.addMouseMotionListener(ma);
            }
        });
    }
}

This should work for both decorated and undecorated windows, as it takes the difference between the positions of the component (on the screen) and the windows current position.  When dragged, it calculates the distance of movement from the click point and updates the window's location accordingly (allowing for the original offset of the click)


text:
Q: Rest Service Not Getting called from Mobile App for Long Text I have Created WCF Rest Service for Mobile App Exposed with Post Method.
In that user has to send Long text. Like 40,000 characters. till 900 Chars it works fine if it more than
that it Gives Error.
"Request URL Too Long
HTTP Error 414. The request URL is too long."
Public Sub Text(ByVal strVersion As String, ByVal strKey As String) Implements IMobileApp.Text
Context.Response.Write(strVersion)
End Sub

In Interface
<OperationContract()> _
<WebInvoke(Method:="POST", RequestFormat:=WebMessageFormat.Json, ResponseFormat:=WebMessageFormat.Json, UriTemplate:="/Text?Version={Version}&strKey ={strKey }")> _
Sub Text(ByVal Version As String, ByVal strKey As String)

What changes I have to do . so It get called for any long text.
I have also tried changing the values in config
<httpRuntime maxUrlLength="90999" maxQueryStringLength="2097151" maxRequestLength="102400" requestValidationMode="2.0" />

<security>
      <requestFiltering allowDoubleEscaping="True" >
        <requestLimits maxUrl="10999" maxQueryString="2097151" />
      </requestFiltering>
    </security>


text:
Q: Is there a Java utility class to do data management in a desktop UI? Is there a Java utility class to help with data management in a desktop UI?
I am writing a UI to configure a network device that will be connected to the serial port of the computer while it is being configured. There is no web server for my application.
The UI has a large number of fields (50+) spread across 16 tabs.
I will write the UI in Java (Java FX?). It should run inside the browser when launched, and issue commands to the network device through the serial port. A UI has several input fields spread across tabs and one single Submit button. If a field is edited, and the submit button clicked, it issues a command and sends the new datum to the device, retrieves current value and any errors. so if input field has bad data, it is indicated for example, the field has a red border.
Is there a standard design pattern or Java utility class to accomplish the frequently encountered, 'generic' parts of this scenario? lazy loading, submitting only what fields changed, displaying what fields have errors etc.
(I dont want to reinvent the wheel if it is already there). Otherwise I can write such a class and share it back here if it is useful.

A: You need a data model : a set of classes with different kind of relationships (UML design may help).
You can learn more about MVC pattern.

A: Java encourages the Model Control View pattern for separating the levels of responsibility when it comes to the management of data.
Essentianlly the idea is to provide a model that a view can show to the user. The model doesn't care how its displayed nor does the view care about how the data is managed, they simply have an agree dead interface through which they can communicate


text:
Q: NavigationView no encontrado en android studio 3.0.1
Me da este error y no se porque estuve buscando y este es el resultado de mi gradle...
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
implementation 'com.android.support:recyclerview-v7:26.1.0'
implementation 'com.android.support:cardview-v7:26.0.0-beta1'
}

configurations.all {
resolutionStrategy.eachDependency { DependencyResolveDetails details ->
    def requested = details.requested
    if (requested.group == 'com.android.support') {
        if (!requested.name.startsWith("multidex")) {
            details.useVersion '25.3.0'
        }
    }
}
}

Pero ni con lo ultimo añadido me funciona que fue lo que encontre... Alguna ayuda??? Gracias

A: Para agregar un NavigationView a tu proyecto debes agregar la dependencia de diseño.
Ejemplo:
dependencies {
     ...
     ...
     implementation 'com.android.support:design:26.1.0'
     ...
     ...
     }

Dando Alt + Enter se puede agregar la dependencia adecuada a tu proyecto para la library de Diseño:

Más información:
NavigationView
Android Design support library
Después de agregarla simplemente sincroniza tu archivo build.gradle con el proyecto.


text:
Q: How to call a function named coffeescript function via ajax In a Rails 3.2 app I have a jquery function that renders a chart on a DOM element
#assets/scripts.coffee.erb
$(document).ready ->
  $("#chart_container").do_some_stuff

#view

I'm in the process of ajaxifying this view to enable the user to switch the data that is presented on the chart. The problem is that the coffeescript is not triggered via the ajax response.
If I put the function within some  tags on the view, everything works fine, but this is not a very 'nice' solution.
Alternatively I know that it is possible to call functions from the view.js.erb rendered by the ajax response. Something like
#view.js.erb
$('#chart_container')['myFunction']();

But my javascript knowledge is limited, and I'm having trouble working out how to name coffeescript function correctly.
I need the function to be triggered when the document is ready. But I also need to be able to call the function manually via the ajax response. How should I set this up?
(I suspect this is a very basic javascript question, and not very well asked, but I appreciate any guidance).

A: You can wrap the code to a function at first
#assets/scripts.coffee.erb
$(document).ready ->
  $(document).chart_action()

$.fn.chart_action = ->
  $("#chart_container").do_some_stuff

Then call this function at your ajax response template
#view.js.erb
$(document).chart_action()

Upate Version
Thanks for @muistooshort's suggestion, it's better to use a custom namespace instead of polluting jQuery's, even in small usage.
So, refactor the above
# Custom functions for this app
class App
  chart_action: ->
    $("#chart_container").do_some_stuff

# Normal code for initializing page
app = new App
$(document).ready ->
  app.char_action()

# view.js.erb
app.chart_action()


text:
Q: Как вытащить время создания файла и по своему отформатировать? Есть список файлов с названиями вида "fileName.txt".
И есть задание: переименовать файлы в формате "old_fileName_2020-09-23T15:25.txt"
Как вытащить время создания файла, да еще и нужным образом отформатировать его?
К слову, в каждом файле есть дата создания этого файла в текстовом виде, если что. Но находится оно там не в ISO формате.
Нагуглил следующую инфу:
Вот этот код:
from os.path import getctime
from time import ctime

print(ctime(getctime('fileName.txt')))

Выводит информацию о файле в виде Tue Dec  8 20:35:22 2020
И судя по всему, эту тупиковый путь.
Можно, конечно, попытаться срезами повырезать из текста отдельные участки и по-вставлять их куда нужно, но это слишком сложное решение для такого простого назначения.
Есть ли какая-то альтернатива?
Спасибо.

A: Думаю это то, что вам нужно:
from os.path import getctime
import datetime

print(datetime.datetime.fromtimestamp(getctime('fileName.txt')).strftime('%H:%M:%S'))

Подробнее про форматирование можно почитать здесь


text:
Q: pg_dump error while running rake db:migrate I have postgres container and a ruby container. When running docker-compose run web rake db:migrate I got an error like this
rake aborted!
failed to execute:
pg_dump -s -x -O -f /usr/src/app/db/structure.sql --schema=public --schema=partitioning docker_rails_dev

Please check the output above for any errors and make sure that `pg_dump` is installed in your PATH and has proper permissions.

/usr/local/bundle/gems/activerecord-4.2.7.1/lib/active_record/tasks/postgresql_database_tasks.rb:90:in `run_cmd'
/usr/local/bundle/gems/activerecord-4.2.7.1/lib/active_record/tasks/postgresql_database_tasks.rb:55:in `structure_dump'
/usr/local/bundle/gems/activerecord-4.2.7.1/lib/active_record/tasks/database_tasks.rb:183:in `structure_dump'
/usr/local/bundle/gems/activerecord-4.2.7.1/lib/active_record/railties/databases.rake:279:in `block (3 levels) in <top (required)>'
/usr/local/bundle/gems/activerecord-4.2.7.1/lib/active_record/railties/databases.rake:53:in `block (2 levels) in <top (required)>'
/usr/local/bundle/gems/activerecord-4.2.7.1/lib/active_record/railties/databases.rake:45:in `block (2 levels) in <top (required)>'
Tasks: TOP => db:structure:dump
(See full trace by running task with --trace)

The pg_dump command is available in the postgres container but not in ruby container but I have linked them together in my docker-compose.yml file.

A: If you don't actually want the dump (why would you in CI?) put this in your test.rb:
config.active_record.dump_schema_after_migration = false

Now, no more need for PG tools (besides the client driver) in the ruby container.

A: Short answer:   Install the tools you need -inside- the container, -inside- the container.
If you need pg_dump running inside the ruby container, install postgress in the ruby container.   Binaries are rarely portable in that way.


text:
Q: "finish_bundle" method executing multiple times: Apache beam, Google Dataflow I am trying to create JSON files in batches of 100 records each using apache beam pipeline as a Google Dataflow job.
I am reading records from BigQuery and trying to create JSON files each having 100 records i.e. batch_size = 100
So I expect 7 JSON files to be created when Dataflow is executed which reads 700 records from BQ, but I see more files created and the batch size is not as expected.
I expect that the "finish_bundle" method executes once but I see it gets executed multiple times there by creating JSON batch files having records lesser than 100.
Here's the log details of current DF execution
batch id - 1 - length of batch (process)- 100 - flie name - my_bucket/29_09_2021/jbatch_20210929_093207.json
batch id - 2 - length of batch (process)- 100 - flie name - my_bucket/29_09_2021/jbatch_20210929_093239.json
batch id - 3 - length of batch (finish_bundle) - 43 - flie name - my_bucket/29_09_2021/jbatch_20210929_093253.json
batch id - 1 - length of batch (process)- 100 - flie name - my_bucket/29_09_2021/jbatch_20210929_093329.json
batch id - 2 - length of batch (finish_bundle) - 66 - flie name - my_bucket/29_09_2021/jbatch_20210929_093349.json
batch id - 1 - length of batch (process)- 100 - flie name - my_bucket/29_09_2021/jbatch_20210929_093423.json
batch id - 2 - length of batch (process)- 100 - flie name - my_bucket/29_09_2021/jbatch_20210929_093454.json
batch id - 3 - length of batch (finish_bundle) - 61 - flie name - my_bucket/29_09_2021/jbatch_20210929_093512.json
batch id - 1 - length of batch (finish_bundle) - 30 - flie name - my_bucket/29_09_2021/jbatch_20210929_093525.json

I wish to create batches of JSON file with the correct sequence and batch size with 100 records each like this
batch id - 1 - length of batch (process)- 100 - flie name - my_bucket/29_09_2021/jbatch_20210929_093207.json
batch id - 2 - length of batch (process)- 100 - flie name - my_bucket/29_09_2021/jbatch_20210929_093239.json
batch id - 3 - length of batch (process)- 100 - flie name - my_bucket/29_09_2021/jbatch_20210929_093253.json
batch id - 4 - length of batch (process)- 100 - flie name - my_bucket/29_09_2021/jbatch_20210929_093329.json
batch id - 5 - length of batch (process)- 100 - flie name - my_bucket/29_09_2021/jbatch_20210929_093349.json
batch id - 6 - length of batch (process)- 100 - flie name - my_bucket/29_09_2021/jbatch_20210929_093423.json
batch id - 7 - length of batch (finish_bundle)- 100 - flie name - my_bucket/29_09_2021/jbatch_20210929_093454.json

Here's my pipeline code to create JSON batch files and store in GCS bucket.
import os
import json
import apache_beam as beam
import logging

from datetime import datetime
from apache_beam.options.pipeline_options import PipelineOptions

class CreateJSONBatch:

    def execute_pipeline(self):
        try:
            query = "SELECT id, name, region, country, language, pin-code  FROM `project.dataset.table` LIMIT 700"

            beam_options = {
                "project": "<project>",
                "region": "<region>",
                "job_name": "create_json_batch",
                "runner": "DataflowRunner",
                "temp_location": f"gs://<bucket>/temp_location/",
                "setup_file": "./setup.py"
            }

            options = PipelineOptions(**beam_options, save_main_session=True)

            with beam.Pipeline(options=options) as pipeline:
                raw_data = (
                        pipeline | 'Read from BQ ' >> beam.io.Read(beam.io.ReadFromBigQuery(query=query,
                                                                                use_standard_sql=True))
                )
                _ = (raw_data | 'Create JSON batch files ' >> beam.ParDo(CreateBatch()))

        except Exception as e:
            logging.error(f"Exception in execute_pipeline - {str(e)}")

class CreateBatch(beam.DoFn):

    def __init__(self):
        self.project = None
        self.region = None
        self.batch_size = None
        self.data_bucket = None
        self.json_folder = None
        self.batch_id = 0
        self.json_batch = []

    def get_file_name(self):
        try:
            cur_time = datetime.now()
            date_folder = f"{cur_time.strftime('%d_%m_%Y')}"
            file_name = cur_time.strftime('%Y%m%d_%H%M%S')
            file_name = os.path.join(self.data_bucket, self.json_folder, date_folder, f"jbatch_{file_name}.json")
            return file_name    # file_name -my_bucket/folder_to_store_json_files/29_09_2021/jbatch_20210929_060346.json
        except Exception as e:
            logging.error(f"Exception in CreateBatch.get_file_name - {str(e)}")

    def create_json_files(self, json_file):
        try:
            json_file = f"gs://{json_file}"

            beam_options = {
                "project": self.project,
                "region": self.region,
                "runner": "DataflowRunner",
                "temp_location": f"gs://<bucket>/temp_location/",
                "setup_file": "./setup.py"
            }

            options = PipelineOptions(**beam_options, save_main_session=True)

            with beam.Pipeline(options=options) as pipeline_for_json:
                data = (
                        pipeline_for_json
                        | 'Create pcollection' >> beam.Create(self.json_batch)
                        | 'Write Output' >> beam.io.WriteToText(json_file, shard_name_template='')
                )
        except Exception as e:
            logging.error(f"Exception in CreateBatch.create_json_files - {str(e)}")

    def prep_data(self):
        try:
            formatted_json_batch = []

            for x in range(len(self.json_batch)):
                element = self.json_batch[x]

                modified_element = "<logic to modify the element JSON to the needed format>"

                # sample modified element
                # {
                #     "id": "",
                #     "name": "",
                #     "address": {
                #         "region": "",
                #         "country": "",
                #         "language": "",
                #         "pin-code": ""
                #     }
                # }

                formatted_json_batch.append(json.dumps(modified_element))

            return formatted_json_batch
        except Exception as e:
            self.logger.log_n_notify(log_type="error", msg=f"Exception in CreateBatch.prep_data - {str(e)}")

    def process(self, record):
        try:
            self.project = "<project>"
            self.region = "<region>"
            self.batch_size = 100
            self.data_bucket = "my_bucket"
            self.json_folder = "folder_to_store_json_files"

            if len(self.json_batch) < self.batch_size:
                self.json_batch.append(record)
            else:
                self.batch_id = self.batch_id + 1

                file_name = self.get_file_name()

                # prepare for push
                self.json_batch = self.prep_data()

                logging.info(msg=f"batch id - {self.batch_id} - length of batch (process) - {str(len(self.json_batch))} - flie name - {file_name}")

                # write to JSON
                self.create_json_files(file_name)

                self.json_batch = []

                self.json_batch.append(record)
        except Exception as e:
            logging.error(f"Exception in CreateBatch.process - {str(e)}")

    def finish_bundle(self):
        try:
            self.batch_id = self.batch_id + 1
            if len(self.json_batch) > 0:

                file_name = self.get_file_name()

                # prepare for push
                self.json_batch = self.prep_data()

                logging.info(msg=f"batch id - {self.batch_id} - length of batch (finish_bundle) - {str(len(self.json_batch))} - flie name - {file_name}")

                # write to JSON
                self.create_json_files(file_name)
        except Exception as e:
            logging.error(f"Exception in CreateBatch.finish_bundle - {str(e)}")

if __name__ == "__main__":
    create_batch = CreateJSONBatch()
    create_batch.execute_pipeline()

I am not sure on why the "finish_bundle" is called multiple times ?
What modifications in my pipeline code would make the files to get created with given batch size ?
Edit: I tried executing the same program with "DirectRunner", and it created the correct number of files.

A: When processing a PCollection, the elements of the PCollection are split up into any number of bundles which are then executed (generally concurrently on many workers, but a worker may also receive multiple bundles sequentially as well). The start_bundle and finish_bundle are then called for each of these individual bundles. See more details at https://beam.apache.org/documentation/runtime/model/


text:
Q: The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine in NUnit I have NUnit installed on my 64 bit Windows 7 machine and office 2010 (32bit).
I tried reading excel file(.xls) using oledb data reader and it works fine in Visual Studio 2013. I have added app.config file for this.
Now the problem occurs in NUnit when I tried running this dll in it. It gives above error. I tried all the solutions like compiling in x64 and installing
this http://www.microsoft.com/en-us/download/confirmation.aspx?id=13255.
I am trying hard to resolve this problem. Can anyone help me out with this?
Machine : Windows 7 (64 - bit)
Office : 2010 (32 - bit)


text:
Q: Oauth, Devise and Mongoid session cookies Trying to login with another account, i found that on login not asks again for a gmail account.
My action/method is this
class Users::SessionsController < Devise::SessionsController

  def destroy
    super
    cookies.delete :_myapp_session
  end
end

It comes here as delete method in routes.rb
When i delete all cookies from browser, i can login watching the gmail page.
If i login with another account stills loading the data from the other account.
I use Devise with omniauth and Mongoid instead ActiveRecord

A:
Problem was that user not created before as properly fields needed on
  model like uid and provider


text:
Q: Suppose $3_1+2_2−_3=_4$. Which of the following statements are true? $\newcommand{\span}{\text{span}}$
Question: Suppose $3_1+2_2−_3=_4$. Which of the following statements are true?

*

*$\span( {_1,_2,_3} ) = \span( {_1,_2,_3,_4} )$

*$\span( {_1,_2,_4} ) = \span( {_1,_2,_3,_4} )$

*$\span( {_1,_2,_3} )$ is contained in but not equal to $\span( {_1,_2,_3,_4} ).$

*$\span( {_1,_2,_4} )$ is contained in but not equal to $\span( {_1,_2,_3,_4} ).$
I chose answers 1 and 2, but I am new to this topic so I am not entirely sure if it's correct.
Does $_3$ qualify as a valid linear combination of all vectors: $$ _3 = 3_1 + 2_2 - _4 + 0_3$$ AND/OR  $$ _3 = 6_1 + 4_2 - 2_4 - _3$$
If yes, then 2nd statment is true right?
Thank you!

A: The correct answer is the first one since the non trivial containment is due to the fact that you find a $\textbf{non trivial}$ combination of $u_{4}$, expressed as linearly dependant from $u_{1},u_{2},u_{3}$.


text:
Q: Writing "latin1" encoded byte array with escape characters I'm working on a database import/export process in VB.NET which writes data from a MySQL (5.5) database to a plain text file.  The application reads the data to a DataTable, then goes through the rows/columns to actually write the data to the OutputFile (System.IO.StreamWriter object).  The encoding on the tables in this database is Latin1.  There is a MediumBlob field in one of the tables I've been using for testing which contains image files stored as a byte array.
In my attempts to validate the output from my application, I've exported the data directly from the database using the MySQL Workbench, then compared that with the results I get when I write the same data from my application.  In the direct export from MySQL Workbench, I see some of these bytes are exported with the backslash.  When I read the data through my application, however, this escape character does not appear.  Viewed through Notepad++, it clearly shows some distinct differences between the two output results (see screenshot).

Obviously, while apparently very similar, the two are not completely identical.  My application is not including the backslashes for escaped characters, and some characters such as NULL are coming out differently altogether.  My code for writing this field to the file is:
OutputFile.Write("'" & System.Text.Encoding.GetEncoding(28591).GetString(CType(COPYRow(ColumnIndex), Byte())) & "'")

There doesn't appear to be an overload for the GetString method that allows me to specify an escape character, so I'm wondering if there's another way that, using this method, I can ensure the characters are correctly encoded, including escape characters.
I'm "assuming" that this method should also work in general when I start working with my PostgreSQL database, but with possibly a different encoding.  I'm trying to build things as "generic" as possible, but I'll have to worry about specifying encodings at run-time instead of hard-coding them later.

EDIT
I just ran across another SO question, which might point me in the right direction: Convert a Unicode string to an escaped ASCII string.  Obviously, it might take a bit more work to get it right, but this looks like the closest thing to what I'm trying to accomplish.


text:
Q: Flash does not reappear after hiding on FB canas app using wmode=direct I'm working on a FB canvas app using Flash with 3D graphics.
I must embed my SWF with param wmode="direct".
On FB, when opening FB UI dialog (such as: purchase credits), FB automatically hides (visibility=hidden) the flash, and after dialog closes, FB returns the old visibility value.
On Chrome and Firefox it works, but on IE, after the dialog closes I checked the flash element style and I saw that visibility=visible, but still the flash is still hidden!
Anyone know how to fix this?
Thanks!
Roei

UPDATE: Just for clarify: it works when using wmode is transparent, opaque and window. Just when using "direct" it does not re-appear...


text:
Q: Problems with click listener for header in a ListView So, I have a header view defined as follows:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="10dp"
    android:paddingTop="5dp"
    android:paddingBottom="5dp">

    <TextView android:id="@+id/purchase_menu_header_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#000000"
        android:textSize="20sp"
        android:text="@string/purchase_options_label"/>

</LinearLayout>

Inflated as follows:
View header = ((Activity) context).getLayoutInflater().inflate(R.layout.purchase_menu_header, options, false);
options.addHeaderView(header);
I have an click listener for items in the options ListView:
options.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                Offer offer = (Offer) options.getItemAtPosition(position);
                initiatePurchase(offer.getStoreProduct());
            }
        });

And a click listener for the header view itself:
header.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                baseLayout.removeView(background);
                baseLayout.removeView(overlay);
            }
        });

My problem is that the header only registers clicks on the text portion of the header. The desired behaviour is to have the entire header clickable. I have tried solutions such as using setOnItemClickListener with a getItemAtPosition(0), but this returns null. Have also tried to expand the text view in the header with MATCH_PARENT, but no luck there.

A: Try making your LinearLayout clickable using the android:clickable attribute.

A:
My problem is that the header only registers clicks on the text
  portion of the header.

Cause your header is just the TextView with wrap_content as width and height. Hence you are applying clicklistener to TextView with restricted clickable area.

Solution:

*

*use match_parent as width for TextView. Or

*use the LinearLayout that contains the TextView in it, as the header and make that clikable.

Hope it helps you.


text:
Q: Best way to transpose sed regex from Shell to Python script I have a file containing these lines
Entry :  12300000
F Blocks:   0x00000020 0x00000000 0x000a1b00
S Blocks:   0x00100000 0x0000001c 0x00000150

Using a shell script, the hex values from line starting with F Blocks: can be extracted using the line below :
blocks="$(sed -nE 's/F Blocks:[\t ]+(0x)?([0-9a-f]+)[ ]+(0x)?([0-9a-f]+)[ ]+(0x)?([0-9a-f]+)/0x\2 0x\4 0x\6/p' filename)"

I would like to do the same extract in a Python script, using the subprocess module
import subprocess
sed_cmd = ['sed', '-n', '-E', "s/F Blocks:[\t ]+(0x)?([0-9a-f]+)[ ]+(0x)?([0-9a-f]+)[ ]+(0x)?([0-9a-f]+)/0x\\2 0x\\4 0x\\6/p", 'filename']
proc = subprocess.Popen(sed_cmd, stdout=subprocess.PIPE)
blocks = proc.stdout.read()

Is there a best practice to extract data and the output in a variable, or could it be simplify ?

A: Use plain Python:
results = []                                # Define a list for matches
with open(filepath,'r') as fr:              # Open the file stream
    for line in fr:                         # Read line by line
        if line.startswith("F Blocks:"):    # If line starts with our value
            results = line[line.find(':')+1:].split() # Get all after : and split with whitespace
            # break                         # Uncomment this if you needn't process the file any longer

print(results)

See an online demo.


text:
Q: Create a .CSS, .HTML and .JS file using Node JS I am quite new to Node and hence stuck with this!!
I am trying to write a node script that makes a folder (lizardproject) which has three different files i.e. index.html, app.js, style.css.
Code
const fs = require('fs');
const folderName = process.argv[2] || 'Project'

try {
fs.mkdirSync(folderName);
fs.writeFileSync(`${folderName}/index.html`)
fs.writeFileSync(`${folderName}/app.js`)
fs.writeFileSync(`${folderName}/style.css`)
} catch(e) {
    console.log("Something went wrong!!");
    console.log(e);
}

On execution, the folder is being created.
Execution
hp\nodeintro>node boilerplate.js lizardproject

Result
hp\nodeintro>ls
boilerplate.js   lizardproject

But the files are not, and this error is being displayed:-
Error

Something went wrong!!
TypeError [ERR_INVALID_ARG_TYPE]: The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received undefined
at Object.writeFileSync

A: Look at the documentation for that function:

fs.writeFileSync(file, data[, options])
file <string> | <Buffer> | <URL> | <integer> filename or file descriptor
data <string> | <Buffer> | <TypedArray> | <DataView> | <Object>

data is the second argument.
You aren't providing the second argument so it is undefined. Hence the error message: Received undefined at Object.writeFileSync.
The error tells you what types of values are acceptable. Provide one of those. A string would be simplest.


text:
Q: Why is Python 3.x's super() magic? In Python 3.x, super() can be called without arguments:
class A(object):
    def x(self):
         print("Hey now")

class B(A):
    def x(self):
        super().x()

>>> B().x()
Hey now

In order to make this work, some compile-time magic is performed, one consequence of which is that the following code (which rebinds super to super_) fails:
super_ = super

class A(object):
    def x(self):
        print("No flipping")

class B(A):
    def x(self):
        super_().x()

>>> B().x()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in x
RuntimeError: super(): __class__ cell not found

Why is super() unable to resolve the superclass at runtime without assistance from the compiler? Are there practical situations in which this behaviour, or the underlying reason for it, could bite an unwary programmer?
... and, as a side question: are there any other examples in Python of functions, methods etc. which can be broken by rebinding them to a different name?

A: The new magic super() behaviour was added to avoid violating the D.R.Y. (Don't Repeat Yourself) principle, see PEP 3135. Having to explicitly name the class by referencing it as a global is also prone to the same rebinding issues you discovered with super() itself:
class Foo(Bar):
    def baz(self):
        return super(Foo, self).baz() + 42

Spam = Foo
Foo = something_else()

Spam().baz()  # liable to blow up

The same applies to using class decorators where the decorator returns a new object, which rebinds the class name:
@class_decorator_returning_new_class
class Foo(Bar):
    def baz(self):
        # Now `Foo` is a *different class*
        return super(Foo, self).baz() + 42

The magic super() __class__ cell sidesteps these issues nicely by giving you access to the original class object.
The PEP was kicked off by Guido, who initially envisioned super becoming a keyword, and the idea of using a cell to look up the current class was also his. Certainly, the idea to make it a keyword was part of the first draft of the PEP.
However, it was in fact Guido himself who then stepped away from the keyword idea as 'too magical', proposing the current implementation instead. He anticipated that using a different name for super() could be a problem:

My patch uses an intermediate solution: it assumes you need __class__
  whenever you use a variable named 'super'. Thus, if you (globally)
  rename super to supper and use supper but not super, it won't work
  without arguments (but it will still work if you pass it either
  __class__ or the actual class object); if you have an unrelated
  variable named super, things will work but the method will use the
  slightly slower call path used for cell variables.

So, in the end, it was Guido himself that proclaimed that using a super keyword did not feel right, and that providing a magic __class__ cell was an acceptable compromise.
I agree that the magic, implicit behaviour of the implementation is somewhat surprising, but super() is one of the most mis-applied functions in the language. Just take a look at all the misapplied super(type(self), self) or super(self.__class__, self)  invocations found on the Internet; if any of that code was ever called from a derived class you'd end up with an infinite recursion exception. At the very least the simplified super() call, without arguments, avoids that problem.
As for the renamed super_; just reference __class__ in your method as well and it'll work again. The cell is created if you reference either the super or __class__ names in your method:
>>> super_ = super
>>> class A(object):
...     def x(self):
...         print("No flipping")
...
>>> class B(A):
...     def x(self):
...         __class__  # just referencing it is enough
...         super_().x()
...
>>> B().x()
No flipping


text:
Q: Successfully trained Model.fit but prompted resource error when running model.predict on collab I am using google Collab to train a 3D autoencoder.
I successfully trained the model using model.fit function with the following model.summary():
Layer (type)                 Output Shape              Param #
=================================================================
input_1 (InputLayer)         (None, 128, 128, 128, 1)  0
_________________________________________________________________
conv3d_1 (Conv3D)            (None, 64, 64, 64, 64)    1792
_________________________________________________________________
conv3d_2 (Conv3D)            (None, 32, 32, 32, 128)   221312
_________________________________________________________________
conv3d_3 (Conv3D)            (None, 16, 16, 16, 256)   884992
_________________________________________________________________
conv3d_4 (Conv3D)            (None, 8, 8, 8, 256)      1769728
_________________________________________________________________
conv3d_5 (Conv3D)            (None, 8, 8, 8, 256)      1769728
_________________________________________________________________
up_sampling3d_1 (UpSampling3 (None, 16, 16, 16, 256)   0
_________________________________________________________________
conv3d_6 (Conv3D)            (None, 16, 16, 16, 256)   1769728
_________________________________________________________________
up_sampling3d_2 (UpSampling3 (None, 32, 32, 32, 256)   0
_________________________________________________________________
conv3d_7 (Conv3D)            (None, 32, 32, 32, 128)   884864
_________________________________________________________________
up_sampling3d_3 (UpSampling3 (None, 64, 64, 64, 128)   0
_________________________________________________________________
conv3d_8 (Conv3D)            (None, 64, 64, 64, 64)    221248
_________________________________________________________________
up_sampling3d_4 (UpSampling3 (None, 128, 128, 128, 64) 0
_________________________________________________________________
conv3d_9 (Conv3D)            (None, 128, 128, 128, 1)  1729
=================================================================
Total params: 7,525,121
Trainable params: 7,525,121
Non-trainable params: 0

the training is successful, and I saved the model as model.h5
i ran a seperate cell within the same project to test the model with the following code:
from tensorflow.keras.models import load_model
from keras import backend as K
K.clear_session()
model = load_model('model.h5')
x_test = np.load('test.npy')
x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.
x_train = np.reshape(x_train, (len(x_train), 128, 128, 128, 1))
x_test = np.reshape(x_test, (len(x_test), 128, 128, 128, 1))
decoded_imgs = model.predict(x_test)

and it prompts me the following error code:
ResourceExhaustedError:  OOM when allocating tensor with shape[25,128,128,64,64] and type float on /job:localhost/replica:0/task:0/device:GPU:0 by allocator GPU_0_bfc
     [[node model_1/up_sampling3d_4/concat_1 (defined at :47) ]]
Hint: If you want to see a list of allocated tensors when OOM happens, add report_tensor_allocations_upon_oom to RunOptions for current allocation info.
 [Op:__inference_predict_function_63155]
Function call stack:
predict_function
why is it possible that I am able to train the model with the same system but not able to run the model.predict?! anyone has an answer please :(
I am using googla colab pro with the following GPU specs:
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 440.82       Driver Version: 418.67       CUDA Version: 10.1     |
|-------------------------------+----------------------+----------------------+
| GPU  Name        Persistence-M| Bus-Id        Disp.A | Volatile Uncorr. ECC |
| Fan  Temp  Perf  Pwr:Usage/Cap|         Memory-Usage | GPU-Util  Compute M. |
|===============================+======================+======================|
|   0  Tesla P100-PCIE...  Off  | 00000000:00:04.0 Off |                    0 |
| N/A   62C    P0    48W / 250W |  15559MiB / 16280MiB |      0%      Default |
+-------------------------------+----------------------+----------------------+

+-----------------------------------------------------------------------------+
| Processes:                                                       GPU Memory |
|  GPU       PID   Type   Process name                             Usage      |
|=============================================================================|
+-----------------------------------------------------------------------------+

A: Tensorflow errors can be really painful to parse out. I see them all the time, and yet I have no idea what this one means. I have a couple suggestions on things to try out. First, see if it really is a resource error and feed in just one example to predict.
x_test_single = np.reshape(x_test[0], (1, 128, 128, 128, 1))
model.predict(x_test_single)

Secondly, typically if you want to test an entire set you'd use model.evaluate, see if that works.
Lastly, if you really are having resource allocation issues (i.e. you can't fit the as much as you want to in GPU memory since you have 3D sets that are super memory hungry) then use the data API and make datasets and feed in batches.
Just one more suggestion, I find it better to use the tensorflow SavedModel format if you are saving. https://www.tensorflow.org/tutorials/keras/save_and_load#savedmodel_format


text:
Q: Keras Graph disconnected cannot obtain value for tensor KerasTensor Tensorflow: 2.4.0
This is the Full Error Message:
ValueError: Graph disconnected: cannot obtain value for tensor KerasTensor(type_spec=TensorSpec(shape=(None, 64, 64, 3), dtype=tf.float32, name='input_1'), name='input_1', description="created by layer 'input_1'") at layer "flatten". The following previous layers were accessed without issue: []

I have been trying to make a controllable Autoencoder where I have 10 features I can variy to get an image (64x64 RGB)
And i have been having Trouble getting it working. I want to seperate the Neural Network into a full model which i can fit and an Decoder which i can use to later after training parse values into to generate images
btw i know this is not the perfect way to do an autoencoder it's just the simplest i can think of.
def Create_Generator(Image_Shape):
    Input_Layer = Input(shape=Image_Shape)
    Flatten_Layer1 = Flatten()(Input_Layer)
    Dense_Layer1 = Dense(12288,activation="relu")(Flatten_Layer1)
    Dense_Layer2 = Dense(6144,activation="relu")(Dense_Layer1)
    Dense_Layer3 = Dense(1024, activation="relu")(Dense_Layer2)

    Dense_Layer4 = Dense(10,activation="relu")(Dense_Layer3)

    Dense_Layer5 = Dense(1024, activation="relu")(Dense_Layer4)
    Dense_Layer6 = Dense(6144,activation="relu")(Dense_Layer5)
    Dense_Layer7 = Dense(12288,activation="relu")(Dense_Layer6)
    Reshape_Layer = Reshape(Image_Shape)(Dense_Layer7)

    AutoEncoder = Model(Input_Layer,Reshape_Layer)
    AutoEncoder.compile(optimizer='adam', loss ='binary_crossentropy')

    encoded_input = Input(shape=(10,))
    Decoder = Model([encoded_input,Dense_Layer5,Dense_Layer6,Dense_Layer7],Reshape_Layer)

    return AutoEncoder,Decoder

data = np.load("data.npz")
X_train = data['X']

AutoEncoder,Decoder = Create_Generator((64,64,3))

#Just for testing if it works
print(AutoEncoder.predict([X_train[0]]))
print(Decoder([[1,1,1,1,1,1,1,1,1,1]]))

A: I think you have an error here:
Decoder = Model([encoded_input,Dense_Layer5,Dense_Layer6,Dense_Layer7],Reshape_Layer)

Dense_Layer5, Dense_Layer6, Dense_Layer7 are not tf.keras.layers.Input. You can not create Decoder this way.


text:
Q: How to create a program that counts number of works and characters in a line in C++ WITHOUT using #include  I am having a problem
Does anyone knows how to create a program using just loops and iostream that calculates number of characters (including whitespace/tab/spacebar) in a sentence.
The catch is that #include string, #include fstring is not allowed to be used in the program.
Only libraries allowed is iomanip, iostream, cmath. Also arrays is not allowed to be used.
I hope you could help me with this problem. Thank you in advance. Good day

A: For counting characters, you can read the characters in one-by-one (see istream::get()), maintaining a count until you hit an end-of-sentence marker. That means something like (pseudo-code, since only classwork tends to have these bizarre limitations and you'll learn very little if we do the work for you):
# Initial count.

set charCount to 0

# Process every character until end of sentence.

set ch to getNextChar()
while ch is not end-of-sentence:
    # Each character increments the count.

    add 1 to charCount

    # Go get next character.

    set ch to getNextChar()

At the end of that loop, you have the character count (including spaces).
Getting a word count is slightly trickier but you can do it by simply maintaining the state of the last character (state being either SPACE or NONSPACE).
A word ends when you transition from NONSPACE to SPACE. That means you can use conditional statements within that loop to increment a wordCount variable on one of those transitions.
Just watch out for the edge case when you hit the end-of-sentence marker and the previous state was NONSPACE, that's also a word ending.
A good start for that code for counting both characters and words would be (though it's up to you to implement and debug):
# Initial counts and state.

set charCount to 0
set wordCount to 0
set prevState to SPACE

# Process every character until end of sentence.

set ch to getNextChar()
while ch != end-of-sentence:
    # Characters are easy.

    add 1 to charCount

    # Get state of current character.

    if ch is a space:
        set currState to SPACE
    else:
        set currState to NONSPACE

    # Word end detected when transition NONSPACE to SPACE.

    if prevState is NONSPACE and currState is SPACE:
        add 1 to wordCount

    # Update previous state and get next character.

    set prevState to currState
    set ch to getNextChar()

# Edge case, word at end of sentence.

if prevState is NONSPACE:
    add 1 to wordCount

A: We won't give you code for something that looks like a homework assignment, but you'll probably want to have one loop calling cin.get(), and then check each character as it comes in.


text:
Q: Android Service onTaskRemoved() is not called on Device ,But works on Emulator Genymotion Android Service onTaskRemoved() is not called on Device ,But works on Emulator Genymotion
 @Override
public void onTaskRemoved(Intent rootIntent) {

    Toast.makeText(getBaseContext(), "TASK ON REMOVE ", Toast.LENGTH_LONG).show();
    Intent restartServiceIntent = new Intent(getApplicationContext(),
            this.getClass());
    restartServiceIntent.setPackage(getPackageName());

    PendingIntent restartServicePendingIntent = PendingIntent.getService(
            getApplicationContext(), 1, restartServiceIntent,
            PendingIntent.FLAG_ONE_SHOT);
    AlarmManager alarmService = (AlarmManager) getApplicationContext()
            .getSystemService(Context.ALARM_SERVICE);
    alarmService.set(AlarmManager.ELAPSED_REALTIME,
            SystemClock.elapsedRealtime() + 1000,
            restartServicePendingIntent);

    super.onTaskRemoved(rootIntent);
}

Emulator Genymotion Android 6.0   ,    Device Huawei android 6.0
Help me.   Thank you.


text:
Q: How to add two columns in the listview How to add two columns in the listview and get the value of the first column.
I have Adapter that receives the data from a select and this data is added in the listview.
I would like the listview to be two columns and whenever I click on a row it takes the value of the first column
My listview is being populated like this:
  adapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleListItemMultipleChoice, observacao);
            lv.Adapter = adapter;
            lv.ChoiceMode = ChoiceMode.Multiple;

A: you should use RecycleView and set Recycleview as GridView by creating GridLayoutManger reference and also you can specify column number in it.
 recyclerView.setLayoutManager(new GridLayoutManager(getContext(),2));
            adapter = new FoodAdapter( context,filteredList);
            recyclerView.setAdapter(adapter);
            adapter.notifyDataSetChanged();

A: There is official document about Creating Custom Row Layouts for Xamarin Android.
Please follow that official tutorial to create a custom layout for the item of ListView and use your custom adapter for it.
In the GetView method of your custom adapter, you can inflate your row layout:
View view = convertView;
if (view == null)
    view = context.LayoutInflater.Inflate(Android.Resource.Layout.YourCustomLayout, null);

I would like the listview to be two columns and whenever I click on a row it takes the value of the first column

In the ItemClick event of your ListView, you can get the position of the selected item:
private void MListView_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
{
    var position = e.Position;
}

The position can be used for matching the relative item of your List, which is added into the ListView, then you can find your data there.


text:
Q: When do you have to wrap callback function of a spec with Async? For some reason these two specs are passing, however the second spec is testing interpolation within the template, with async data from a service. Why is it not necessary to wrap the callback function with async?
describe('SaangComponent', () => {
  let component: SaangComponent;
  let fixture: ComponentFixture<SaangComponent>;
  let compiled: HTMLElement;
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ SaangComponent ],
      providers: [
        {provide: GetSomeService, useValue: getSomeServiceMock}
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(SaangComponent);
    component = fixture.componentInstance;
    compiled = fixture.debugElement.query(By.css('h1')).nativeElement;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  it('should update the h1 attribute with the title', () => {

    fixture.detectChanges();
    const expectedText = compiled.innerHTML;
    expect(expectedText).toEqual('lord');
  });
});

const getSomeServiceMock = {
  getSomeData() {
    return Observable.of({title: 'lord'});
  }
};

A: It is necessary to wrap callback function in testing block with async or fakeAsync Angular helpers if a function is expected to be asynchronous.
getSomeServiceMock uses Observable.of and is synchronous. This is why async is optional.
If the components involved in this test suit doesn't contain asynchronously loaded components, async in beforeEach is optional, too.
As a rule of thumb, all testing blocks may be wrapped with fakeAsync. It's faster than async and will let you know if it's unsuitable (when real asynchronous operations happen in a block).

A: I assume that 'getSomeData' is called in the component's ngOnInit lifecycle hook. If so the mock response you are using is already used when you are creating the component.


text:
Q: automatic failover if webserver is down (SRV / additional A-record / ?) I am starting to develop a webservice that will be hosted in the cloud but needs higher availability than typical cloud SLAs provide.
Typical SLAs, e.g. Windows Azure, promise an availability of 99.9%, i.e. up to 43min downtime per month. I am looking for an order of magnitude better availability (<5min down time per month). While I can configure several load balanced database back-ends to resolve that part of the issue I see a bottleneck at the webserver. If the webserver fails, the whole service is unavailable to the customer. What are the options of reducing that risk without introducing another possible single point of failure? I see the following solutions and drawbacks to each:

*

*SRV-record:
I duplicate the whole infrastructure (and take care that the databases are in sync) and add additional SRV records for the domain so that the user tying to access www.example.com will automatically get forwarded to example.cloud1.com or if that one is offline to example.cloud2.com. Googling around it seems that SRV records are not supported by any major browser, is that true?

*second A-record:
Add an additional A-record as alternatives. Drawbacks:
a) at my hosting provider I do not see any possibility to add a second A-record but just one... is that normal?
b)if one server of two servers are down I am not sure if the user gets automatically re-directed to the other one or 50% of all users get a 404 or some other error
Any clues for a best-practice would be appreciated
Cheers,
Sebastian

A: The availability of the instance i.e. SLA when specified by the Cloud Provider means the "Instance's Health is server running in the context of Hypervisor or Fabric Controller". With that said, you need to take an effort and ensure the instance is not failing because of your app / OS / or pretty much anything running inside the instance. There are few things which devops tend to miss and that kind of hit back hard like for instance - forgetting to configure the OS Updates and Patches.
The fundamental axiom with the availability is the redundancy. More redundant your application / infrastructure is more availabile is your app.
I recommend your to look into the Azure Traffic Manager and then re-work on your architecture. You need not worry about the SRV record or A-Record. Just a CNAME for the traffic manager would do the trick.

The idea of traffic manager is simple, you can tell the traffic
  manager to stand after the domain name ( domain name resolution of the
  app ) then the traffic manager decides where to send the request on
  considerations of factors like Round-Robin, Disaster Management etc.

With the combination of the Traffic Manager and multi-region infrastructure setup; you will march towards the high availability goal.
Links
Azure Traffic Manager Overview
Cloud Power: How to scale Azure Websites globally with Traffic Manager

A: Maybe You should configure a corosync cluster with DRBD ?
DRBD will ensure You that the data on both nodes are replicated (for example website files and db files).
Apache as web server will be available under a virtual IP to which domain is pointed. In case of one server is down corosync will move all services to second server within few seconds.


text:
Q: What should I do to use MFC dialogs from other libraries in my C++ project? I have an MFC ActiveX control project written in Visual Studio 2008 that contains a dialog box.  The dialog box is wrapped in a class, as is normal.  I want to use the dialog box in another project.  Since an ActiveX (.ocx) file is a DLL, I can merely use the ActiveX file as I would a DLL.
The problem I ran into is that the dialog box's class has this near the top:
// Dialog Data
    //{{AFX_DATA(CDeploymentDlg)
    enum { IDD = IDD_DEPLOYMENT };

IDD_DEPLOYMENT is defined in the OCX's resource.h file.  My current project also has a resource.h file.  When I build my current project, I get an error because IDD_DEPLOYMENT is missing in my current project's resource.h file.  My workaround was to copy the OCX project's resource.h file into a file named DeploymentDlgResource.h in my current project, and #include it before I #include the declaration for the dialog class.
This should work for now because I won't need any more dialog boxes in my current project.  But what would happen if I created a project that needed another dialog box?  What if that second dialog box also came from a separate library?  Do I always need to use duplicate resource files like this?  Do I have to worry about possible duplication of numbers used in them?


text:
Q: @Notnull Spring Custom Annotation Validation with multiple field How to write (type level annotation) custom annotation to allow a choice validation (exactly one of a number of properties has to be not null)?

A: Even if this "question" is very broad I will give an answer as I have exactly the needed piece of code here:
@Target(ElementType.TYPE)
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = ChoiceValidator.class)
public @interface Choice {
    String[] value();

    boolean multiple() default false;

    String message() default "{com.stackoverflow.validation.Choice.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

Here a validator using a bean property access:
public class ChoiceValidator implements ConstraintValidator<Choice, Object> {
    private String[] properties;
    private boolean allowMultiple;

    @Override
    public void initialize(Choice constraintAnnotation) {
        if (constraintAnnotation.value().length < 2) {
            throw new IllegalArgumentException("at least two properties needed to make a choice");
        }
        properties = constraintAnnotation.value();
        allowMultiple = constraintAnnotation.multiple();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        try {
            BeanInfo info = getBeanInfo(value.getClass());
            long notNull = Stream.of(properties)
                    .map(property -> Stream.of(info.getPropertyDescriptors())
                            .filter(desr -> desr.getName().equals(property))
                            .findAny()
                            .orElse(null)
                    )
                    .map(prop -> getProperty(prop, value))
                    .filter(Objects::nonNull)
                    .count();
            return allowMultiple ? notNull != 0 : notNull == 1;
        } catch (IntrospectionException noBean) {
            return false;
        }
    }

    private Object getProperty(PropertyDescriptor prop, Object bean) {
        try {
            return prop.getReadMethod() == null ? null : prop.getReadMethod().invoke(bean);
        } catch (ReflectiveOperationException noAccess) {
            return null;
        }
    }
}

A typical usage can look like this (lombok annotation to generate getters and setters):
@Data
@Choice({"one", "two"})
class OneOf {
    private String one;
    private String two;
    private String whatever;
}

@Data
@Choice(value = {"one", "two"}, multiple = true)
class AnyOf {
    private String one;
    private String two;
}

But to clarify: Stackoverflow is a QA community for developers to exchange knowledge. It is not a place to ask "Can you please code this for me for free?". All valuable contributors at least try to solve problems first and come with detailed questions afterwards. People answering questions spend their spare time and are not payed for. Please show respect by asking for specific problems and showing own efforts in the future.