text:
Q: Mapstruct: HashMap as source to Object How could I use a HashMap<String, Object> as source to an object?
Here is my target object:
public class ComponentStyleDTO{
    private String attribute;
    private Object value;
}

I've tried to use this approach that I found and that is also in the documentation, but it's failing for me.
My Mapper:
@Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE, componentModel = "spring", uses = ComponentStyleMapperUtil.class)
public interface ComponentStyleMapper {

    ComponentStyleMapper MAPPER = Mappers.getMapper(ComponentStyleMapper.class);

    @Mappings({@Mapping(target = "attribute", qualifiedBy = ComponentStyleMapperUtil.Attribute.class),
    @Mapping(target = "value", qualifiedBy = ComponentStyleMapperUtil.Value.class)})
    ComponentStyleDTO hashMapToComponentStyleDTO(HashMap<String, Object> hashMap);
}

My Util:
public class ComponentStyleMapperUtil{
    @Qualifier
    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.SOURCE)
    public @interface Attribute {
    }

    @Qualifier
    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.SOURCE)
    public @interface Value {
    }

    @Attribute
    public String attribute(HashMap<String, Object> in){

        return (String) in.entrySet().stream().findFirst().get().getKey();
    }

    @Value
    public Object value(HashMap<String, Object> in) {
        Object value = in.entrySet().stream().findFirst().get().getValue();

        if(value instanceof String){
            return value;
        }else if(value instanceof LinkedHashMap){
            List<ComponentStyleDTO> childs = new ArrayList<ComponentStyleDTO>();
            HashMap<String, Object> child = (HashMap<String, Object>) value;
            for(String key: child.keySet()){
                ComponentStyleDTO schild = new ComponentStyleDTO();
                schild.setAttribute(key);
                schild.setValue((String) child.get(key));
                childs.add(schild);
            }
            return childs;
        }else{
            return value;
        }

    }

}

And here's how I'm using this:
    HashMap<String, Object> hmap = new HashMap<String, Object>();
    hmap.put(attr.getKey(), attr.getValue());
    ComponentStyleDTO componentDTO = componentStyleMapper.hashMapToComponentStyleDTO(hmap);

But it's returning me empty in attribute and value. Any idea of what I could be doing wrong?

A: IMHO The best way is the simpliest way:
default ComponentStyleDTO hashMapToComponentStyleDTO(HashMap<String, Object> hashMap){
    ComponentStyleDTO result = new ComponentStyleDTO();
    result.setAtribute1(hashMap.get("atribute1"));
    result.setAtribute2(hashMap.get("atribute2"));
    result.setAtribute3(hashMap.get("atribute3"));
    ...
    return result;
}

or
default List<ComponentStyleDTO> hashMapToComponentStyleDTO(HashMap<String, Object> hashMap){
    return hashMap.entrySet()
                  .stream()
                  .map(e -> new ComponentStyleDTO(e.getKey(), e.getValue()))
                  .collect(Collectors.toList());
}

A: Not sure what you are trying to achieve. If your mapping is more complex maybe the best way is indeed to go with the approach in https://stackoverflow.com/a/54601058/1115491.
That a side, the reason why it is not working for you is that you have not defined the source for your mapping. In the example you linked there is a POJO as source parameter and the source is a map in that POJO. In order to make it work your mapper needs to look like:
@Mapper(unmappedTargetPolicy = ReportingPolicy.IGNORE, componentModel = "spring", uses = ComponentStyleMapperUtil.class)
public interface ComponentStyleMapper {

    @Mapping(target = "attribute", source = "hashMap", qualifiedBy = ComponentStyleMapperUtil.Attribute.class)
    @Mapping(target = "value", source = "hashMap", qualifiedBy = ComponentStyleMapperUtil.Value.class)
    ComponentStyleDTO hashMapToComponentStyleDTO(HashMap<String, Object> hashMap);
}

NB: When using the non default componentModel you should not use the Mappers factory for getting an instance of the mapper. If you do that you will get an NPE when working with other mappers.

A: For future reference. As of Mapstruct 1.5 I think this usecase is supported out of the box. See mapstruct release note


text:
Q: Excel formula to list unique value excluding multiple criteria I have the following values in a2:14:
Red
Blue
Red
Red
Yellow
(Blank)
Green
Black
Brown
Brown
Green
55
Silver

I want to generate a list if unique items in column c, so I have this formula in c2
= unique(filter(a2:a14,a2:a14<>""))

This removes the blank row, but now I want to remove the row with 55. Bot sure how to add that criteria.

A: Just need a slight tweak to the formula:
=UNIQUE(FILTER(A2:A14,(A2:A14<>"")*(ISTEXT(A2:A14))))

This will also filter text-only values. As long as you don't care about something like 55-blue-1 and exclude it, then it's fine.

A: Use the following formula:
=UNIQUE(FILTER(A2:A14,(A2:A14<>"")*(A2:A14<>55)))

The '*' acts AND, allowing to have multiple criteria.

redpajama_set_name: RedPajamaStackExchange


text:
Q: tmux + putty: Using mouse off window shows junk characters Setup: tmux 1.8 running on Ubuntu 12.04  connecting from Windows with Putty. tmux has mouse mode on.
Steps to reproduce: Select the putty window as active, but use the mouse off the window (i.e in another window) Typically this happens when I am scrolling in another application on another monitor but forgot to switch the mouse focus.Also, this only happens if the putty window is large or maximized.
Issue: Junk commands get dumped into tmux (e.g 7#, H#, 7a etc.)
If I scroll off window with only PuTTY (no tmux) the screen scrolls as expected.

Update: I have determined that this happens if my putty window is has >= 224 columns

A: This is now resolved by Nicholas Marriott - tmux's author - with the patch at http://sourceforge.net/p/tmux/mailman/tmux-users/thread/20130801222920.GI15241%40yelena.nicm.ath.cx/#msg31242833


text:
Q: List all directories in a folder and pass those each to another script I am working on a deduplication script and decided it would be easier to hand it a parent directory and let it work on each child folder, rather than doing each folder separately.  I was assuming this was going to be simple, but I can't seem to get this to work properly.  This is roughly what I have now:
SET base_folder=%1

for /d %%d in ("%1\*") do (
    set current_dir=%%d
    -- here is where I want to call my script with current_dir as the %1 --
)

A: You're don't appear to be using base_folder, so there's no need to set it.
You don't need to set current_dir; just use %%d directly. If the script you want to use to process each directory is also a batch file, you'll need to CALL it:
for /d %%d in ("%1\*") do (
    CALL myotherscript "%%d"
)

See SS64 on CALL.


text:
Q: Why SMTP service should be started for email receiving? Windows Server 2003, SP2. Configured both mail services POP3 and SMTP. And found, that when SMTP service is stopped, pop3 service doesnt receiving email messages... outlook express is configured to use local pop3 server and remote smtp service - so no need to have smtp localy, but.. when smtp service is stopped, outlook express checks for new mail, login succesfully, found no no messages and logout, BUT i sent some test messages before this! and then i'll start smtp service messages are arriving again.. can't understand why these services are related...

A: The POP3 service does not receive mail, it only serves it to POP3 clients.
The SMTP service receives the email, then writes it to disk in a folder which is later read by the POP3 service when a POP3 client looks for mail.


text:
Q: Fragment in viewpager savedinstancestate is always null I know this question has been asked before but none of the answers given so far is of any help to me.
I have a viewpager which is populated with fragments (android.support.v4.app.Fragment) from a FragmentStatePagerAdapter . Some of these fragments contain logic that needs to be retained when the orientation changes, such as keeping track of which view is currently selected.
However, although I save the data in question in onSaveInstanceState the savedInstanceState is always null. I can solve this by storing the data in a static variable (which since I only have one instance of each fragment would work for me) but i found this to be a quite ugly solution and there has to be a proper way of doing this.
This is one of the fragments that doesn't retain it's state on rotation:
    public class PriceSelectFragment extends Fragment {

    private TableRow mSelected;
    private int mSelectedPos = 0;

    // newInstance constructor for creating fragment with arguments
    public static PriceSelectFragment newInstance() {
        PriceSelectFragment fragmentFirst = new PriceSelectFragment();
        return fragmentFirst;
    }

    public PriceSelectFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_price_select, container, false);
        TableLayout mTable = (TableLayout)view.findViewById(R.id.price_table);

        List<PriceGroup> mPriceGroups = ((MainActivity) getActivity()).getPriceGroups();

        int i = 0;
        for (final PriceGroup group : mPriceGroups) {
            //Create row from layout and access child TextViews
            TableRow r = (TableRow)inflater.inflate( R.layout.price_group, mTable, false);
            TextView size = (TextView)r.getChildAt(0);
            TextView dimension = (TextView)r.getChildAt(1);
            TextView weight = (TextView)r.getChildAt(2);
            TextView price = (TextView)r.getChildAt(3);

            //Populate row with PriceGroup Data
            size.setText(group.sizeIndicator);
            dimension.setText(String.format("%2.0fx%2.0fx%2.0f", group.length, group.width, group.height));
            weight.setText(Float.toString(group.weight));
            price.setText(Integer.toString(group.price));

            //Alternate background color every other row
            if (i % 2 == 0) {
                r.setBackgroundDrawable(getResources().getDrawable(R.drawable.price_selector_1));
            }
            else {
                r.setBackgroundDrawable(getResources().getDrawable(R.drawable.price_selector_2));
            }
            mTable.addView(r); // Add to table

            r.setTag(i);
            r.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    selectRow((TableRow) v);
                }
            });
            i++;
        }

        mSelected = (TableRow)view.findViewWithTag(mSelectedPos);
        selectRow(mSelected);

        return view;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("selected", mSelectedPos);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (savedInstanceState != null) {
            mSelectedPos = savedInstanceState.getInt("selected");
        }
    }

    private void selectRow(TableRow row) {
        if ((int) mSelected.getTag() % 2 == 0) {
            mSelected.setBackgroundDrawable(getResources().getDrawable(R.drawable.price_selector_1));
        }
        else {
            mSelected.setBackgroundDrawable(getResources().getDrawable(R.drawable.price_selector_2));
        }
        mSelected = row;
        mSelectedPos = (int) mSelected.getTag();
        mSelected.setBackgroundColor(getResources().getColor(R.color.light_blue));
    }

}

How do I solve this without having to save my states in static variables?
Edit
I should point out that all of the fragments are programatically created and as such they do not have an id and I read that that might be the problem but I don't know how to solve that either.
Also my application is structured like this:

*

*MainActivity with NavigationDrawer

*

*Fragment1

*

*ViewPager

*

*subfragment1 - subfragment5

*Fragment2

*Fragment3

The fragments whose states I'm having trouble with are the subfragments.

A: In your Activity which is hosting your Fragment you need to store a refernce to the fragment in the Bundle.
Something like this should work for you
public void onCreate(Bundle savedInstanceState) {

    if (savedInstanceState != null) {
        //Restore your fragment instance
        fragment1 = getSupportFragmentManager().getFragment(
                    savedInstanceState, "fragment");
    }
}

protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    getSupportFragmentManager().putFragment(outState, "fragment", fragment1);
}

fragment1 is the instance of the Fragment1 that you mentioned in your question that needs to get recreated.
I haven't done this with a structure like yours before but this is how I would start:
In the onSaveInstanceState in your Fragment1 I believe you would need to do the same with each of the fragments in your ViewPager. Then in the onCreateView on your Fragment1 get the fragments from the fragment manager and recreate your ViewPager.
I have found this answer here which is pretty much the same but has a little more detail: https://stackoverflow.com/a/17135346/1417483

A: FragmentPagerAdapter is not calling onSaveInstanceState in frgments that are not visible anymore. Maybe this is what causing your issues.
Try to use FragmentStatePagerAdapter instead.

A: I finally got a solution and explanation why this is happening. I had a very similar problem. I recognized that when I was scrolling right to my 3rd subfragment and then back to the 1st then the state of the 1st got saved. But not on Orientation Change.
I figured that the state is only saved if the adapter's destroyItem(..) is called. That is not called automatically if orientation changes.
So now onSaveInstanceState of the MainFragment (which holds the ViewPager) I call destroyItem for each active fragment. I check for activity.isChangingConfigurations() because onSaveInstanceState is called too if I turn off the screen, but in that case all the fragments just stay active and nothing has to be changed.
I extended the adapter with an onDestroy(boolean retain) which is called then:
//in the main-fragment which holds the ViewPager:
@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    if(getActivity()!=null && getActivity().isChangingConfigurations())
    {
        if (pager != null) {
        try {
            Log.w(TAG, TAG + " pager.onDestroy(true)");
            pager.onDestroy(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

And the implementation in MyFragmentStatePagerAdapter:
public void onDestroy(boolean retain)
{
    this.m_allowDynamicLoading = false;
    if(retain)
    {
        try{
            if(getAdapter()!=null)
            {
                int limit = this.getOffscreenPageLimit();
                int currentIndex = this.getCurrentItem();
                if(currentIndex <0 || getAdapter().getCount() <= 0)
                    return;
                //active fragments = fragments that are (less or equal) then
                //offscreenPageLimit awaw from the currently displayed one.
                for(int i = Math.min(currentIndex+limit, getAdapter().getCount()-1);
                        i>= Math.max(0, currentIndex-limit);//erstes aktives fragment ist current - offscreen limit, aber nicht unter 0..
                        i--)
                {
                    getAdapter().destroyItem(MessagingViewPager.this, i, getAdapter().instantiateItem(MessagingViewPager.this, i)); //this saved the state of that fragment, that will be restored after orientation change
                    Log.e(TAG,TAG + " orientation-change: destroying item " + i);
                }
            }
        }catch(Exception e){}
    }
    else{ //retain = false is called onDestroy of the Fragment holding this Pager.
        try{
            this.setAdapter(null);
            //this will destroy all fragments and forget the position
        }catch(Exception e){}
    }
}

Some other things are to be said:

*

*Adapter takes the ChildFragmentManager not the normal one

*The SubFragments must NOT use setRetainInstance(true) (Exception otherwise)
The MainFragment can (and in my case does) use setRetainInstance(true)

*Create the adapter in onCreate of the MainFragment, so it will NOT be   recreated on Orientation change. Setting adapter to pager should be done in onCreateView.

*OnDestroy (or onDestroyView) of the MainFragment use setAdapter(null) to terminate all fragments and release resources. (This is done by MyViewPager.onDestroy(false)  in my case)

et voiá: now you get your savedInstanceState bundle in the SubFragments after the orientation change. And it will not destroy the items if you only switch the screen off.


text:
Q: How to extract a database from a text file (word or libreoffice) with styles and content I ask my question after searching an answer on stackoverflow and on the web, without success.
I'm sorry if there is already an answer somewhere.
Global objective
I aim to create my questionnaires in libreoffice ( I need to print it, it's not for an online survey), and secondly to use it in a R shiny app I've created for register the collected answers and to export the data.
I want to create the fields in R (questions, answers...) automatically from the styles of my questionnaires in .odt, .docx or others formats.
I need to have well formatted questionnaires, nice-looking.
There is the problem:
I have written a questionnaire on a libreoffice .odt file (or if necessary in microsoft word).
I uses styles for different text blocks: one style for the "questions", one for the "answer", one for the parts of the questionnaire, one for the "instructions"...
I want to get a database ( in .csv format) with one column with the styles, and one column with the text content.
Solutions?

*

*I try to open the xml files in the .odt or .docx archives, but the conversion to a simpler and readable format seems quite difficult.

*Is it possible to export a toc from libreoffice or word to a spreadsheet format?

*R can read in such files (.odt or .dox, or.xml) ?
Thank you very much for your ideas, and more generaly for your feedbacks on my project.
I'm sorry for my english

A: I would recommend using .Rmd (for rmarkdown) or .Rnw (for knitr) files as the source for your questionaires, rather than starting with .odt or .docx.  You can produce output in various formats, including .docx, .pdf, .html (only .pdf for .Rnw) to display the questionaire to the subjects, but you can also develop functions to manage the data, or even interactive displays to collect and record the data.
I'm not familiar with R packages that do all of this for you, but I expect they already exist.  Maybe someone else will give an answer with more details.

A: You might explore using the .fodt format in libreOffice Writer. That format is an "unzipped" version of the Writer xml format, so could be directly readable by xml utilities (and probably R, with appropriate libraries). I note that for another answer you seemed to want to avoid markdown or knitr composition, and .fodt would provide a "text" format completely compatible with LibreOffice as a front end.
(Note the other parts of LibreOffice have "flat" versions, so you could, in theory, process text versions of spreadsheets, graphics, and presentation files in your R utility.)
A few web searches indicates some relevant libraries and utilities for R exist, which may get you closer to what you need for your project.


text:
Q: Extjs: Drag panels inside responsiveLayout config I have a panel like admin-dashboard example dashboard in extjs 6 examples with responsiveColumn Layout.
Can I make the child panels draggable from one position to other?

A: If i understand correctly you are trying to achieve something like in this example: Ext JS Portal.
I haven't had a chance to try it out myself, but this documentation leads me to believe it already supports drag & drop: Ext.dashboard.Dashboard.
Check those out. They should help you along. Good luck!


text:
Q: Swift Framework "Module 'RealityKit' not found" I want to create my own Framework that will use RealityKit functionalities. Framework project compiles properly without errors, but when I import it to my new project and try to compile I get an error

"Module 'RealityKit' not found"

Can I add RealityKit somehow to my Framework so it will be included or should I change path somewhere ?
When I import RealityKit directly to new project it works, but when I try importing my Framework I get this error.
I get the error at this point in MyFramework-Swift.h
#if __has_feature(modules)
#if __has_warning("-Watimport-in-framework-header")
#pragma clang diagnostic ignored "-Watimport-in-framework-header"
#endif
@import ARKit;
@import CoreGraphics;
@import Foundation;
@import QuartzCore;
@import RealityKit; // Module 'RealityKit' not found
@import UIKit;
#endif

A: After going through all the files that use RealityKit I found what was causing the error. In one of the files I was making extension to ARView to add some custom functionalities and even if I leave it blank like that:
import RealityKit
extension ARView {}

It still gives me "module RealityKit not found" so to walk this around I just created class that makes the same operations as my previous extension and it worked. When I import framework to the project now, it builds without errors.

A: RealityKit is not supported in objective-c


text:
Q: ZF2 Doctrine2 DQL... how can I find out what's wrong? I created simple Action based on this tutorial (the same entities and stuff).
$em = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
$dql = "SELECT b, e, r FROM Bug b JOIN b.engineer e JOIN b.reporter r ORDER BY b.created DESC";

$query = $em->createQuery($dql);
$query->setMaxResults(30);
$bugs = $query->getResult();

And now Zend just throws 500 without any information. By commenting the lines I found out that tha problem occures on $bugs = $query->getResult(); line but I have no information - just 500 (even apache error log is empty). Are there any tools for debug?

A: Check if error reporting/show exceptions is properly configured to render errors/exceptions just like @Moby04 suggested.
You should check for example if you have these lines in your application config array:
'view_manager' => array(
    'display_not_found_reason' => true,
    'display_exceptions'       => true,
    'not_found_template'       => 'error/404',
    'exception_template'       => 'error/index',
)

And make sure that the template values actually map to 'proper' view templates.


text:
Q: Spark to parse backslash escaped comma in CSV files that are not enclosed by quotes Seems spark is not able to escape characters in CSV files that are not enclosed by quotes, for example,
Name,Age,Address,Salary
Luke,24,Mountain View\,CA,100

I am using pyspark, the following code apparently won't work with the comma inside Address field.
df = spark.read.csv(fname, schema=given_schema,
                sep=',', quote='',mode="FAILFAST")

Any suggestions?

A: Could you please give a try using rdd first, reformat it and then create a dataframe over it.
df  = sc.textFile(PATH_TO_FILE) \
    .map(lambda x: x.replace("\\," ,"|")) \
    .mapPartitions(lambda line: csv.reader(line,delimiter=','))\
    .filter(lambda line: line[0] != 'Name') \
    .toDF(['Name','Age','Address','Salary'])

this is how your dataframe looks like now:
>>> df.show();
+----+---+----------------+------+
|Name|Age|         Address|Salary|
+----+---+----------------+------+
|Luke| 24|Mountain View|CA|   100|
+----+---+----------------+------+

I have to replace address column "\," with "|" and then I splitted the data using delimiter ','. Not sure how it matches your requirement but it's working.


text:
Q: Debugging compiler error in ngfactory file I'm trying to build my Angular 2 app, using ng build --prod. The error started after upgrading to angular-cli 1.0.0. I'm using angular 2.3.1.
The build is failing with an error:

....filters.component.ngfactory.ts (975,35): Supplied parameters do not match any signature of call target.

My question is: given that all the interim files get deleted when the compilation fails, how can I use the compiler error (ngfactory line 975) to identify the problem in my source code?
Update: JB Nizet found the bug in the code below (now edited to make it easier for later readers to see the error), but my question still stands regarding how to make use of the debugging info from the compiler.
Here is my component
     getFavourites() {
        this.overlay = false;
        // this.router.navigate(['/recommendations', 'close']);
        this.action.emit({
            type: GET_FAVOURITES
        });
    }

}

and the template
            <button class='afbutton hidden-xs' (click)='getFavourites($event)'>
                <span class="icon">
                    <svg class="favourite heart" viewBox="0 0 32 29.6">
                    <path d="M23.6,0c-3.4,0-6.3,2.7-7.6,5.6C14.7,2.7,11.8,0,8.4,0C3.8,0,0,3.8,0,8.4c0,9.4,9.5,11.9,16,21.2
                c6.1-9.3,16-12.1,16-21.2C32,3.8,28.2,0,23.6,0z" /></svg>
                </span>
                favourites
            </button>

A: Optionally add a genDir to your src/tsconfig.app.json so that the files are generated out-of-source.
"angularCompilerOptions": {
  "genDir": "aot"
}

Then just run ngc ./node_modules/.bin/ngc --project src/tsconfig.app.json to produce the intermediate ngfactory.ts files, e.g. my error was in src/aot/app/app.component.ngfactory.ts.
Found under Compiling the application.
I did not found any options to preserve the intermediate files with angular-cli (ng build).


text:
Q: Teaching examples for internal validity: published experiments later shown to be confounded in an interesting way There are some good examples of interesting/fun spurious correlations here (Examples for teaching: Correlation does not mean causation). Many/most of these are "funny" examples that aren't likely to affect real life decision making. In contrast, this thread (Real examples of Correlation confused with Causation) has some interesting examples of real-life misinterpretation of spurious correlations.
I'm wondering if anyone has cool/interesting favorites along the lines of the second thread, for a related-but-different phenomenon: published experiments (i.e., not correlational data) whose results were later discovered to be confounded in an interesting/unexpected/memorable way.

A: There is one example explained in Causality (2009) p. 358:

... a study involving injected vitamin E as a treatment
  for incubated children at risk for retrolental fibroplasia. The
  randomized experiment indicated efficacy for the injections, but it
  was soon discovered that the actual effective treatment was opening
  the pressurized, oxygen-saturated incubators several times per day to
  give the injections, thus lowering the barometric pressure and oxygen
  levels in the blood of the infants.

The problem here was that experimenters were not only doing $X$ (vitamin E injection), but doing $X$ and $Z$ (vitamin injection and opening the incubator), thus what they thought was the effect of one intervention ($X$) was in fact the effect of another ($Z$).  This could have been detected with a placebo group in the study.


text:
Q: Gapps ContactsApp timeout for second request I wrote little Google Apps Script that should get my contacts it looks
function myFunction() {
  var contacts = ContactsApp.getContacts()
  var contact = contacts[0];
  Logger.log(contact.getFullName());
}

When I run it for the first time it works ok (At least it shows me no errors). But next time it gives me an error.
[18-02-05 06:55:14:122 PST] Starting execution
[18-02-05 06:55:28:911 PST] ContactsApp.getContacts() [14.782 seconds]
[18-02-05 06:55:28:923 PST] Execution failed: Server error.
Wait a bit and try again later. (line 2, file "Код") [14.785 seconds total runtime]

And I will get this error all the time from now. If I wait for an hour I'll be able to make one more 'good' request and then again an error.
UPD: If I will copy this code to a new google account that has only 5 contacts stored - it will work.

A: From https://developers.google.com/apps-script/guides/support/troubleshooting#common_errors
There is a bug in Google Apps Script that is causing this error. Report the error on the issue tracker.


text:
Q: Why can't I toggle  visibility with jQuery 1.7.2 in Google Chrome? See this fiddle: http://jsfiddle.net/Walkman/ZpF8F/
If I try to .toggle() <br> elements, they wont disappear, but with .hide() it works. Why ?
What is the difference between the two methods ?
Also If you hide them first, then .toggle() unhide them.

A: here is a bug ticket on jquery site for that may be this will clear your doubt
http://bugs.jquery.com/ticket/11289

A: Toggle will hide a tag with a content inside, here's an exemple while hide just hide the tag even without content inside.
For more details about the difference you can still check the source code of jquery 1.8


text:
Q: Why doesn't using nonlocal scope variable as default value for parameter work? Code would explain this much better :)
def a():
    x=0
    def b(z=x):
        print("X: %d, Z: %d" % (x,z,))
    x=5
    b()

Result:
X: 5, Z: 0

What's going on here?
(Ok, now I've figured it out)

A: Ok, the answer from the Python docs is:

Default parameter values are evaluated when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that the same "pre-computed" value is used for each call.

Fair enough.


text:
Q: Why can't EWL Development Utility find Microsoft.Web.Administration assembly? Here is the error:

System.IO.FileNotFoundException: Could not load file or assembly 'Microsoft.Web.Administration, Version=7.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.

The machine that gets this error has Microsoft.Web.Administration version 7.9.0.0 installed, but not version 7.0.0.0. The reference to this assembly from EWL is to version 7.0.0.0 but has Specific Version = False.
Could this be an IIS Express issue? I know that EWL has never been tested with IIS Express.
The machine is running Windows XP.

A: "Specific Version" in Visual Studio is only used at build-time, not run-time, which explains why version 7.9.0.0 of the assembly was not automatically loaded. See https://stackoverflow.com/a/1232955/35349.
Version 7.0.0.0 of Microsoft.Web.Administration was not present on the machine because it's running Windows XP, which doesn't include, or even support, IIS 7.

A: In my case I was not able to find the Microsoft.Web.Administration in the GAC while I was writing a console app.
Environment: Windows 8, IIS 8, x64.
I browsed to iis folder i.e. "C:\Windows\System32\inetsrv" and found it.


text:
Q: Java Oracle Example on Guarded Blocks EDIT: Ok, this is really stupid but I don't know why I didn't see it was a normal loop without the usual increments. I hope I was drunk when I posted this question because now I feel super idiot. Thanks anyway guys!
I'm following some tutorials on Java multi-threading in order to gather as much information and examples as possible.
On the Oracle website there is an official tutorial on Java Concurrency and I am looking at the Guarded Blocks section (here).
Whereas all the concepts are clear, I am reading the Producer/Consumer example at the bottom of the page and I do not understand some parts of the code.
Specifically, in the following is the code for the run() method of the Consumer class, where I do not understand how that for loop is supposed to work. It doesn't even look as it can work to me.
Can anyone explain me?
public void run() {
        Random random = new Random();
        for (String message = drop.take();
             ! message.equals("DONE");
             message = drop.take()) {
            System.out.format("MESSAGE RECEIVED: %s%n", message);
            try {
                Thread.sleep(random.nextInt(5000));
            } catch (InterruptedException e) {}
        }
    }

A: It's just for loop being used in a non-idiomatic way.
You have the initialization String message = drop.take(); (instead of int i = 0;).
Then you have the test !message.equals("DONE"); (instead of i < 10).
Finally you have the "increment" or loop-advance or whatever the actual term is. Get the next value with message = drop.take(); (instead of i++).

A: Maybe it would be easier to understand when converted to a while-loop:
public void run() {
    Random random = new Random();

    String message = drop.take()
    while (!message.equals("DONE")) {
        System.out.format("MESSAGE RECEIVED: %s%n", message);
        try {
            Thread.sleep(random.nextInt(5000));
        } catch (InterruptedException e) {}
        message = drop.take()
    }
}

Keep in mind that the for-loop generally consists of three parts:
for (INITIALIZATION; CONDITION; AFTERTHOUGHT)
{
// Code for the for-loop's body goes here.
}

INITIALIZATION is run once before the first iteration, CONDITION is checked prior to every iteration and AFTERTHOUGHT is executed after every iteration.
(Taken from https://en.wikipedia.org/wiki/For_loop#Traditional_for-loops)
So in this example, the INITIALIZATION of the for-loop creates the message variable and takes the first message from drop. It then checks it in the CONDITION block to see if its is anything but DONE. If it is, the loop body is executed once, printing the message and sleeping for up to 5000 milliseconds. Then the next message is taken in the AFTERTHOUGHT clause and the loops checks the CONDITION block again to either print the next message or leave the loop once it receives DONE.


text:
Q: Remove words except last one in String I have a String with different value every time:
String words = "My name is Rob Joe";

I want to get only last word
Joe
but every time I don't know how many words the string consists of

A: In Flutter(Dart), you can get the last word of a string by splitting the string into an array of substrings using the split method and then accessing the last element of the resulting array. Here's an example:
   String words = "My name is Rob Joe";
   List<String> wordsArray = myString.split(" ");
   String lastWord = wordsArray[wordsArray.length - 1];
   print(lastWord); // "Joe"

A: String words = "My name is Rob Joe";
var array = words.split(" "); // <-- [My, name, is, Rob, Joe]
print(array.last); // output 'Joe'

A: Instead of splitting, you can also use substring and lastIndexOf:
final words = "My name is Rob Joe";
final lastWord = words.substring(words.lastIndexOf(" ") + 1);
print(lastWord);

A: If you want to find the last word, you should first properly define what a "word" is.
It's clearly obvious here, which is why it's doubly important to write it down, because something else may be just as obvious to someone else.
(Read: Nothing is obvious. Document it all!)
But let's say that a word is a maximal contiguous sequence of ASCII letters.
Then that's what you should look for.
Splitting on space characters works for this string, but won't if you have punctuation, or trailing whitespace, or any number of other complications.
I'd probably use a RegExp:
  // Matches a word. If used properly, only matches entire words.
  var wordRE = RegExp(r"[a-zA-Z]+");

  // Assume at least one word in `words`. Otherwise need more error handling.
  var lastWord = wordRe.allMatches(words).last[0]!;

This can be a little inefficient, if the string is long.
Another approach that might be more efficient, depending on the RegExp implementation, is to search backwards:
  /// Captures first sequence of [a-zA-Z]+ looking backwards from end.
  var lastWordRE = RegExp(r"$(?<=([a-zA-Z]+)[^a-zA-Z]*)");

  var lastWord = lastWordRE.firstMatch(words)?[1]!;

If you don't want to rely on RegExps (which are admittedly not that readable, and their performance is not always predictable), you can search for letters manually:
  String? lastWord(String words) {
    var cursor = words.length;
    while (--cursor >= 0) {
      if (_isLetter(words, cursor)) {
        var start = 0;
        var end = cursor + 1;
        while (--cursor >= 0) {
          if (!_isLetter(words, prev)) {
            start = cursor + 1;
            break;
          }
        }
        return words.substring(start, end);
      }
    }
    return null;
  }

  bool _isLetter(String string, int index) {
    var char = string.codeUnitAt(index) | 0x20; // lower-case if letter.
    return char >= 0x61 /*a*/ && char <= 0x7a /*z*/;
  }

But first of all, decide what a word is.
Some very real words in common sentences might contain, e.g., ' or -, but whether they matter to you or not depends on your use-case.
More exotic cases may need you to decide whether"e.g." is one word or two? Is and/or? Is i18n?
Depends on what it'll be used for.


text:
Q: Stepping up voltage from solar for a power brick (5V to 15V) possible? i have a 28mAh power brick capable of charging my laptop when charged.
I bought a 28W solar panel which outputs 5V over usb capable of charging ipads etc, however when i connected it to power brick's input it couldnt charge it (or at least charging light didnt come on)
Its only then i realised power brick is running off 15-19V 2A mains charger.
Is it possible to step up my solar panel to this voltage and trickle charge the power brick at all?

A: You didn't provide enough details so I can't say for sure but it's possible to step up the voltage but it will not help you that you for a simple reason:
your device runs on 15-19 volts 2 amps which means it runs on 30-38 watts but the solar panels output is 28 watts , so if your power brick doesn't work on less than 2 amps or a voltage below 15 volts then it won't work again.

A: Yes, it is possible. You need a boost or step-up converter. A step-up converter can increase the voltage (but the power VI is constant.)


text:
Q: What is n value in a confidence interval how large must n be if the length of the 99% CI is to be 40? the distribution is normal, sigma= 20.
The book says that the answer is 7, but I keep getting 5.4
This is how I solved it:
(X+Z(sigma/ (root n))- (X-Z(sigma/ (root n))=40
basically, it is Upper Bound-Lower Bound=40.
X then cancels out, and it reduces to 2Z(sigma/(root n))=40. When I do invnorm(0.99)=2.326 and plug it in for z, and plug in 20 for sigma and solve the equation, I get 5.4. What am I doing wrong?

A: First, find $z$ such that $P(Z \geq z)=0.005$. Note the division by $2$ because your original problem is two-tailed. I get about 2.576 when I do this. So your confidence interval is going to be $2z=5.148$ standard deviations wide. So you need $5.148\sigma/\sqrt{n} \leq 40$, hence $5.148/\sqrt{n} \leq 2$. From this I get $n \geq 7$ as in your book.
So it looks like your only mistake is taking invnorm(0.99) instead of invnorm(0.995).

A: The formula for a 2-sided $100(1-\alpha)\%$ confidence interval for the mean of normally distributed data with known variance $\sigma^2$ is $$[L,U] = \left[\bar x - z_{\alpha/2} \frac{\sigma}{\sqrt{n}}, \; \bar x + z_{\alpha/2} \frac{\sigma}{\sqrt{n}}\right],$$ where $\bar x$ is the sample mean, $n$ is the sample size, and $z_{\alpha/2}$ is the upper $\alpha/2$ quantile of the standard normal distribution; i.e., $$\Pr[Z > z_{\alpha/2}] = \alpha/2.$$  So for a 2-sided $99\%$ confidence interval, we require that $$\Pr[-z_{\alpha/2} < Z < z_{\alpha/2}] = 1 - \alpha = 0.99,$$ which is why we wrote $\alpha/2$.  The upper $0.5$ percentile of the standard normal distribution is $$z_{0.005} \approx 2.5758293.$$  Therefore, if $U - L = 40$, this is equivalent to $$2z_{0.005} \frac{\sigma}{\sqrt{n}} = 40,$$ or $$n = \left(\frac{2z_{0.005} \sigma}{40}\right)^2 = z_{0.005}^2 \approx 6.63489.$$  But since $n$ is a positive integer, the minimum such $n$ that guarantees the width of the confidence interval is at most $40$ is $n = 7$:  the width of the interval decreases with increasing $n$.
What is the actual width of the CI if $n = 7$?  It is easily calculated to be approximately $38.94$.  If $n = 6$, it is too large, about $42.06$.


text:
Q: How to create webservice with digital certificate I Have to build a webservice with digital certificate but i don't have experiencie in this area, i got some examples but it was not sufficent for me yet. In the code below i can get a public and private keys from a JKS file, encrypt a string and verify if that string is assigned. But i have some doubts about who i should use that:

*

*I have 1 private and 1 public key. If i have more than one cliente calling my webservice, both of them need to have the public key? and the private key?

*how i should send the public key to the client? is a file or string ? the return of my public test key is:
PUBLIC KEY: Sun RSA public key, 2048 bits
  modulus: 17250324892612486858507429685448839704055777462217619737452934774822672851497966978790916432466790842915878683120882004958695145419939098968836614824888409393052061936762455389263916348884908835001481590512979961376093665985176086582620326688971144157926968064917610077028818131909416605240046026228844714588221891425654992455455846135152245033503553286312978619541722235228388013887009488301495951905133704760137236960349458111717499961995019021977295294912070129505927611114331851407796798585518424426757876237265884912360355209124912153937505471115177310252984915833469781596755813935167181407292034238159965045653
  public exponent: 65537

*

*In the code, i can only verify if tha signature is correct, i can't decrypt that to get the real value.
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.Key;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.cert.Certificate;
public class Certificado {
/**
 * @param args
 * @throws Exception
 */
public static void main(String[] args) throws Exception {

    String txt = "TEST_STRING";

    File certificado = new File("C:\\temp\\teste.jks");
    PrivateKey privateKey = getPrivateKeyFromFile(certificado, "TESTE", "123");

    System.out.println("PRIVATE KEY: " + privateKey.toString());

    PublicKey publicKey = getPublicKeyFromFile(certificado, "TESTE", "123");

    System.out.println("PUBLIC KEY: " + publicKey.toString());

    //a chave privada serve pra encriptar os dados.
    byte[] txtAssinado = createSignature( privateKey, txt.getBytes() );

    System.out.println("txtAssinado: " + txt2Hexa( txtAssinado ) );

    if( verifySignature( publicKey, txt.getBytes(), txtAssinado ) ) {
        System.out.println("Assinatura OK!");
    } else {
        System.out.println("Assinatura NOT OK!");
    }

}

public static PrivateKey getPrivateKeyFromFile( File cert, String alias, String password ) throws Exception {
    KeyStore ks = KeyStore.getInstance ( "JKS" );
    char[] pwd = password.toCharArray();
    InputStream is = new FileInputStream( cert );
    ks.load( is, pwd );
    is.close();
    Key key = ks.getKey( alias, pwd );
    if( key instanceof PrivateKey ) {
        return (PrivateKey) key;
    }
    return null;
}

/**
 * Retorna a assinatura para o buffer de bytes, usando a chave privada.
 * @param key PrivateKey
 * @param buffer Array de bytes a ser assinado.
 */
public static byte[] createSignature( PrivateKey key, byte[] buffer ) throws Exception {
    Signature sig = Signature.getInstance("MD2withRSA");
    sig.initSign(key);
    sig.update(buffer, 0, buffer.length);
    return sig.sign();
}

/**
 * Verifica a assinatura para o buffer de bytes, usando a chave pública.
 * @param key PublicKey
 * @param buffer Array de bytes a ser verficado.
 * @param sgined Array de bytes assinado (encriptado) a ser verficado.
 */
public static boolean verifySignature( PublicKey key, byte[] buffer, byte[] signed ) throws Exception {
    Signature sig = Signature.getInstance("MD2withRSA");
    sig.initVerify(key);
    sig.update(buffer, 0, buffer.length);
    return sig.verify( signed );
}

/**
 * Extrai a chave pública do arquivo.
 */
public static PublicKey getPublicKeyFromFile( File cert, String alias, String password ) throws Exception {
    KeyStore ks = KeyStore.getInstance ( "JKS" );
    char[] pwd = password.toCharArray();
    InputStream is = new FileInputStream( cert );
    ks.load( is, pwd );
    Key key = ks.getKey( alias, pwd );
    Certificate c = ks.getCertificate( alias );
    PublicKey p = c.getPublicKey();
    return p;
}

public static String txt2Hexa(byte[] bytes) {
    if( bytes == null ) return null;
    String hexDigits = "0123456789abcdef";
    StringBuffer sbuffer = new StringBuffer();
    for (int i = 0; i < bytes.length; i++) {
        int j = ((int) bytes[i]) & 0xFF;
        sbuffer.append(hexDigits.charAt(j / 16));
        sbuffer.append(hexDigits.charAt(j % 16));
    }
    return sbuffer.toString();
}

}

A: Why do you need it? If it's just for encrypted communication you can do that on the transport level with SSL/TLS. If it's for authentication, I would suggest the a robust webservice stack (Apache CXF and Metro for example) with WS-Policy framework. It'll take care of the lowlevel crypto stuff for you.
(You can use authentication on transport level of course and encryption on message level, but the first couples your code with the application server and the latter is just painfully slow.)

A: I resolved to use ws-security following this tutorial:
http://www.developer.com/java/other/article.php/3802631/Securing-Web-Services-in-JBoss-Application-Server-with-WS-Security.htm
thanks!


text:
Q: Multiple submit on form php On my form I have 3 submit,I want to know the best way to handle these buttons because the default action is the same form:
<form method="POST" action="file_where_form_is.php">
      Name:<input type='text' name='name'>
      <input type='submit' name='add' value='Add Names' ONCLICK='window.location.href="file_where_form_is.php">
      <input type='submit'name='Preview'value='Preview'ONCLICK='window.location.href="file_where_form_is.php">
      <input type='submit' name='submit'value='Submit' ONCLICK='window.location.href="send.php">

</form>

This not seems to work completely,just the 2 first work and for the last submit does nothing(with name='submit')
Any suggestions?

A: I finally found in header part add something like this:
 if(isset($_POST['submit'])){
      header("location: somefile.php");
 }
 elseif(isset($_POST['Preview'])){
       header("location: anotherfile.php");
 }
 elseif(isset($_POST['add'])){
       header("location: anotheronefile.php");
 }


text:
Q: GraphQL AppSync DynamoDB only update one field in mutation So I am working on an app with AWS amplify. I am using a single table design and I am trying to run a mutation where I only update the profile field of the UserV0 in the single table design. I am trying to only update the profile(s3key) but when I run my mutations it deletes the rest of the contents of UserV0.
Graph QL Schema
type SingleTable @model {
  pk: String! @primaryKey(sortKeyFields: ["sk"])
  sk: String!
  user: UserV0
  post: PostV0
}

type UserV0 {
  name: String
  username: String
  email: String
  profile: String

}

type PostV0 {
  ...
}

query getUserInfo {
  getSingleTable(pk: "TEST", sk: "TEST") {
    user {
      username
      name
      profile
      email
    }
  }
}

mutation createTable {
  createSingleTable(input: {pk: "TEST", sk: "TEST", user: {email: "email@email.com", name: "testname", profile: "testPath", username: "testusername"}}) {
    updatedAt
  }
}

mutation updateTable {
  updateSingleTable(input: {pk: "TEST", sk: "TEST", user: {profile: "TESTING", username: "TESTING123"}}) {
    createdAt
  }
}

If I run the update mutation above, then the entire user is reset and when I check it in my DynamoDB field the name and email fields are all lost. How can I make it so that when I run the mutation, I only update the profile field and leave the other fields without deleting them. Thanks in advance.
Edit: I put in all of the queries and mutations that I am running in AppSync. I run createTable and then getUserInfo and it returns this as it should.
{
  "data": {
    "getSingleTable": {
      "user": {
        "username": "testusername",
        "name": "testname",
        "profile": "testPath",
        "email": "email@email.com"
      }
    }
  }
}

But after I run the updateTable and then getUserInfo it returns this.
{
  "data": {
    "getSingleTable": {
      "user": {
        "username": "TESTING123",
        "name": null,
        "profile": "TESTING",
        "email": null
      }
    }
  }
}

As you can see the name and email fields are reset, set to null and removed from the DynamoDB database. I am pretty sure it is because it sees the user object as a new input. But how do I get it just recognize that I only want to update certain fields in userV0 and not the entire thing.

A: Make sure your function updateSingleTable uses the UpdateItem operation:
"operation" : "UpdateItem"
If you're using PutItem which I assume you are, it performs and overwrite and thus removing existing data.
https://docs.aws.amazon.com/appsync/latest/devguide/resolver-mapping-template-reference-dynamodb.html
Under the hood I believe the DynamoDB client is DynamoDB Mapper. As a result, it will delete values if set to null. To avoid this, you must ensure you do not set values to null, instead omit any values not being used in the request.


text:
Q: Excel scatter plot with multiple series from 1 table Say I have a table as follows:

Label |  X  |  Y  |
  A   |  1  |  1  |
  B   |  2  |  2  |
  B   |  3  |  2  |
  A   |  4  |  3  |
  C   |  5  |  4  |
  A   |  4  |  3  |
  C   |  2  |  1  |

How can I make this into an Excel scatter plot with 3 series (A,B,C) without manually selecting the correct rows manually for each series (like this answer). This table would be this chart:

Sorting won't help, as I want to do this relatively dynamically with new data.

A: Easier way, just add column headers A, B, C in D1:F1. In D2 enter this formula:
=IF($A2=D$1,$C2,NA())
and fill it down and right as needed.

Select B1:B8, hold Ctrl while selecting D1:F8 so both areas are selected, and insert a scatter plot.

A: Excel won't dynamically add new series, so I'm going to assume while the data can change, the names and number of series won't.
What I would recommend is transforming the data in a dynamic way that is easier to place a spot for each series by itself.
In Column D put:
=A2&COUNTIF(A2:A$2)

This will give values such as B3 for the 3rd element of the B series.  Now that you have sequential labels for all elements of all series you can do lookups.
In a new sheet put
A1="Number"
A2=1
A3=A2+1

B1="A"
B2=Match(B$1&$A2,Sheet1!$D$1:$D$100,FALSE)

C1="A - X"
C2=IF(ISERROR(B2),"",INDEX(Sheet1!$B$1:$B$100,B2))

D1="A - Y"
D2=IF(ISERROR(B2),"",INDEX(Sheet1!$C$1:$C$100,B2))

And just add 3 columns just like that for each of your series.  So it'll find which row the series named "A" has its first entry, the one you labeled A1, and then in column C it'll look up the X value, and in column D it'll look up the Y value. Then create a series A on your graph with X coordinates from column C and Y coordinates from column D, and as your underlining data gets more rows or rows change which series they are in, the graph will automatically update.

A: If you put the data into two columns, leaving one column blank each time, that should do the trick


text:
Q: How can I overlay a native view on top of PhoneGap's CordovaWebView in Android? I'm building a phonegap plugin which needs to render a native UI view on top of the WebView that PhoneGap provides.  In iOS this is very simple, just create the view and add it to PhoneGap's webView's scrollView.  This will render the control on top of the webView and allow it to scroll with the HTML content (note that this example uses a UIButton, but I will be applying this to a custom UI control):
-(void)createNativeControl:(CDVInvokedUrlCommand *)command
{
    NSDictionary* options = [command.arguments objectAtIndex:0];
    NSNumber* x = [options objectForKey:@"x"];
    NSNumber* y = [options objectForKey:@"y"];
    NSNumber* width = [options objectForKey:@"width"];
    NSNumber* height = [options objectForKey:@"height"];

    CGRect rect = CGRectMake([x floatValue], [y floatValue], [width floatValue], [height floatValue]);
    self._nativeControl = [UIButton buttonWithType:UIButtonTypeSystem];
    self._nativeControl.frame = rect;

    [self._nativeControl addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self._nativeControl setTitle:@"Click me" forState:UIControlStateNormal];
    [self.webView.scrollView addSubview:self._nativeControl];

    CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
    [self.commandDelegate sendPluginResult:result callbackId:command.callbackID];
}

I have tried doing something roughly equivalent in Android, but have not had success.  Here is my most recent attempt:
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    System.out.println(String.format("%s action called", action));

    if ("echo".equals(action)) {
        String message = args.optString(0);
        this.echo(message, callbackContext);
        return true;
    } else if ("createNativeControl".equals(action)) {
        this.createNativeControl(callbackContext);
        return true;
    }

    return false;
}

private void createNativeControl(CallbackContext callbackContext) {
    // Find the frame layout parent and place the control on top - theoretically
    // this should appear on TOP of the webView content since the TextView child is
    // added later
    FrameLayout frameLayout = (FrameLayout) webView.getParent().getParent();

    TextView view = new TextView(frameLayout.getContext());
    view.setText("Hello, Android!");
    view.setVisibility(View.VISIBLE);

    frameLayout.addView(view, 100,100);
    callbackContext.success();
}

How can I accomplish this in Android?

A: With Cordova Android 4.0.2, I was able to add a view on top of the webview, like this:
public class HVWMaps extends CordovaPlugin {

    @Override
    public void initialize(CordovaInterface cordova, CordovaWebView webView) {

        FrameLayout layout = (FrameLayout) webView.getView().getParent();

        TextView textView = new TextView(layout.getContext());
        textView.setBackgroundColor(Color.BLUE);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(500, 500);
        params.setMargins(100, 100, 100, 100);
        textView.setLayoutParams(params);
        layout.addView(textView);
    }
}

It seems that the interface for CordovaWebView has changed recently, so this may not work with older versions. For this example, you'll also need to add <param name="onload" value="true" /> to the feature in your plugin.xml so that initialize(..) gets called:
<platform name="android">
    <config-file target="res/xml/config.xml" parent="/*">
        <feature name="YourPlugin" >
            <param name="android-package" value="com.your.plugin"/>
            <param name="onload" value="true" />
        </feature>
    </config-file>
</platform>

This doesn't scroll with the webview as you mentioned iOS does, but for my project I didn't need it to.

A: So I spend some time on this myself, my solution has multiple parts:

*

*You have your CordovaWebView in your layout XML

*Your Activity extends the CordovaActivity

*You override few methods:
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_page);
super.init();
loadUrl("file://" + getFilesDir()+"index.html");

....and other code you like...
}

 @Override
    protected CordovaWebView makeWebView() {
        SystemWebViewEngine systemWebViewEngine =
        new SystemWebViewEngine((SystemWebView) findViewById(R.id.cordovaWebView));
return new CordovaWebViewImpl(systemWebViewEngine);
    }

    @Override
    protected void createViews() {
//must override this, otherwise crash
if (preferences.contains("BackgroundColor")) {
    int backgroundColor = preferences.getInteger("BackgroundColor", Color.BLACK);
    // Background of activity:
    appView.getView().setBackgroundColor(backgroundColor);
}
        appView.getView().requestFocusFromTouch();
    }

So the makeWebView() is the key part, where you override the CordovaActivity's method to return your own CordovaWebView instance from the XML.
The createViews() method has to be override too, since if you check the CordovaActivity code there is a setContentView(appView.getView()), which going to cause crash otherwise. You make sure when you override you REMOVE that part.
finally the xml (not the whole content):
    <!-- The main content view -->
    <org.apache.cordova.engine.SystemWebView
    android:id="@+id/cordovaWebView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

A: Have you tried to see the order of your views?
Maybe it's overlapped down your webview

//hide webview
//webview.setVisibility(View.GONE); //to test if the
new view appear
webview.setZOrderOnTop(true);
//show the new view myView.setVisibility(View.VISIBLE);
myView.bringToFront();

I will asume you are 100% sure this line get a valid parent which you can add a view.

FrameLayout frameLayout = (FrameLayout)
webView.getParent().getParent();


text:
Q: Obtain iterators from std::regex_search and use these in string::replace I am having ridiculous difficulties matching a regex and replacing the match with another string. I want to achieve this with iterators, as outlined below. The part that does not work is getting iterators that delimit the match in the original string and that I could then pass to string::replace. I tried using a std::match_results object to get a pair of iterators, but replacing m by mr in the call of regex_search fails.
I have the vague feeling that I either use the wrong match class or the wrong type of iterator, but somehow can't find my way out of template jungle.
std::string txt{ "aaa bbb" };
std::smatch m;
std::regex rx(R"(aaa)");
std::match_results<std::string::iterator> mr;

if (std::regex_search(cbegin(txt), cend(txt), m, rx)) {
    std::cerr << m[0] << std::endl;

    // what I need here are iterators that I can pass
    // to string::replace

    // txt.replace(i1 ,i2, std::string("ccc"));
}

A: Try this segment
std::string::const_iterator start = txt.begin();
std::string::const_iterator end   = txt.end();

if ( std::regex_search( start, end, m, rx ) )

Typical use in while loop
while ( std::regex_search( start, end, m, rx ) )
{
    // do stuff with match
    start = m[0].second;
}

A: Why do you want to replace with iterators? You might know this but there is std::regex_replace method that could do this.
std::string stringText{ "aaa bbb" };
std::regex regexMatch("aaa");
std::string stringResult;

std::regex_replace(std::back_inserter(stringResult), std::cbegin(stringText), std::cend(stringText), regexMatch, "ccc");

Another similar sample from a regex tutorial using regex_replace (scroll down a bit)
It is possible to use iterators but then you need to build a new string from current. if you want i can do a sample.

A: Thanks to @Edward I realized that m[0] contains a pair of iterators that defines the matching substring. I had tried first and second but on m instead of m[0], which of course failed.
With this the replacement was easy:
std::string txt{ "aaa bbb" };
std::smatch m;
std::regex rx(R"(aaa)");

if (std::regex_search(cbegin(txt), cend(txt), m, rx)) {
    txt.replace(m[0].first, m[0].second, std::string("ccc"));
}


text:
Q: Hypothesis test with restricted domain may I have some key words about how to due with a hypothesis test with restricted domain?
Here is an sample question to my problem. Alice have a dice with $1/3$ chances to get $1$, $2/3$ to get $0$. Bob have another dice with $1/4$ and $3/4$ chances instead.
Given $n$ dices and with $r$ $1$, assuming the number of dices from Alice is $k$, and $n-k$ from Bob. The likelihood of the value of $k$ is
$$C^n_r (k * 1/3)^k ((n-k)* 1/4)^{n-k}$$
in this case, $k \in [0, n]$. However the distribution are still continuing beyond the domain.
What is the proper way to handle this scenario? I couldn't search some relevant results up to this moment, may I have some keywords about some topic discussion this kind of question?

A: Too long for a comment.
Let us assume that we have two Bernoulli distributions $\mathsf{Ber}(\frac{1}{3})$ and $\mathsf{Ber}(\frac{1}{4}).$ If $k$ independent and identically distributed experiments of $\mathsf{Ber}(p)$ are performed and $X$ is number of successes then $X \sim \mathsf{Bin}(k, p).$ In your context, you want to estimate $k$ knowing that there is a total of $n$ trials with $r$ sucesses (so $n$ and $r$ are fixed while $k$ is unknown). So, you have two random variables $X \sim \mathsf{Bin}(k, \frac{1}{3})$ and $Y \sim \mathsf{Bin}(n-k, \frac{1}{4}).$ Under these circumstances, we have $X + Y = r.$ You need to write
$$
\{X+Y = r\} = \bigcup_{s = 0}^{\min(r, k)} \{X = s\} \cap \{Y = r-s\}.
$$
Then,
$$
P(X + Y =  r) = \sum_{s = 0}^{\min(r, k)} \dbinom{k}{s} \left( \frac{1}{3} \right)^s \left( \frac{2}{3} \right)^{k-s} \dbinom{n-k}{r-s} \left( \frac{1}{4} \right)^{r-s} \left( \frac{3}{4} \right)^{n-k-r+s}.
$$
Even if you assumed $r \leq k,$ this sum is not easy. It also seems that you will need to do computer estimates directly.


text:
Q: What's the correct way to back up all Photos from the Photos app? I downloaded the macOS Sierra (GM) and installed it on my MacBook. Before I installed it a backed up all my data that isn't stored in the cloud or somewhere else.
I'm using iCloud Photos to sync all my photos and videos with iCloud. Every photo and video is already in iCloud so I may don't need to back up my Photos library, but I did - just in case something goes wrong.
So I wiped off all the data from my MacBook to do a complete and clean installation of Sierra. Finally everything works fine and I'm going to get all my photos and videos back to the Photos app.
My backup of my photos and videos has ~13GB and I really have a slow internet connection, so it would be nice if I could use the backed up library instead of downloading everything from iCloud.
As soon as I open my library with Photos it starts importing and optimizing etc. and all photos and videos are there. But it starts uploading every single photo and video to iCloud? How can I tell Photos that my photos and videos are already in iCloud and it should stop uploading?

A: The Photos app in macOS Sierra is able to do a comparison between what is in the cloud, and what is stored in the local library on your Mac. (Likely through some means of signature/hash function).
To provide some insight with actual numbers - My Photos library is approximately 53GB, and only required about ~1.5GB worth of bandwidth to validate/sync the library after migrating the library to a different Mac with a fresh install of macOS Sierra (1.5GB includes any photos that it also needed to sync since the last my library was active).
With that being said, you can be confident that your bandwidth limitation, or capacity, should not have to handle the full file size. However, be mindful that if there are other cloud services (iCloud Drive) they too can utilize bandwidth.

A: The correct way is exactly as you did it. Photos.app should determine that the photos are identical to the ones already in the cloud. A limited amount of data may be used to accomplish this, but it should not use anywhere near the size of your whole library.


text:
Q: How to put a cite command next to a theorem with square brackets and no parentheses? In my bachelor thesis, I use a theorem from another author. I have to cite him. When I use
\newtheorem{proposition}{Proposition}[chapter]
\begin{proposition}\textup{\cite[Proposition 4.7]{LPW}}

I get

This is not exactly what I want. As you can see, there is a point behind "Proposition 4.8". I want that point to be behind the last bracket, so that get

I hope I clarified my problem. Thanks for your help!


text:
Q: url gets no data unless search button is pressed I am trying webscraping with python.  The link "https://www.etnet.com.hk/www/eng/stocks/realtime/quote.php?code=00883" get no data unless the search button is pressed.  So, how to solve this for python webscraping?
I am trying to web scrape stock data via this link "https://www.etnet.com.hk/www/eng/stocks/realtime/quote.php?code=883" but failed as the url doesn't work.  The detailed data won't appear unless after I have manually press the search button.
Any idea how to fix it?
import requests
from bs4 import BeautifulSoup

url = "https://www.etnet.com.hk/www/eng/stocks/realtime/quote.php?code=883"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
TRs = soup.findAll('tr')
print(TRs)

A: Check the difference between working page headers (http://i.imgur.com/wNUimeE.png) and non-working one (http://i.imgur.com/I3PS7ji.png). The first difference - you need to add a Referer to your requests. If still no results - check any other differences through the Network tab.


text:
Q: VirtualBox PXE Boot using PCnet-FAST III - Windows 7 driver required? I'm using WDS to deploy a windows 7 image that I've captured.
Unfortunately, the AMD PCnet-FAST III is not recognised by windows 7 with VirtualBox.
Can anyone help me find a driver and or suggest another NIC to use with VirtualBox?

A: Have you tried using the NDIS5 Driver for Microsoft Windows driver?
If you have trouble getting it into the VM, use something like genisoimage to generate an ISO you can mount in VirtualBox.


text:
Q: form field required not working I have a form and not sure why one field works for the required attribute and the other doest:
doesnt work
<input name="ch_register_first_name" id="ch_register_first_name" type="text" value="First Name" class="regular-text" required />

does work
<input type="checkbox" name="ch_register_agree" value="1" required>

Does it not work if there is a default value for a text box???? If so how do I keep the default value and make it required??

A: Try using the placeholder attribute to display your 'label' inside of the <input /> and remove the value attribute. This way, required is respected:
<input name="ch_register_first_name" id="ch_register_first_name" type="text" placeholder="First Name" class="regular-text" required />

jsFiddle Demo
It's worth noting though, that you shouldn't really use placeholder in place of a true <label> element. For example, Mozilla (as always) puts it best:

Do not use the placeholder attribute instead of a <label> element.
  Their purposes are different: the <label> attribute describes the
  role of the form element; that is, it indicates what kind of
  information is expected, the placeholder attribute is a hint about
  the format the content should take. There are cases in which the
  placeholder attribute is never displayed to the user, so the form
  must be understandable without it.


text:
Q: WPF positioning take full height of window Here's my layout.
<Window>
 <StackPanel Orientation="Vertical">
       <StackPanel HorizontalAlignment="Stretch" Height="30">
       </StackPanel>
       <Canvas HorizontalAlignment="Center" Width="1020">
                    <!--i want this to take the remaining full height of the screen-->
                    <Canvas x:Name="bottomInfoBar" Canvas.Bottom="0" Width="720" Height="39">
                    <!--I want this at the very bottom of the screen-->
                    </Canvas>
       </Canvas>
</Window>

I want the canvas to take the full height of the window so that the 'bottomInfoBar' always remains at the very bottom of the user's screen. However if i don't specify a height for the canvas 'bottomInfoBar' appears at the very top. How do i achieve this? Please help.

A: Easiest way:
<Window>
    <DockPanel>
        <Whatever x:Name="bottomInfoBar" DockPanel.Dock="Bottom"/>

        <PrimaryContent/>
    </DockPanel>
</Window>

Based on your question, you really should read about WPF's layout system before you write another line of code. You'll save yourself a world of pain if you understand that before proceeding.


text: Q: flutter_stripe 3d Secure (SCA), how working? In the new flutter_stripe library there is a 3d sca by default. I didn't understand what it means since there is no card confirmation to start the security scan before paying, can anyone tell me more?


text:
Q: Webframework written in / compiling to SQL? Many of the tasks in many web applications consist of checking and updating the state in a (typically relational) database. Often this logic is not more complex than the SQL statements needed to get and update the data. It seems to me that much of the logic should be  processable in SQL and that avoiding trips between the web app and the database would save a lot of time.
Is there a (preferably open source) web application framework that is written in SQL or compiles to SQL?


text:
Q: Overwatch Update Keeps Restarting After Finishing Since updating to patch 1.4.0.2 (1.68GB), Overwatch keeps restarting the update, like this:

*

*Overwatch starts updating to the new patch

*Update finishes

*Update starts all over again
Is it a problem with my PC, or something else?

A: I happened to have the same issue. Not to worry, you can try selecting the options button once your in the battle.net desktop app on the Overwatch section and continue to select the option for 'scan and repair' and allow it to scan for a while. After, it will download the necessary remaining files needed to play the game.

A: After updating, try closing everything related to overwatch in taskmanager (use ctrl + shift + esc) , and after that, restart your computer, and open overwatch again.
If this doent fix the problem, Try reinstalling the game, and apply update after


text:
Q: TSQL to return NO or YES instead TRUE or FALSE How can I show a different value if some columns return FALSE,
for example,
COLUMN "BASIC" returns FALSE, but I need show for the user YES or NO. Case FALSE, return NO.

A: since SQL 2012 you can use IIF function
IIF(BASIC = 'TRUE', 'YES', 'NO')

A: case when column = 'FALSE' then 'NO' else 'YES' end

A: If varchar or bit, handling NULLs
case
    when BASIC = 'FALSE' then 'NO'
    when BASIC <> 'FALSE' then 'YES'
    else 'UNDEFINED'
end

or if just bit
case
    when BASIC = 1 then 'YES'
    when BASIC = 0 then 'NO'
    else 'UNDEFINED'
end

Edit:
SELECT
    TipoImovel_Id AS TII_SEQ,
    Descricao AS TII_DSC,
    Sigla AS TII_DSC_SIGLA,
    -- choose which one you want from the answers here
    case
        when BASIC = 1 then 'YES'
        when BASIC = 0 then 'NO'
        else 'UNDEFINED'
    end AS SomeColumnName
FROM San_TipoImovel";

A: Use CASE statement:
case BASIC when 'True' then 'Yes' ELSE 'No' end

A: Like this:
SELECT TipoImovel_Id AS TII_SEQ, Descricao AS TII_DSC, Sigla AS TII_DSC_SIGLA, case when basic = 'FALSE' then 'NO' else 'YES' end
FROM San_TipoImovel

A: You could create a user defined function so in the future you can just say something like:
select dbo.YesNo(Active) from APAccount

here is the function
CREATE FUNCTION [dbo].YesNo(@Value Bit)
    RETURNS varchar(3)
    BEGIN
      DECLARE @R as varchar(3)

      SET @R =
        (
        Select
            case
                when @Value = 1 then 'Yes'
                else 'No'
            end
        )
       RETURN @R
    END


text:
Q: Android Keyboard - android:windowSoftInputMode="adjustPan" I know there is heaps on here related to the virtual keyboard in Android, but I just cant seem to figure out how to achieve a solution to my problem.
For those that are not familiar with AdjustPan and AdjustResize you can check out what they are/do here - Difference between adjustResize and adjustPan in android?
What I am trying to achieve is the AdjustPan result in which my webview is not resized, but scrolls to the input box instead as I have submit/cancel buttons that are position:absolute to the bottom of the screen. When I use the AdjustPan setting, the keyboard opens up but covers my input and doesn't scroll the webview to the input.
On the other hand when I use the AdjustResize option, the position:absolute buttons from the footer cover the last few inputs as there is quite a lot of content to fit in half the screen size.
Currently my Activity looks like this
<activity android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale" android:label="@string/activity_name" android:launchMode="singleTop" android:name="MainActivity" android:screenOrientation="portrait" android:theme="@android:style/Theme.Black.NoTitleBar" android:windowSoftInputMode="adjustResize">

I am trying to avoid the Javascript listener solutions as they seem a bit hackery and from my experience usually don't provide a seamless look and feel.

A: *

*OPTION 1

Add a blank layout with height approximately equal to the height of keypad. Move the webview and the blank layout into a ScrollView and disable the webviews scroll.

*OPTION 2

Append a few line breaks to the web content that is loaded in the webview.


text:
Q: Error when connecting to XTB API with Real account I know this XTB question could be rare but I find troubles and I want to know if somebody has connected an API from XTB. My problem is the following:
I have downloaded a wrapper for python from this url : http://developers.xstore.pro/api/wrappers/2.5.0
XTB can have 2 types of account: Demo & Real. For demo account the streaming and no-streaming methods work, but when I try to connect to a REAL account I got this error:
{'status': False, 'errorCode': 'EX017', 'errorDescr': 'You are trying to login using the account from
a different platform'}

So, if somebody can help me out in how to use the wrapper to connect to REAL acoount would be great.
Thanks

A: The wrapper uses demo port numbers, to connect to the live API you need to change the ports:
DEFAULT_XAPI_PORT           = 5112
DEFUALT_XAPI_STREAMING_PORT = 5113

This is described in the documentation, section 4:
Here are the details of DEMO and REAL servers hosted on each of the addresses above:
DEMO: main port: 5124, streaming port: 5125,
REAL: main port: 5112, streaming port: 5113.
Just spent half an hour solving this problem :/


text:
Q: LGBMClassifier create_tree_diagraph not showing in notebook I am using LightGBM's LGBMClassifier for a binary classification problem and want to print out the actual diagram.
Here is how I trained/fit the model
clf = lgb.LGBMClassifier()
clf.fit(x_train, y_train, categorical_feature = x_train.select_dtypes(include = 'category').columns.tolist())

And here is how I am trying to print the diagram
lgb.create_tree_digraph(clf, orientation='vertical')

However, the only output I am getting is
<graphviz.graphs.Digraph at 0x7f6a10a5ed00>

I also tried using the parent lightgbm.train() method to build the model and as the booster argument in create_tree_diagraph, however I am getting similar output.
Is there an additional library or function I have to call to print out the tree, or is there another way to perhaps save it to a .png file?
I am using a Python Notebook in Databricks.

A: The REPL explained to you that you have a Digraph in hand.
Good. Let's assign it to a temp var, and render it.
https://graphviz.readthedocs.io/en/stable/manual.html#basic-usage
g = lgb.create_tree_digraph( ... )

g.render(view=True)

g.format = "png"
g.render("output.png")

g.view()

This relies on dot being already installed
so it works when bash invokes it.


text:
Q: How to create new instances of a wrapped vector in Rust? I'd like to create my own vector struct, so I can attach extra methods.
pub struct MyStructVec(pub Vec<MyStruct>);

Having done this, how would a new instance of this vector be created?
MyStructVec::new() isn't recognized. How would existing vector creation methods be used with this type? (new, with_capacity... etc.)

A:
MyStructVec::new() isn't recognized.

Indeed, because you've defined a new type but not defined any methods yet.  You can do so easily:
impl MyStructVec {
    pub fn new() -> MyStructVec {
        MyStructVec(Vec::new())
    }
}

but as said well in the other answer you don't get the wrapped type's methods directly on your new struct directly, so you'd need to wrap the ones you want.  (In some cases you might be able to automate to some extent it using macros)

A: A newtype "hides" its internals. You do not get transparent access to the interior. To create a new object of MyStructVec, you need to call the inner type's constructor and then wrap it:
MyStructVec(Vec::new())

MyStructVec(Vec::with_capacity(42))

After the creation of such an object, you can use the object somewhat transparently by implementing Deref and DerefMut for your type:
impl std::ops::Deref for MyStructVec {
    type Target = Vec<MyStruct>;
    fn deref(&self) -> &Vec<MyStruct> {
        &self.0
    }
}

impl std::ops::DerefMut for MyStructVec {
    fn deref_mut(&mut self) -> &mut Vec<MyStruct> {
        &mut self.0
    }
}

so I can attach extra methods

That's not the way newtypes are used. Newtypes are used for type safety. If all you want is that all Vec<MyStruct> have new methods, create an extension trait:
trait VecMyStructExt {
    fn foo(&self);
}
impl VecMyStructExt for Vec<MyStruct> {
    fn foo(&self) { println!("foo"); }
}


text:
Q: Stream Scheduling, reload application, published stream break I am trying to build a video scheduling app using wowza 4.1.
I follow the tutorial given here , build an application and an smil file ,
as given .
i am able to play schedule video. but when i make some changes in my smil file ,
i need to restart my app. which make my streaming break.
so i need an mechanism so that if i change my smil file , changes should reflect on published stream without stream breaking .


text:
Q: Turn someone's life around
Turned someone's life around by mastering falconry.

1.What does this mean? (Is it his/her life has changed or he spent his whole time in falconry?)

*Can I use this in negative connotation?

A: There is a book "H is for Hawk" by Helen Macdonald that describes how she took up falconry after a difficult time in her life. Having to concentrate on training the bird intensively freed her mind from her past troubles. That would be an example of someone turning their life round through mastering falconry. Maybe the phrase you quote is from a review of that book.


text:
Q: sentiment analysis for arabic language I'm looking for analysing sentiment in arabic language , to do that I collect some status from facebook and I classify them into positive and negative , I'm using RapidMiner software so I do the tokenization and stemmig and stop words remove , now I want that my corpus consider the emoticons " :( and :) " as a positive and begative sentiment , how to add that to my corpus.

this the model that I used , what operator I have to incorporate in order to deal with smileys as positive and negative sentiment

A: Tokenization will typically remove punctuation.  Are you implementing your own tokenizer to avoid this?  Perhaps a custom TokenMarker?


text:
Q: how to make this code run only before_create I am trying to convert my users' ips from string to integers :
class User < ActiveRecord::Base
  [:current_sign_in_ip, :last_sign_in_ip].each do |field|
    define_method(field) do
      ip = read_attribute(field)
      return nil unless ip
      ip += 4_294_967_296 if ip < 0 # Convert from 2's complement
      "#{(ip & 0xFF000000) >> 24}.#{(ip & 0x00FF0000) >> 16}.#{(ip & 0x0000FF00) >> 8}.#{ip & 0x000000FF}"
    end

    define_method("#{field}=") do |value|
      quads = value.split('.')
      if quads.length == 4
        as_int = (quads[0].to_i * (2**24)) + (quads[1].to_i * (2**16)) + (quads[2].to_i * (2**8)) + quads[3].to_i
        as_int -= 4_294_967_296 if as_int > 2147483647 # Convert to 2's complement
      else
        as_int = nil
      end
      write_attribute(field, as_int)
    end

  end
end

This code works fine, it converts the string to integers and saves them. However, I want this code to run only before_create action. I tried to put it in a before_create do block but I got errors about undefined method define_method' for #<User:0x007fb97c7076b8> . Even if you could just direct me to the right direction that'd be great.
Thanks

A: You have to execute it against the eigenclass of the object:
before_create do
  class << self
    [:current_sign_in_ip, :last_sign_in_ip].each do |field|
      define_method(field) do
        ip = read_attribute(field)
        return nil unless ip
        ip += 4_294_967_296 if ip < 0 # Convert from 2's complement
        "#{(ip & 0xFF000000) >> 24}.#{(ip & 0x00FF0000) >> 16}.#{(ip & 0x0000FF00) >> 8}.#{ip & 0x000000FF}"
      end

      define_method("#{field}=") do |value|
        quads = value.split('.')
        if quads.length == 4
          as_int = (quads[0].to_i * (2**24)) + (quads[1].to_i * (2**16)) + (quads[2].to_i * (2**8)) + quads[3].to_i
          as_int -= 4_294_967_296 if as_int > 2147483647 # Convert to 2's complement
        else
          as_int = nil
        end
        write_attribute(field, as_int)
      end

    end
  end
end


text:
Q: Determine which sections of UITableViewController are visible when it is scrolled I am trying to determine which section of the UITableView is visible (on top, if there are 2 sections simultaneously), in swift 2. So far I found this solution:
Is there any way to know if the user is scrolling tableview up or down? in swift IOS , this: How to get a UITableView's visible sections? and this one:  Swift - UITableView scroll event
All of them not working for me for reasons:
1. I can not add UIScrollViewDelegate, because swift 2 is giving error on redundant conforming to protocol (because it is UITalbeView, and it already conforms to UIScrollView).
2. However, this:
func scrollViewDidScroll () {
    print("scrolled: \(self.tableView.indexPathsForVisibleRows)")
}

is never being launched.
Delegate and data source for the UITableView are defined through storyboard interface builder.
How would you determine in swift 2 that UITableViewController is being scrolled, and which section is visible?

A: please try to get visible cell from willDisplayCell method and then get section from this visible cell.
For Example:
First get Indexpath from Cell and then retrive section from Indexpath.
let section = indexPath.section
Code is:
override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
    let cell = self.tableView.dequeueReusableCellWithIdentifier("CustomCell") as! CustomCellViewController

    let position: CGPoint = cell.convertPoint(CGPointZero, toView: self.tableView)
    if let indexPath = self.tableView.indexPathForRowAtPoint(position)
    {
        let section = indexPath.section
        print("will display section: \(section)")
    }
}


text:
Q: Flutter, how to automatically animate without a button trigger I have some animation code that changes background color infinitely
but the problem is I want to do this without a button trigger
and I want this to be automated at first time (when it's firstly loading)
below is code
I`m so stuck could anyone help please
the purpose is to animate without a trigger, it automatically runs animation that changes background
import 'package:flutter/material.dart';

class ScreenTime extends StatefulWidget {
 @override
_ScreenTimeState createState() => _ScreenTimeState();
}

class _ScreenTimeState extends State<ScreenTime> {
  List<Color> colorList = [
  Colors.red,
  Colors.blue,
  Colors.green,
  Colors.yellow
 ];
List<Alignment> alignmentList = [
  Alignment.bottomLeft,
  Alignment.bottomRight,
  Alignment.topRight,
  Alignment.topLeft,
];
 int index = 0;
 Color bottomColor = Colors.black54;
 Color topColor = Colors.white10;
 Alignment begin = Alignment.bottomLeft;
 Alignment end = Alignment.topRight;

@override
Widget build(BuildContext context) {

return Scaffold(
    body: Stack(
      children: [
        AnimatedContainer(
          duration: Duration(seconds: 2),
          onEnd: () {
            setState(() {
              index = index + 1;
              // animate the color
              bottomColor = colorList[index % colorList.length];
              topColor = colorList[(index + 1) % colorList.length];

              //// animate the alignment
              // begin = alignmentList[index % alignmentList.length];
              // end = alignmentList[(index + 2) % alignmentList.length];
            });
          },
          decoration: BoxDecoration(
              gradient: LinearGradient(
                  begin: begin, end: end, colors: [bottomColor, topColor])),
        ),
        Positioned.fill(
          child: IconButton(
            icon: Icon(Icons.play_arrow),
            onPressed: () {
              setState(() {
                bottomColor = Colors.blue;
              });
            },
          ),
        )
      ],
    ));
 }
}

A: To keep as much as your original implementation as possible while fixing the problem, doing
WidgetsBinding.instance.addPostFrameCallback((_) => setState(() {bottomColor = Colors.blue;}));

in initState would not pose an issue. This is as long as it's done in initState. Calling it in build would lead to an undesirable extra infinite loop.
However, using an AnimationController on repeat would almost certainly be a cleaner implmentation.

A: the purpose of this question was basically "how to animate AnimatedContainer without a trigger"
and I think I found a solution
what I did is
just make a new function and then in the build method, invokes the method
and method code is like below
 setState(() {
  index = index + 1;
  bottomColor = Colors.blue;
});

my second solution is this and I think it works
but I worry if it has a any side effects
WidgetsBinding.instance.addPostFrameCallback((_) => setState(() {}));

A: Use this
bool selected = false;

@override
void initState() {
Future.delayed(const Duration(seconds: 1), () {
  setState(() {
    selected = true;
  });
});
super.initState();
}

@override
Widget build(BuildContext context) {
return Container(
    width: MediaQuery.of(context).size.width,
    height: MediaQuery.of(context).size.height,
    color: Colors.white
    child: Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        AnimatedAlign(
          alignment: selected ? Alignment.topRight : Alignment.bottomLeft,
          duration: const Duration(seconds: 1),
          curve: Curves.fastOutSlowIn,
          child: const FlutterLogo(size: 50.0),
        ),
      ],
    ));}

This Will automatically starts the animation. You can change the duration or animation type also.


text:
Q: Geometrical Sequence I have a sequence $U(n)$ with $U(n+1) = f(U(n))$ with $f(x) = ax+b$.
I'm supposed to express $U(n)$ as a function dependant on $n$.
Doing so with an auxiliary sequence $V(n) = U(n) - ɑ$.
Where $ɑ$ is the solution to $f(x) = x$. Also I have to prove that $V(n)$ is geometric.
I don't know where to start on that problem.

A: Suppose that $a\not=1$. Since we have
$$U_{n+1}-\frac{b}{1-a}=a\left(U_n-\frac{b}{1-a}\right),$$
we have
$$V_{n+1}=aV_n$$
where $V_n=U_n-\frac{b}{1-a}$ is geometric.


text:
Q: What is the state of the equilibrium for a second derivative equal to zero? Considering a potential energy of $U$, and a displacement of $x$, the force is given by
$F=-\frac{\partial U}{\partial x}$.
Since equilibrium is defined as the point at which $F=0$, we can express this as $\frac{\partial U}{\partial x}=0$. This is clear to see on the following graph;

It is also clear that some equilibria are stable and some are not; given a small displacement at $x_2$ the system will return to equilibrium, whereas this would not happen at $x_3$. Hence, we can say that for $\frac{\partial ^2U}{\partial ^2x}>0$ the equilibrium is stable, whereas for $\frac{\partial ^2U}{\partial ^2x}<0$ the equilibrium is unstable. Is there a general solution to this case, or does each have to be considered individually?
What is not clear to me is the case where $\frac{\partial ^2U}{\partial ^2x}=0$. Does this simply mean that the equilibrium is stable given a displacement in one direction and not the other, or is it more complicated - for example if a particle were to oscillate about a stable equilibrium point, its motion would be dampened until it were at rest, but this would not be possible at a point where $\frac{\partial ^2U}{\partial ^2x}=0$; if the particle were to move to the side where $\frac{\partial ^2U}{\partial ^2x}<0$, it would not return to the equilibrium point. Is there a general solution to this case, or does each case have to be considered by inspection?

A: First of all you have an imprecise idea about stability: also small velocities matter not only small displacements from the equilibrium. An equilibrium $x_0$ is stable if the motion is confined around $x_0$ and its velocity is confined around the vanishing velocity for every positive time, for every initial condition close to $x_0$ and every initial velocity close to $0$ at time $t=0$.
In other words, according to the general theory of stability (e.g., see Arnold's or Fasano-Marmi's textbooks) the equilibrium $x_0$ is stable (in the future) if
fixing a neighborhood $U$ of $(x_0,0)$, there exists a second neighborhood $V\subset U$ of $(x_0,0)$ such that, every pair of  initial conditions $x(0)=y_0$ and $\dot{x}(0) = \dot{y}_0$ with $(y_0, \dot{y}_0) \in V$ gives rise to a motion $x=x(t)$ such that $(x(t), \dot{x}(t)) \in U$ for every $t\in (0, +\infty)$.
A theorem (as above I restrict myself to the one-dimensional case) proves that if all forces are conservative then
(a)  a configuration $x_0$ is an equilibrium if and only if $\frac{dU}{dx}|_{x_0}=0$,
(b)  an equilibrium $x_0$ is stable if $U$ has a strict minimum at $x_0$ (i.e. $U(x)>U(x_0)$ for $x\neq x_0$ in a neighborhood of $x_0$).
(c)  an equilibrium $x_0$ is unstable if $\frac{d^2U}{dx^2}|_{x_0}>0$.
The condition in (b) is satisfied if $\frac{d^2U}{dx^2}|_{x_0} <0$, but this is just a sufficient condition (think of $U(x)=x^4$ with $x_0=0$, it is evidently stable and satisfies (b), but $\frac{d^2U}{dx^2}|_{x_0}=0$).
It remains open the case $\frac{d^2U}{dx^2}|_{x_0}=0$. It has to be studied case-by-case. However certain cases are easy. In particular consider any point $x_0 > x_5$ in your picture. It is clear that the condition in (a) is true, so that $x_0$ is an equilibrium and also $\frac{d^2U}{dx^2}|_{x_0}=0$.
However, perhaps contrarily to the naive idea, $x_0>x_5$  is unstable. Indeed if you start with an initial condition $x(0) = y_0$ arbitrarily close to $x_0$ and a speed $\dot{x}(0) = \dot{y}_0 > 0$ arbitrarily close to $0$, the arising motion is $x(t) = \dot{y}_0 t + y_0$ and, waiting a sufficiently large time $t>0$, $x(t)$ exits from every neighborhood of $x_0$ initially fixed.
(Statement (b) is nowadays an elementary  subcase of a famous theorem due to Lyapunov but a proof was already known by Lagrange and Dirichlet. As a matter of fact, the total energy $E(x, \dot{x})$ is a Lyapunov function for the system for the critical point $(x_0,0)$ when $U$ has a strict minimum at $x_0$.)

A: Taylor expand the force $F(x) = -U'(x)$ about $x = x_0$:
$$F(x_0 + \Delta x) = -U'(x_0) - U''(x_0)\Delta x - \frac{1}{2}U'''(x_0)(\Delta x)^2 + \cdots$$
Stipulate that $F(x_0) = 0$ and then
$$F(x_0 + \Delta x) = -U''(x_0)\Delta x - \frac{1}{2}U'''(x_0)(\Delta x)^2 + \cdots$$
In the case that $U''(x_0) \gt 0$, then for $\Delta x$ small, the force is approximately a linear restoring force.
However, in the case that $U''(x_0) = 0$  (and at least one higher order derivative is non-zero), then for $\Delta x$ small, the force is non-linear and not necessarily a restoring force.
For example, if $U'''(x_0) \ne 0$, then the sign of the force does not change as $\Delta x$ goes through zero; the force is opposite the displacement in one direction and with the displacement in the other direction (which will drive the particle away from $x=x_0$).
For the force to be restoring in the case that $U''(x_0) = 0$ requires that the lowest order non-zero derivative (higher than the 2nd) be even order and positive

A: Consider the following potentials:
\begin{align} U(x) &= x^4 \\ U(x) &= x^6 - x^4 \\ U(x) &= x^4 + x^3  \end{align}
All three of these potentials have an equilibrium point at $x = 0$. All three of these potentials are such that the second derivative of $U(x)$ at this equilibrium point is zero. However, you should convince yourself (perhaps by plotting these potentials) that in the first  case the equilibrium is stable, in the second case it is unstable, and in the third case the equilibrium is, as you put it, "stable in one direction but unstable in the other".
The moral is: knowing only that the second derivative is zero tells us nothing about stability. We need to look at higher derivatives if we want to know more.