text:
Q: React-Native Native UI component doen't resize (Android) I have issues with React Native respecting the height of an Android Native UI Component. I have created a very simple use-case to demonstrate the issue.
React Native version = 0.61.5.
Android, React Native ViewManager:
public class CustomTextViewManager extends SimpleViewManager<TextView> {

    @NonNull
    @Override
    protected TextView createViewInstance(@NonNull ThemedReactContext reactContext) {
        return new TextView(reactContext);
    }

    @NonNull
    @Override
    public String getName() {
        return "CustomTextView";
    }

    @ReactProp(name = "text")
    public void setText(TextView view, String text) {
        view.setText(text);
    }
}

JavaScript, native view reference:
import {requireNativeComponent} from 'react-native';

const CustomTextView = requireNativeComponent('CustomTextView')

export default CustomTextView;

JavaScript, simple app:
import React from 'react';
import CustomTextView from './CustomTextView';

const App: () => React$Node = () => {
  return (
    <CustomTextView
      text={'Some test text'}
    />
  );
};

export default App;

When you run this code nothing is shown. After adding style={{height: 100}} the view is shown at the provided fixed height.
I actually expected that the height of the Android View would be reflected in React Native. Apparently this is not the case.
Note: height: "auto" doesn't work.
I hope that someone can tell me what I'm missing.

A: I faced the same problem recently. Your need to use a shadow node to measure the final size which the TextView will have after the text was rendered.
I found a good article about this. click me
If your TextView will render simple text only, you can just use the ReactTextShadowNode which is part of the native library of react native.
To do so just override the method createShadowNodeInstance of your ViewManager and return an instance of the ReactTextShadowNode.
    override fun createShadowNodeInstance(): ReactTextShadowNode {
        return ReactTextShadowNode(null)
    }

If your TextView has to render some special Spanns, you need to write your own implementation of ShadowNode. I did so by coping the ReactTextShadowNode and changed the way how the field mPreparedSpannableText was bild. This field holds the span which will be used to measure the desired height.
eg. you could use something like that
    @ReactProp(name = "text")
    fun setText(text: String?) {
        this.text = text ?: ""
        mPreparedSpannableText = useYourMethodToCreateYourSpannable()
        dirty()
    }

This post was quiet old but I hope my answer will help someone facing the same problem.


text:
Q: Gradle: Building a modularized library that is compatible with Java 8 So Java 9 is there, soon to be followed by Java 10. Time we should make our libraries ready for use in Java 9 projects. I did it in the following way:

*

*provide a module-info.java

*added the (experimental) jigsaw plugin in build.gradle

*Manually made changes according to the guide on the gradle site instead of using the jigsaw plugin.

So far, both approaches work fine, and I can use the generated Jar in Java 9 projects.
The problem is, the resulting Jar is not compatible with Java 8 although I used no Java 9 features except the module-info.java. When I set targetCompatibility = 8, an error message tells me to also set sourceCompatibility = 8 accordingly. Which then rejects the module-info.java for which I should set sourceCompatibility = 9.
How can this be solved?
I removed the jigsaw plugin again, and tried this, but am stuck:

*

*set sourceCompatibility = 8 and targetCompatibility = 8

*create a new source set moduleInfo that contains the single file module-info.java

*set sourceCompatibility = 9 and targetCompatibility = 9 for the new sourceset

Now compilation works, and Gradle uses Java 9 when it tries to compile the module-info.java. However, modules (in this case log4j) are missing, and I get this error:
:compileJava UP-TO-DATE
:processResources NO-SOURCE
:classes UP-TO-DATE
:jar UP-TO-DATE
:sourcesJar UP-TO-DATE
:assemble UP-TO-DATE
:spotbugsMain UP-TO-DATE
:compileModuleInfoJava
classpath:
compilerArgs: [--module-path, , --add-modules, ALL-SYSTEM]
D:\git\utility\src\module-info\java\module-info.java:14: error: module not found: org.apache.logging.log4j
    requires org.apache.logging.log4j;
                               ^
warning: using incubating module(s): jdk.incubator.httpclient
1 error
1 warning
:compileModuleInfoJava FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':compileModuleInfoJava'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 1s
5 actionable tasks: 1 executed, 4 up-to-date

This is the build.gradle used (Gradle version is 4.5.1):
plugins {
  id "com.github.spotbugs" version "1.6.0"
}

apply plugin: 'maven'
apply plugin: 'maven-publish'
apply plugin: 'java-library'
apply plugin: 'com.github.spotbugs'

sourceCompatibility = 8
targetCompatibility = 8

group = 'com.dua3.utility'

repositories {
    mavenLocal()
    jcenter()
}

dependencies {
  compile     group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.10.0'
  testRuntime group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.10.0'

  // Use JUnit test framework
  testImplementation 'junit:junit:4.12'
}

ext.moduleName = 'com.dua3.utility'

sourceSets {
    moduleInfo {
        java {
            srcDir 'src/module-info/java'
        }
    }
}

compileModuleInfoJava {
    sourceCompatibility = 9
    targetCompatibility = 9

    inputs.property("moduleName", moduleName)

    doFirst {
        options.compilerArgs = [
            '--module-path', classpath.asPath,
            '--add-modules', 'ALL-SYSTEM'
        ]
        classpath = files()
        System.out.println("classpath: "+classpath.asPath)
        System.out.println("compilerArgs: "+options.compilerArgs)
    }
}

tasks.withType(com.github.spotbugs.SpotBugsTask) {
    reports {
        xml.enabled false
        html.enabled true
    }
}

task sourcesJar(type: Jar, dependsOn: classes) {
    classifier = 'sources'
    from sourceSets.main.allSource
}

task javadocJar(type: Jar, dependsOn: javadoc) {
    classifier = 'javadoc'
    from javadoc.destinationDir
}

artifacts {
    archives sourcesJar
// fails with jigsaw:    archives javadocJar
}

defaultTasks 'build', 'publishToMavenLocal', 'install'

And this is module-info.java:
module com.dua3.utility {
    exports com.dua3.utility;
    exports com.dua3.utility.io;
    exports com.dua3.utility.jfx;
    exports com.dua3.utility.swing;
    exports com.dua3.utility.lang;
    exports com.dua3.utility.math;
    exports com.dua3.utility.text;

    requires javafx.controls;
    requires javafx.web;
    requires java.xml;
    requires java.desktop;
    requires org.apache.logging.log4j;
}

A: OK, I finally got it working. In case anyone else wants to know how to do it, this is what I have done:

*

*set the Java version to 8, so that the library will be usable by Java 8 applications:
sourceCompatibility = 8
targetCompatibility = 8

*configure the module name
ext.moduleName = com.dua3.utility

*add a new sourceset consisting only of module-info.java:
 sourceSets {
        moduleInfo {
            java {
                srcDir 'src/module-info/java'
            }
        }
    }

*set compatibility to Java 9 for the moduleInfo, sourceSet, configure modules, and set the output directory:
 compileModuleInfoJava {
    sourceCompatibility = 9
    targetCompatibility = 9

inputs.property("moduleName", moduleName)

doFirst {
    classpath += sourceSets.main.compileClasspath

    options.compilerArgs = [
        '--module-path', classpath.asPath,
        '--add-modules', 'ALL-SYSTEM,org.apache.logging.log4j',
        '-d', sourceSets.main.output.classesDirs.asPath
    ]
}
}

*configure the jar task to include moduleInfo:
jar
{
  from sourceSets.main.output
  from sourceSets.moduleInfo.output
}

In case you are using the SpotBugs plugin, you also have to configure the sourceSet explicitly because it will otherwise fail when it tries to process the ModuleInfo sourceSet.
I finally ended up with this version of build.gradle:
plugins {
  id "com.github.spotbugs" version "1.6.0"
}

apply plugin: 'maven'
apply plugin: 'maven-publish'
apply plugin: 'java-library'
apply plugin: 'com.github.spotbugs'

sourceCompatibility = 8
targetCompatibility = 8

group = 'com.dua3.utility'

repositories {
    mavenLocal()
    jcenter()
}

dependencies {
  compile group: 'org.apache.logging.log4j', name: 'log4j-api', version: '2.10.0'
  testRuntime group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.10.0'

  // Use JUnit test framework
  testImplementation 'junit:junit:4.12'
}

ext.moduleName = 'com.dua3.utility'

sourceSets {
    moduleInfo {
        java {
            srcDir 'src/module-info/java'
        }
    }
}

compileModuleInfoJava {
    sourceCompatibility = 9
    targetCompatibility = 9

    inputs.property("moduleName", moduleName)

    doFirst {
        classpath += sourceSets.main.compileClasspath

        options.compilerArgs = [
            '--module-path', classpath.asPath,
            '--add-modules', 'ALL-SYSTEM',
            '-d', sourceSets.main.output.classesDirs.asPath
        ]
    }
}

jar
{
    from sourceSets.main.output
    from sourceSets.moduleInfo.output
}

spotbugs {
    sourceSets = [sourceSets.main]
}

tasks.withType(com.github.spotbugs.SpotBugsTask) {
    reports {
        xml.enabled false
        html.enabled true
    }
}

task sourcesJar(type: Jar, dependsOn: classes) {
    classifier = 'sources'
    from sourceSets.main.allSource
}

task javadocJar(type: Jar, dependsOn: javadoc) {
    classifier = 'javadoc'
    from javadoc.destinationDir
}

artifacts {
    archives sourcesJar
    archives javadocJar
}

defaultTasks 'build', 'publishToMavenLocal', 'install'

A: The question is over a year old, but in case anyone stumbles here, this functionality is now supported by Gradle Modules Plugin since version 1.5.0.
With this plugin, you don't have to create a custom source set, and you only need to call modularity.mixedJavaRelease method.
Here's a sample of how to apply the plugin to one's main build.gradle:
plugins {
  // your remaining plugins here

  id 'org.javamodularity.moduleplugin' version '1.5.0' apply false
}

subprojects {
  // your remaining subproject configuration here

  apply plugin: 'org.javamodularity.moduleplugin'
  modularity.mixedJavaRelease 8 // sets "--release 8" for main code, and "--release 9" for "module-info.java"

  // test.moduleOptions.runOnClasspath = true // optional (if you want your tests to still run on classpath)
}

A: I have developed a Gradle plugin for this: https://github.com/Glavo/module-info-compiler
I have tried Gradle Modules Plugin, but there are still some troublesome problems, so I developed this plugin, a compiler specifically used to compile module-info.java.
It is not implemented by calling javac. It is a complete compiler that can run above Java 8. It recognizes the syntax of module-info.java and generates the corresponding module-info.class file according to it.
It only checks the grammar, and does not actually check those packages, classes or modules, so it can work without configuration of any module path.
This Gradle plugin has processed everything for you. For a Java 8 project containing module-info.java, you only need to do this:
plugins {
    id("java")
    id("org.glavo.compile-module-info-plugin") version "2.0"
}

tasks.compileJava {
    options.release.set(8)
}

This answer copy the answer written by myself under another question (https://stackoverflow.com/a/72074642/7659948).

redpajama_set_name: RedPajamaStackExchange


text:
Q: NSURLSession download speed For my tvOS app I need to download a file at app startup which is around 500 Mb. With NSURLSession it's an easy task to download large files directly to disk.
I'm able to download file pretty fast as per network profiler. Graph says I've got an average speed of around 6Mb per second during last 24 seconds.

So far so good.
Another part of my application requires communication via custom NetService. So I'm preparing and posting the service:
self.service = [[NSNetService alloc] initWithDomain:@"local."
                                               type:SERVICE_NAME
                                               name:@"Remote receiver"
                                               port:0];
[self.service publishWithOptions:NSNetServiceListenForConnections];

Publishing happens at 30th second of app's life. Upon service's didPublishMethod I observe 2 changes in network profiler. First 2 new active TCP connections with state "Listening" for ipv4 and ipv6. The second one is surprisingly dramatic drop of download speed for the first active connection.
As you see after 30th second download speed decreased to couple of Kb/s.
The question is what's going on here? Does NSNetService interfere with NSURLSession? Why publishing of local service affects separate TCP connection? If resources shared between connection why does NSURLSession's receive such a small share?


text:
Q: applying a generalized additive model to an xarray I have a netCDF file which I have read with xarray. The array contains times, latidude, longitude and only one data variable (i.e. index values)
# read the netCDF files
    with xr.open_mfdataset('wet_tropics.nc') as wet:
    print(wet)

    Out[]:
    <xarray.Dataset>
    Dimensions:       (time: 1437, x: 24, y: 20)
    Coordinates:
      * y             (y) float64 -1.878e+06 -1.878e+06 -1.878e+06 -1.878e+06 ...
      * x             (x) float64 1.468e+06 1.468e+06 1.468e+06 1.468e+06 ...
      * time          (time) object '2013-03-29T00:22:28.500000000' ...
    Data variables:
        index_values  (time, y, x) float64 dask.array<shape=(1437, 20, 24), chunksize=(1437, 20, 24)>

So far, so good.
Now I need to apply a generalized additive model to each grid cell in the array. The model I want to use comes from Facebook Prophet (https://facebook.github.io/prophet/) and I have successfully applied it to a pandas array of data before. For example:
cns_ap['y'] = cns_ap['av_index']  # Prophet requires specific names 'y' and 'ds' for column names
cns_ap['ds'] = cns_ap['Date']
cns_ap['cap'] = 1
m1 = Prophet(weekly_seasonality=False,  # disables weekly_seasonality
             daily_seasonality=False,  # disables daily_seasonality
             growth='logistic',  # logistic because indices have a maximum
             yearly_seasonality=4,  # fourier transform. int between 1-10
             changepoint_prior_scale=0.5).fit(cns_ap)
future1 = m1.make_future_dataframe(periods=60,  # 5 year prediction
                                   freq='M',  # monthly predictions
                                   include_history=True)  # fits model to all historical data
future1['cap'] = 1  # sets cap at maximum index value
forecast1 = m1.predict(future1)
# m1.plot_components(forecast1, plot_cap=False);
# m1.plot(forecast1, plot_cap=False, ylabel='CNS index', xlabel='Year');

The problem is that now I have to
1)iterate through every cell of the netCDF file,
2)get all the values for that cell through time,
3)apply the GAM (using fbprophet), and then export and plot the results.
The question: do you have any ideas on how to loop through the raster, get the index_values of each pixel for all times so that i can run the GAM?
I think that a nested for loop would be feasible, although i dont know how to make one that goes through every cell.
Any help is appreciated


text:
Q: How to implement Azure B2C for an Angular Website hosted across multiple URIs We are trying to develop a new (Angular) website that uses Azure B2C for authentication. This website will connect to a .NET API.
The problem is that this website (single code base) will be hosted on more than 250 different URIs (each client has a unique URI). It is not feasible or possible to add all these different URIs as Redirect URIs on the Azure B2C app.
We have tried looking into things like implementing BFF (Backend for Front End Pattern), Server Side Rendering the website, and looked at the tonnes of Microsoft examples. However, we have no idea how to get around the need for Azure Redirect URIs, in a safe, secure way.
We toyed with the idea of creating a "proxy" layer (website?/api?) that would be the Azure Redirect URI for all websites, where it would then maybe pass the Access Token to the calling front end so it can add it to its HTTP header (bearer token) when calling the API. But there may be many issues with that idea, e.g. security, load balancing, 1 user belonging to multiple sites etc.
If there is anyone with any ideas to try or helpful links I should look up, that would be helpful.

A: •   An angular website can surely be hosted across multiple URIs when you use 'Webpack' internally to construct the build that is surely customizable as it is possible to extend the webpack configuration with something called 'Angular CLI builders'. Thus, considering that all the URIs on which you must host your website have different themes and a particular feature that is shared across all the sites. The minimum configuration for each site is considered as the requirement of a theme in particular, a domain/URI, list of all features and fetching some common domain-specific properties.
For the above purpose of fetching the required details from the API, the query should be as below: - 'GET /configuration?domain=www.xyz.com' and its response can be different based on the "domain" parameter you pass in the configuration as below: -
Response: -
 {
     "theme": "dark",
     "domain": {
     "uri": "www.xyz.com",
     "phone": 1234567890,
     "support": "eg@xyz.com"
 },
     "features": [
     "dashboard",
     "profile",
     "subscription"
   ]
 }

•   Thus, once retrieved, then store all the properties in an Angular state such that they are available across modules which can be achieved through 'NGRX Entity' which is a reactive state management tool for Angular. NGRX Entity is used to store a collection (mainly JavaScript objects) and is highly recommended when you want to share the data across modules / components. For more details regarding the configuration of themes from API configuration, kindly refer to the detailed multi-site setup as described in the below documentation link: -
https://medium.com/cactus-techblog/multi-site-architecture-in-angular-993a1984a539
Also, would suggest you to please try to build the website with reference to the other URIs as below: -
ng build --prod --base-href "/abc1/"

 ng build --prod --base-href "/abc2/" '

For more information, kindly refer to the below community forum link: -
How to run one angular app with two urls?


text:
Q: Conditional downcast from 'String' to 'String' always succeeds - Swift Error I'm trying to essentially do an valid check on a String in Swift, however I'm getting an error Conditional downcast from 'String' to 'String' always succeeds.
zipCode is created:
var zipCode = String()

Checking for a valid string at a later time:
if let code = zipCode as? String {
    println("valid")
}

Can someone help me understand what I'm doing wrong?

A: If zipCode can be "unset", then you need to declare it as an optional:
var zipCode: String?

This syntax (which is known as optional binding):
if let code = zipCode {
    print("valid")

    // use code here
}

is used for checking if an optional variable has a value, or if it is still unset (nil).  If zipCode is set, then code will be a constant of type String that you can use to safely access the contents of zipCode inside the if block.


text:
Q: CSS - Control Margin between  and
* I have a client that doesn't want any space between a paragraph and a list item. Is there a CSS way to control the margin between a <p> tag and a <li> tag?
Naturally I can add a class such paragraphs but in a CMS world that is not practical. I need some kind of
p + li { margin-top: 1px };

or something like that.

A: You could use jQuery (or another JS framework) to tweak it on page load.  Otherwise you'd have to wrap both elements in another element and select them in the CSS via that.  That's about your only options though.

A: How about li:first-child { margin-top:1px; }?

A: I think this space is caused by the <ul> tag and not the <li> tag. Does this work?
ul{
  margin-top:1px;
  margin-bottom:1px;
}

A: This ended up being somewhat problematic since this is a CMS environment. I am also working with a client that is not totally html savvy.
Turns out he was stripping the ul tags out of the lists which complicated the spacing issues.
My solution was to restore the ul tags and then do the following:
ul {margin-top: -10px;}

This effectively pulled the list up to the preceding paragraph and looks right.
Thanks for all the input.


text:
Q: Status bar app popover always on top when mission control is launched OSX I'm working on a status bar app for OSX and I'm trying to replicate the behaviour of the popover that Dropbox uses, so far I've managed to get all of the desired behaviour working except for the fact that when I open mission control the popover doesn't fade away, it simply stays on top covering part of mission control. I've searched quite hard the last few days and have yet to come up with a solution. The only thing I could think of perhaps doing would be to have a listener listening for an upwards 3 finger swipe? Getting the dropbox like popover behaviour has been a royal pain so I plan on uploading a sample app to GitHub once I get this all working to help save people some time trying to find workarounds! Has anyone encountered this issue? Cheers!
Here is the class with the logic for the popover "MenuBarController"
    #import "MenuBarController.h"
@implementation MenuBarController
@synthesize statusItem;
@synthesize popover;
@synthesize popoverTransiencyMonitor;
-(id)init{
    self.statusItem = [[NSStatusBar systemStatusBar]     statusItemWithLength:NSVariableStatusItemLength];
    self.popover = [NSPopover new];
    popover.behavior = NSPopoverBehaviorTransient;
    return self;
}

-(void)runMenuBarItem{
    // The text that will be shown in the menu bar
    statusItem.title = @"";

    // The image that will be shown in the menu bar, a 16x16 black png works best
    statusItem.image = [NSImage imageNamed:@"redicon"];

    [statusItem setEnabled:YES];
    [statusItem setHighlightMode:YES];
    [statusItem setTarget:self];
    [statusItem setAction:@selector(togglePopover:)];

}

- (void) showPopover:(id)sender {
    MenuBarPopOverViewController * viewController = [[MenuBarPopOverViewController alloc] initWithNibName:@"MenuBarPopOverViewController" bundle:nil];
    popover.contentViewController = viewController;
    [popover showRelativeToRect:NSZeroRect ofView:(NSView *)sender preferredEdge:NSMinYEdge];

}

- (void) closePopover:(id)sender {
    [popover performClose:sender];
}

-(void)togglePopover:(id)sender{
    if(popover.shown){
        [self closePopover:sender];
    }else{
        [self showPopover:sender];
    }
    if (self.popoverTransiencyMonitor == nil) {
        self.popoverTransiencyMonitor = [NSEvent addGlobalMonitorForEventsMatchingMask:(NSLeftMouseDownMask | NSRightMouseDownMask | NSKeyUpMask) handler:^(NSEvent* event) {
            [NSEvent removeMonitor:self.popoverTransiencyMonitor];
            self.popoverTransiencyMonitor = nil;
            [self.popover close];
        }];
    }
}
@end


text:
Q: How to enable reliability for one-way methods? The What You Need To Know About One-Way Calls, Callbacks, And Events article tells:

The fact that the client doesn't care about the result of the invocation does not mean the client doesn't care if the invocation took place at all. In general, you should turn on reliability for your services, even for one-way calls

I've tried to find how can I enable reliability, but didn't find anything meaningful.
Could you please help me:

*

*How to enable reliability?

*How to check if one-way method reached server?

Thanks a lot!

A: I'm going to assume you mean Message Reliability as described in "Programming WCF Services" by Juval Lowy - the author of your linked article (and consequently that quote appears, word for word, in the book too).
Reliability is only valid on certain bindings.  Take this TCP binding example.  In your configuration file:
<binding>
    <netTcpBinding>
        <binding name="MyTcpBinding">
            <reliableSession enabled="true" />
        </binding>
    </netTcpBinding>
</binding>

To check reliability I will quote the book (p. 66):

Message reliability does not guarantee
  message delivery.  All it provides is
  a guarantee that if the message does
  not reach its destination, the sender
  will know about it.

I've no idea how the sender will know, I've never encountered it, but hopefully it will give you some more insight to research the topic in more depth.
Further reading:
http://msdn.microsoft.com/en-us/library/ms733136.aspx

A: @Budda: that's right, you don't have to wait for an answer or acknowledgment immediately after sending every single message to the server. That would be synchronous operation. I believe you would use asynchronous operation: a message is sent and sometime later -- when the acknowledgment arrives from the server, or when the socket tells you the transmit failed -- you get control in your "callback" function to tell about the error, take the message off the queue, or whatever. That way, you avoid the big deal that you are rightly worried about. BUT now that I've jumped in with a possibly-confusing answer, I see that the whole question is around wcf, which I've never heard of till this very moment. So, if I've muddied the waters, I apologize. Perhaps there's asynchronous comm in wcf; in general, I'd think that's the way to go if it's possible. Maybe that's what "one-way comm" means.

A: Usually if you need OneWay operations and reliability, it is a good sign that you are building a queue based mechanism. Client puts message in queue, workers pick the messages and process them.
Maybe you could have a look at MSMQ and see if it can help you.
Most of the time, OneWay operations should not carry an important task or information because they are inherently not guaranteed to be processed by the server. The OneWay calls returns on the client side when the message has been routed by the dispatcher on the service side. After the dispatcher, you have no reliability whatsoever.


text:
Q: Grub kernel upgrade (two different systems) My system is partitioned this way:
hdda 500 giga (/dev/sda)
ssd 20 giga   (/dev/sdb)
/dev/sda
/boot(300 mega)
/home(remaining space)
(/dev/sdb)
/ (14 giga main system with ubuntu 14.04 x64)
/ (7  giga to test another O.S. versions , actually with ubuntu 14.04 )
swap (2 giga)
After install ubuntu 14.04 to (/dev/sdb) second partition(7 giga) i suppose grub has been replaced . The problem is even after upgrade kernel to last version using my main system ((/dev/sdb 14 giga)it doesn`t go automatically to last version after reboot  even choosing with grub customizer , just if reboot and go to second system installed and use grub customizer there

A: With two installs you have to normally do two updates. Whichever system's grub is in MBR must be booted and sudo update-grub run to find newer kernel in second install.
But since you have two drives, put main working install's grub into the MBR of sdb. And keep test install's grub in MBR of sda. When you install grub defaults to sda. Better to use Something Else and on partitioning screen change to MBR of same drive.
You can boot into install in sdb and install grub to the SSD's MBR. Then change BIOS to boot SSD.
sudo grub-install /dev/sdb
sudo update-grub

If you can only boot from sda, then just change /dev/sda.
But if you originally installed grub to sda, it remembers that setting for reinstall on major updates. So you also need to reset that:
To see what drive grub2 uses see this line (BIOS only, not UEFI)   - grub-pc/install_devices:
sudo debconf-show grub-pc

It will show drive model & serial number
to see drive info
sudo lshw -C Disk -short

to get grub2 to remember where to reinstall on updates:
sudo dpkg-reconfigure grub-pc

Enter thru first pages,spacebar to choose/unchoose drive, enter to accept, do not choose partitions
You can also avoid the double update by manually adding your own boot stanza in 40_custom and directly boot partition or link to most current kernel.
https://help.ubuntu.com/community/MaintenanceFreeCustomGrub2Screen
UEFI systems do not use grub-pc but grub-efi-amd64 if 64 bit or perhaps signed versions. So all of above is only for BIOS based systems.


text:
Q: Kivy button binding function with argument I am trying to learn how to create application in Kivy and I have problem with sending argument to the function. I want to send text from input to the function and print it. Can somebody tell me how can I do it ?
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button

class TutorialApp(App):
    def gratulation(self, *args):
        print args

    def build(self):
        boxLayout = BoxLayout(spacing=10,orientation='vertical')
        g = TextInput(text='Enter gratulation',
                      multiline=False,
                      font_size=20,
                      height=100)
        button = Button(text='Send')
        button.bind(on_press=self.gratulation)

        boxLayout.add_widget(g)
        boxLayout.add_widget(button)
        return boxLayout

if __name__ == "__main__":
    TutorialApp().run()

A: Yo must get the text from "g" and then send it to the button callback, there is 2 ways of doing this, by a lambda function, or calling your class method aplying to it.
Lambda Version:
from __future__ import print_function ##Need to import this for calling print inside lambda

def build(self):
    boxLayout = BoxLayout(spacing=10,orientation='vertical')
    g = TextInput(text='Enter gratulation',
                  multiline=False,
                  font_size=20,
                  height=100)
    button = Button(text='Send')
    buttoncallback = lambda:print(g.text)
    button.bind(on_press=buttoncallback)
    ...

The partial version:
from functools import partial ##import partial, wich allows to apply arguments to functions returning a funtion with that arguments by default.
def build(self):
    boxLayout = BoxLayout(spacing=10,orientation='vertical')
    g = TextInput(text='Enter gratulation',
                  multiline=False,
                  font_size=20,
                  height=100)
    button = Button(text='Send')
    buttoncallback = partial(self.gratulation, g.text)
    button.bind(on_press=buttoncallback)
    ...

A: One way to do it:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button

class TutorialApp(App):

    def gratulation(self, instance):
        print(self.g.text)

    def build(self):
        boxLayout = BoxLayout(spacing=10,orientation='vertical')
        self.g = TextInput(text='Enter gratulation',
                      multiline=False,
                      font_size=20,
                      height=100)
        button = Button(text='Send')
        button.bind(on_press=self.gratulation)

        boxLayout.add_widget(self.g)
        boxLayout.add_widget(button)
        return boxLayout

if __name__ == "__main__":
    TutorialApp().run()

Hope it helps!


text:
Q: Ldap Configuration Help from Linux We had a domain migration.
Since then, users are unable to login to our Mediawiki.
It seems that the first ldap binding is failing, hence the web users are unable to authenticate and login.
This is the Log output:
2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Entering validDomain

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a User is using a valid domain (my-domain).

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Setting domain as: my-domain

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Entering getCanonicalName

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Username is: WebLoginUser

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Entering validDomain

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a User is using a valid domain (my-domain).

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Entering Connect

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Using TLS or not using encryption.

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Using servers:  ldap://my-domain.com:389

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a PHP's LDAP connect method returned true (note, this does not imply it connected to the server).

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Entering getUserDN

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Doing a proxy bind

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Failed to bind as ADAdminUser

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Failed to bind

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Fetched username is not a string (check your hook code...). This message can be safely ignored if you do not have the SetUsernameAttributeFromLDAP hook defined.

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Munged username: WebLoginUser

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Entering getCanonicalName

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Username is: 172.xx.xx.xx

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Entering validDomain

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a User is using a valid domain (my-
domain).

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Entering Connect

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Using TLS or not using encryption.

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Using servers:  ldap://my-
domain.com:389

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a PHP's LDAP connect method returned true (note, this does not imply it connected to the server).

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Entering getUserDN

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Doing a proxy bind

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Failed to bind as ADAdminUser

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Failed to bind

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Fetched username is not a string (check your hook code...). This message can be safely ignored if you do not have the SetUsernameAttributeFromLDAP hook defined.

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Munged username: 172.xx.xx.xx

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Entering getCanonicalName

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Username is: 172.xx.xx.xx

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Entering validDomain

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a User is using a valid domain (my-
domain).

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Entering Connect

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Using TLS or not using encryption.

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Using servers:  ldap://my-domain.com:389

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a PHP's LDAP connect method returned
true (note, this does not imply it connected to the server).

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Entering getUserDN

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Doing a proxy bind

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Failed to bind as ADAdminUser

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Failed to bind

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Fetched username is not a string (check your hook code...). This message can be safely ignored if you do not have
the SetUsernameAttributeFromLDAP hook defined.

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Munged username: 172.xx.xx.xx

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Entering userExists

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Entering authenticate for username WebLoginUser

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Entering Connect

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Using TLS or not using encryption.

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Using servers:  ldap://my-
domain.com:389

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a PHP's LDAP connect method returned true (note, this does not imply it connected to the server).

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Entering getSearchString

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Doing a straight bind

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a userdn is: WebLoginUser

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Binding as the user

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Failed to bind as WebLoginUser

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Entering allowPasswordChange

2020-03-29 19:29:23 wiki wikidb-exa_: 2.0a Entering modifyUITemplate

This is the config:
require_once( "$IP/extensions/LdapAuthentication/LdapAuthentication.php" );

$wgAuth = new LdapAuthenticationPlugin();

$wgLDAPDebug = 3;

$wgLDAPDomainNames = array( 'my-domain');

$wgLDAPServerNames = array( 'my-domain' => 'my-domain.com',);

$wgLDAPSearchStrings = array('my-domain' => 'USER-NAME',);

$wgLDAPEncryptionType = array( 'my-domain' => 'clear',);

$wgLDAPBaseDNs = array( 'my-domain' => 'CN=Users,DC=my-domain,DC=com');

$wgLDAPSearchAttributes = array( 'my-domain' => 'sAMAccountName');

$wgLDAPProxyAgent =  array( 'my-domain' => "ADAdminUser");

$wgLDAPProxyAgentPassword = array( 'my-domain' => "********");

$wgLDAPUpdateLDAP = array('my-domain'=>false);

$wgLDAPAddLDAPUsers = array('my-domain'=>false);

$wgLDAPPreferences = array( 'my-domain' => true );
$wgDebugLogGroups["ldap"] = "/tmp/debug_ldap.log";

Testing LDAP connection and query with this command, returned the expected result:
ldapsearch -x -D "CN=ADAdminUser,CN=Users,DC=my-domain,DC=com" -W -h my-domain.com -b "CN=saWebLoginUserarn,CN=Users,DC=my-domain,DC=com"

What in my configuration is wrong?


text:
Q: Como fazer upload de uma imagem, porém salvá-la com o nome baseado em dados do cliente? Gostaria que o usuário fizesse o upload da foto dele, porém ao salvar, gostaria que ela fosse salva com o nome igual ao CPF do cliente.
Hoje eu consigo salvar a imagem em uma pasta, mas ela vem com o nome dado pelo cliente.
PHP que salva a imagem na pasta destino que escolhi:
<?php
$cpf   = $_SESSION['cpf'];

$nome_temporario=$_FILES["Arquivo"]["tmp_name"];
$nome_real=$_FILES["Arquivo"]["name"];
copy($nome_temporario,"imagens/$nome_real");
?>

HTML da página:
<form action="envia_arquivo.php" method="post" enctype="multipart/form-data">

    <input name="Arquivo" id='arquivo' type='file' required accept="image/*">
    <button class="botao1" type="submit" value="Continuar">Continuar</button>

</form>

Já procurei em tudo quanto é canto e não acho uma forma em PHP que funcione, a maioria que tentei não enviava a foto para a pasta.

A: copy($nome_temporario,"imagens/$cpf");
Sendo $cpf uma variavel que voce precisa declarar e setar antes, ai esse valor pode vir de onde quiser , banco, do prorio form, da sessao etc....

A: Você pode mudar o nome da imagem na hora de mover ela para o servidor.
$temp = explode(".", $_FILES['Arquivo']['name']); //Usado para pegar a extensão da imagem

$novo_nome = $_SESSION['CPF'].".".end($temp); //concatena o a variavel do novo nome com a extensão da imagem cpf+.+extensão

if(move_uploaded_file($_FILES['Arquivo']['tmp_name'], "imagem/".$novo_nome)){
     //código caso upload tenha sucesso
 }


text:
Q: Can't pass relative img src route in React + Webpack I can't dynamically pass relative img src route in React + Webpack with this.props.
This is a very simplified part of the parent component. It iterates some data list and generates ImgComponents passing props. Here is only tiny part of it:
return (

        <ImgComponent srcProp={videolist.anotherImage.src} />

    );

The ImgComponent  has:
render() {
    return (

          <img src={`${this.props.srcProp}`} />

    );
  }

In console I get exactly the same route as i pass with this.props.srcProp, but it would not find the folder and the img there. As if webpack does not load the img.
Here is the console:

No matter what route i indicate, the img is never found in the folder.
Here is the webpack config for png:
{ test: /\.png$/, loader: "url-loader?mimetype=image/png" }

BTW. It works fine if i require the file, like:

or indicate some remote route, like http://route.to.some.img
Seems like webpack does not load it. What should i do to dynamically load local img files by dynamically passing src with {this.props.src} ? As I can see, the loader loads img fine if i indicate the file with require. But this way i cannot do it dynamically, as require does not take variables.

A: What I managed to do is to require('../../assets/images/myFirst.img') in the object, containing the routs to the locally stored files:
in    playlist.js
export default (
  {
    cartoons: [{
        images: {
        poster: require('../../assets/images/myFirst.png')
      },
      streams: [{
        type: 'mp4',
        url: 'http://media.w3.org/2010/05/bunny/movie.mp4'
      }]
    });

Then I work with this list as with any object:
import playlist from '../../playlist';

and iterate this object in a usual manner. The image will be there.

A: Webpack will not traverse your code to find and convert all possible references to files.
Consider following code:

It is your responsibility (perhaps using a build target) to ensure that baz.jpg is copied into the foo/bar directory under your web app root.


text:
Q: Visual Studio code sidebar Vertical guideline (customize sidebar) Does anybody know an extension for Visual Studio code to show a vertical guideline on sidebar (for file and folders) like netbeans?
Or maybe have some settings in vscode?
Netbeans Snapshot
Thanks for your help.

A: And in v1.36 tree indent guides are implemented, see release notes, tree indent guides.
Plus, you can change their color with this colorCustomiztion:
"tree.indentGuidesStroke": "#ff0000"

A: You can add guidelines with:
"workbench.tree.renderIndentGuides": "always", // Can also be set to "onHover"

You can also change their color with:
"workbench.colorCustomizations": {
    "tree.indentGuidesStroke": "#008070"
},

And if you want to change the indentation width, you can use:
"workbench.tree.indent": 18,

A: It's still not available. I assume you have problem with navigation through this tree when it comes about projects with complex directory structure (for me it's very, very annoying).
Right now I'm using extension seti-cons. It doesn't create vertical line, but adds icons for folders etc. what helps a little bit :)
Here, how it looks like on example project:

It's not perfect, but always something.

A: I bring up on GitHub. see that:
Visual Studio code sidebar Vertical guideline (customize sidebar)
and other Issue
Directory tree indent guides in File Explorer


text:
Q: Use keyboard drawables I'm working on a layout that looks like a numeric keyboard.
I was looking around in my folder:

C:\Program Files\Android\platforms\android-8\data\res\drawable-mdpi

And I found some drawables like sym_keyboard_feedback_ok or sym_keyboard_num(1-9) that I could use :)

But when I type

android.R.drawable.

There are no drawables that start with sym_keyboard..
How can I access those drawables without copying them manually to my resource folder ?

A: Well, I was looking for the same thing but then I realized that all R.drawables are not accessible. If you look at the android.R.drawable reference you will not found those items that you are looking for. Also this sample shows all accessible drawables in a list which might be useful.
In the given sample, there is a for loop, if you change the loop's interval in the following way you might found those items (in my case, I see drawables that start with sym_keyboard):
for (int idx = 17301504; idx <= 17303380; idx++) {
        data = new HashMap<String, Object>();
        try {
            String stg = Resources.getSystem().getResourceName(idx);
            data.put("line1", stg);
            data.put("line2", idx);
            data.put("img", idx);
            resourceNames.add(data);
        }
        catch (Resources.NotFoundException nfe) {
        }
    }

At the end, this approach is not suggested because the drawable references might be different in different APIs so I was forced to copy my favorite drawables to the project and use them as regular drawables.


text:
Q: Задать имя файла при использование WriteXML Доброе время суток,сообщество! Подскажите,как добавить переменную в путь при использование метода WriteXML ? Хочу чтобы было вида :
    string name = DateTime.Today.ToString();
    sRDataSet.WriteXml("C:/sanbak/name.xml");

A: Метод WriteXML, в принципе, не причем. Путь передается в виде строки, а в строках можно делать конкатенацию, в том числе с переменными:
string myValue = "Hello, world";
Console.WriteLine("Текст из переменно myValue: " + myValue);

Соответственно строка будет в вашем случае:
string name = DateTime.Today.ToString();
sRDataSet.WriteXml("C:/sanbak/" + name + ".xml");

Только не забудьте подформатировать дату в том виде, какой вас интересует.
Потому, что в сыром виде, т.е. когда пишите DateTime.Today.ToString(); или DateTime.Now.ToString(); и т.д. - дата будет иметь вид 6/18/2016 5:07:03 PM/AM. Как видим оно будет иметь слэши, а также двоеточия, которые недопустимы в имени файла. Из-за этого будут вываливаться ошибки, что Данный формат пути не поддерживается.
Значит нужно принудительно привести к корректному формату.
Например:
string name = DateTime.Today.ToString("d-MM-yyyy");

Чтоб был формат день-месяц-год
Или посложнее
string name = DateTime.Now.ToString("dd.MM.yyyy HH'h'mm'm'ss's'");

Выведет что-то типа: 19.06.2016 10h23m38s

Какие форматы есть - можно смотреть прям на MSDN, к примеру
https://msdn.microsoft.com/ru-ru/library/zdtaw1bw(v=vs.110).aspx
https://msdn.microsoft.com/ru-ru/library/az4se3k1(v=vs.110).aspx
Или еще где


text:
Q: Bash script optimisation This is the script in question:
for file in `ls products`
do
  echo -n `cat products/$file \
  | grep '<td>.*</td>' | grep -v 'img' | grep -v 'href' | grep -v 'input' \
  | head -1  | sed -e 's/^ *<td>//g' -e 's/<.*//g'`
done

I'm going to run it on 50000+ files, which would take about 12 hours with this script.
The algorithm is as follows:

*

*Find only lines containing table cells (<td>) that do not contain any of 'img', 'href', or 'input'.

*Select the first of them, then extract the data between the  tags.

The usual bash text filters (sed, grep, awk, etc.) are available, as well as perl.

A: Looks like that can all be replace by one gawk command:
gawk '
    /<td>.*<\/td>/ && !(/img/ || /href/ || /input/) {
        sub(/^ *<td>/,""); sub(/<.*/,"")
        print
        nextfile
    }
' products/*

This uses the gawk extension nextfile.
If the wildcard expansion is too big, then
find products -type f -print | xargs gawk '...'

A: Here's some quick perl to do the whole thing that should be alot faster.
#!/usr/bin/perl

process_files($ARGV[0]);

# process each file in the supplied directory
sub process_files($)
{
  my $dirpath = shift;
  my $dh;
  opendir($dh, $dirpath) or die "Cant readdir $dirpath. $!";
  # get a list of files
  my @files;
  do {
    @files = readdir($dh);
    foreach my $ent ( @files ){
      if ( -f "$dirpath/$ent" ){
        get_first_text_cell("$dirpath/$ent");
      }
    }
  } while ($#files > 0);
  closedir($dh);
}

# return the content of the first html table cell
# that does not contain img,href or input tags
sub get_first_text_cell($)
{
  my $filename = shift;
  my $fh;
  open($fh,"<$filename") or die "Cant open $filename. $!";
  my $found = 0;
  while ( ( my $line = <$fh> ) && ( $found == 0 ) ){
    ## capture html and text inside a table cell
    if ( $line =~ /<td>([&;\d\w\s"'<>]+)<\/td>/i ){
      my $cell = $1;

      ## omit anything with the following tags
      if ( $cell !~ /<(img|href|input)/ ){
        $found++;
        print "$cell\n";
      }
    }
  }
  close($fh);
}

Simply invoke it by passing the directory to be searched as the first argument:
$ perl parse.pl /html/documents/

A: What about this (should be much faster and clearer):
for file in products/*; do
    grep -P -o '(?<=<td>).*(?=<\/td>)' $file | grep -vP -m 1 '(img|input|href)'
done

*

*the for will look to every file in products. See the difference with your syntax.

*the first grep will output just the text between <td> and </td> without those tags for every cell as long as each cell is in a single line.

*finally the second grep will output just the first line (which is what I believe you wanted to achieve with that head -1)  of those lines which doesn't contain img, href or input (and will exit right then reducing the overall time allowing to process the next file faster)

I would have loved to use just a single grep, but then the regex will be really awful. :-)
Disclaimer: of course I haven't tested it


text:
Q: How to install Tomcat on Windows XP? I'm having trouble installing Tomcat on my windows XP machine. I already have Apache and JDK 6 installed, what I need to know is:

*

*Which file to download from the Lastest Tomcat download page

*And how to install it so I can run the sample web app by going to http://localhost/
In my C:\Program Files\Java folder, I see the following folders, this should give you an idea of whether I need any additional stuff installed:

*

*jdk1.6.0_10

*jre1.6.0_04

*jre1.6.0_06

*jre1.6.0_07

*jre6

Thanks.

A: Tomcat 6 doesn't really need the full JDK and it runs with Java 1.5 as well, so Java wise you should be well off. Just make sure that JAVA_HOME environment variable is set.
You can either get the core zip or tar.gz file, or the Windows Service installer file.
Core zip file:
http://www.apache.org/dist/tomcat/tomcat-6/v6.0.18/bin/apache-tomcat-6.0.18.zip
Just unzip it and run bin/startup.bat. If you'd like to install it as a Windows service (and get the "usual" program entry in Windows add/remove programs) you can get the Windows Service Installer file instead:
http://www.apache.org/dist/tomcat/tomcat-6/v6.0.18/bin/apache-tomcat-6.0.18.exe
By default tomcat listens to port 8080, so to check out the sample apps you need to go to http://localhost:8080/examples/. You can change the default port by editing server.xml in the conf directory.

A: I'm not sure what that URL is that you provided ("CGI" seems strange from a J2EE site), but the download links for tomcat are on its home page: http://tomcat.apache.org/
You should probably download version 6, particularly if you're using it for personal development. The older versions are available and maintained primarily to support users who don't want to migrate J2EE versions.
Finally: unless you are already using Apache, don't bother with it. Most commercial sites use Apache as a front-end because of its configurability (particularly URL rewriting). If you're just looking to develop web apps, Tomcat will act as web server in addition to servlet/JSP container.
Installation instructions (as well as all other instructions) are here:http://tomcat.apache.org/tomcat-6.0-doc/index.html
If you haven't done any J2EE development before, you'll need some docs on it. The Sun Tutorial is OK, but targeted to the Sun app-server and covers a lot of XML that isn't really necessary. Look at the intro chapters on web apps, then jump to chapter 11: http://java.sun.com/j2ee/1.4/docs/tutorial/doc/index.html

A: From the download page you should download the "Windows Service Installer" package.
As for the rest of the install process, follow just "Step 3: install Tomcat" described in the following page:
http://mircwiki.rsna.org/index.php?title=New_Installation_Instructions

A: Not a complete answer, but an add-on (how does Stack Overflow handle this?):
For a Windows (XP, Vista, 7) install, you can choose (from the options listed at http://tomcat.apache.org/download-60.cgi):

*

*.zip (pick according to your Windows version)

*Windows Service Installer

Now the difference between the top two options:

*

*.zip -- This is a manual install, where you extract the .zip and move it into whatever folder you wish. It does not install Tomcat as a service. It does not "do" anything unless you manually do something with it or have another program use it. It is a manual setup.

*Windows Service Installer -- This is a self-installer, just run the .exe. It installs Tomcat as a Windows Service, which if you load up your Windows services (run "services.msc"), you'll see it listed as "Apache Tomcat 6.0 Tomcat6". During the install it will ask you certain setup questions like.

If you choose "Windows Service Installer", here are the default settings the install will ask you:

*

*Type of install: Normal

*Server Shutdown Port: 8005

*HTTP/1.1 Connector Port: 8080

*AJP/1.3 Connector Port: 8009

*Windows Service Name: Tomcat6

*Create shortcuts for all users: disabled (not that this matters if it's your machine)

*Tomcat Administration Login - User Name: blank

*Tomcat Administration Login - Password: blank

*Tomcat Administration Login - Roles: manager-gui

*Path of a Java SE 5.0 or later JRE installed on your system: C:\Program Files\Java\jre7 (if you are running Java SE 7)

*Destination (install) folder: C:\Program Files\Apache Software Foundation\Tomcat 6.0

Hope this helps.


text:
Q: Custom macOS-like character shortcuts in Linux I would like to make combination Alt-x to input symbol × (U+00D7).
It should be implemented at level as low as possible: using X11 utilities is good, using KDE/Gnome utilities is bad.
It must not interfere with keyboard layout and work with every one of them.
It must behave exactly as I described in first line.
Using compose key to input Alt, then x and x is not a solution.
I achieved some progress with xmodmap, however I do not know if it is a dead end or not:
xmodmap -e 'keycode 53 = x X U00D7 U00D7' does the trick, but interferes with keyboard layout. In fact it overrides it.
xmodmap -e 'keycode 53 = x X ч Ч U00D7 U00D7 breaks layout too. Archlinux wiki says that it defines symbols for AltGr modifier (and no clue how to bind it to Alt). Manual does not say anything about 5th and 6th entries at all.


text: Q: Script that automatically closes one program after I manually close another program in Windows I need help making a simple script that automatically closes one program after I manually close another program in Windows. For example if I close Battlefield V I want Origin to automatically close after I manually close Battlefield V from inside the game. I want to make a simple batch or power shell script. Would I need to use Task Schedule to do this? Thank you, Jack.


text:
Q: How to add videos to index page? I need to add videos to my single page Wordpress website. I've been looking at some plugins for this but all of these only allow adding videos to posts or pages. Since I'm only using the index.php I don't know how to add a video there.. And I would prefer not to use embedded videos from Youtube, Vimeo etc.
Anyone who can help me?

A: @andreas Could you please explain better what you are trying to achieve?
if is only a video in your template you can use something like this..
<object width="425" height="344"><param name="movie" value="http://www.mydomain.com/myvideo.mov"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param>
<embed src="http://www.mydomain.com/myvideo.mov" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object>


text:
Q: To delete the "del" action in Opportunity for the Quote related list Can anyone plz tell how the below can be done ?
I want to remove the "del" option from the below in the Opp object. removing possibility of entire Action column also would be OK. thanks

A: As you need edit option its not possible to update the setting in permission.
Best way is to create custom vf with edit (re-direct) as related list and put a trigger check to prevent from delete.

A: You can create a new VF page which suits your requirement and add that vf page as an inline page in the detail page


text:
Q: Adding the current date as selected within custom widget I have created a custom widget that will hold Date + Time with a select option.
Now each Month, day, year, hours and minutes have its own select box.
I have tried many different ways to get these select boxes to automatically have the days date and current time within them. Is this Evan possible with the way i have wrote the custom widget?
Bellow is the class to initialise the form,
from widgets import SelectDateTimeWidget
class CreateEvent(forms.ModelForm):
    class Meta:
        model = Event
        fields = ['title', 'start', 'end', 'description', 'category']
        widgets = {

            'start': SelectDateTimeWidget(date_format= '%d/%m/%Y'),
            'end': SelectDateTimeWidget(date_format= '%d/%m/%Y')
        }

The custom widget(holds another custom widget):
class SelectDateTimeWidget(forms.MultiWidget):
    supports_microseconds = False

    def __init__(self, attrs=None, date_format=None, time_format=None):
        widgets = (SelectDateWidget(empty_label=( "Year", "Month", "Day")),
                   SelectTimeWidget(use_seconds=False))
        super(SelectDateTimeWidget, self).__init__(widgets, attrs)

    def decompress(self, value):
        if value:
            value = to_current_timezone(value)
            return [value.date(), value.time().replace(microsecond=0)]
        return [None, None]

    def subwidgets(self, name, value, attrs=None):
        if self.is_localized:
            for widget in self.widgets:
                widget.is_localized = self.is_localized
        # value is a list of values, each corresponding to a widget
        # in self.widgets.
        if not isinstance(value, list):
            value = self.decompress(value)
        output = []
        final_attrs = self.build_attrs(attrs)
        id_ = final_attrs.get('id')
        for i, widget in enumerate(self.widgets):
            try:
                widget_value = value[i]
            except IndexError:
                widget_value = None
            if id_:
                final_attrs = dict(final_attrs, id='%s_%s' % (id_, i))
            output.append(widget.render(name + '_%s' % i, widget_value, final_attrs))
        return output

Is there anyway i can set the the value to the current date?
Thanks J

A: From Django docs:

A widget is Django's representation of an HTML input element.The widget handles the rendering of the HTML, and the extraction of data from a GET/POST dictionary that corresponds to the widget.

So, adding a default value, like current date is not widget's purpose. It's what form fields are for. If you want to add a default value to your form then it's better to do it via form field, like this:
your_field = forms.DateField(initial=datetime.date.today)
# in case of modelForm, just override the fields you need.

or when you initialise the form
form = CreateEvent(
    initial={'start': datetime.datetime.now, 'end': datetime.datetime.now}
)

Related docs: providing initial values to form field and providing initial values to modelForm


text:
Q: Remove files of certain type, retain directory tree I'm trying to move a bunch of .doc and .xls files, which are stored in a bunch of folders and subfolders, to a new location. I previously tried cp -r **/{*.doc,*.xls} /wherever/you/want/, which worked except that it didn't retain the directory tree faster.
Question: Is there a command/set of commands to purge all files except for .doc and .xls in a folder and its subfolders, yet retain directory tree structure?
And better yet, is there a command to remove empty folders, so I don't have to go through afterwards and manually delete empty folders?

A: You can use the find command. These commands are meant to be run from inside the directory where your .xls and .doc files (and other directories) are kept. DO NOT run this on your home directory!
The easiest way to do it is deleting all non-xls and non-doc files (CAREFUL, this command will delete all other files):
find ./ -type f -not -name "*.xls" -and -not -name "*.doc" -exec rm {} \;

Then you can use this to find and delete empty directories. To avoid using a potentially very destructive rm -rf, this deletes one level at a time, you may have to run it several times to delete all empty directories:
find ./ -type d -empty -exec rmdir {} \;

See this question for more details on what find does and how to use it.

A: This should do it all at once:
find path/to/dir '!' -iname "*.doc" '!' -iname "*.xls" -empty -delete

(Except your folders have extensions like .xls or doc...)
Replace -delete with -print to see what gets deleted first.

A: This requires some fairly fancy rsync syntax, but it can be done:
rsync -r --filter="+ */" --filter="+ **/*.xls" --filter="+ **/*.doc" --filter="- **" --prune-empty-dirs /path/to/source/ /path/to/target/

Demonstration:
me@banshee:/tmp$ find source
source
source/1.xls
source/1
source/1/2
source/1/2/2.xls
source/1/1.doc
source/lol.crapfile

me@banshee:/tmp$ find target
target

me@banshee:/tmp$ rsync -r --filter="+ */" --filter="+ **/*.xls" --filter="+ **/*.doc" --filter="- **" --prune-empty-dirs source/ target/

me@banshee:/tmp$ find target
target
target/1.xls
target/1
target/1/2
target/1/2/2.xls
target/1/1.doc


text:
Q: Python algorithm with numpy I want to group in a 2D array (couples) to see the family:
rij = [[11, 2], [15, 6], [7, 8], [3, 6], [9, 2], [2, 3], [2, 3]]
rij = np.sort(rij, axis=1) #sort inside array
rij = np.unique(rij, axis=0) #remove duplicates

After this code I get this:
[[ 2  3]
 [ 2  9]
 [ 2 11]
 [ 3  6]
 [ 6 15]
 [ 7  8]
 [ 7  20]]

This is where I get stuck, I need to loop through and see if the number already exists.
Expected result (the family) would be:
[2, 3, 6, 9, 11, 15]
[7, 8, 20]

Nice to have would be that I could add the degree, family in 2nd degree.
[2, 3, 9, 11]
[6, 15]
[7, 8, 20]

family in 3rd degree.
[2, 3, 6, 9, 11, 15]
[7, 8, 20]

family in last degree. (same as previous in this example)
[2, 3, 6, 9, 11, 15]
[7, 8, 20]

A: We can solve this using scipy's sparse matrix and graph module. Your rij forms an adjacency matrix. That is a matrix that is 1 if two nodes are connected and 0 if not. From this, we can compute other properties.
Let's apply this to your problem. We start by cleaning up your input. As @Ali_Sh noted, there is an inconsistency in your example. The first list of rij has different elements than the sorted and unique array below. I ignore the first line and start with the sorted unique version.
import numpy as np

pairings = ((2, 3), (2, 9), (2, 11), (3, 6), (6, 15), (7, 8), (7, 20))
pairings = np.array(pairings)

The IDs are not consecutive. This will waste resources further down so let's compress our range. The index will be the graph node. The value at the index is the original ID in pairings. We can use this as a lookup table. For the inverse mapping I use a simple dictionary.
node_to_id = np.unique(np.sort(np.ravel(pairings)))
id_to_node = {id_: node for node, id_ in enumerate(node_to_id)}

Now we build a sparse adjacency matrix. A node i is connected to node j if matrix[i, j] is true. Since our "family" relationship is undirected (if i is related to j, then j is always related to i), we build a symmetric matrix.
Scipy claims that directed graph algorithms with symmetric matrices are faster. So this allows us to do just that.
The graph algorithms need CSR format (compressed sparse row). We start with DOK format (dictionary of keys) and convert afterwards because it is easier to build. Since our input is sorted, LIL format (list of lists) may be faster but DOK has better worst-case performance in case we don't sort beforehand.
from scipy import sparse

n_nodes = len(node_to_id)
dok_mat = sparse.dok_matrix((n_nodes, n_nodes), dtype=bool)
for left, right in pairings:
    row, col  = id_to_node[left], id_to_node[right]
    dok_mat[row, col] = True
    dok_mat[col, row] = True # undirected graph
csr_mat = dok_mat.tocsr()
del dok_mat

Connected components gives us our families. For each row in the matrix, we get an integer label that marks its component.
import collections
from scipy.sparse import csgraph

_, components = csgraph.connected_components(csr_mat)
families = collections.defaultdict(list)
for id_, component in zip(node_to_id, components):
    families[component].append(id_)
print("families", list(families.values()))

The shortest path gives the number of hops, i.e. the distance in relationship. Unrelated nodes have infinite distance.
shortest_paths = csgraph.shortest_path(csr_mat)
maxdist = 2.
for id_, row in zip(node_to_id, shortest_paths):
    immediate_family = node_to_id[row <= maxdist]
    print(id_, immediate_family)

The output will be
families [[2, 3, 6, 9, 11, 15], [7, 8, 20]]
2 [ 2  3  6  9 11]
3 [ 2  3  6  9 11 15]
6 [ 2  3  6 15]
7 [ 7  8 20]
8 [ 7  8 20]
9 [ 2  3  9 11]
11 [ 2  3  9 11]
15 [ 3  6 15]
20 [ 7  8 20]


text:
Q: UITableView with UITableViews as children? Our designers gave us a design where the home page of our app is collection of different views scrollable vertically.
Some are images, others are custom sliders and then there are two (dynamic) lists, meaning that we need to create a UITableView that contains two more UITableViews as two of its cells.
We've managed to achieve that by making the child TableViews expanded (full heigth), so the parent cell knows what height to get. However, the child TableView's cells are not being reused, since the view controlelr does not know when to reuse the child cells, and they all get allocated when the TableView gets allocated, resulting in poor performance.
Is there a better way of achieving the "scrollable list of objects that contains lists of other objects" design? Can the child cells be reused?
We've also thought of using a UICollectionView as the parent "scrollable list" container, but the child cell reusability problem is still there. Any ideas are greatly appreciated.


text:
Q: Swift add subview within function I am attempting to display a loading subview when a button is pressed. I am not sure why but the subview only appears when the alert view is displayed. I would like to have the loading screen displayed as soon as the function begins.
What is causing this and how would I rectify it?
 @IBAction func registerManual(_ sender: Any) {

        // Check the validity of the inputs
        let isValid = manualRegistration().validate(firstName: "\(String(describing: firstName.text!))", lastName: "\(String(describing: lastName.text!))", email: "\(String(describing: email.text!))", password: "\(String(describing: password.text!))", dob: dobSelected)

        if(isValid == "success"){
            let loadingScreen = xibLoad().loadingScreen()
            loadingScreen.frame.size.height = view.frame.height
            loadingScreen.tag = 100
            view.addSubview(loadingScreen)

            // Submit to backend.
            let params = "firstname=\(escpae().url(string: firstName.text!))&lastname=\(escpae().url(string:lastName.text!))&email=\(escpae().url(string:email.text!))&dob=\(escpae().url(string: selectedDateText.text!))&password=\(escpae().url(string:password.text!))&currency=\(currency)&language=\(language)&region=\(region)"

            let resultArray = serverCall().post(endPoint: "registermanual.php?", params: "\(params)", fromViewController: self)

            if(resultArray.count > 0 && resultArray[0]["error"] == nil){
                self.defaults.set("\(resultArray[0]["token"]!)", forKey: "token")
                DispatchQueue.main.async {
                self.performSegue(withIdentifier:"goLoading", sender: self)
                }
            }
            if(resultArray.count > 0 && resultArray[0]["error"] != nil){
                alert().show(title: "ERROR", message: "\(resultArray[0]["error"]!)", button: "OK", viewc: self)
            }
        }else{
            alert().show(title: "Oops!", message: "\(isValid)", button: "OK", viewc: self)
        }
    }

Loading Screen:
class loadingScreen: UIView {

    @IBOutlet weak var gifView: UIImageView!

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        //custom logic goes here
         gifView.loadGif(name: "loading")
    }

}

A: You can try this , it would be a matter of milli seconds [ depending in validation time ] even if you add the subview out of the if statement , but it will prevent any user event
@IBAction func registerManual(_ sender: Any) {

   loadingScreen.frame.size.height = view.frame.height
   loadingScreen.tag = 100
   view.addSubview(loadingScreen)
   // view.layoutSubviews() don't call it directly

    // Check the validity of the inputs
    let isValid = manualRegistration().validate(firstName: "\(String(describing: firstName.text!))", lastName: "\(String(describing: lastName.text!))", email: "\(String(describing: email.text!))", password: "\(String(describing: password.text!))", dob: dobSelected)
    if(isValid == "success"){


text:
Q: How can I assign a value to a an integer when a certain character appears in an array? Given String[] c
I am trying to make it so that if "X" is present in the array 10 is added to int xvalue. Otherwise something else happens.
This is what I have tried so far I am not sure what exactly is going wrong.
if (i==c.length - 1 && !c[i].contains("X") )
  sum += 0 ;
else if (c[i].contains("X"))
xvalue+=10;
else
  sum += (Integer.parseInt(c[i])*pos) ;

Also the "X" is only ever present in the last value of the array.
Thanks for the help.

A: Don't know your actual logic make it simple
if (c[i].contains("X") )
xvalue+=10
else
sum += (Integer.parseInt(c[i])*pos)

Whats value is printing? Assuming i is a loop value..
Edit: It will check if the value X or not then add 10 value, if its other value its escape...
public void xCheck(String c[]){
    int sum = 0;
    int xValue = 0;
    int pos = 1;
    for (int i = c.length - 1; i >= 0; i--) {
        if (c[i].contains("X")) {
            xValue += 10;

        } else if (pos == 1) {
            pos++;
            continue;
        } else {
            //if(sum==0)
            sum += pos * (Integer.parseInt(c[i]));
        }
        pos++;
    }
    System.out.println(xValue);
    System.out.println(sum);
}


text:
Q: JAVA- package ArcadeCounter does not exist Please help me with the code for Java provided..
Whenever I try to compile, it gives me an error stating: "package ArcadeCounter does not exist"..
What does it mean by that?
I've tried what it says on the other sites but they don't seem to work either.
    import ArcadeCounter.java;

    /*TokenDispenser has 4 methods:
    •   addTokens() – adds a given number of tokens to the dispenser
    •   getTokensSold() – returns the number of tokens sold
    •   getCash() – returns the amount collected so far
    •   dispense() – dispenses tokens, given the cash amount*/

    public class TokenDispenser
    {
        // Declare your attributes here
    private int tokens = 0;
        private int tokensSold = 0;
        private double cash = 0.0;

        public void addTokens( int num )
        {
            tokens += num;
        }

        public int getTokensSold()
        {
            return tokensSold;
        }

        public double getCash()
        {
            return cash;
        }

        public void dispense( double amt )
        {
        if (amt < 30.00)
            {
                System.out.println( "Sorry, not enough cash."+amt );
            }
            else
            {
                if (tokens < 15)
                {
                    System.out.println( "Not enough tokens" );
                }
                else
                {
                    cash += 30;
                    tokensSold += 15;
                    tokens -= 15;
                    if (amt > 30)
                    {
                        System.out.println( "Change: " + (amt-30) );
                    }
                }
            }
        }
    }

A: It means that there's no directory on the class path (including inside any jar files on the class path) named ArcadeCounter. The way you've written your import, that's what the compiler is looking for. The argument to import is the name of a class, including its package name. The compiler thinks ArcadeCounter is the package, and java is the class name.
It seems likely you have a class named ArcadeCounter which is not placed in a package; in that case, the import statement is not only unnecessary but invalid, so remove it; if ArcadeCounter.java is in the current directory, the compiler will find it.
Despite what several commenters have said, it is not legal to say
import ArcadeCounter;

Check the Java Language Specification:

It is a compile time error to import a type from the unnamed package.


text:
Q: Is it possible to change the entire array element in JavaScript to number type? Ex)
const a = ['1' , '2' , '3']

When there is an array called ,
is there a way to change it all at once without looping?
i want result [1,2,3]

A: Kind of, but not really.
The best approach is likely to do an array map as such:
const a = ['1' , '2' , '3'];
const b = a.map(function(i) {return Number(i);});

The advantage to mapping is that it theoretically can be done in parallel instead of sequentially. However, JavaScript's particular implementation doesn't really allow for this because JS uses a single thread and a scheduler instead of a truly multi-threaded approach.
However, using mapping is a cleaner and better approach because if some day JavaScript implements multithreading, the map() method could theoretically be changed to go multithreaded. If that was ever done, your code would already benefit from that (very unlikely) change.

A: There is a way possible.
Read more about Array.map() here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
It's very simple. You just have to do this:-
a.map(strN => (!isNaN(strN)) ? Number(strN) : strN)

*Notice: This will return the same value if the string isn't a number.


text:
Q: Which Ubuntu is oriented to programming and robotics? server, desktop or other distro? Well, rather than a question is an opinion from you, it goes well,
What version of ubuntu is better oriented programming to robotics or anything related to programming languages (like C, perl, c + +, java, etc..?) I have read on other forums that say Ubuntu (desktop) is unstable , EYE I mean when you start playing the system configuration files and goes crazy.
Also not sure if ubuntu server is most convenient for programming, robotics and stuff or if other distros are better for it as mint, fedora, suse, or debian arch, and then based on their experience and knowledge I would like to give their opinions regarding this.
Greetings (:

A: There "under the hood" difference between ubuntu flavours is very minor. All flavors use the same archive (use the same packages). Each flavor is basically just a set of default installed packages. You can install all flavors concurrently, or switch between them, by adding and removing packages.
So, no, there's no good reason to install "Ubuntu Server" if you are intending to use the machine as a desktop, and vice-versa.

A: For robotics you would be interested in installing ROS (Robot Operating System). As pointed out, there isn't a big difference between Desktop and Server besides the default packages. Since Desktop is geared to GUI-based applications, it would be better for running robot simulations.

A: As the other poster said, all of the linux "flavors" are very similar at the core. Some, like puppy linux, are small enough to boot straight from a flash drive, and others, such as ubuntu, offer what you might call an easier to use UI and design, though larger in size. Ubuntu, and other distros I assume, come built in with a python interpreter you can run straight from the terminal. You can also compile and run C/C++ files straight from the terminal, as long as you have the right packages installed, gcc I believe. There are also plenty of IDEs you can install such as Code::Blocks, Eclipse, KDevelop, NetBeans and etc.


text:
Q: Simple Terrain and Terrain Following Camera Implementation in LibGDX I apologize if this topic is duplicated, but I not find something simple on other topics.
I'm new in 3D with LibGDX and I'm trying to make a basic implementation of a 3D Terrain (even very simple, only an inclined plane) and a Terrain Following Camera.
I've googled but not found an example so simple as well for a beginner.
Can anyone give me an example code or indicate where I can find?
I've tried to use this: https://github.com/eerock/libgdx/blob/master/tests/gdx-tests/src/com/badlogic/gdx/tests/TerrainTest.java, but it does not work, because I'm using the LibGDX 1.9.3 with OpenGL 2.0.
Thanks in advance for any help.


text:
Q: Regex Replace $nth element with Javascript Is it possible that I replace the $n element with a particular string?
In my example the $1 element.
For example, i want to replace the last element of a url
"http://my.domain.com/sub/file.extension" with my string "other.other".
my regex is something like this : /([^/]+)\.extension$
But it also replaces the slash before "file".
Here is a complete example:
var url = "http://my.domain.com/sub/file.extension";
var replace = "other.other";
var regex = new RegExp("/([^/]+)$");
console.log(url.replace(regex,replace));

I know i could prepend the slash in my replace like this: var replace = "/other.other"; but I want a different approach, that I could also use in other Projects.
In short, I am looking for a possibility to replace something without the delimiting character to replace with.
PS:
I read something about positive lookahead, but I can't get it to work.
And I know about this Post and this Post, but it's not what I'm looking for.

A: A small change has been made within your code .try the below code and check
var url = "http://my.domain.com/sub/file.extension";
var replace = "other.other";
var regex = new RegExp("([^/]+)$");
console.log(url.replace(regex,replace));

A: var url = "http://my.domain.com/sub/file.extension";
url = url.split("/");
url.pop();
url.push("other.other");
url = url.join("/");
console.log(url);