text:
Q: VBA (Macros) executed from JAVA program I am try to generate an excel report base on output from a JAVA program each time the program is executed. So from the way i see it, there are several steps to achieve this.
(I have done some research but may have some holes in my understanding, please correct me if I'm wrong)

1) Inserted output into an excel workbook (which i understand can be done using Apache poi but only to read/write).
2 (option A) ) Have pre-written VBA code in each workbook. Have JAVA program execute said macros which will generate my desired report format.
2 (option B) ) With the new excel Workbook created in step 1, have JAVA execute an external code on the workbook (VBS?) which does the same function as option A
Will either of these method work? I keep seeing terms such as JAVA-COM bridge. But i don't understand what it does. What are libraries/methods I can use to achieve this
Thanks for your help everyone


text:
Q: Using Highcharts.js with odoo I would like to use Highcharts in a dashboard for my company, I am using Odoo framework to do so. I've integrated another Js library with Odoo before, I have followed the same steps. In the end, I get the chart but no text, legends or anything else showed. What is the problem?
var chart = new Highcharts.chart('container', {
                    chart: {
                        type: 'pyramid'
                    },
                    title: {
                        text: 'Sales pyramid',
                        x: -50
                    },
                    plotOptions: {
                        series: {
                            dataLabels: {
                                enabled: true,
                                format: '<b>{point.name}</b> ({point.y:,.0f})',
                                softConnector: true
                            },
                            center: ['40%', '50%'],
                            width: '80%'
                        }
                    },
                    legend: {
                        enabled: false
                    },
                    series: [{
                        name: 'Unique users',
                        data: [
                            ['Website visits', 15654],
                            ['Downloads', 4064],
                            ['Requested price list', 1987],
                            ['Invoice sent', 976],
                            ['Finalized', 846]
                        ]
                    }],

                    responsive: {
                        rules: [{
                            condition: {
                                maxWidth: 500
                            },
                            chartOptions: {
                                plotOptions: {
                                    series: {
                                        dataLabels: {
                                            inside: true
                                        },
                                        center: ['50%', '50%'],
                                        width: '100%'
                                    }
                                }
                            }
                        }]
                    }
                });

A: I have deleted the Accessibility module The Highcharts use because aria-hidden comes from that library and it worked.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Windows 7 Visual C++ 2008 Strange Seg Fault and Null Pointer behavior By the time our development machines have been upgraded to windows 7 something strange started to happen. When our program (visual c++ 2008, some owl to mfc adapter, sql server 2008r2) accesses for example a null pointer it does not crash as expected but it goes on running just closing the actual window. Might be a good idea, but this makes database-transaction handling a nightmare. In case of a hidden crash in the program a started transaction with uncommitted changes is remaining opened and the user is able to go on using the program. When the next transaction gets committed normally, the changes "hanging" in the first half completed transaction are saved too. This is definitely not intended and leads to data corruption.
Before Windows 7 we didn't care about that, a crash was a crash. Program was closed, all transactions running were rolled back.
What can we do to switch back to the old behavior?

A: You can have your own unhandled exception routine to catch segfaults/access violations.
// global scope
    bool in_region_of_interest(_EXCEPTION_POINTERS *ep) {
        // TODO: Check if you aren't breaking some 3rd party functionality by exiting now.
        return ep && ep->ExceptionRecord; // Pretty much a stub.
    }
    static const bool  feelin_gentle = false; // Do we care for semi-clean exits?
    static const DWORD min_virt_rng  = 0x1000; // max virtual address that 'indicates' null ptr access.
    LONG WINAPI my_unh_exc_hndlr(_EXCEPTION_POINTERS *excPtrs)
    {
        if (in_region_of_interest(excPtrs)) {
           DWORD code = excPtrs->ExceptionRecord->ExceptionCode;
           if (EXCEPTION_ACCESS_VIOLATION == code && // If fingers burn in fire.
              min_virt_rng > excPtrs->ExceptionRecord->ExceptionInformation[1]) { // If it was a *(void*)0 that we accessed.
              if (feelin_gentle)
                 ExitProcess(code);
              else
                 TerminateProcess(GetCurrentProcess(), code);
           }
        }
        return EXCEPTION_CONTINUE_SEARCH; // Give control to the next filter.
    }

// ... somewhere in the beginning of main()
    SetUnhandledExceptionFilter(my_unh_exc_hndlr);

The reason you SHOULDN'T always crash is that some dependencies might depend on being able to handle a segfault. You should use a mechanism to dynamically switch this feature on or off, depending on where you expect a crash. Unless you are really sure it won't get broken, it's better to ignore everything except invalid access at address of or around 0. I took a value if 0x1000 out of my ass, as I won't expect any offset in an object be larger than that in my program.
Extra info: http://msdn.microsoft.com/en-us/library/windows/desktop/aa363082(v=vs.85).aspx


text:
Q: Copy MySQL Workbench query output to clipboard I've used Microsoft SQL Server Management Studio and one feature allowed me to run an SQL script and copy the output table to my clipboard. Something like this:

When I right click on my output table in MySQL Workbench, I can only copy the row content.
Does anyone know how to copy the whole table including headers?

A: You may have an old version of MySQL Workbench. I can press Ctrl+A on Win or Cmd+A on Mac to select all records. Then Ctrl/Cmd+C to copy to clipboard (or use the "Copy Row" entry which should probably just be named "Copy").

A: Follow these steps in the workbench to get the data and the header rows into Excel.

*

*Click on the box to the left of the first column on any data record.

*Click on the header on the box to the left of the column headers.

*Do a Ctrl+C to copy the data to the clipboard.

*Do a Ctrl+V to paste the data to your excel file.

Like so:

A: In the Workbench you go to File > Export > Forward Engine SQL CREATE Script and this will guide you through three easy steps to create the SQL script for the complete shema.

A: screenshot of mysql workbench corresponding to the info below
On Mac, hit cmd+a to select all
Then right-click and select "copy row (with names, tab separated)"
This will copy all of the data in the rows, as well as the header/column names. And it will be formatted to past into excel.
I assume this would work similarly on Windows, but I can't confirm that since I only have a Mac.

A: Vishal's answer is absolutely correct:

*

*Click on the box to the left of the first column on any data record.

*Click on the header on the box to the left of the column headers. Do a

*Ctrl+C to copy the data to the clipboard. Do a Ctrl+V to paste the

*data to your excel file.

But if the cells content exceeds the maximum number of bytes configured in the Max. Field Value Length to Display in (in bytes) setting, this will copy only the content showing including the ellipsis.
This setting is located at Edit > Preferences > SQL Editor > SQL Execution

If the results are being truncated, in order to copy the entire result, adjust this value to whatever size you need to display to full cell contents for copying, or set a value of -1 to avoid truncation.


text:
Q: How can I see all properties (including inherited) in nodejs? When working with nodejs, I like to use console.log to see what data is available in an object.
However, this doesn't work with inherited properties:
var Person = function () {};
Person.prototype.name = "anonymous";
var p = new Person();

console.log(['p', p]); // [ 'p', {} ]
// This doesn't even give me a hint that it's inherited from Person!
console.log(['typeof p', typeof p]); // [ 'typeof p', 'object' ]
console.log(['p.name', p.name]); // "anonymous"

Given an object, how can view all the properties I can access?

A: You are assigning property to constructor function Person. It does not share properties with instances. You need to add property to Person's prototype:
Person.prototype.name = "anonymous";

To find out if your object inherited from Person you can do:
p instanceof Person; // true

You can print out all of an object's enumerable properties by performing the following:
for (var key in p) {
    console.log(key);
}

A: Use Object.getOwnPropertyNames() to get all properties that belong to an object:
console.log(Object.getOwnPropertyNames(Person))
// [ 'length', 'name', 'arguments', 'caller', 'prototype' ]

console.log(Object.getOwnPropertyNames(Object))
// ['length','name','arguments','caller','prototype','keys','create',  'defineProperty','defineProperties','freeze','getPrototypeOf','setPrototypeOf','getOwnPropertyDescriptor','getOwnPropertyNames','is','isExtensible','isFrozen','isSealed','preventExtensions','seal','getOwnPropertySymbols','deliverChangeRecords','getNotifier','observe','unobserve','assign' ]

Also you can combine Object.getOwnPropertyNames() with walking up the prototype chain:
var getAllProperties = function (object) {

  var properties = []
  do {
    Object.getOwnPropertyNames(object).forEach((prop) => {
      if (!~properties.indexOf(prop)) {
        properties.push(prop)
      }
    })
  } while (object = Object.getPrototypeOf(object))

  return properties
}

A: If your purpose is just for debugging, you can check the __proto__ object:
function Person() {};
Person.prototype.name = "abc";
Person.prototype.smallObj = {
    name: "abc"
};

Person.prototype.deepObj = {
    one: {
        two: {
            three: {
                four: "4"
            }
        }
    }
};

var p = new Person();

console.log(p);
// Person {}

console.log(p.__proto__);
/*
Person {
    name: 'abc',
    smallObj: { name: 'abc' },
    deepObj: { one: { two: [Object] } }
}
*/
var util = require("util");
console.log(util.inspect(p.__proto__, {depth: null}));
/*
Person {
    name: 'abc',
    smallObj: { name: 'abc' },
    deepObj: { one: { two: { three: { four: '4' } } } }
}
*/

On the last one, using util.inspect() with the depth option will allow you to look further into deeply nested objects.


text:
Q: jQuery selector not working as I expected I have a simple html

Alberta

British Columbia

Manitoba

New Brunswick

Newfoundland

Nova Scotia

Ontario

Prince Edward Is

Quebec

Saskatchewan

And I am trying to access the "a" but it's giving me undefined.
I have no idea what I am doing wrong, any help will be appreciated
I am trying to access like this,
alert($("#dCA").find("ul>li>a:contains('" + "Alberta"+ "')").attr("id"));

A: Your code works and gives "AL", however there is no need of " + "Alberta"+ ". This also works
alert($("#dCA").find("ul>li>a:contains('Alberta')").attr("id"));

Fiddle: Demo

A: Put your code in $(document).ready
$(document).ready(function() {
      alert($("#dCA").find("ul>li>a:contains('Alberta')").attr("id"));

})

or add the script after the html.


text:
Q: Footer Content Align I have a webpage I am working on for a school project. Here is the jsfiddle.
https://jsfiddle.net/adamkerik/6c17ajqa/

Follow Us

Contact Us

3678 Poe Road

Mount Pleasant, South Carolina 29464

843-216-9434

The problem is that on the footer of the page, I want the content to be centered with the "div class va" in the middle of the buttons and the list. I just cant seem to get the content centered. Thanks for any help!
ps the css is in the jsfiddle page, cause i know that will probably be needed

A: Add this to your footer element CSS:
 margin: 0 auto;
 display: block;
 text-align:center;

Fiddle: https://jsfiddle.net/6c17ajqa/6/

A: You need to make this container to be center.
  .social-container {
      width: 400px;
      position: absolute;
      z-index: 6;
      margin: 0 auto;
      left:50%;
      top: 60%;
      transform:translate(-50%, -50%)
    }

Follow the link of fiddle https://jsfiddle.net/jb7f2mwy/


text:
Q: Inkscape: Convert SVG with text to a stencil image, from command line CLI I have an SVG that consists of a main outline shape plus text, that I want to convert into a "stencil" where the text is cut out from the main image (the text is in a stencil font).
I went through the process manually in the Inkscape GUI, converting the text to paths, using Union to combine all the letters into a single path, then using Path-Exclude to cut the text path from the main outline.
Now I want to automate this process through the Inkscape command line, exporting the result as a bitmap/PNM image (which will get converted to a DXF with potrace). But I can't seem to find the correct Inkscape CLI commands for this.
This is on Windows 10.

A: I found a much easier way to accomplish this, avoiding Inkscape entirely:
Use imagemagick to convert the source SVG (with embedded text) into an intermediate B&W PNM image, then use potrace to convert that to a DWG (or a flat SVG):
#!/usr/bin/env bash
# Convert monochrome SVG to cuttable DWG
# potrace manpage: http://potrace.sourceforge.net/potrace.1.html

declare magick='/c/Program Files/ImageMagick-7.0.10-Q8/magick.exe'
declare potrace='/c/Program Files/potrace-1.16.win64/potrace.exe'

declare input_svg="${0%/*}/SVG/test-input.svg"
declare intermediate="${0%/*}/SVG/intermediate.pnm"
declare output="${0%/*}/SVG/test.svg"

declare idim=2000x2000          # dimensions of intermediate pixel file
declare -a potrace_opts=(
    --backend svg               # output type: svg|dxf
    --flat                      # for SVG
    --tight                     # No margins, trim surrounding whitespace
    --width 8in
    #--height 16in
    #--resolution 20             # dpi - for dimension-based backends
    #--scale 0.1                 # for pixel-based backends
    --opttolerance 0.1          # default 0.2. Larger values allow more consecutive Bezier curve segments to be joined together in a single segment, at the expense of accuracy.
    --alphamax 1.08             # corner threshold (default 1); smaller=more sharp corners; 0=output is a polygon; >1.33 = output is completely smooth.
)

"$magick" convert -size $idim "$input_svg" "$intermediate"   || exit
"$potrace" "${potrace_opts[@]}" "$intermediate" -o "$output" || exit


text:
Q: Facebook Account SMS integration failed on Android Facebook Account kit sms integration didn't work.
When I used code from github it works and send sms through already integrated account in this App.
https://github.com/fbsamples/account-kit-samples-for-android/tree/master/samples/AccountKitSimpleSample
But when i Create App at Facebook account kit, copy Client Token and App Id. then it didn't work.
"A system issue occurred. Please try again" error occurred
How can i resolve this problem?

A: I guess you did not  enable Enable client access token flow in Facebook Developers panel.
Go to : Developer page
After login Select your app - > go to : Products-> Account Kit

Now enable the permission:


text:
Q: How to boot up Surface 3 in English I just got my Surface and as I boot it up, I see some languages but those are all Scandinavian (Swedish, Norwegian, Danish, Finnish). I can select the app language to English but the rest stays in Swedish.
How can I reset and reboot the device so it's all in English?
Can it be done if I install Windows 10 (preview)?

A: You can change the language in windows 8 by:

*

*Swiping in from the right and clicking on "Settings".

*Click on "Change PC Settings"

*Click "Time and language"

*Click on "Region and language"

*Click on the language you want and click "Set As Primary"

*Log out and log in

Reference from Microsoft where they also talk about how to install alternate languages.
This should be identical in result to the old way it was done in windows 7 but I'll include a reference to it as well.  This would be accomplished in Desktop mode (Control Panel -> Language and Region -> Administrative -> Change System Locale.


text:
Q: Astro - react useEffect hook is not working I am trying to build a web app with Astro + Reactjs, but I got an issue on calling useEffect. Basically useEffect is not calling, I don't get any logs in the terminal or any warnings/errors in the terminal or in the browser.
I am exporting the function as: export default function SecondSection(){}, I changed the file extension from .jsx to .tsx, still no result. I followed all instructions from astro docs to integrate react.
I am trying to use react hooks, like useEffect/useState, but for some reasons it's not working any of that.
What can cause that issue? Thank you for your time.

A: The first thing to check would be to make sure you are hydrating your React component where you're using it. In Astro, components ship zero JS by default, just plain HTML. Components will only be interactive in the browser if you add a client:* directive. This is part of Astro's "Islands Architecture".
To include a component's JS you need a client directive saying when to load it. In this example the component will load its JS when the page loads:
---
// src/pages/index.astro
import SecondSection from '../components/SecondSection.jsx';
---
<SecondSection client:load />

There are different directives like client:idle or client:visible that you can use to control exactly when a user needs the interactivity. There's more about the client directives in Astro's docs.


text:
Q: Jquery multiple lists of products dropdown I need help with jquery to select multiple options from Jquery dropdown.
I currently can select single value from option list with jquery. But I need to be able to select a list of items on option selection. For example in below example I can select values fine. But I also have products for each country in select options. How can I display products per country with a selectbox upon user's selection. Idea is for user to get number of products displayed in dropdown and upon selection of country it will display number of products exists for the country on click. Image is attached for more clarification.
Countries:
<select id='selectCountry'>
<option selected='selected' value='USA">United States</option> # I need to include all the products related to this country here
<option value='PK'>Pakistan</option>
<option value='UK'>United Kingdom</option>
<option value='CA'>Canada</option>
</select>

Script:
<script type='text/javascript'>
$(document).ready(function(){
$('#selectCountries').change(function(){
var selectOption = $("#selectCountries option:selected');
$('#divResult').html('Value = ' + selectOption.val()
+ ', Text + selectOption.text());
});
});
<script>
})

Image:

A: I think u can use multi-select dropdown , please check this link. it may helpful to you  :  click here


text:
Q: Name for logical predicates which act like homomorphisms from set union to logical conjunction? Is there a name for predicates defined over sets with the property that:
$$P(S\cup Q)\iff P(S)\land P(Q)$$
For example the predicate $P(Q)=``Q\text{ is empty"}$ would be one such predicate because:
$$S\cup Q=\emptyset\iff (S=\emptyset)\land (Q=\emptyset)$$
It looks sort of like the definition for a homomorphism between algebraic structures.

A: These are semilattice homomorphisms. A semilattice is a set with a binary operation that is associative, commutative, and idempotent (i.e., $x \vee x = x$). As in algebra, a semilattice homomorphism is a function that preserves the operation. Examples of semilattices include:

*

*subsets of a given set, where the operation is union

*subsets of a given set, where the operation is intersection

*propositions, where the operation is conjunction

*propositions, where the operation is disjunction.

So, if you specify what your semilattices are, you get the notion of homomorphism you're looking for.

Something to file away for later, since I'm guessing you haven't seen category theory yet: it is very natural, also, to view these maps as functors between certain categories. You're then asking questions related to whether the functors are "left exact" or "right exact."


text:
Q: Android activity started by itself? I have the first activity SimpleServiceController.java as follow:
public class SimpleServiceController extends Activity {

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

        Button start = (Button) findViewById(R.id.serviceButton);
        Button stop = (Button) findViewById(R.id.cancelButton);

        start.setOnClickListener(startListener);
        stop.setOnClickListener(stopListener);
        Log.v("Steps", "1");
        br = new BroadcastReceiver() {
            @Override
            public void onReceive(Context c, Intent i) {
                Log.v("Steps", "2");
                Toast.makeText(c, "Baboii!", Toast.LENGTH_LONG).show();
            }
        };
        Log.v("Steps", "3");
        registerReceiver(br, new IntentFilter("boom") );
        Log.v("Steps", "4");
    }
    private OnClickListener startListener = new OnClickListener() {
        public void onClick(View v) {
            startService(new Intent(SimpleServiceController.this,
                    SimpleUpdateService.class));
            startActivity(new Intent (SimpleServiceController.this, AlarmManagerListening.class));
        }
    };

I have another activity AlarmManagerListening.java as follow:
public class AlarmManagerListening extends Activity{
    final static private long ONE_SECOND = 1000;
    final static private long TEN_SECONDS = ONE_SECOND * 10;

    PendingIntent pi;
    BroadcastReceiver br;
    AlarmManager am;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        pi = PendingIntent.getBroadcast( this, 0, new Intent("boom"), 0 );
        Log.v("Steps","5");
        am = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE ));
        Log.v("Steps","6");
        am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,          SystemClock.elapsedRealtime()+ONE_SECOND, TEN_SECONDS, pi);
        Log.v("Steps","7");
    }

Logically, AlarmManagerListening activity should be started only when button being clicked.
However, it's been started by itself. Can anyone please explain the code to me?
Thanks a lot!


text:
Q: Python Como clickar em divs usando selenium Estou tentando pegar empregos no google empregos e extrair dados para guadar em banco de dados ou em json.
Sites: GOOGLE EMPREGOS TELA
Notem como tenho no lado esquerdo uma lista com varios empregos e quando clico em algum ele exibe na tela ao lado informações mais detalhas, como faço pra cada emprego na lista da esquerda ser clickado e depois extrair o texto do titulo do emprego, como ali na imagem onde está escrito Estágio TI no lado de exibição
Meu codigo:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

url1 = 'https://www.google.com/search?client=firefox-b-d&ei=Ja39X_nUIKif5OUPp6eUkAE&q=vagas+estagio+ti&oq=vagas+estagio+ti&gs_lcp=CgZwc3ktYWIQAzIICAAQsQMQgwEyAggAMgIIADICCAAyAggAMgIIADICCAAyAggAMgIIADICCAA6BAgAEEc6CggAELEDEIMBEEM6BAgAEEM6DggAELEDEIMBEMcBEK8BOgsIABCxAxDHARCjAjoFCAAQsQM6BQguELEDOggIABDHARCvAVDeMFipTmClUGgCcAN4AIABnQKIAbUckgEGMC4xLjE1mAEAoAEBqgEHZ3dzLXdpesgBCMABAQ&sclient=psy-ab&uact=5&ibp=htl;jobs&sa=X&ved=2ahUKEwjZlb7fyJbuAhXWGbkGHdiZAEUQutcGKAB6BAgDEAQ#htivrt=jobs&fpstate=tldetail&htilrad=-1.0&htidocid=jN52cIGLUm9ZT0BQAAAAAA%3D%3D'

# Definindo Drive
driver = webdriver.Chrome(executable_path=r'./chromedriver')
driver.get(url1) # Entrando no url1

# Click

time.sleep(10)
driver.quit() # Fechando o driver

Como posso fazer?

A: Um elemento pode ser clicado no Selenium através da função click():
elemento = driver.find_element_by_class_name('foo')
elemento.click()


text:
Q: Flexible inclusion of floating environments from external files I'm interested in using the approach described in the following exchange:
Move figures around in a document with a simple command
In a nutshell, the idea is to store labeled figure and table environments in one file and position them in your master tex file by reference to their label, thus making it easier to move figures/tables around and making it easier to make repeated inclusions or to share figures across documents.
The code written by egreg and described above works well for figures and tables, but no longer works with the sidewaysfigure environment of the rotating package. Question 1: Can the code be adapted to accept a sidewaysfigure?
To make this question self-contained, I am going to copy egreg's code. I have modified the original code a little to customize it to my tastes.
I store the code in a .sty file and call it with \usepackage{floats}.
The original code expected the user to store the floats in a file named the same as the master file but with a .flo extension. I found I wanted several master documents to use/reuse the floats, so the main change I made to the original code was to allow the user to specify the name of the .tex file storing the floats. This is done with the command \loadfloats{figures}, where the floats are stored in figures.tex in the same directory as the master file.
Comments welcome, naturally. I have two more questions, which I may ask separately if they turn out to be involved.
Question 2 Can the code be adapted to allow lists? e.g. \loadfloats{figures,tables}, as one may want to organize floating environments by chapter and/or separate figures and tables
Question 3 Can the same approach can be ported to the beamer class and applied to frames?
There are 3 files named floats-template.tex (the master file), floats.sty (egreg's code renamed and packaged), and figures.tex (the floating environments). In addition, an image named placeholder with standard extensions is expected in the same directory as everything else.
floats-template.tex
    \documentclass{article}
    \usepackage{lipsum}% \lipsum prints random text
    \usepackage{floats}% provides the \includefloat and \loadfloat commands
    \loadfloat{figures}% stores labeled figure environments

    \usepackage{rotating}% provides \sidewaysfigure environment

    \begin{document}
    \section{Lorem}
    \lipsum[5]
    \includefloat{fig:test1}

    \section{Dolor}
    \lipsum[5]
    \includefloat{fig:test2}

    \section{Final section}
    \lipsum[5]
    \includefloat{fig:test3}

    \end{document}

floats.sty
    \NeedsTeXFormat{LaTeX2e}

    \ProvidesPackage{floats}[2014/12/12 custom LaTeX style]

    % https://tex.stackexchange.com/questions/118323/
    %move-figures-around-in-a-document-with-a-simple-command/

    \RequirePackage{environ}%

    \AtBeginDocument{%
      \begingroup
      \InputIfFileExists{\thefloats.tex}{\setupprefloats}{}%
      \endgroup
    }

    \makeatletter
      \newcommand{\loadfloat}[1]{%
        \newcommand{\thefloats}{#1}%
    }

    \newcommand{\setupprefloats}{%
      \let\figure\relax\let\endfigure\relax
      \let\table\relax\let\endtable\relax
      \prefloat@rename{figure}\prefloat@rename{table}%
    }

    \newcommand{\prefloat@rename}[1]{%
      \NewEnviron{#1}{%
        \let\label\prefloat@label
        \renewcommand\caption[2][]{####2}%
        \setbox\z@=\vbox{\BODY}
        \toks@=\expandafter{\BODY}
        \expandafter\xdef\csname prefloat@\theprefloat@label\endcsname{%
          \noexpand\begin{#1}\the\toks@\noexpand\end{#1}}%
      }%
    }
    \newcommand{\prefloat@label}[1]{%
      \gdef\theprefloat@label{#1}%
    }
    \newcommand{\includefloat}[1]{%
    \expandafter\show\csname prefloat@#1\endcsname
      \@nameuse{prefloat@#1}%
    }
    \makeatother

    \endinput

figures.tex
    % A multi-paragraph \caption[short]{long} without a short caption option produces an error

    \begin{figure}[thbp]
      \centering%
      \includegraphics[width=\textwidth]{placeholder}%
      \caption[test]{\lipsum[2]}
      \label{fig:test1}
    \end{figure}

    \begin{figure}[thbp]
      \centering%
      \includegraphics[width=\textwidth]{placeholder}%
      \caption[test]{\lipsum[2]}
      \label{fig:test2}
    \end{figure}

    % OFFENDING PIECE OF CODE
    %\begin{sidewaysfigure}
    %  \includegraphics[width=\textwidth]{placeholder}%
    %  \caption[test]{\lipsum[2]}
    %  \label{fig:test3}
    %\end{sidewaysfigure}

A: Like in the answer I referenced in my comment, I used my boxhandler package as a starting point, and modified it by creating the macros \storeFigure[label]{caption}{content} and \recallFigure[htbp]{label}.
With boxhandler, figures (and tables) are created with macros, not environments.  The package provides flexible captioning options.  Disclaimer: clearly, the store and recall options should not be used in conjunction with the package's \holdFigures option.
In my MWE, I define three figures in an external file beginning with a 1/2" wide figure with caption "side caption". Then I create a 1" wide figure with "caption1" followed by a 2" wide figure with "caption2".  Then I recall the figures in the MWE in the order "caption2", "caption 1" "side caption", referencing them by their labels.
The MWE has been EDITED to allow the use of sidewaysfigure on the final figure.
\documentclass{article}
\usepackage{lipsum}
\usepackage[demo]{graphicx}
\usepackage{boxhandler, filecontents, rotating}

\begin{filecontents}{myfigures.tex}
% DEFINE ALL FIGURES AT THE BEGINNING
\storeFigure{fig:test3}{side caption}
{\includegraphics[width=0.5in]{testfig}}

\storeFigure{fig:test1}{caption1}
{\includegraphics[width=1in]{file1}}

\storeFigure{fig:test2}{caption2}
{\includegraphics[width=2in]{file2}}
\end{filecontents}

\makeatletter

\newcommand\storeFigure[3]{\@StoreFigure[#1]{#2}{#3}{\WrapperText}{\wrapper}}

\newcommand\@StoreFigure[5][]{%
  \addtocounter{FigureIndex}{1}%
  \setlength\DeadMargin\FigureDeadMargin%
  \def\FigureBoxLabel{fig\roman{FigureIndex}}%
  \def\FigureCaptionLabel{figcap\roman{FigureIndex}}%
  \def\FigCaptionWidthLabel{figcapwdth\roman{FigureIndex}}%
  \def\FigureWrapper{figwrap\roman{FigureIndex}}%
  \def\WrapperStatus{figwrapstatus\roman{FigureIndex}}%
  \expandafter\SaveCBox\csname\FigureBoxLabel\endcsname{#3}%
  \expandafter\def\csname\FigureCaptionLabel\endcsname{#2\label{#1}}%
  \expandafter\newlength\csname\FigCaptionWidthLabel\endcsname%
  \expandafter\setlength\csname\FigCaptionWidthLabel\endcsname%
                                              \CaptionBoxWidth%
  \expandafter\edef\csname\FigureWrapper\endcsname{#4}%
  \expandafter\edef\csname\WrapperStatus\endcsname{#5}%
%% After storing figure, reset wrapper to default value
  \global\def%
   \WrapperText{\noexpand\WrapperTextStyle\WrapperTextDefault}%
  \expandafter\def\csname FigureRefLabel\roman{FigureIndex}\endcsname{#1}%
}

\newcounter{loopfigindex}
\newcommand\recallFigure[2][ht]{%
  \setcounter{loopfigindex}{0}%
  \whiledo{\value{loopfigindex} < \value{FigureIndex}}{%
    \stepcounter{loopfigindex}%
    \ifthenelse{\equal{#2}{\csname FigureRefLabel\roman{loopfigindex}\endcsname}}{%
%%  \FigureBoxLabel:     : figi,    figii,    figiii,    figiv,    etc.
%%  \FigureCaptionLabel  : figcapi, figcapii, figcapiii, figcapiv, etc.
%%  \FigCaptionWidthLabel: figcapwdthi, figcapwdthii, figcapwdthiii,etc.
    \def\FigureBoxLabel{fig\roman{loopfigindex}}%
    \def\FigureCaptionLabel{figcap\roman{loopfigindex}}%
    \def\FigCaptionWidthLabel{figcapwdth\roman{loopfigindex}}%
    \def\FigureWrapper{figwrap\roman{loopfigindex}}%
    \def\WrapperStatus{figwrapstatus\roman{loopfigindex}}%
    \ReciteFigure[#1]{\csname\FigureCaptionLabel\endcsname}%
                     {\csname\FigureBoxLabel\endcsname}%
                     {\csname\FigCaptionWidthLabel\endcsname}%
                     {\csname\FigureWrapper\endcsname}%
                     {\csname\WrapperStatus\endcsname}%
  }{}}%
}

\newcommand\recallsidewaysFigure[2][ht]{%
  \setcounter{loopfigindex}{0}%
  \whiledo{\value{loopfigindex} < \value{FigureIndex}}{%
    \stepcounter{loopfigindex}%
    \ifthenelse{\equal{#2}{\csname FigureRefLabel\roman{loopfigindex}\endcsname}}{%
%%  \FigureBoxLabel:     : figi,    figii,    figiii,    figiv,    etc.
%%  \FigureCaptionLabel  : figcapi, figcapii, figcapiii, figcapiv, etc.
%%  \FigCaptionWidthLabel: figcapwdthi, figcapwdthii, figcapwdthiii,etc.
    \def\FigureBoxLabel{fig\roman{loopfigindex}}%
    \def\FigureCaptionLabel{figcap\roman{loopfigindex}}%
    \def\FigCaptionWidthLabel{figcapwdth\roman{loopfigindex}}%
    \def\FigureWrapper{figwrap\roman{loopfigindex}}%
    \def\WrapperStatus{figwrapstatus\roman{loopfigindex}}%
    \begin{sidewaysfigure}
    \centering
    \usebox{\csname\FigureBoxLabel\endcsname}
    \caption{\csname\FigureCaptionLabel\endcsname}
    \end{sidewaysfigure}
%    \ReciteFigure[#1]{\csname\FigureCaptionLabel\endcsname}%
%                     {\csname\FigureBoxLabel\endcsname}%
%                     {\csname\FigCaptionWidthLabel\endcsname}%
%                     {\csname\FigureWrapper\endcsname}%
%                     {\csname\WrapperStatus\endcsname}%
  }{}}%
}

\makeatother

\renewcommand\nextFigure[1][]{}% COMMENT THIS OUT TO PLACE FIGURES INLINE
\begin{document}
\input{myfigures.tex}

Figures were created in the order \ref{fig:test1} then \ref{fig:test2}.  That they
show up here as numbers means that the labeling worked.

\section{Lorem}
\lipsum[5]
\recallFigure[ht]{fig:test2}
\lipsum[3]

\section{Dolor}
\lipsum[1]
\recallFigure[ht]{fig:test1}

\section{Final section}
\lipsum[2]

\recallsidewaysFigure{fig:test3}

\lipsum[4-7]

\end{document}


text:
Q: Kafka Connect not consuming from Partition 0 I am facing a weird issues where Kafka connect is not consuming data from one of the topics where we dump our logging data
The topic initially had only 1 partition and has overall size of 250MB+. I increase the partitions of the topic to 5 and now I can see rest all partitions getting consumed but not the original partition 0

GROUP                        TOPIC                 PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG             CONSUMER-ID                                                                    HOST            CLIENT-ID
connect-request-log-elk-sink request-log           0          6               281294          281288          connector-consumer-request-log-elk-sink-0-ed4062a0-8712-46f5-939a-f0b783c3352c /XXX  connector-consumer-request-log-elk-sink-0
connect-request-log-elk-sink request-log           1          9882            16840           6958            connector-consumer-request-log-elk-sink-1-8f4a0ddf-7c91-4cde-93ab-05c5bf1deb2a /XXX  connector-consumer-request-log-elk-sink-1
connect-request-log-elk-sink request-log           3          9994            16918           6924            connector-consumer-request-log-elk-sink-3-83d0863e-dbc5-47ec-b240-b0e8eacbcb94 /XXX   connector-consumer-request-log-elk-sink-3
connect-request-log-elk-sink request-log           4          9744            16628           6884            connector-consumer-request-log-elk-sink-4-2c190184-5787-4b6d-91f4-16dd71fc6ea5 /XXX   connector-consumer-request-log-elk-sink-4
connect-request-log-elk-sink request-log           2          10885           16687           5802            connector-consumer-request-log-elk-sink-2-5e2c46c5-4e43-4a4c-af13-07d133e39038 /XXX   connector-consumer-request-log-elk-sink-2

The offset for partition 0 was stuck at 1, so I manually increased offset for the consumer by 1 multiple times to see if that helps move the topic. But that didn't change much
below is kafka connect config fog the same
{
    "connection.url": "http://xxx:9200",

    "connector.class": "io.confluent.connect.elasticsearch.ElasticsearchSinkConnector",
    "type.name": "request-log-elk-sink",
    "behavior.on.null.values": "delete",
    "auto.create.indices.at.start": "false",
    "read.timout.ms": "10000",
    "tasks.max": "5",
    "key.ignore": "true",
    "retry.backoff.ms": "5000",
    "transforms": "InsertTimestamp",
    "transforms.InsertTimestamp.type":"org.apache.kafka.connect.transforms.InsertField$Value",
    "transforms.InsertTimestamp.timestamp.field": "eventTime",
    "errors.deadletterqueue.context.headers.enable": "true",
    "max.buffered.records": "1000",
    "errors.deadletterqueue.topic.replication.factor": "1",
    "value.converter": "org.apache.kafka.connect.json.JsonConverter",
    "key.converter": "org.apache.kafka.connect.storage.StringConverter",
    "errors.log.enable": "true",
    "topics": "request-log,request-exception-log",
    "batch.size": "500",
    "max.in.flight.requests": "2",
    "schema.ignore": "true",
    "behavior.on.malformed.documents": "IGNORE",
    "flush.timeout.ms": "600000",
    "errors.deadletterqueue.topic.name": "request-log-dead-letter",
    "name": "request-log-elk-sink",
    "value.converter.schemas.enable": "false",
    "linger.ms": "1000"
}

Can anyone throw any light on why only one partition in Kafka will have a problem? I am able to view all data using kafka-ui and also able to dump all data using kafkacat


text:
Q: How many stable(infinitely long time) clients connections(sockets) can handle server (boost::asio) on win32 system? Which model is the most suitable servers model for Windows XP?
if the requirements are:
1. c++ ;
2. using async boost:asio ( BOOST_ASIO_HAS_IOCP is set );
3. client indefinitely long time communicates with the server.
How many socket server based on the boost:asio can normally stable process?

A: There really is no single answer that applies to every type of Windows set-up.  You indicated in a comment that you had 64 concurrent connections serviced by a single thread.  That is fine.  In fact, a single thread can service much more than 64 connections - depending on how much work the average message performs.  Many designs involve copying the message to a queue and then having background worker threads process the messages in that queue.  That way the thread with the message handler remains quite responsive.
How many connections can be serviced by a single thread?  That is something that you need to experiment with.  It could be 5,000, 50,000 or even 500,000+.  Same thing for the thread pool that services the queue of messages waiting to be processed.  You need to try different numbers of threads.  The result could be quite different depending on how much cpu time, file or DB I/O is done,  and how modern your hardware is.  Also, keep in mind that there is some significant overhead with threads.  For example, a SO poster some time ago said that a design with 1,000,000 threads was dead on arrival.  That is still probably true today.  So, it is your job to find the number of threads that can most efficiently serve the most connections.
What is the total number of connections that can be achieved with the most modern hardware and a well designed server?  Based on what I have read - 1,000,000+.  If you were doing it with WCF in C#, plan on less than half that.

A: There is no limit for connections inside boost::asio. But, there is external limits which can hit you(in order of importance):

*

*Your app speed and memory usage.

*Thread model and generally your app design.

*Type of connections(SSL or no-SSL). You can run out of memory before
sockets. On unix i except normal limit 100k for SSL and 1M for
non-SSL.

*Windows maximum socket limit.

A: The number of sockets is limited by the OS, although it is large. The main problem you'll run into is the number of parallel processes (threads) that will try to do work simultaneously as they will all fight for CPU time and memory and disk I/O....
Also, a client that lasts a very long time must be written properly so it does not leak anything (memory and whatever other resources.) Otherwise you'll run troubles (especially if you use threads.)
Speaking of memory, creating separate processes for each socket connection is the best way I know of to avoid memory fragmentation.
One last thing, the boost::asio that I know of opens sockets in non-blocking mode and I have not seen a way to change that. It is very difficult to close such a socket properly (i.e. making sure that you read the whole data because you get a close error before the OS sends you the remainder... so you need a full handshake.)


text:
Q: How do I start a Windows program with spaces in the path from Perl? If I do:
my program = "C:\\MyPath\\MyProg.exe";
system(("start", $program));

MyProg starts up just fine and my script resumes after the system() command.  But if there are spaces in the path like
my program = "C:\\My Path\\MyProg.exe";
system(("start", $program));

It seems to run cmd, not MyProg.
I've tried quoting with things like:
my program = "C:\\My Path\\MyProg.exe";
system(("start", '"' . $program . '"'));

But nothing seems to help.
Of course I can get around it with fork() but I'd like to understand why I can't pass a path with spaces as an argument.

A: That's because the built-in start command is a bit weird when it comes to quotes. You can reproduce this on the command line with start "C:\My Path\MyProg.exe" and see the same result. To properly execute it you need a set of empty quotes before it: start "" "C:\My Path\MyProg.exe".
So your end result should be:
my program = "C:\\My Path\\MyProg.exe";
system('start "" "' . $program . '"');

Edited to include the suggesstion from ikegami. My perl is a bit rusty as I haven't used it in years.

A: Try ...
my program = "C:/\"My Path\"/MyProg.exe";

A: I am not an perl expert but I found the following link.
http://bytes.com/topic/perl/answers/697488-problem-system-command-windows


text:
Q: Ionic android image path from gallery I am new in Ionic, I'm trying to get the proper image path using camera plugin. I have also attached the image.
Please let me know how I can get the image from the following path on my device

A: .config( function( $compileProvider )
  {
  $compileProvider.imgSrcSanitizationWhitelist(/^\s*(https?|file|content|local|blob|cdvfile):|data:image\//);
  }
)

add your project


text:
Q: Methods arrays in java I'm practicing for my final exam on java this semester and am doing some problems from the book.
Write a method that returns true if the arrays list1 and list2 are strictly identical, using the following header:
public static boolean equals(int[] list1, int[] list2)
Here's my code. It gives me "illigal start of statement" next to the return statement. What am I doing wrong?
public class StrictlyIdenticalArrays {

    public static void main(String[] args) {

        java.util.Scanner input = new java.util.Scanner(System.in);

        int[] list1 = new int[12];
        int[] list2 = new int[12];

        System.out.print("Enter list1: ");
        for (int i = 0; i < 12; i++)
            list1[i] = input.nextInt();

        System.out.print("Enter list2 ");
        for (int i = 0; i < 12; i++)
            list2[i] = input.nextInt();

        if (equals(list1, list2) == true)
            System.out.print("Two lists are strictly identical");
        else
            System.out.print("Two lists are not strictly identical");
    }

    public static boolean equals(int[] list1, int[] list2) {

        for (int i = 0; i < 12; i++) {
            if (list1[i] == list2[i])

        } return true;
    }
}

A: For a correct implementation of
public static boolean equals(int[] list1, int[] list2)

you need to do the following:

*

*First check that the arrays have equal lengths; if not return false.

*Next, loop through the arrays, using either i < list1.length or i < list2.length as the termination expression for the loop.

*Within the loop, check that the elements of the arrays are equal; if not return false.

*Finally, after the loop has been finished, return true.

A: if (list1[i] == list2[i])

is not closing statement,
it should be closed by brackets after
if (list1[i] == list2[i]) {}

or by semicolon
if (list1[i] == list2[i]);

but more importantly, why are you checking that condition if you are not taking any decision based on that

A: you have only to use this:
    for (int i = 0; i < 12; i++) {
        if (list1[i] != list2[i])return false;

    } return true;

here you will loop until the end of list is reached when every members are strictly identical and return by true , but if only one member found none identique it return a false. return statement bock method execution whenever is called .

A: You method is not really working the way you want it to. You have to change it a little to make it return true or false
You method will look like this:
public static boolean equals(int[] list1, int[] list2)
{
    for (int i = 0; i < list1.length; i++)
    {
        if (list1[i] != list2[i])
           return false;
    }

    return true;
}


text:
Q: io.UnsupportedOperation: not writable, can't write to .py files Using this code:
data = open("data.py")
for i, line in enumerate(data):
    if i == 7:
        data.write("test")

I get the following error and I don't know how to fix it.
Traceback (most recent call last):
  File "H:\py\Projects\osuGatcha\main.py", line 61, in <module>
    data.write("test")
io.UnsupportedOperation: not writable

A: By default "open" returns a file object that is readable, but not writable.  In other words, you can read the file you opened but you cannot write to it.  To write to the file include a second argument indicating you want to write to the file.
data = open("data.py", "w")

See more in section 7.2 here.  Also, be careful!  Opening a file to write to it will overwrite the contents of the file that currently exist.  If you just want to add to the end of an existing file you would open it in "append" mode, or with an "a" instead of a "w".


text:
Q: Inconsistent behavior with loop=1 on iframe I am having a very frustrating experience trying to get videos to loop consistently using a basic iframe.  I am not interacting with the API via code.  I simply have an iframe with autoplay=1,mute=1,loop=1.  I've tried using stand-alone videos and I've tried playlists (with list=[ID],listType=playlist) and I keep running into the same problem.  Sometimes the player will loop the video and sometimes it will not.  Every time I think I have it figured out and I'm ready to deploy the app, I test it again and the video fails to loop.
Windows 10
Chrome 71.0.3578.98
Angular 6.0.3

A: You can choose any of these options:

*

*Check my answer where I described how you can set your URL for create a playlist (using a single videoId) and simulate a loop.

*Use the YouTube iframe Player API for set your video and (once the video ended), call the playVideo() function for play the current video = hence, creating a loop.
This is the code: - unfortunately, you can't see it working here, but, you can see the working jsfiddle1

var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// Variables of the divs (where the YouTube iframe will load):
var player;

function onYouTubeIframeAPIReady() {

  // Div player:
  player = new YT.Player('player', {
    height: '360',
    width: '640',
    videoId: 'xPCZEoGJi_4',
    playerVars: {
      'autoplay': 1,
      'loop': 1,
      'mute': 1
    },
    events: {
      'onReady': onPlayerReady,
      'onStateChange': onPlayerStateChange
    }
  });

}

// 5. The API calls this function when the player's state changes.
function onPlayerStateChange(event) {

  // When the video ends, it will play again.
  // See: https://developers.google.com/youtube/iframe_api_reference?hl=en#Events
  if (event.data == YT.PlayerState.ENDED) {
    player.playVideo();
  }
}

// Div "player" - The API will call this function when the video player is ready.
function onPlayerReady(event) {
  event.target.playVideo();
}

1 If the video (once has loaded) hasn't play, you have to play manually the video - this is due some kind of restrictions that jsfiddle has.


text:
Q: ASP.net EF Code First - 2 tables  (ASP.net MCV 3 Razor View)
Hey, my problem is this:
I have in the models 2 classes, one called X, one called Y.
X has a property for class Y.
Now, I seeded them and I have a database with 2 tables for each. I need to use both of them in a single page so I passed them with a 3rd class that contains 2 IQueryables properties for each X and Y.
Now, in a page (.cshtml), I made 2 lists, one for X.ToList(), and one for Y.ToList(). I can reach this way both X and Y.
The problem is here, the value of Y inside X is null! Why?! it's so frustrating I spent so much time thinking what's wrong but I came up with nothing!

A: At a guess, the code that reads X doesn't Include() Y.


text:
Q: How to setBackground to MenuItem onPrepareMenuOptions in Android I want to setBackground to a MenuItem on OnprepareMenuOptions Method!
this code where I applying setBackground to MenuItem on OptionsItemSelected
   @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        View usera = findViewById(R.id.usera);
        View userb = findViewById(R.id.userb);
        switch (item.getItemId()){
            case R.id.userb:
        // Here default user styling
                colorb = false;
                if (!colorb){
                    userb.setBackground(ContextCompat.getDrawable(this,R.drawable.color_btn_effect));
                    usera.setBackground(null);
                    menu.getItem(0).setIcon(ContextCompat.getDrawable(this, R.drawable.ic_user_black));
                    menu.getItem(1).setIcon(ContextCompat.getDrawable(this, R.drawable.ic_user_icon));
                }
                Toast.makeText(this, "Default User B Selected", Toast.LENGTH_SHORT).show();
                break;

But I want to apply setBackground to "R.id.userb" while onPrepareMenuOptions or before selection of MenuItem.
I tried this but getting crash
  @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        View userb = findViewById(R.id.userb);
        userb.setBackground(ContextCompat.getDrawable(this,R.drawable.color_btn_effect));
        return super.onPrepareOptionsMenu(menu);
    }

userb.setBackground(ContextCompat.getDrawable(this,R.drawable.color_btn_effect));

please help me, how should I apply this ^^^^^ userb.setBackground on onPrepareMenuOption?
Hope you got me.
Thanks in advance =)

A: Probably you are getting null pointer exception on userb.setBackground.
Can you try getting userb's view by below method.
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    final MenuItem userbMenuItem = menu.findItem(R.id.userb);
    View userb = userbMenuItem.getActionView();
    userb.setBackground(ContextCompat.getDrawable(this, R.drawable.color_btn_effect));
    return super.onPrepareOptionsMenu(menu);
}


text:
Q: How to enforce a 1 to n relationship I'm working on an online muiltiplayer board game & have a SQL server question.
Lets assume the game allows two players. When the game is created, the creator is added as the first user.
At that point, two users could try to join the game simultaneously. One of these users should be blocked.
My database schema is as follows:
tbGame - contains a list of all games. PrimaryKey is GameId
tbPlayers - contains a list of all registered users. PrimaryKey is PlayerId
tbPlayersInGame - contains a list of all players in each game. Foreign key
                  relations to tbGame and tbPlayers.

I feel like I need two things:

*

*A way to lock tbPlayersInGame based on the GameId. This would be used while adding a player to a game. From what I've read it sounds like a key-range lock (on GameId) would be suitable.

*A way to enforce a 1-to-2 relationship so that attempts to add a 3rd player would fail.

A: A couple suggestions:
1) When you try to write to the tbPlayersInGame table first do a SELECT to make sure the game isn't full, then INSERT INTO the table.  Wrap this SELECT and the INSERT INTO in a transaction with the transaction isolation level set to serializable.
2) Don't have a separate tbPlayersInGame table, instead have 2 fields in tbGame: Player1Id, Player2Id

A: Instead of a 1-to-n relationship, you could set up your table to have to columns - probably labelled host_player and visitor_player, or the necessary equivalent (like in chess - black and white).  This has the advantage of keeping funny things to a minimum, and showing the natural state of the relationship.
This of course only works if there is supposed to be a permanently limited number of players - for most instances of boardgames, this will likely work fine....
If you are attempting to make a game where the upper limit is mutable (for whatever reason), you can 'detect' free slots available with the following statement:
INSERT INTO game_players (game_id, player_id)
SELECT VALUES (:GAME_ID, :PLAYER_ID)
WHERE :MAX_PLAYER_COUNT > (SELECT COUNT(*)
                           FROM game_players
                           WHERE game_id = :GAME_ID)

If you get back an error-code of 100 ('No rows selected/updated), the player list is full.  You may need to add other conditions (to prevent players from joining twice), but the concept should still work.


text:
Q: where is Session.setDefault Location Hello I am new in Meteor.
I saw this api documentation.
before I knew Session.setDefault,
use default session setting inside Meteor.startup()
if(Meteor.startup(){
    Session.set("isArchive", false);
}

is this code are exactly same with Session.setDefault(key, value)??

A: No, they are not the same. Values stored in Session survives hot code pushes, so if you use Session.set to initialize "variables", all "variables" will be re-assigned their default values on hot code pushes. With Session.setDefault, they will keep the value they had before the hot code push.


text:
Q: Why people try to kill or protect the Gods' pawns in Malazan series? I have only read Gardens of the Moon series and I am not sure why some people try to kill the tools (pawns) of the Gods where people try to protect them.
For instance Rake doesn't kill Paran when he learns he is not Oponn's tool but his second-in-command Serrat tries to kill the coin bearer. Baruk alto tries to protect the coin bearer at all cost whereas Lorn tries to kill him.
What difference does it make to kill a tool? Is it that easy to kill a tool without the God's help (I mean if there is nobody else to protect the tool)? What are the motives of people who are trying to kill or protect the pawns of the Gods?
PS: Please do not give spoilers if they are related with other books.
Regards


text:
Q: How to convert array of strings into array of struct with conditions I have a pyspark dataframe with single column _c0.
a|b|c|clm4=1|clm5=3
a|b|c|clm4=9|clm6=60|clm7=23

I am trying to convert it to a dataframe of selected columns like this
clm1,clm2,clm3,clm4,clm6,clm7,clm8
a,    b,   c,   1,  null,null,null
a,    b,   c,   9,   60,  23, null

Please note that I removed clm5 and added clm8.
I am using below code:
transform_expr = """
    transform(split(_c0, '[|]'), (x, i) ->
                       struct(
                             IF(x like '%=%', substring_index(x, '=', 1), concat('_c0', i+1)),
                             substring_index(x, '=', -1)
                             )
            )
    """

    df = df.select("_c0",  explode(map_from_entries(expr(transform_expr))).alias("col_name", "col_value")).groupby("_c0").pivot('col_name').agg(first('col_value')).drop("_c0")

The problem is that I have multiple huge files on which I want to perform this action and the result of each file should contain same columns(which is also a long list) which can have null values if not present in input file. How can I add a condition to the above code to select only those column which are present in a list of column names?

A: You can have the desired columns in a list and use it to filter the transformed array :
column_list = ["clm1", "clm2", "clm3", "clm4", "clm6", "clm7", "clm8"]

Now add this filter after the transform step using filter function:
column_filter = ','.join(f"'{c}'" for c in column_list)

transform_expr = f"""
            filter(transform(split(_c0, '[|]'), (x, i) ->
                               struct(
                                     IF(x like '%=%', substring_index(x, '=', 1), concat('clm', i+1)) as name,
                                     substring_index(x, '=', -1) as value
                                     )
                    ), x -> x.name in ({column_filter}))
            """

This will filter out all the columns that are not present in the list.
And finally, add the missing columns as nulls using simple select expression:
df = df.select("_c0",  explode(map_from_entries(expr(transform_expr))).alias("col_name", "col_value")).groupby("_c0").pivot('col_name').agg(first('col_value')).drop("_c0")

## add missing columns as nulls
final_columns = [col(c).alias(c) if c in df.columns else lit(None).alias(c) for c in column_list]

df.select(*final_columns).show()

#+----+----+----+----+----+----+----+
#|clm1|clm2|clm3|clm4|clm6|clm7|clm8|
#+----+----+----+----+----+----+----+
#|   a|   b|   c|   9|  60|  23|null|
#|   a|   b|   c|   1|null|null|null|
#+----+----+----+----+----+----+----+


text:
Q: Выделение определенной строки со словом C# RichTextBpx Необходимо сделать так, чтобы текст, идущий после слова "Ответ:" (включительно) выделялся жирным. "Ответ" в тексте один и он всегда на последней строке.
Как будет вернее это сделать?
Пытался так, не получилось.
int index = 0, charIndex = 0, i = 0;
do
{
    index = richTextBox1.Find("Ответ:", index + 1, RichTextBoxFinds.MatchCase);
    i++;
    if (index != -1) charIndex = i;
}
while ((index != -1));
int lineIndex = richTextBox1.GetLineFromCharIndex(charIndex);
int startFromIndex = richTextBox1.GetFirstCharIndexFromLine(lineIndex);
int lineLength = richTextBox1.Lines[lineIndex].Length;
richTextBox1.Select(startFromIndex, lineLength);
richTextBox1.SelectionBackColor = System.Drawing.Color.Orange;
richTextBox1.DeselectAll();

A:
Необходимо сделать так, чтобы текст, идущий после слова "Ответ:"
  (включительно) выделялся жирным. Ответ один, он всегда на последней
  строке

В этом случае все совсем просто. Я, откровенно говоря, не понял смысл вашей конструкции. То что "Ответ" всего один, сильно упрощает задачу, нам не требуется даже знать на какой именно строке он написан. У меня получилось так:
//тестировал на таком фрагменте.
richTextBox1.Text = "лорршгрртшщрн \r\nолпропор Ответ: \r\n  ншоргшргшршгргшршщг";
//ищем начало слова ответ
int start = richTextBox1.Find("Ответ:");
//выделяем до конца текста
richTextBox1.Select(start, richTextBox1.Text.Length - start);
//в выделенный фрагмент устанавливаем шрифт, созданный из имеющегося,
//но со стилем Bold - жирный
richTextBox1.SelectionFont = new Font(richTextBox1.SelectionFont, FontStyle.Bold);
//сбрасываем выделение, тут в начало текста
richTextBox1.Select(0,0);

Вид текста после обработки:

лорршгрртшщрн
  олпропор Ответ:
    ншоргшргшршгргшршщг

естественно, первый и последний пункты в коде нужно заменить на что-то более нужное и полезное.


text:
Q: How are Desmond's assassin ancestors related to each other? I read somewhere (cannot find the link at the moment) that Altair, Ezio and the Kenways (including Connor) are not directly related to each other except through Desmond. Is there any family tree or something to show how he is related to them?
If the Kenways are on Desmond's father's side, could he not have gone in the Animus as well in Assassin's Creed 3?

A: Here is a family tree of Desmond's ancestry (click on the picture to zoom in).
As you can see, the Auditore and Ibn-La'ahad sections of the tree are completely independent of one another (and their link is currently unknown).
It is not known how directly the Kenway portion of the tree connects to the others, so until future games reveal this link we will be unable to tell how well connected they are to the Auditores or Ibn La'ahads.
We can also see from the tree that the relationship to these ancestors is on Desmond's mother's side of the tree. So Desmond's father would be unable to use the animus to access their memories since he has no direct ancestral link to any of these families.
However, presumably any family member on Desmond's mother's side of the tree (from the generation after Connor to Desmond) would be able to access the same memories we have accessed from Desmond so far.
Hopefully the coming games of Unity and Rogue will help fill in some of these blanks on the family tree.

A:
And if the Kenways are on Desmonds fathers side, could he not have gone in the animus as well in Assassins Creed 3?

At one point in AC 3 Desmond angrily shouts that at his father

after it is revealed that  Haytham is a templar

Right before his father

punches Desmond in the face (something long overdue).

So that suggests the Kenway's are on Desmond's fathers side (at least in Desmond's mind - his father neither confirms nor denies).
As for why his father couldn't go into the animus, it's strongly hinted that there is something special about Desmond. Perhaps it is the convergence of blood lines from his mother and fathers side?


text:
Q: Is there a coding standard for PHP annotations? Is there a PHP coding standard that defines unambiguously how to write docblock annotations for properties and methods:

*

*@var

*@param

*@return

*@throws
including the correct spacing between them?
PSR-2 covers the code itself, but does not enforce the usage of annotations.

A: There's no annotations in PHP. If you use phpdoc to generate documentation, you need to follow phpdoc guides.
http://www.phpdoc.org/


text:
Q: Dynamic favicon that persists after refreshing the browser We have a web application written in Angular (4.3.4 to be exact) that changes settings based on the user account that logs in at the start (each user belongs to a company, which has it's own logo/favicon etc.)
On login, we retrieve the settings from the users database and set them inside the local cache. One of these settings is a URL to a favicon that they have set themselves.
Currently, I execute some jQuery that locates the favicon element inside the <head> tags that changes the href attribute:
private changeFavicon(value: string): void {
    $('#favicon').attr('href', value);
}

But, upon a page refresh, this data is gone and it reverts back to the original favicon (a backup we have stored as an image in /resources/)
The only way I can see solving this problem is adding a 'CanLoad' service that set it every time a route is initialised, but this will have to be added to every route (as a user can obviously refresh on every page) which does not seem the best route to take.
Is there a way I can persist these changes across refreshes?


text:
Q: How to do this in a pythonic way? Consider this Python snippet:
for a in range(10):

    if a == 7:
        pass
    if a == 8:
        pass
    if a == 9:
        pass
    else:
        print "yes"

How can it be written shorter?
#Like this or...
if a ?????[7,8,9]:
    pass

A: for a in range(10):
    if a > 6:
        continue
    print('yes')

A: Based on your original code the direct "pythonic" replacement is:
if not a in [7, 8, 9]:
     print 'yes'

or
if a not in [7, 8, 9]:
     print 'yes'

The latter reads a little better, so I guess it's a bit more "pythonic".

A: Use the in operator:
if a in (7,8,9):
    pass

A: To test if a falls within a range:
if 7 <= a <= 9:
  pass

To test if a is in a given sequence:
if a in [3, 5, 42]:
  pass

A: if a in [7,8,9]

A: Depending on what you want to do, the map() function can also be interesting:
def _print(x):
    print 'yes'

map(_print, [a for a in range(10) if a not in (7,8,9)])

A: What about using lambda.
>>> f = lambda x: x not in (7, 8, 9) and print('yes')
>>> f(3)
yes
>>> f(7)
False

A: Since the question is tagged as beginner, I'm going to add
some basic if-statement advice:

if a == 7:
    pass
if a == 8:
    pass
if a == 9:
   ...
else:
   ...

are three independent if statements and the first two have no effect, the else refers only to

 if a == 9:

so if a is 7 or 8, the program prints "yes". For future use of if-else statement like this, make sure to use elif:
if a == 7:
    seven()
elif a == 8:
    eight()
elif a == 9:
    nine()
else:
    print "yes"

or use just one if-statement if they call for the same action:
if a == 7 or a == 8 or a == 9:
    seven_eight_or_nine()
else:
    print "yes"


text:
Q: How to set environment variables for a shell command I often see this command in node.js programs: NODE_ENV=test node app.js which sets the NODE_ENV variable to test and works. I also read here https://en.wikipedia.org/wiki/Environment_variable that this should work for any shell command, but running some tests on my own, here is what I see
$ HELLO="WORLD"
$ HELLO="MARS" echo "$HELLO"
  WORLD
$

I would expect this to print MARS. Is there something I am missing here?

A: The syntax VAR=value command means that the command will be invoked with the environment variable VAR set to VALUE, and this will apply only for the scope of that command.
However, when you are using the command line:
HELLO="MARS" echo "$HELLO"

The shell first interprets the "$HELLO" parameter, determines that it is WORLD, and then what it actually does is run:
HELLO="MARS" echo "WORLD"

So the echo may have the HELLO variable set, but it doesn't affect what it prints - it has already been interpreted before.
Doing
HELLO="MARS"; echo "$HELLO"

does something else entirely. First it sets HELLO to MARS in the current shell, and then it goes on to interpret the echo command. By this time HELLO contains MARS, not WORLD. But this is an entirely different effect - the variable HELLO stays with the value MARS, which is not the case in the command without the ;.
Your problem is that echo is just a poor choice for a demonstartion of this. You can do other demonstrations to prove that HELLO is changed properly:
HELLO="MARS" eval 'echo $HELLO'

In this case, the shell will not interpret the $HELLO because it is within a string in single quotes. It will first put MARS in HELLO, and then call the eval 'echo $HELLO' with that variable set. The eval command with then run echo $HELLO, and you'll get the output you were expecting.
This syntax is best used for things that don't use the given variable as part of the command line, but rather use it internally.

A: Other answers are correct, but here a refinement :
There are 2 cases in fact when defining a list of variable separated by spaces in bash whether it ends or not with a command.
VAR1=value1 VAR2=value2 ... VARn=valuen command arg1 arg2 ... argn

and
VAR1=value1 VAR2=value2 ... VARn=valuen

don't export VAR1 ... VARn the same way.
In first case VAR1 ... VARn will be set only for command and will then not be exported to current shell.
In second case VAR1 ... VARn will alter current shell.
then ( remark that ';' is very same of using a new line )
HELLO=WORLD
HELLO=MARS echo "i don't export HELLO."
echo "HELLO=$HELLO"

will display
i don't export HELLO.
HELLO=WORLD

and
HELLO=WORLD
HELLO=MARS ; echo "i did export HELLO."
echo "HELLO=$HELLO"

will display
i did export HELLO.
HELLO=MARS


text:
Q: how to find what functions need to be defined for a protocol interface If i want my type to implement a function, eg. contains? how do I find out which interface to extend?
Similarily, if I see an interface, eg. clojure.lang.ILookup how do I find out which methods are required to be implemented?

A: If you want to see what methods an interface requires (including inheritied members) use java reflection at the repl:
 (clojure.pprint/pprint (.getMethods clojure.lang.ILookup))
 [#<Method public abstract java.lang.Object clojure.lang.ILookup.valAt(java.lang.Object)>,
  #<Method public abstract java.lang.Object clojure.lang.ILookup.valAt(java.lang.Object,java.lang.Object)>]

If you're on Clojure 1.2, you could also use clojure.contrib.repl-utils/show

A: First, clone the source from here:  (git) https://github.com/clojure/clojure.git (browser) https://github.com/clojure/clojure
Look at the source for contains? in src/clj/clojure/core.clj, it turns around and calls clojure.lang.RT.contains.
That file is in src/jvm/clojure/lang/RT.java, you can see that it will work with instances of Associate, IPersistentSet, Map, Set, and it also looks like it will index into arrays and strings, so pick what makes sense for your situation.
Likewise, the source for ILookup is in that same directory. You can find out about how interfaces work in Java if you're not familiar with them here.
Back to contains? though, you might be able to use a record to achieve what you want.
e.g.
main=> (defrecord Action [time key args state])
main.Action
main=> (def action (Action. (System/currentTimeMillis) "key" ["arg1" "arg2"] nil))
#'warscor.main/action
warscor.main=> (contains? action :time)
true
warscor.main=> (contains? action :state)
true
warscor.main=> (contains? action :foo)
false
warscor.main=> (def action (assoc action :foo "bar"))
#'warscor.main/action
warscor.main=> (contains? action :foo)
true


text:
Q: Error within if statement conditional I'm building a program to work out the min, max and avg of the users input.
When the user enters 0 or a negative number, the program exits the loop.
I'm currently working on building the input processor. But I'm having some errors. I haven't used conditionals to this extent before, so I must be making a mistake somewhere in there.
Also any suggestion for how I could make this better would be appreciated.
The error:
questionAvg.java:17: error: illegal start of expression
            if(input_into.nextInt() !=0) || input_into.nextInt < 0){
                                         ^
questionAvg.java:17: error: ';' expected
            if(input_into.nextInt() !=0) || input_into.nextInt < 0){
                                                                  ^
questionAvg.java:19: error: 'else' without 'if'
                } else{

The code:
import java.util.*;
public class questionAvg
{
public static void main(String[]args)
{

Scanner input_into = new Scanner(System.in);
ArrayList<Integer> collector = new ArrayList<Integer>();

System.out.println("Enter 0 or a negative number to end input");
System.out.println("Enter a positive integer to populate the arraylist");

    while (input_into.hasNextint()){
                System.out.println("Type another int or exit");

            if(input_into.nextInt() !=0) || input_into.nextInt < 0){
                collector.add(input_into.nextInt());
                } else{
                        System.out.println("You entered 0 or a negative number. Now calculating....");
                }
            }
       }
  }

A: You have a bracket in the wrong place, and you're treating nextInt as a public member variable not a method:
if(input_into.nextInt() !=0) || input_into.nextInt < 0)

needs to be:
if(input_into.nextInt() != 0 || input_into.nextInt() < 0)

as otherwise you're ending the if statement after the first condition hence all the errors.

A: Remove the extra ) in the if statement before || and you also missed () while calling input_into.nextInt() < 0.It should be.
 if(input_into.nextInt() !=0 || input_into.nextInt() < 0){

And also you are reading integer twice in the if(input_into.nextInt() !=0 || input_into.nextInt < 0) and again in the next line collector.add(input_into.nextInt());.Instead you can do
  int inp=input_into.nextInt();
  if( inp!=0 || inp < 0){
                collector.add(inp);

A: You did mistake here :
if(input_into.nextInt() !=0) || input_into.nextInt < 0)

It should be
if(input_into.nextInt() !=0 || input_into.nextInt < 0)

A: Please try the following code (I have tested it):
import java.util.ArrayList;
import java.util.Scanner;

public class questionAvg {
    public static void main(String[] args) {

        Scanner input_into = new Scanner(System.in);
        ArrayList<Integer> collector = new ArrayList<Integer>();

        System.out.println("Enter 0 or a negative number to end input");
        System.out.println("Enter a positive integer to populate the arraylist");

        while (input_into.hasNextInt()) {
            System.out.println("Type another int or exit");

            if ((input_into.nextInt() != 0) || (input_into.nextInt() < 0)) {
                collector.add(input_into.nextInt());
            } else {
                System.out.println("You entered 0 or a negative number. Now calculating....");
            }
        }
    }
}


text:
Q: Modifying strings in Java practice public static void displayWords(String line)
{
  // while line has a length greater than 0
  //   find the index of the space.
  //   if there is one,
  //    print the substring from 0 to the space
  //    change line to be the substring from the space to the end
  //   else
  //    print line and then set it equal to the empty string

}
  line = "I love you";
  System.out.printf("\n\n\"%s\" contains the words:\n", line );
  displayWords(line);

Hi, i'm having trouble with the above code, it;s a practice problem but "change line to be the substring from the space to the end" really confuses me. I know how to find the index of space and printing the string from the beginning to the index.
Expected Output:
I
love
you

A: SLaks is recommending in his comment you to use the substring() method. Checking the API documentation for String:

public String substring(int beginIndex, int endIndex)
  Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.
  Examples:

*

*"hamburger".substring(4, 8) returns "urge"

*"smiles".substring(1, 5) returns "mile"

So, consider this:
public static void displayWords(String line) {
    while(line.length() > 0) { // This is the first part (the obvious one)
        /*
           You should do something here that tracks the index of the first space
           character in the line. I suggest you check the `charAt()` method, and use
           a for() loop.
           Let's say you find a space at index i
         */
         System.out.println(line.substring(0,i)); // This prints the substring of line
                                                  // that goes from the beginning
                                                  // (index 0) to the position right
                                                  // before the space
         /*
           Finally, here you should assign a new value to line, that value must start
           after the recently found space and end at the end of the line.
           Hint: use substring() again, and remember that line.lengh() will give you
                 the position of the last character of line plus one.
          */
    }
}

You've had enough time... and I'm feeling generous tonight. So here is the solution:
public static void displayWords(String line) {
    int i; // You'll need this
    while(line.length() > 0) { // This is the first part (the obvious one)
        /*
           Here, check each character and if you find a space, break the loop
         */
        for(i = 0; i < line.length(); i++) {
            if(line.charAt(i) == ' ') // If the character at index i is a space ...
                break;                // ... break the for loop
        }
        System.out.println(line.substring(0,i)); // This prints the substring of line
                                                 // that goes from the beginning
                                                 // (index 0) to the position right
                                                 // before the space
        /*
          Here, the new value of line is the substring from the position of the space
          plus one to the end of the line. If i is greater than the length of the line
          then you're done.
         */
        if(i < line.length())
            line = line.substring(i + 1, line.length());
        else
            line = "";
    }
}

After reading your question again, I realised that it should be a recursive solution... so here is the recursive approach:
public static void displayWords(String line) {
    int i;
    for(i = 0; i < line.lengh(); i++) {
        if(line.charAt(i) = ' ')
            break;
    }
    System.out.println(line.substring(0, i);
    if(i < line.lengh())
        line = line.substring(i + 1, line.lengh();
    else
        line = "";
    if(line.lengh() > 0)
        displayWords(line);
}

A: Another way of doing it.
public static void displayWords(String line)
{
  Scanner s = new Scanner(line)
  while (s.hasNext())
  {
    System.out.println(s.next())
  }
}

http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html < Use this for reference.


text:
Q: how to add "abstract" in Table of contents I form abstract.tex as
\renewcommand{\abstractname}{Abstract}
\begin{abstract}
... % eng version
\end{abstract}

\renewcommand{\abstractname}{Kurzfassung}
\begin{abstract}
... % de version
\end{abstract}

How to add Abstract and Kurzfassung ( both) in the table of the contents?

A: Something along the lines:
\renewcommand{\abstractname}{...}
\begin{abstract}
\addcontentsline{toc}{chapter}{\abstractname}
...
\end{abstract}

% and similarly for your second abstract.

As you have not provided an MWE I guessed that you might want the abstracts' ToC entries to be like a chapter. If they are more like a section then change the chapter to section. There is more information in the tocloft package manual but I don't think that you need the package for what you want.


text:
Q: Time based greeting app not working, swift So I'm trying to make a simple time based greeting app in swift but it's not working, when I press return in the text field of my app it just freezes, Xcode brings me to AppDelegate and has one line with a little mark on it, I don't know whats wrong and why.
Xcode says there are no errors in my code while I'm editing it, but then the app doesn't work. Here's my code:
import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var nameLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    @IBAction func nameTextField(nameTextField: UITextField) {
        var currentTimeOfDay = ""

        let hour = NSCalendar.current.component(.hour, from: NSDate() as Date)
        if hour >= 0 && hour < 12 {

            currentTimeOfDay = "Morning"

        } else if hour >= 12 && hour < 17 {

            currentTimeOfDay = "Afternoon"

        } else if hour >= 17 {

            currentTimeOfDay = "Evening"

        }

        nameLabel.text = "Good \(currentTimeOfDay) \(nameTextField)"
    }
}

Any help is appreciated!
EDIT:
I am no longer in need of the answer as I was just playing around in Swift. Thank you anyway to all who answered or commented though!
-Moose

A: Here's my full working app.
import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var helloLbl: UILabel!
    @IBOutlet weak var nameText: UITextField!

    var heyName = "Hey"
    var greeting = ""

    func greetingLogic() {
        let date = NSDate()
        let calendar = NSCalendar.current
        let currentHour = calendar.component(.hour, from: date as Date)
        let hourInt = Int(currentHour.description)!

        if hourInt >= 12 && hourInt <= 16 {
            greeting = "Good Afternoon"
        }
        else if hourInt >= 7 && hourInt <= 12 {
            greeting = "Good Morning"
        }
        else if hourInt >= 16 && hourInt <= 20 {
            greeting = "Good Evening"
        }
        else if hourInt >= 20 && hourInt <= 24 {
            greeting = "Good Night"
        }
        else if hourInt >= 0 && hourInt <= 7 {
            greeting = "You should be sleeping right now"
        }

        helloLbl.text = greeting
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        greetingLogic()

    }

    @IBAction func sayHello(_ sender: UIButton) {

        helloLbl.text = greeting + ", " + nameText.text!.capitalized + "!"

    }

}

A: Just clean function
    private func getGreeting() -> String {
        let hour = Calendar.current.component(.hour, from: Date())

        switch hour {
        case 0..<4:
            return "Hello"
        case 4..<12:
            return "Good morning"
        case 12..<18:
            return "Good afternoon"
        case 18..<24:
            return "Good evening"
        default:
            break
        }
        return "Hello"
    }


text:
Q: Using keypress in android I am creating an android application, a converter. Every time I am going to press any number, I want it to be displayed automatically on a textfield. I don't know how to use the keypress in android application. Is it just like using keypress in a simple java program, let's say ran on netbeans?

A: Um ...
public class MainActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(new EditText());
    }
}

A: Your question is not very clear.. but i think you are saying that your layout contain a EditText and TextView,  when user type in a number in EditText at same time the TextView should also set the same text at rumtime. if this is your requirement then you can do it as follows:
public class MainActivity extends Activity
{
   @Override
   public void onCreate(Bundle b)
   {
      super.onCreate(b);
      setContentView(R.layout.main_activity);
      TextView tv = (TextView)findViewById(R.id.textview1);
      EditText et = (EditText)findViewById(R.id.edittext1);
      et.addTextChangedListener(new TextWatcher()
        {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count)
            {
                tv.setText(s);
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after)
            {
            }

            @Override
            public void afterTextChanged(Editable s)
            {
            }
        });
        }
   }


text:
Q: Match nested subdirectories with a Scotty RoutePattern I'm serving some static files with my Scotty webserver. They can also be located in subdirectories. My current approach looks like this:
get "/:fileName" $ do
    fileName <- param "fileName"
    file $ pathToStaticFiles </> fileName

get "/:dirName/:fileName" $ do
    dirName <- param "dirName"
    fileName <- param "fileName"
    file $ pathToStaticFiles </> dirName </> fileName

get "/:dirName1/:dirName2/:fileName" $ do
    dirName1 <- param "dirName1"
    dirName2 <- param "dirName2"
    fileName <- param "fileName"
    file $ pathToStaticFiles </> dirName1 </> dirName2 </> fileName

....

Is there a possibility to match paths with different directory nesting depth using only one single pattern?

A: Scotty has several other route patterns on top of the default one (which is called capture). Those can be found in the documentation.
regex seems to be exactly what you want. Here is the example from the documentation :
get (regex "^/f(.*)r$") $ do
   path <- param "0"
   cap <- param "1"
   text $ mconcat ["Path: ", path, "\nCapture: ", cap]

For your use case, it'd be a matter of catching the whole path, splitting on "/" and folding the resulting list with </>.


text:
Q: Automatically select template's typename in C++ I'm working in a group and I have to deliver a class template which will be later composed into other classes like this:
template <typename type>
class foo{
};

class bar{
    foo<bar> a;
};

The template's type will be always of the higher class.
class foobar{
    foo<foobar> a;
};

Is there any way to automtize/bind it, so that coworkers wouldn't need to always write the typename?

A:
Is there any way to automtize/bind it, so that coworkers wouldn't need
  to always write the typename?

the actual answer
No
the pedantic answer
Yes, probably with some macros. But you really shouldn't.
"So what should I do?"
Nothing
"Why?"
Follow the "code is written once, but read many times" mantra. So just let them write the template parameter. It's just so insignificant of a inconvenience that the clarity of it far more outweighs the cost of a macro.
"Ok, ok, I just wish there was a way"
So do I. And actually there is work done to bring reflection to C++ which should solve this (I hope, I don't actually know if it is possible with any of the two current proposals).

A: Well you could add a class that would serve as a base class for you actual classes.
template <typename derivedType>
class foo_holder
{
protected:
    foo<derivedType> a;
};

class bar : private foo_holder<bar> { };

If you use private inheritance there, then it is mainly equivalent to you original code.
I am not sure if it would be possible to make the field private in base class and derivedType a friend of it. If so, then it could a bit less error prone (giving too much access to details which can lead to unnoticed abuses).


text:
Q: Save value of Id in other field sqlalchemy flask I am creating a table in database using flask sqlalchemy
In models.py,
Class User(model):
    user_id = Column(Integer, primary_key=True)
    du_id = Column(Integer)
    name = Column (NVARCHAR(20))
    #other fields...

In this table, when inserting new record, the user_id is created automatically.
How to save the user_id value in du_id field automatically when creating/inserting new record?
Thanks

A: You can use a hybrid attribute instead of a new column
class User(model):
    user_id = Column(Integer, primary_key=True)
    name = Column (NVARCHAR(20))
    #other fields...

    @hybrid_property
    def length(self):
        return self.user_id


text:
Q: "Error in install.packages : missing value where TRUE/FALSE needed" in RStudio but not in R. Why? When I execute:
install.packages(c("rj", "rj.gd"), repos="http://download.walware.de/rj-2.1")

It works in R but not in RStudio. Why?
In RStudio I get:
> install.packages(c("rj", "rj.gd"), repos="http://download.walware.de/rj-2.1")
Error in install.packages : missing value where TRUE/FALSE needed

traceback:
> traceback()
3: installed.packages()
2: as.data.frame(installed.packages(), stringsAsFactors = F)
1: (function ()
   {
       uniqueLibPaths <- .rs.uniqueLibraryPaths()
       x <- suppressWarnings(library(lib.loc = uniqueLibPaths))
       x <- x$results[x$results[, 1] != "base", ]
       pkgs.name <- x[, 1]
       pkgs.library <- x[, 2]
       pkgs.desc <- x[, 3]
       pkgs.url <- file.path("help/library", pkgs.name, "html",
           "00Index.html")
       loaded.pkgs <- .rs.pathPackage()
       pkgs.loaded <- !is.na(match(normalizePath(paste(pkgs.library,
           pkgs.name, sep = "/")), loaded.pkgs))
       instPkgs <- as.data.frame(installed.packages(), stringsAsFactors = F)
       pkgs.version <- character(length = length(pkgs.name))
       for (i in 1:length(pkgs.name)) {
           pkgs.version[[i]] <- .rs.packageVersion(pkgs.name[[i]],
               pkgs.library[[i]], instPkgs)
       }
       pkgs.library <- .rs.createAliasedPath(pkgs.library)
       packages = data.frame(name = pkgs.name, library = pkgs.library,
           version = pkgs.version, desc = pkgs.desc, url = pkgs.url,
           loaded = pkgs.loaded, check.rows = TRUE, stringsAsFactors = FALSE)
       packages[order(packages$name), ]
   })()

I use Windows 10 Enterprise with RStudio 1.0.143 as well as:
> R.version
               _
platform       x86_64-w64-mingw32
arch           x86_64
os             mingw32
system         x86_64, mingw32
status
major          3
minor          4.0
year           2017
month          04
day            21
svn rev        72570
language       R
version.string R version 3.4.0 (2017-04-21)
nickname       You Stupid Darkness


text:
Q: Implement Message Signaled Interrupt in DOS mode I'm bit stuck at programming device MSI(Message Signaled interrupt) and any pointers welcomed...(my environment is Watcom C + DOS/32a - dos extender, in flat mode...)
@ PIC(8259) mode is ok for me...
I list what I have done as below and maybe someone can help to clarify these...Thanks !
(1) Multiple Message Enable = 0( for single MSI set this field = 0; MMC = 100b)
(2) For MSI message address register in the MSI capability

*

*bit[31:20] = 0xFEE

*bit[19:12] = 0 (Destination ID, and found Local APIC ID = 0...)

*bit3 = 0 (Redirection hint = 0)

*bit2 = 0 (Destination Mode, don't care because of RH = 0)

(3) For MSI message data register in the MSI capability

*

*bit15 = 0 (trigger mode = edge)

*bit14 = 0 (trigger level, ignored if trigger mode = edge)

*bit[10:8] = 000 (delivery mode = fixed)

*bit[7:0] = 0x20 (vector, and I choose to use 0x20)

(4) Finally enable MSI by setting MSICAP.MC.MSIE = 1

*

*I have roughly read the doc(chapter 10) http://download.intel.com/products/processor/manual/253668.pdf

*I think there is no need to program IO APIC and Local APIC registers because MSI does not route to APIC system...!

Current status: I found system hang after enabling MSIE = 1 and device generates interrupt via MSI !
Note: In above sequence the service routine is NOT installed because I have no idea how to do it...( is this the reason why my app hang ? )
Thanks !
[20120822 updated]
When setting the vector in Message Data field to 0x20, app hang...But if set to 0x76, I found app did not hang and then I can check if device generates interrupt and Local APIC receives this interrupt message as below:

*

*For PCI device(AHCI controller):

*

*ID(Interrupt Disable) = 0

*IS(Interrupt Status) = 0

*MSI Cap = 09,FEE00000,00000076

*For AHCI HBA registers:

*

*PxIS = 00000023

*PxIE = 7DC0007F

*IS = 00000001

*IE bit1 = 1

By 1 and 2 I think device successfully sends the message to request service because:

*

*IS bit0 = 1(Port 0 has pending interrupt status)

*IE(Interrupt Enable) = 1

*PCI Command register bit10(ID) = 0

*MSICAP.MC.MSIE = 1(to MSI engine)

Also I found the LAPIC receives this interrupt message because:

*

*Local APIC IRR(Interrupt Request Register) bit118(=0x76) = 1

*Local APIC ISR(In-Service register) bit118(=0x76) = 1

Thus it seems that device generates the interrupt and Local APIC receives this; even so, my service routine is NOT called !

A: To implement the MSI feature in DOS mode, you can reference below sequences:
Check if Local APIC is enabled

*

*Read CPU MSR 0x1B and check if Local APIC global enable/disable bit = 1

*Read Local APIC register Spurious Interrupt Vector Register bit8(APIC SW enable/disable)=1

Initialize MSI capability registers

*

*Configure Message Control register(Ex. MME...)

*Configure Message Address register(Ex. Destination ID, DM, and RH)

*Configure Message Data register(Ex. Trigger mode, Assert, Delivery mode, and vector)

Install your own service routine

*

*It depends on what compiler/programming language you use...

*Take (Watcom C+Dos32a) for example you can use below to declare and install service routine

*Use __interrupt __far to declare and create YourISR

*Use DPMI calls 0x204/0x205 to get(old) and set(new) interrupt vector !

Notes:

*

*The interrupt vector in Message Data register can be Ex. 0x70,0x71,..., or 0x76

*At the end of ISR and before return please "write" Local APIC register(EOI)" then LAPIC will clear the bit in In-Service Register and then ready to service another interrupt !

Enable device to request service via MSI by

*

*PCI Command register bit10(ID) = 0

*Device's Interrupt Enable bit = 1(device specific)

*MSICAP.MC.MSIE = 1 (interrupt routed to MSI engine)

You can check if device generates request and LAPIC receives this

*

*Device will issue PCI DWORD write transaction to write 32bit data to 32bit memory address thus you can probe if this occur by LA, or you can check if (ID = 0 && Interrupt status !=0 && MSIE = 1)

*Check LAPIC register IRR and ISR to see if request is received and serviced by LAPIC !

@ References:
Intel 64 and IA-32 Architectures Software Developer Manuals
APIC
PCI Local Bus Specification v2.2
Access CPU MSR
DOS/32 Advanced


text:
Q: insert decimal values of an integer as their ASCII representation into a char vector I have an int and I would like to convert it to a vector<char>.
For example:
std::vector<char> MyVct;
int i = 2046;

So I want a vector of size 4 which will have:
MyVct[0] = '2';
MyVct[1] = '0';
MyVct[2] = '4';
MyVct[3] = '6';

How can I do it in the most efficent way ?

A: One convenient way would be to use std::to_string:
auto s1 = std::to_string(i);
std::vector<char> vec1(s1.begin(), s1.end());

A: Do this:
if (n == 0) { MyVct.push_back('0'); }

else { for ( ; n; n /= 10) { MyVct.push_back('0' + (n % 10)); } }

std::reverse(MyVct.begin(), MyVct.end());


text:
Q: Selenium-Webdriver (Java) failing to execute 'hoverover and click' function consistently I'm trying to access a screen in an application, which appears when I do a mouse-hover over a tab and click on one of the options. I used Actions method to execute this using selenium. Here's my code:
element=driver.findElement(By.id("tab"));
Actions hoverover=new Actions(driver);
hoverover.moveToElement(element).moveToElement(driver.findElement(By.id("menu"))).click().build().perform();

When I login to the application and directly call this tab, I'm able to access this without any issue. But the problem occurs when I access this tab from a different screen in the application.
Whenever I access the hover-over page from a different page in the application, sometimes the page loads correctly but most of the time it fails and I recieve 'no such element' or 'stale element reference' error.
I'm really not sure how it is able to access the tab without any issue sometimes and how sometimes it is throwing errors. Please guide me here and let me know if there is anything else(any additional functions/or an alternative to Actions?) I can do so that the mouse-over click works all the time.
EDIT: I tried using both Explicit and Implicit waits and even thread.sleep as well, but in vain. In Chrome(only in chrome) when i do a manual screen refresh while it tries to access the tab, it works. But when I do the same in my code [driver.navigate().refresh()], it's not working!!

A: The stale element exception is probably occurring between when you set element and when you hoverover. Selenium does something like:
WebElement element = driver.findElement(By.id("tab"));
// "element" has been set
Actions hoverover=new Actions(driver);
// Between here and hoverover, "element" has changed on the DOM
hoverover.moveToElement(element).moveToElement(
    driver.findElement(By.id("menu"))).click().build().perform();
// Uh-oh, what's "element?" Better throw an exception!

Try eliminating the element= line and moving driver.findElement to the inside of moveToElement().
Actions hoverover = new Actions(driver);
hoverover.moveToElement(driver.findElement(By.id("tab")))
    .moveToElement(driver.findElement(By.id("menu"))).click().build().perform();

You could also try throwing in a WebDriverWait between hovering over tab and menu.
hoverover.moveToElement(driver.findElement(By.id("tab"))).build().perform();
new WebDriverWait(driver, 10))
    .until(ExpectedConditions.presenceOfElementLocated(By.id("menu")));
hoverover.moveToElement(driver.findElement(By.id("menu"))).click().build().perform();


text:
Q: How to start server by my source code (app.js) using FTP? I'm new to develop server. I already coded my server app.js with Node js and I tested it locally and successfully.
The way I tested my server is that after executing the terminal, moving to the directory having app.js file, command app.js. So then my server is alive and I could test what I want to.
But it's my first time to use FTP to make my server globally. By FTP, I don't know how to do 'node app.js' command.
And if it's done, I don't know the path to test my GET, POST methods.


text:
Q: How to stop execution at a certain point in visual basic 6? What I want to do is execute my program and pause and go to the line where it paused. For example, for inspecting data before sending a form.
I tried with ctrl + pause button but it only pauses the execution.
How can I acheive this?

A: Ctrl+Break does the thing. There's no Break key on my laptop keyboard so I have to press Ctrl+Fn+B instead.
If you want, you can open the call stack window after that (View->Call Stack...) and see where's your execution at this point.

A: are you talking in debug while writing the code in the Vb6 IDE(before it's compiled?). Just left click the grey frame to the left of the line of code in the editor, where you want to set a break point at (the line will show the default maroon font backcolor and a little round dot will appear to the line of the code in that grey frame). run the source (f5) and your code will 'pause' at that break point you added. Alternatively, right click the line of code, choose toggle, then breakpoint - (under toggle you can also set, Break On All Errors, Break on Class etc). F8 lets you step through your code in the Vb6 IDE

A: Don't forget about the Stop statement.


text:
Q: fnDrawCallback how to loop through each row How do i loop through the enitre datset within the in datatables method?
 "fnFooterCallback": function (nFoot, aData, iStart, iEnd, aiDisplay) {
        $(aData).each(function (index) {
     $(".it").append("
");
        });
    },

The above works if the pagination is removed. But if iDisplayLength is set to 25 for example then it only goes through 25 records, not all 100 etc.

A: "fnFooterCallback": function (nFoot, aData, iStart, iEnd, aiDisplay) {

        $(aData).each(function (index) {
            $(".it").append("

" + aData[index][1] + "

");
        });
    },

The above did it