Need help in Android Layout Text in Button

Question: I have a problem. I have a good looking Layout. So now I want to set a text in the middle of the button. The button includes an image. So how can I change it, that the images have same size and looks good too. I have tried with setting the background but the imagessize change very bad.
Solution please..
<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:orientation="horizontal" >

    <Button
        android:id="@+id/button1"
        style="@style/Button"
        android:layout_height="125dp"
        android:drawableTop="@drawable/zettelnew"
        android:text="asdsad"
        />

    <Button
        android:id="@+id/button2"
        style="@style/Button"
        android:layout_height="125dp"
        android:drawableTop="@drawable/notizzettel"
        android:text="test"/>
</LinearLayout>

style.xml

Answer: You if I undersoot correctly I think you want to show some text below an image in side a button. If you wanto do this I would suggest trying to setting gravity of the button in the layout xml,
android:gravity="center_horizontal"

or
android:gravity="center_horizontal|bottom"

please note that this has to be done on the button tag of the layout xml.
If my understanding was incorrect them I am sorry to have wasted your time.
Comment: No I want to use the background function instead of the drawableTop function. But if I use the drawableTop function the layout looks different. Thats the problem. The images are different sizes.
Answer: Are these images dynamic or static, in other words are you grabbing them from the web or storing them locally.  If they are local images I think the best option is probably just to re-size them manually, so that they are all the same size.
If you can not re-size them manually then I would recommend embedding an imageview inside of the button.  Then you can call the setImageResource(int) or setImageBitmap(Bitmap bm) or setImageDrawable(Drawable drawable).  This will set the image to the forground and then you can use the setScaleType(ImageView.ScaleType scaleType) to scale all the images to fit the button.
For more details on those methods check out the Google resource for imageview
Answer: set the gravity to android:gravity="center" of the button


What material is this toilet water supply line?

Question: Photos of my toilet water supply line, which is the part below the valve:

Without Flash
[
With Flash

Based on the appearance, it only fits the description of galvanized iron (which is apparently the same as galvanized steel). However, based on numerous sources, galvanized steel has been mostly phased out in the 1960s, but my house was built in the 1990s (in Toronto, Ontario, Canada, if that matters).
I want to cut this pipe in order to install a quarter-turn valve with compression connections, but I am unable to find any close quarters tubing cutters that can cut galvanized iron/steel.
So my questions are:

What material might the toilet water supply line be?
Should I attempt to cut a galvanized iron/steel line with a cutter that is meant for everything but iron/steel (E.g. The Ridgid 40617 cutter states it is for "hard and soft copper, aluminum, brass and plastic tubing", but doesn't state iron/steel)?

Update 1
So, I scraped the back of the tubing with a file as one user suggested as shown here, and it appears to be copper. Also, a neodymium magnet was not attracted to it, as another user suggested in trying to do so.
Comment: See if a magnet is attracted to it. What is the (outside) diameter?
Comment: @JimStewart The outside diameter is 5/8". I updated my post to show the scratched surface of the tubing. I used a neodymium magnet on it, which had no attraction.
Just for my knowledge, what material does it suggest if a magnet was indeed attracted to it? Apparently, steel may or may not attract magnets, depending if it has nicklel in it, right?
Answer: That is either a painted or plated 1/2" copper line. If it is plated, the plating is failing or failed. Either way take a strip of emery cloth and clean it up before adding the compression fitting
Comment: I agree, that looks like 1/2" copper pipe that someone has painted with silver paint.
Comment: I also pictured the plumber gave it a solder coat to color it, note the little spatter on the escution, it looks like unfluxed soldering that fell on the surface... I don't see a solder joint and I don't think it is one of the toilet stops that come with a chromed copper supply the connects below the floor.
Comment: I thought that was splatter too until I blew up the photo close, looks like lint/dust that got in the way of some chrome spray paint.
Comment: @Jack The patch was just some dust left behind by my tissue paper that I used to clean it up before snapping the photos.
I don't have emery cloth. Can I use a steel wool or sandpaper in its place? Do I have to clean it until the orange colored copper is revealed?
Answer: It looks like copper with blue green patina, the result of ordinary oxidation, hiding the characteristic orange color of fresh copper.  If you are uncertain, scratch the surface with something like sandpaper, steel wool, file etc.  You will most likely see the same color as newly minted pennies.
If you see copper, your question number 2 is of no concern.  If it does not show copper, then you can always use a hacksaw or a jigsaw with a metal cutting blade to cut the pipe.  Of course, no matter how you cut the pipe, make certain that the water is turned off up-stream.
Comment: Indeed it does appear to have an orange color after scratching the surface with a file, as shown [here](http://imgur.com/rUbZuwG). Thanks!
Answer: If you cut the pipe, you will have solder or shark bite a replacement. Are you sure it's not just threaded onto the pipe? Hex sides on the valve are a small give away that it could just be a threaded pipe and valve.
Comment: ...No. The hex on the valve is so you can connect the fitting on the top without torquing the pipe connection below. If you "try to unscrew" a soldered joint, you'll twist/flatten the pipe, and then you'll have to rip the floor open to get to the next joint - bad plan. If it was threaded pipe, you would see pipe threads below the valve.
Comment: The more I looked at the picture, it did look soldered, but in regards to "seeing threads", none of my pipes have visible threads, but then again, most of mine are now pcv, cvpc or pex.
Comment: @JeffCates Yeah I don't think it's a threaded pipe. I tried twisting it lightly and it did not turn one bit.

Is a compression fitting not also an option if I cut the pipe?
Comment: I'm not sure I would trust a compression fitting for that, but a shark bite would work. I used them in several places on the 2 remodels I did. Similar to compression, but you push it on right and it locks in place.


Cannot reach a service inside my docker-compose

Question: I'm new with Docker and I'm trying to create a project using Microservices with .Net Core. I've two services: Identity.API and Writer.API. Using docker-compose, I declare two services:
version: '3.4'

services:
 identity.api:
  image: ${DOCKER_REGISTRY-}identityapi
  build:
   context: .
   dockerfile: Services/Identity/Identity.API/Dockerfile
  ports:
   - "5100:80"
   - "5101:443"
  depends_on:
  - sqldata
  - rabbitmq

 writer.api:
  image: ${DOCKER_REGISTRY-}writerapi
  build:
   context: .
   dockerfile: Services/Writer/Writer.API/Dockerfile
  ports:
   - "5200:80"
   - "5201:443"
  depends_on:
   - rabbitmq

 rabbitmq: # login guest:guest
  image: rabbitmq:3-management
  hostname: "rabbitmq"
  labels:
   NAME: "rabbitmq"
  ports:
    - "4369:4369"
    - "5671:5671"
    - "5672:5672"
    - "25672:25672"
    - "15671:15671"
    - "15672:15672"

The first service is on 5100, the second on 5101. When I start the docker-compose, I can see this:

So if I try to open the first service, I can see swagger without any problem:
https://localhost:5101/swagger/index.html
But if I try to reach the second service, I've a not found.
https://localhost:5201/swagger/index.html
If I try to run Writer.API service alone in Docker, it runs just fine.
My swagger configuration at startup:
public static IServiceCollection AddSwaggerConfiguration(
    this IServiceCollection services, IConfiguration configuration)
{
    services.AddSwaggerGen(swaggerGenOptions =>
    {
        swaggerGenOptions.SwaggerDoc("v1", new OpenApiInfo
        {
            Title = configuration["Swagger:ApiName"],
            Version = configuration["Swagger:ApiVer"]
        });

        //...
    });

    return services;

public static class DependencyInjection
{
    public static IServiceCollection AddPresentation(
        this IServiceCollection services, IConfiguration configuration)
    {
        services.AddControllers();
        services.AddMappings();
        services.AddSwaggerConfiguration(configuration);

        services.AddCors(options =>
        {
            options.AddPolicy(
            "CorsPolicy",
             builder => builder.AllowAnyOrigin()
                 .AllowAnyMethod()
                 .AllowAnyHeader());
        });

        return services;
    }
}

//Program.cs
builder.Services
    .AddApplication(configuration!)
    .AddInfrastructure(configuration!)
    .AddPresentation(configuration!);

builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

//...

I really cannot understand how to reach the other service, and I cannot understand why the addresses are different. I'm missing something? For some reason on Identity.API docker create 4 addresses, for Writer.API there are only two addresses.
I really cannot understand what's wrong with this configuration. Any help?
Thanks! :)
Comment: Could you please share the code part of swagger config in startup.cs?
Comment: Just posted above :). It's the same for both services. Writer.Api runs fine if I run it directly in docker, without docker compose.
Comment: please share the related part in the Configure method as well, and I suggest first to comment the security parts to simplify the problem
Comment: Done as you can see above. But I think this not a swagger problem. I cannot reach the endpoint even with Postman. :/
Comment: Is the service still running after 10 seconds or it is stopped and also Could you use this line and comment the if condition "app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "API v1"));" and one more thing is to delete the image and build it again
Answer: Finally I understand where the problem was. For some reason, Visual Studio creates a docker-compose.override.yml without the Writer.API service. So I opened the file and added my service just like this:
version: '3.4'

services:
  identity.api:
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
      - ASPNETCORE_URLS=https://+:443;http://+:80
    ports:
      - "80"
      - "443"
    volumes:
      - ${APPDATA}/Microsoft/UserSecrets:/root/.microsoft/usersecrets:ro
      - ${APPDATA}/ASP.NET/Https:/root/.aspnet/https:ro

#SERVICE NOT ADDED AUTOMATICALLY!
  writer.api:
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
      - ASPNETCORE_URLS=https://+:443;http://+:80
    ports:
      - "80"
      - "443"
    volumes:
      - ${APPDATA}/Microsoft/UserSecrets:/root/.microsoft/usersecrets:ro
      - ${APPDATA}/ASP.NET/Https:/root/.aspnet/https:ro

So not it seems to work just fine :/.


Facebook Users Search API

Question: I am using latest version of facebook php sdk i want searched user list.
<code>$response = $fb->get('search?q=programming&type=user', '{access-token}');
</code>
$response is always returns blank value in version 5.
Thanks in advance..!!!
Comment: Should `serach` be `search`?
Comment: Yes it is typo and corrected.
Answer: That was removed in 4/2018 already.
https://developers.facebook.com/docs/graph-api/changelog/breaking-changes#search-4-4

You can no longer use the /search endpoint with the following object types:

event
group
page
user

Facebook Users Search API


Can't open JFoenix-window

Question: Whenever I try to open my JFoenix programm the same error message appears in the console...
When I use the standard JavaFx components everything works nice
Information about the Java, I use:
I have already imported the JFoenix library into eclipse;
I use jdk1.8.0_111;
I have the newest JFoenix jar
That's the error:

    Exception in Application start method
java.lang.reflect.InvocationTargetException
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
 at java.lang.reflect.Method.invoke(Method.java:498)
 at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:389)
 at com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:328)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
 at java.lang.reflect.Method.invoke(Method.java:498)
 at sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:767)
Caused by: java.lang.RuntimeException: Exception in Application start method
 at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:917)
 at com.sun.javafx.application.LauncherImpl.lambda$launchApplication$155(LauncherImpl.java:182)
 at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.UnsupportedClassVersionError: com/jfoenix/controls/JFXButton has been compiled by a more recent version of the Java Runtime (class file version 53.0), this version of the Java Runtime only recognizes class file versions up to 52.0
 at java.lang.ClassLoader.defineClass1(Native Method)
 at java.lang.ClassLoader.defineClass(ClassLoader.java:763)
 at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
 at java.net.URLClassLoader.defineClass(URLClassLoader.java:467)
 at java.net.URLClassLoader.access$100(URLClassLoader.java:73)
 at java.net.URLClassLoader$1.run(URLClassLoader.java:368)
 at java.net.URLClassLoader$1.run(URLClassLoader.java:362)
 at java.security.AccessController.doPrivileged(Native Method)
 at java.net.URLClassLoader.findClass(URLClassLoader.java:361)
 at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
 at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
 at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
 at javafx.fxml.FXMLLoader.loadTypeForPackage(FXMLLoader.java:2916)
 at javafx.fxml.FXMLLoader.loadType(FXMLLoader.java:2905)
 at javafx.fxml.FXMLLoader.importClass(FXMLLoader.java:2846)
 at javafx.fxml.FXMLLoader.processImport(FXMLLoader.java:2692)
 at javafx.fxml.FXMLLoader.processProcessingInstruction(FXMLLoader.java:2661)
 at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2517)
 at javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2441)
 at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2409)
 at application.Main.start(Main.java:26)
 at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$162(LauncherImpl.java:863)
 at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$175(PlatformImpl.java:326)
 at com.sun.javafx.application.PlatformImpl.lambda$null$173(PlatformImpl.java:295)
 at java.security.AccessController.doPrivileged(Native Method)
 at com.sun.javafx.application.PlatformImpl.lambda$runLater$174(PlatformImpl.java:294)
 at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
 at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
 at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
 ... 1 more
Exception running application application.Main

My Main class:

package application;

import java.io.IOException;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;

public class Main extends Application {

 private AnchorPane root;
 private Stage primaryStage;

 @Override
 public void start(Stage primaryStage) {
  try {

   this.primaryStage = primaryStage;
   this.primaryStage.setTitle("SimpleMySQLConnector - Login");

   FXMLLoader load;
   load = new FXMLLoader(getClass().getResource("/application/LoginScreen.fxml"));
   root = load.load();
   Scene scene = new Scene(root);
   primaryStage.setScene(scene);
   primaryStage.show();

  } catch(Exception e) {
   e.printStackTrace();

  }
 }

 public static void main(String[] args) {
  launch(args);

 }
}

package application;

import java.io.IOException;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;

public class Main extends Application {

 private AnchorPane root;
 private Stage primaryStage;

 @Override
 public void start(Stage primaryStage) {
  try {

   this.primaryStage = primaryStage;
   this.primaryStage.setTitle("SimpleMySQLConnector - Login");

   FXMLLoader load;
   load = new FXMLLoader(getClass().getResource("/application/LoginScreen.fxml"));
   root = load.load();
   Scene scene = new Scene(root);
   primaryStage.setScene(scene);
   primaryStage.show();

  } catch(Exception e) {
   e.printStackTrace();

  }
 }

 public static void main(String[] args) {
  launch(args);

 }
}

That's the fxml file:

<?xml version="1.0" encoding="UTF-8"?>

<?import com.jfoenix.controls.JFXButton?>
<?import com.jfoenix.controls.JFXCheckBox?>
<?import com.jfoenix.controls.JFXPasswordField?>
<?import com.jfoenix.controls.JFXTextField?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.paint.LinearGradient?>
<?import javafx.scene.paint.Stop?>
<?import javafx.scene.text.Font?>

<AnchorPane prefHeight="700.0" prefWidth="1118.0" style="-fx-background-color: #000000;" xmlns="http://javafx.com/javafx/9.0.1" xmlns:fx="http://javafx.com/fxml/1">
   <children>
      <AnchorPane layoutX="587.0" layoutY="55.0" prefHeight="590.0" prefWidth="500.0" style="-fx-background-color: #0a52c9;">
         <children>
            <JFXTextField focusColor="#fafafa" layoutX="109.0" layoutY="156.0" prefHeight="42.0" prefWidth="282.0" promptText="Benutzername" unFocusColor="#3fd6f4">

            </JFXTextField>
            <JFXPasswordField focusColor="WHITE" layoutX="112.0" layoutY="279.0" prefHeight="42.0" prefWidth="282.0" promptText="Passwort" unFocusColor="#3fd6f4">

            </JFXPasswordField>
            <JFXButton layoutX="204.0" layoutY="375.0" prefHeight="42.0" prefWidth="91.0" style="-fx-background-color: #3fd6f4;" text="Login" textFill="WHITE">

            </JFXButton>
            <JFXCheckBox layoutX="159.0" layoutY="479.0" text="Angemeldet bleiben" textFill="WHITE">

            </JFXCheckBox>

               <textFill>
                  <LinearGradient endX="1.0" endY="1.0">
                     <stops>
                        <Stop color="#3fd6f4" />
                        <Stop color="WHITE" offset="1.0" />
                     </stops>
                  </LinearGradient>
               </textFill>

         </children>
      </AnchorPane>

         <textFill>
            <LinearGradient endX="1.0" endY="1.0">
               <stops>
                  <Stop color="#00eade" />
                  <Stop color="WHITE" offset="1.0" />
               </stops>
            </LinearGradient>
         </textFill>

         <textFill>
            <LinearGradient endX="1.0" endY="1.0">
               <stops>
                  <Stop color="#02dbea" />
                  <Stop color="WHITE" offset="1.0" />
               </stops>
            </LinearGradient>
         </textFill>

   </children>
</AnchorPane>

I hope you're able to help me with these Information
Answer: İf you don't want to upgrade your jdk;
1.Change Jfoenix version to 8.0.9 , if you use Java9&10 use v9.0.9.
2.Change AnchorPane xmlns="http://javafx.com/javafx/9.0.1" to
xmlns="http://javafx.com/javafx/8.0.999-ea"

or
xmlns="http://javafx.com/javafx"

3.Change JavaFx Scene Builder version according to the version you are using.
Answer: Try upgrading your jdk to jdk 9 ver.
Answer: try to upgrade your jdk that is connected with your IDE to the current version don't use the old 1_8 version

Can't open JFoenix-window


Class [org.apache.derby.jdbc.ClientDriver] not found. When trying to connect to db

Question: I have set up a project in Netbeans, created a script, made a new database with javadb. I can connect to it by gui - display the tables contents etc, but when i run an application with:
 EntityManager em = Persistence.createEntityManagerFactory("lab5PU").createEntityManager();

i get this quite long exception:
[EL Info]: 2013-04-05 21:40:45.554--ServerSession(1198260109)--EclipseLink, version: Eclipse Persistence Services - 2.3.0.v20110604-r9504
[EL Severe]: 2013-04-05 21:40:45.574--ServerSession(1198260109)--Local Exception Stack:
Exception [EclipseLink-4003] (Eclipse Persistence Services - 2.3.0.v20110604-r9504): org.eclipse.persistence.exceptions.DatabaseException
Exception in thread "AWT-EventQueue-0" javax.persistence.PersistenceException: Exception [EclipseLink-4003] (Eclipse Persistence Services - 2.3.0.v20110604-r9504): org.eclipse.persistence.exceptions.DatabaseException
Exception Description: Configuration error.  Class [org.apache.derby.jdbc.ClientDriver] not found.
Exception Description: Configuration error.  Class [org.apache.derby.jdbc.ClientDriver] not found.
    at org.eclipse.persistence.exceptions.DatabaseException.configurationErrorClassNotFound(DatabaseException.java:82)

I can see the javadb drivers in the driver section in services, so i have no idea what the error might be.
EDIT: persistance.xml as requested:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
  <persistence-unit name="lab5PU" transaction-type="RESOURCE_LOCAL">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
    <class>lab5.Colleagues</class>
    <properties>
      <property name="javax.persistence.jdbc.url" value="jdbc:derby://localhost:1527/lab5"/>
      <property name="javax.persistence.jdbc.password" value="mypass"/>
      <property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver"/>
      <property name="javax.persistence.jdbc.user" value="admin"/>
      <property name="eclipselink.ddl-generation" value="create-tables"/>
    </properties>
  </persistence-unit>
</persistence>

Comment: Where your db connection is configured? In `persistence.xml`? Can you show that configuration?
Comment: @PatrykRoszczyniała added persistance.xml as requested
Comment: I'm new in JEE but this driver `com.mysql.jdbc.Driver` works for my application.
Comment: Which version of NetBeans are you using?
Comment: changing it to your driver, caused an unexpected driver error.
Comment: @jalopaba NetBeans IDE 7.1 (Build 201112071828)
Comment: How do you run the db?
Comment: @RomanC netbeans runs it for me i think. I can connect to it via gui, and excecute scripts, so i think its there.
Comment: @BartlomiejLewandowski So, what the driver your GUI uses to connect to the db?
Comment: @RomanC in connection properties it says it is the same driver - org.apache.derby.jdbc.ClientDriver
Comment: @BartlomiejLewandowski Ok, look at this http://stackoverflow.com/questions/14547109/java-sql-error-no-suitable-driver-found/14547321#14547321
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/27665/discussion-between-bartlomiej-lewandowski-and-roman-c)
Answer: I think the problem you have is that you don't have the Derby driver in the classpath of the project.
You can easily achieve that adding the JavaDB library to your project:

Right-click on the project
Properties ->  Libraries
Add Library -> JavaDB driver

This includes derby.jar, derbyclient.jar and derbynet.jar in your project's classpath.
The derbyclient.jar contains the class org.apache.derby.jdbc.ClientDriver your code is complaining about.
Comment: i do not have an option to select that libary, i have downloaded the derby libs, where should i put them?
Comment: Sorry, it is not "Java DB" but "Java DB Driver"... (in NetBeans 7.3)


Keras Convolutional Autoencoder blank output

Question: Quick disclaimer: I'm pretty new to Keras, machine learning, and programming in general.
I'm trying to create a basic autoencoder for (currently) a single image. While it seems to run just fine, the output is just a white image. Here's what I've got:
img_height, img_width = 128, 128

input_img = '4.jpg'
output_img = '5.jpg'

# load image
x = load_img(input_img)
x = img_to_array(x)  # array with shape (128, 128, 3)
x = x.reshape((1,) + x.shape)  # array with shape (1, 128, 128, 3)

# define input shape
input_shape = (img_height, img_width, 3)

model = Sequential()
# encoding
model.add(Conv2D(128, (3, 3), activation='relu', input_shape=input_shape,
padding='same'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Conv2D(64, (3, 3), activation='relu', padding='same'))
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Conv2D(64, (3, 3), activation='relu', padding='same'))

# decoding
model.add(Conv2D(64, (3, 3), activation='relu', padding='same'))
model.add(UpSampling2D(size=(2,2)))
model.add(Conv2D(64, (3, 3), activation='relu', padding='same'))
model.add(UpSampling2D(size=(2,2)))
model.add(Conv2D(128, (3, 3), activation='relu', padding='same'))
model.add(Conv2D(3, (3, 3), activation='sigmoid', padding='same'))

model.compile(loss='binary_crossentropy', optimizer='adam')
print(model.summary())

checkpoint = ModelCheckpoint("autoencoder-loss-{loss:.4f}.hdf5", monitor='loss', verbose=0, save_best_only=True, mode='min')
model.fit(x, x, epochs=10, batch_size=1, verbose=1, callbacks=[checkpoint])

y = model.predict(x)

y = y[0, :, :, :]
y = array_to_img(y)
save_img(output_img, y)

I've looked at a handful of tutorials for reference, but I still can't figure out what my issue is.
Any guidance/suggestions/help would be greatly appreciated.
Thanks!
Answer: this solved the problem. The code was just missing
x = x.astype('float32') / 255.

This is a numpy built-in function to convert the values contained in that vector to floats.
This allows us to get decimal values, where the values are divided by 255. RGB values are stored as 8 bit integers, so we divide the values in the vector by 255 (2^8 - 1), to represent the colour as a decimal value between 0.0 and 1.0.
Comment: That's really helpful.

I guess what I'm really looking for is essentially the same image as output. For that, it doesn't seem like I should need any label, as the output should "match" the input. Can you point me in the direction as to how I might do that?
Comment: Oh I see. Looking around on the Keras blog, I was able to find [this](https://blog.keras.io/building-autoencoders-in-keras.html)  tutorial on convolutional autoencoders. Perhaps that could be what you're looking for?
Comment: That tutorial solved the problem (even though I've already seen it about 1000 times). I was missing `x = x.astype('float32') / 255.` which normalizes pixel values between 0 and 1. Thanks for the help!
Comment: That's awesome! The `astype(..)` bit is a numpy built-in function to convert the values contained in that vector to floats. This allows us to get decimal values too when the values are then divided by 255. RGB values are stored as 8 bit integers, so we divide the values in the vector by 255 (2^8 - 1), to represent the colour as a decimal value between 0.0 and 1.0.
Comment: This answer, though it happened to be useful to the OP, is incorrect: The `model.fit(x, x, ...)` is exactly the right thing to do, when you're training an autoencoder...


Fluent NHibernate LazyLoad Issues

Question: I couldn't find an answer to this issue so I assume it is something I am doing wrong.
I have a PersistenceModel set up where I have set a convention as follows: -
persistenceModel.Conventions.Add(DefaultLazy.Always());

However, for one of the HasManyToMany relationships in one of my entities I want eager loading to take place which I am setting up as follows: -
HasManyToMany(x => x.Affiliates).Not.LazyLoad();

Intuitively, I expect eager loading to take place as I am overriding the lazy load default that I have specified as a convention but it still lazy loads.  If I set the DefaultLazy convention to never and then set LazyLoad on an individual relationship it doesn't work either.
Any ideas?
Answer: When you set Not.LazyLoad(), you tell NHibernate to load Affiliates when the parent loads. NHibernate will do this by performing another select on the Affliates many-to-many table regardless of whether you access the Affiliates collection or not. NHibernate is using another select because that is the default fetching mode. You want to override fetching mode as well, either in the query or in the mapping. To do it in the mapping, add the following:
HasManyToMany(x => x.Affiliates)
    .Not.LazyLoad()
    .Fetch.Join();

You might also want to include a ".Cascade.AllDeleteOrphan()" if you want NHibernate to persist new Affiliaites added to the collection and delete orphaned ones. If you do not do this, you will have to explicitly call session.Save(newAffiliate). Otherwise you'll receive a TransientObjectException when your Affiliates collection contains a new Affiliate.
Comment: Sorry, I removed the parts of the code that I didn't think were relevant here.  I do have .FetchType.Join() also and turning off lazy loading still doesn't work.  The only way to turn off lazy loading I have found that works for me is by setting the convention.
Comment: I added the DefaultLazy.Always() convention and the HasManyToMany() relationship is correctly eager loading when Fetch.Join() is applied. You can grab my sample from GitHub here: https://github.com/JamesKovacs/JamesKovacs.StackOverflow/tree/master/FluentNhHacking/
Comment: Alright, well I pretty much mimicked your code in my situation and it still didn't work, so I will have to have a closer look.  I am using .ShowSql() to determine whether the queries have been run lazily or eagerly which I presume to be accurate?
Comment: Your sample project appears to be using XML mapping
Answer: It may be one stupid thing to ask, but have you execute the query inside your session? Say,
Using(var session = OpenSession())
{
    session.Query<Entity>().ToList();
}

I had this problem before, and finally realized the objects that I was accessing hadn't been queried before disposing the session.

Fluent NHibernate LazyLoad Issues


How to change wlan0's channel

Question: When setting the channel to wlan0, I get an error:
SET failed on device wlan0 ; Device or resource busy.

I tried to shutdown wlan0 by:
sudo ifconfig wlan0 down

and wlan0 did not appear in the ifconfig result, but I still get the error when I use this command to switch channels:
sudo iwconfig wlan0 channal 1

The funniest thing is I just used this method to change channal from 4 to 6, and now I want to change the channal from 6 to 1, but I can't finish it. Did I miss something?
Comment: I think that the main problem is that you are typing "channal", instead of *channel*.
Answer: Change command from
sudo iwconfig wlan0 channal 1

to
sudo iwconfig wlan0 channel 1

How to change wlan0's channel


DELETE/PUT verbs result in 404 Not Found in WebAPI, only when running locally

Question: I know this is a commonly addressed issue, and I've done everything that many posts here on SO suggest.  When I try to delete a record using WebAPI (version 2) from my MVC5 front end running under local IIS, I get a 404 Not Found response.  Here are the things I've tried:
I've added the following under <system.webServer /> in my WebAPI web.config:
<system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules runAllManagedModulesForAllRequests="true">
      <remove name="WebDAVModule" />
    </modules>
    <handlers>
      <remove name="WebDAV" />
      <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
      <remove name="OPTIONSVerbHandler" />
      <remove name="TRACEVerbHandler" />
      <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
  </system.webServer>

I've followed the instructions at: http://geekswithblogs.net/michelotti/archive/2011/05/28/resolve-404-in-iis-express-for-put-and-delete-verbs.aspx, which basically say to modify the ExtensionlessUrlHandler-Integrated-4.0 in IIS "Handler Mappings".  It says to double click on the handler, click "Request Restrictions", and "Allow PUT and DELETE verbs".  I've done this, and I still get the 404 error.
I've done an IIS reset.
Here's my MVC5 front end code that calls the WebAPI delete method - please note that when I manually navigate to api/bulletinboard/get/{0} where {0} is an integer, I get a valid JSON response.  Below, contactUri is http://localhost/SiteName/api/bulletinboard/get/53 which returns valid JSON:
[HttpPost, ActionName("Delete")]
        public ActionResult Delete(string appId, int id)
        {
            response = client.GetAsync(string.Format("api/bulletinboard/get/{0}", id)).Result;
            contactUri = response.RequestMessage.RequestUri;
            response = client.DeleteAsync(contactUri).Result;

            if (response.IsSuccessStatusCode)
            {
                return RedirectToAction("MessageList", new { appId = appId });
            }
            else
            {
                LoggerHelper.GetLogger().InsertError(new Exception(string.Format(
                    "Cannot delete message due to HTTP Response Status Code not being successful: {0}", response.StatusCode)));
                return View("Problem");
            }
        }

Here's my WebAPI delete method:
[HttpDelete]
        public HttpResponseMessage Delete(int id)
        {
            BulletinBoard bulletinBoard = db.BulletinBoards.Find(id);
            if (bulletinBoard == null)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }

            db.BulletinBoards.Remove(bulletinBoard);

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
            }

            return Request.CreateResponse(HttpStatusCode.OK, bulletinBoard);
        }

Here's my WebApiConfig.cs in my WebAPI project:
public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            config.EnableCors();

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "ApiWithActionName",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            var json = config.Formatters.JsonFormatter;
            json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
            config.Formatters.Remove(config.Formatters.XmlFormatter);

            config.Formatters.Add(new PlainTextFormatter());
        }

QUESTION: What else can I try to resolve this error?  This works fine when deployed from my local environment to my company's development servers.
Comment: your request url is `api/bulletinboard/get/{0}` whereas you are trying to reach the delete action...shouldn't it be `api/bulletinboard/delete/{0}`?
Comment: @KiranChalla  No, it should be how I have it.  The `DeleteAsync` gets the result of the GET request and deletes it.  I have this working as is in another project.  I did however change it to what you suggested just to see what would happen, and I had the same 404 error.  I think there's something about the DELETE request that IIS doesn't like...
Comment: @KiranChalla Ah, it's a very strange situation... take a look at my answer below.
Answer: for those who still looking for enable DELETE & PUT The below code solve my problem
<validation validateIntegratedModeConfiguration="false" />
<handlers>
  <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
  <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
  <remove name="ExtensionlessUrlHandler-Integrated-4.0" />

  <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
  <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
  <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>

Comment: I only needed the headers added to the WebAPI web.config to fix my scenario. My config didn't need the validation portion.
Comment: In my case adding all the lines returned duplication error. So, I only added/enabled what was created by default, which was:

Also note the scenario my be Classic or Integrated, depending on how your IIS is set up
Answer: I've followed the instructions at: https://forums.asp.net/t/1961593.aspx?DELETE+PUT+verbs+result+in+404+Not+Found+in+WebAPI+only+when+running+locally
That says to only change this piece of code in your Web.config, and works fine for me!
<system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Headers" value="Content-Type" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
      </customHeaders>
    </httpProtocol>
    <validation validateIntegratedModeConfiguration="false" />
    <handlers>
       <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
       <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
       <remove name="ExtensionlessUrlHandler-Integrated-4.0" />

       <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
       <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
       <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
</system.webServer>

Answer: If you are using IIS, make sure you have the HTTP Verb set to allowed in Request Filtering. If its not there, you can set it to allow it on the side.
Answer: We were struggling with DELETE/PUT returning 404 errors on IIS 8.  We did all of the above answers changing web.config to accept all Verbs, enabling put/delete in the request filtering.  We had also disabled webDAV multiple ways.  We found that the application pool was set to classic verses integrated (what it should have been).  Now DELETE/PUT verbs work fine.
Answer: Mark Jensen solution worked for me.
Just changed my Application Pool from "Classic" to "Integrated" and my requests worked.
Answer: This issue can be fixed by IIS level configuration-
Open IIS->select your website->IIS (section) ->Request Filtering ->HHTP Verbs
Remove DELETE verb/ OR allow DELETE verb
Issue will get resolved.
Comment: TY, this solved my issue. it seems the web config didnt auto add this, or it just doesn't auto-add this. ty
Answer: What I did was just switch from using local IIS to IIS Express via the project properties on my WebAPI project, as a workaround.  Doing this and deleting a record then resulted in a 405 Method Not Allowed error.  I then changed the lines of code:
response = client.GetAsync(string.Format("api/bulletinboard/get/{0}", id)).Result;
contactUri = response.RequestMessage.RequestUri;
response = client.DeleteAsync(contactUri).Result;

To:
response = client.DeleteAsync(string.Format("api/bulletinboard/delete/{0}", id)).Result;

This is very strange because I have another project that runs the first block of code and it deletes records just fine.  Anyways, this resolved my local problem.  I understand this doesn't really resolve my main issue which was using local IIS, but this workaround worked for me.
Answer: If your project is working under IIS and not under IISExpress, try to set IISExpress Managed Pipeline Mode to Integrated.
PUT and DELETE verbs seems to have problem under Classic Managed Pipeline mode.
Good luck..
Roberto.
Answer: For me it was an ISAPI module called UrlScan which I had to completely remove from the application.


Room Bookings: What approach is best/intuitive/user friendly?

Question: I currently have a side project going where I am learning AngularJS, the side project I am working on is a web based room bookings application.
So imagine you are an employee of a company, and you want to book an hour at one of the many meeting rooms available at the company building.
When it comes to the UI of room booking systems, I have seen some shocking stuff, stuff that will make the people on Dribbble pull their hair out, but no matter how bad the styling, I've always seen two approaches taken.
Approach 1:
Room Schedule view as a Calendar where the user can see what meetings are booked on what days by looking at the calendar, he/she can then add a meeting by clicking on the calendar itself in the spot he/she wants the meeting and book a meeting there and then. Similar to this (only decent one I can find)

Approach 2:
To book a room you basically have a form with input fields specifying the date, time and location that you would like to book the meeting room.

Which approach do you think is best? more intuitive and user friendly? Do you have better examples?
My Vision:
When I was thinking about this, I was asking myself, "wouldn't it be nice to have a CAD drawing of the building, where users can click the actual room, see a schedule and then make a booking?" .. but I'm not sure than can be achieved in HTML5/CSS3/JavaScript. I do not want to use Flash (I know it can be done in that).
Any feedback and help would be greatly appreciated.
Thank You.
Answer: I speculate that you have two main types of user in this situation:

People who have a particular time/date in mind and want to find a free room (any room) on that date ("I need to arrange an urgent meeting for Tomorrow morning and I don't care where");
People who require a particular room and want to find a date when that room is free ("I want to book the large meeting room for a workshop sometime in the next two weeks").

With these two scenarios in mind, the calendar view has a few of strengths:

When a particular time/date is important, the user can quickly navigate to that date and see the availability of all rooms side-by-side;
When a particular room is important, the user can see the availability of that particular room over a period of time.
Calendars are a great way of presenting upcoming dates, particularly in the near future when the day is known but not necessarily the actual date. That's what they are designed for and people know how to use them.

The alternative approach suggested in the question whereby users would refer to a diagram of the building to first select a room and then check the schedule of that room is perhaps more visually engaging but sounds less efficient. Users motivated by date are forced to click in and out of each of the rooms to compare the schedules. That said, having a diagram of the building alongside the calendar view would be a useful addition.
Comment: Thanks, makes perfect sense to me, and you identified two class of users that I had missed. Cheers Matt :)
Comment: you got in before me. One of the first big projects I worked on was designing a room booing system. And we found use cases varied with the interaction. "I want to book a room anywhere at this time - show me what's free" and "I want to book this room because it has specific facilities I need" and "if my time slot isn't free suggest me alternatives"
Comment: correct. I worked on a large room booking software project back in the day and this is exactly how folks book "show my rooms with my time or close time" and "show me times for my amazing meeting room with pool table in it"
Answer: Why would you do CAD for room booking? Isn't the process of finding a room and selecting the available time slot already not too cumbersome! Top that with a heavy page having a 3D rotating building which looks nothing like a booking website! Now the user has to learn how to control that 3D structure!
I don't care about the architecture of the building and the exact location of the room in the building. All I wanted was a photo of the room.
Comment: Well, maybe with a photo, a small plan of the room in "details" section could be useful, so that you know that the there are two whiteboards and the beamer points in a 3rd direction, and that the tables can be re-arranged in a circle, ...
Answer: I would have to agree with BlueFlame, a three dimensional view of the building would make the experience worse. I don't think the point is where in the building the meeting should take place, but when it's taking place.
Which is where your first option looks like the winner. Take Google Calender for example, it's interface is something along the lines of Approach 1, no? Perhaps use that as inspiration? This could reduce the use of the keyboard a bit (time/date) too.
Answer: There is fundamentail difference in both approaches, which is defined by resource accessibility.

To manage Exclusive resource you should provide planning, sheduling, or queuing tools to make the task easy. So the interface becomes more complex, to make the task more efficient.
You case probably falls into this category.
Non-exclusive resources don't require management tools, as the  availability is high and interface should be simple to reduce cognitive load to reach high performance.
Booking the fly tickets is the example for this category.


HTML - Img alt attribute hides image

Question: I'm grabbing favicon's from sites programmatically by generically making a request for the icon to "example.com/favicon.ico".
If the site doesn't have a favicon, I want to use the "alt" attribute of the image to hide the image so that it doesn't appear and doesn't have a "missing image" icon.
For example

Can this be done?
Comment: Yes the source fills, but then the file isnt found. In my implementation there's no way to check beforehand
Answer: You can use the built-in error() method. Hide your image based upon that.

$("img").on("error", function() {
  $(this).hide();
});

If you want an alternative image when the image is not available, give the new image source.

$("img").on("error", function() {
  $(this).attr("src", "https://homepages.cae.wisc.edu/~ece533/images/mountain.png");
});

Comment: What about using a function in the onerror tag within the image?
Comment: @SteveAlereza See the example here: [element.onerror](https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror#element.onerror)
Answer: You can put your placeholder immediately and check if the image loads on script. If it loads, replace the img src

var thisImage = new Image();
thisImage.src = 'https://www.businessinsider.com/favicon.ico';
thisImage.onload = function() {
  console.log("Image 1 ready to append");
  document.querySelector('.bg-image').src = thisImage.src;
};

HTML - Img alt attribute hides image


How do I use my home directory on a separate partition?

Question: My understanding of disc partitioning has always been that you partition a disc to install multiple operating systems so you can boot from multiple operating systems on a single disc. However I'm reading a ubuntu server book and it talks about partitioning the /home directory of a ubuntu installation.

"The /home directory is a popular partitioning candidate among both administrators and desktop users alike because it holds all of the personal files for user accounts on that machine. If you maintain /home as a separate partition, you can install new versions of a distribution or even different distributions altogether without wiping out any user settings."

I don't see how and why anyone would partition the home directory or any other directory for that matter in the file system of a ubuntu installation.
Answer: When installing Ubuntu to a hard drive the installer takes care of partitioning. In case it finds an empty unpartitioned space it will use this for your Ubuntu Installation. If you had already installed an OS the Installer will let you shrink a partition to then hold Ubunutu.
By default a single partition, and an additional swap partition will be created. In case the installer finds a pre-existing swap partition it will not create an additional one. We may want to hold our HOME in a separate partition, be it to

mirror this partition
easy format the OS partition without deleting HOME
having the OS on a fast SSD but HOME on a conventional drive,
or a variety of other reasons.

Note that it is not a good idea to share all of the HOME partition with different distributions or releases as this may lead to conflicting configuration settings from differing application versions. Rather than sharing all of HOME we should share data on a shared partition only. These data directories can then be symlinked to from the user's home subdirectories.

In the following sections let me depict procedures for having HOME on a partition or a drive different to the OS:

Backup all of your important data before you change partitions.

Desktop installation

On installing Ubuntu choose "Something else" to have access to the partitioner.
If the drive was used before, remove the partition table or delete partitions to hold your Ubuntu. All data on these partitions will be deleted.
Create a new partition to hold the OS root directory.
Choose the mount point / for this root partition:

Note the different mount points you may be able to choose for any partition created.
Repeat step 3. and 4. for the /home partition:

In case there is a pre-existing HOME partition holding data we now have to make sure to untick "Format?" before we proceed with the installation to not delete this data:

Choose "Install now" to partition and format the drive and proceed with the installation.

Ubuntu Server installation
The server installation will guide you through the partitioning using partman. At the partitioning step we may delete, or create new partitions similar to the desktop installation. Shown below are interim steps when we do so:

Choose "Manual" partitioning for an individual setup:

Choose partition to change or free space to create a partition

Select mount points / for root or /home for HOME:

Repeat steps 2. to 4. until finished:

Continue server installation:

Move exisiting HOME to a different location
See question and answers below on procdeures to move the HOME directory to a different partition or drive:

Move home folder to second drive
Answer: You quoted the answer to your own question...

If you maintain /home as a separate partition, you can install new versions of a distribution or even different distributions altogether without wiping out any user settings.

A partition is just a way to separate the files in the hard drive, it doesn't need to be a place for an operating system. If your system partition and your home partition are separated, if you upgrade your system it'll only affect the system partition, leaving your data alone.
There are other uses for a different data partition such as encrypting it or a having a different filesystem than the operating system's one.
Note that Linux treats /home, /usr, /var... as folders, even if they are separate partitions (they are mounted at bootup). So having a separate /home partition won't affect you in any negative way, go ahead and do it.
If you intend to have a server someday, I'd advise to use a separate /var partition, and probably a separate /usr and /tmp too.
Comment: I'm not sure what you mean. A live system isn't installed to the HD, it usually doesn't use your harddrive, at least not permanently, it runs from the CD and on the RAM. You can use a tool called GParted available on most live CDs to partition your harddrive, but the live CD itself won't be using the partitions you make unless you install it to the drive.
Comment: Can you partition a folder on a live system?
Comment: I mean once ubuntu is installed on a partition in the hard drive, can I then after installation repartition a folder in it?
Comment: I have never tried it, but it [seems to be possible](http://www.psychocats.net/ubuntu/separatehome).


How do i install drupal 7 on tomacat server

Question: I'm new to Drupal. I googled for installation of Drupal on Tomcat server but i couldn't find any procedure for installation.
Can anyone tell the procedure for installation of Drupal 7 on Tomcat server in windows 7 environment?
Thanks in Advance.
Comment: Can u please give the reason for down Voting
Comment: Is it possible to install Drupal on tomcat server.  I would really appreciate any help. Great thanks in advance!
Answer: Install the following packages php5-cgi php5-gd php5-mysql tomcat mysql-server in your system.
Download the PHP/Java Bridge from http://sourceforge.net/projects/php-java-bridge/files/Binary%20package/p...
Download and extract drupal in your system.
Move the "JavaBridgeTemplate621.war" file to the Tomcat webapps directory. Wait a few seconds for Tomcat to create a "JavaBridgeTemplate621" directory.
sudo cp JavaBridgeTemplate621.war /opt/tomcat/webapps/
Copy the directory created by Tomcat and name it "drutomcat".
sudo cp -R /opt/tomcat/webapps/JavaBridgeTemplate621 /opt/tomcat/webapps/drutomcat
Remove the index.php and test.php files from the "drutomcat" directory.
sudo rm /opt/tomcat/webapps/drutomcat/index.php
sudo rm /opt/tomcat/webapps/drutomcat/test.php
Copy the Drupal files to the "drutomcat" directory, create the "settings.php" file.
sudo cp -R drupal/ /opt/tomcat/webapps/drutomcat
sudo cp /opt/tomcat/webapps/drutomcat/drupal/sites/default/default.settings.php /opt/tomcat/webapps/drutomcat/drupal/sites/default/settings.php
Now point to your browser by typing http: // localhost :8080 / drutomcat /drupal and run the drupal installer
Comment: I am able to install tomcat ,mysql server in my PC but unable to install " php5-cgi php5-gd php5-mysql".can you please provide the installation procedure for the above mentioned packages @Naim FS
Comment: r u using windows/kinux.?
Comment: i am using windows 7 @Naim FS
Comment: I too found the above procedure in google but unable to install " php5-cgi php5-gd php5-mysql" @NaimFS
Answer: Your question is a bit surprising.
Tomcat is primarily targeted to Java/JEE applications, not PHP (like Drupal).
Though, you may be able to install Drupal on Tomcat : I found this link :
https://groups.drupal.org/node/180139
It's outdated (2011), but may be still relevant. It involves installing a PHP/Java bridge.
Unless you really need Drupal on Tomcat, I would suggest you install a WAMP environment (Apache / PHP + MySQL).
Note : first answer posted just copy pasted the contents of the link I provided...please always add the source !!
Comment: For front end we targeted to java/JEE applications only. @user7


do i need to install motherboard and graphic card drivers..? if yes then how..?

Question: Right now I am windows user but I am thinking of using of ubuntu. So if I install ubuntu do I need to install motherboard and graphic card drivers like windows?
My motherboard is Gigabyte B75M-D3V and graphic card is Sapphire Radeon HD6450 (2GB)
Answer: You do not need to install "motherboard" drivers.
But you probably may want to install proprietary video drivers from System Settings -> Software & Updates -> Additional Drivers
Answer: Let me explain some facts about Linux:

Linux is "Plug and Play" in 99% of the cases. Most drivers are present by default in the Linux kernel, and that means you'll rarely need to install any additional drivers (unlike in Windows). For example, if you buy a brand new flash drive you can be pretty sure that you'll connect it in your Linux box and it WILL work.
The same happens with most hardware. Video cards/GPUs, wireless adapters, bluetooth cards... If you have extremely new hardware, prefer getting a newer Ubuntu version (current is 15.10). The kernel is more up-to-date and new hardware will probably be recognized. If you have older hardware, prefer a LTS version (current is 14.04), which comes with more stable packages and is usually very trusty (get it? Trusty Tahr?).
Ubuntu comes with an application called "Additional drivers". You can use it to easily manage your hardware drivers. Ubuntu automatically selects the open source drivers for your GPU, for example, but you can install proprietary drivers to have better performance, if you want.


Any way to provide reason to a disabled suite in Jasmine

Question: Currently, we can give reason to pending spec using pend() function this way -
xit("pending spec", function(){
    //Skipped spec
}).pend("This is a reason");

Output of the above function would be -
Sample Test: pending spec
This is a reason
Executed 1 of 1 specs (1 PENDING)

Now, how to get the same reason for the disabled suites?
xdescribe('Disabled suite' , function(){
    it('example spec', function(){
        //example
    });
}).pend("This is a reason");

Output of the above disabled suite is -
No reason given

and remains the same even if I use pend() function. Thanks!
Comment: The pending message on a suite is not yet supported. See by yourself: https://github.com/jasmine/jasmine/blob/master/src/core/Suite.js#L45
Comment: Thanks @FlorentB. I was hoping to see some way I can make this happen. I know `pend()` doesn't work, but is there any other way that we can do it? Simply showing "No reason given" doesn't make sense without adding a customization feature to it. Thanks!
Answer: The pending message is not implemented on a suite, but you could override the pend method to make it write the message on each spec:
jasmine.Suite.prototype.pend = function(message){
    this.markedPending = true;
    this.children.forEach(spec => spec.pend(message));
};

Usage:
xdescribe('Suite', function() {

}).pend("Feature not yet implemented");

Source code for Suite.js:
https://github.com/jasmine/jasmine/blob/master/src/core/Suite.js#L45
Comment: cool, I forgot that I could override the implementation.. Thanks!


Grub problem after installation

Question: I wanted to install Ubuntu to my fujitsu desktop pc so I created a live usb , booted it and clicked on install. I didn't notice it was installing to my 500 gb portable HDD as it had the most free space.
It created a new partition and then finished the installation. After restarting, my pc says the (partition) cannot be found and so enters grub rescue.
Apparently Ubuntu created an entry in the Grub menu but it can't find the HDD on boot.
My PC and all files are intact but Windows isn't booting, and my BIOS is locked with a password so I cannot change BIOS settings.
PC Specs:

1.87 GB ram
3.6 GHz Pentium (dual core) processor
PHOENIX BIOS
320 GB hitachi HDD
500 GB toshiba portable HDD
Comment: You can reset your BIOS settings, and thus the password, by removing the battery or pressing/switching the CMOS switch on your mainboard.
Answer: The easy option is just to boot from the live usb, install boot-repair from the software center, then run it.

Grub problem after installation


parameters lost when open new window in C#

Question: I develop a site where certain pages a user can only access when he is logged in.
For certain requests I would be better when I open new window. Mostly I use the session to store data including the user data.
To open a new window I use:
<code>ScriptManager.RegisterStartupScript(this, typeof(string), "OpenWindow",
              "window.open( '~/smsftd1', null,'height=400,width=600, status=yes,
               toolbar=no, menubar=no,location=no' );", true);
</code>
It opens the window and it looks how I want it and how it should behave. The only downside is that all data I have saved with the session variables are gone.
If I redirect in the same pages or even open a new tab it works fine and all session variables are available.
When I search for the issue it was pointed out it is an IE issue (older versions). I changed the settings in the IE browser settings but it did not help.
The main issue is that I loose the authorisation the user made.
At the moment I removed to opening of a new window and just redirect.
If someone has done this I wish to know so I can organise a better flow.
The only option I could think of is storing data in a cookie instead of the session.
Any feedback please?
Answer: There is no direct answer, but you can check with fiddler or trash tool in firefox.
Please increase your session timeout.
Also check in global.aspx, that there is no event call when new window open.
The best thing is fiddler to check where you all history show about what are the cookie/session variable, link to redirect etc.
Please this link before doing anything.
After a few window.open calls my ASP.NET session times out
http://bytes.com/topic/asp-net/answers/287080-session-variable-window-open
Keeping ASP.NET Session Open / Alive
Add in web.config and try(reference from above link)
<code>"<httpHandlers>
<add verb="GET,HEAD" path="SessionHeartbeat.ashx" validate="false" type="SessionHeartbeatHttpHandler"/></httpHandlers>"
</code>
Comment: I am still working my way around this and try to fix it:) getting closer to the solution but have still some issues. I hope I can mark it next week as answer. Thank you @Ajay2707 to suggest these solutions
Comment: Tnx dear that my comment helps you. The best thing is firefox Session manager  https://addons.mozilla.org/en-US/firefox/addon/session-manager/


bash `mv -n` detect if not overwritten

Question: I tried searching but couldn't find a similar question. If this is a duplicate, please let me know and I'll gladly remove it.
I've got a script for renaming files inside of a loop, running:
mv -vn "$file" $newname
if [ $? -eq 0 ]
then
    *do something*
fi

With -v I can see on the screen xxx not overwritten, but I'm trying to detect when a file is not renamed by the script due to a file with the same name already existing.
The mv utility exits 0 on success, which is the case whether the file is renamed or not.
Any pointers?
Comment: Can't you just use `ls` on the filename before you try to move? `ls` will return different values for `file does not exist` and `file does exist`.
Comment: @FlorinStingaciu Ughhh... No, don't parse `ls` output. However, something like `if [[ -a "${newname}" ]]; then ...` would work to check if the file exists.
Comment: @twalberg - Race condition.
Comment: @TomZych True, but I'm not entirely sure what the OP is looking for can be done entirely race-free in `bash`, at least not without sacrificing a significant amount of simplicity and/or performance... And it's no worse than the other comments/answers in that regard.
Answer: You can check if the file exists, if not rename:
test -e $newname || mv $file $newname
If you need message saying xxx not overwritten:
test -e $newname && echo "$newname not overwritten" || mv $file $newname

Comment: @Tiago - yes. Granted this is more of a concern in an automated context than with this sort of manual tool, but you never know how something will end up being used.
Comment: Wow I had the blinders on...I should have been thinking along these lines...thanks!
Comment: @TomZych do you mean that in the interval between the `test` and `mv`  a file may have been created?

bash `mv -n` detect if not overwritten


Pandas: Generate a new df from 3 dfs based on conditions and comparisons

Question: I have a large dataset split into three dfs.
df1 contains grided (lat-long) and vegetation type data.
df1:
col      row    Type    TypeNo
-125    42.5    BF        4
-125    42.5    MTF       8
-125    42.5    TCF       9
-125    42.5    TDF       10
-125    42.5    SG        13
-125    42.5    AS        15
-125    42.5    XFW       19
-125    42.5    TBEF      33
-125    32.5    BF        4
-125    32.5    MTF       8
-125    32.5    TCF       9
-125    32.5    TDF       10
-125    32.5    SG        13
-125    32.5    AS        15
-125    32.5    XFW       19
-125    32.5    TBEF      33

df2 contains temperature data for each grid.
df2:
col     row     Tmin    Tmax
-125    42.5    7.1     36.7
-125    32.5    7.1     16.7

df3 contains temperature limits for each vegetation type in df1.
df3:
Type    TypeNo  limit_Tmin  limit_Tmax
BF        4          -60    21
MTF       8           -5    23
TCF       9          -40    10
TDF      10          -30    30
SG       13          -20    38
AS       15          -20    38
XFW      19          -40    15
TBEF     33          -40    20

I am trying to apply the temperature limits to df1 such that for every vegetation type:
if (df2: Tmax > df3: limit_Tmax) then vegetation is False, else, True
This has to be done in each grid.
An example output would be df1 and a new column with True/False, i.e.:
col      row    Type    TypeNo     Possible
-125    42.5    BF        4         False
-125    42.5    MTF       8         False
-125    42.5    TCF       9         False
-125    42.5    TDF       10        False
-125    42.5    SG        13        True
-125    42.5    AS        15        True
-125    42.5    XFW       19        False
-125    42.5    TBEF      33        False
-125    32.5    BF        4         True
-125    32.5    MTF       8         True
-125    32.5    TCF       9         False
-125    32.5    TDF       10        True
-125    32.5    SG        13        True
-125    32.5    AS        15        True
-125    32.5    XFW       19        False
-125    32.5    TBEF      33        True

I am new pandas and need help on how to do this.  Thank you!
Answer: First we use merge to put all the data into a new data frame, then we define a new column for df1 based off the values of the new dataframe.
#pd is pandas
import pandas as pd
#Merge df1 and df2
dft = pd.merge(df1, df2, on=["col", "row"], how="left")
#Merge result of that with df3
dft = pd.merge(dft, df3, on=["Type", "TypeNo"], how="left")
#Create new column and put it in df1
df1["Possible"] = dft["Tmax"] <= dft["limit_Tmax"]

Answer: just bunch of simple joins to get your desired result:
df_data = df1.merge(df3 , on=[ 'Type', 'TypeNo'],how='left')
df_data = df_data.merge(df2 , on=[ 'col', 'row'],how='left')
df1['possible'] = df_data['Tmax'] <= df_data['limit_Tmax']
print(df1)

output:
>>>
    col   row  Type  TypeNo  possible
0  -125  42.5    BF       4     False
1  -125  42.5   MTF       8     False
2  -125  42.5   TCF       9     False
3  -125  42.5   TDF      10     False
4  -125  42.5    SG      13      True
5  -125  42.5    AS      15      True
6  -125  42.5   XFW      19     False
7  -125  42.5  TBEF      33     False
8  -125  32.5    BF       4      True
9  -125  32.5   MTF       8      True
10 -125  32.5   TCF       9     False
11 -125  32.5   TDF      10      True
12 -125  32.5    SG      13      True
13 -125  32.5    AS      15      True
14 -125  32.5   XFW      19     False
15 -125  32.5  TBEF      33      True


Privacy issue when waking up suspended machine

Question: Using Xfce, when I close the notebook lid it suspends, and when I open the lid it wakes up. When it wakes up it shows the screensaver until I press a key or move the mouse then it asks me for my password. All that is working beautifully. The issue is that when I open the lid, for a second or so I can see what is on the desktop, all the open windows, etc. Then it does a fade into the screensaver. The expected behaviour is that I see a blank screen, or the login prompt, immediately.
I've removed the screen saver (set it to be a black screen) but that made no difference.
Is this something that can be configured?
System details: Lenova E540, Mint 16, Xfce 4.10.
(In contrast, my Ubuntu 10.04 notebook did not have this issue: when the case was opened it always showed a blank screen. However I always had to suspend from the power control menu, as closing the case was unreliable as a way to get it to suspend, so maybe that was why??)

More Notes:
(Thanks to Nattgew for finding a related bug report.)
There appears to be a distinct difference between closing the screen, and going to the power manager and choosing suspend.
Close screen: screen visible when opening, then it goes to screensaver, then I have to type password to login. Wifi net connection is preserved.
Explicit suspend: wifi is disconnected. When I resume the screen is visible, it doesn't go to screensaver, it doesn't ask password. It needs to reconnect to wifi.
  --> FIXED THIS BIT. launch xfce4-session-settings, go to last tab ("Advanced") and mark "Lock screen before sleep" checkbox. You also have to check the checbox that says the same thing in Power Manager preferences!! (Source.)   So, now I've fixed this, both ways of suspending show the screen fading away into the screensaver, then prompt for password. However the explicit suspend is still the only one that disconnects wifi.
(Using pm-suspend from the commandline works just like going to the power manager menu.)
Comment: Sounds like the bug here: https://bugs.launchpad.net/ubuntu/+source/unity-2d/+bug/830348
Comment: It's a little mind-blowing that such a glaring security issue hasn't yet been fixed since it was reported [in 2011](https://bugs.launchpad.net/ubuntu/+source/unity-2d/+bug/830348), but apparently there's a plausible reason for that - see comment #19 in that bug report.
Answer: This seems to be present in a lot of distros. This is a workaround I'm using for Cinnamon on Debian, but it should be possible to do something similar with other distro/window manager combinations:

Use dconf-editor to change the button-suspend action at org>cinnamon>settings-daemon>plugins>power to 'nothing' (you could also amend lid-close-ac-action and lid-close-bettery-action as well if you're using a laptop).
Save the following script to a convenient location:
#!/bin/bash
cinnamon-screensaver-command -l
systemctl suspend

Use the System Settings app to create a custom keybinding for the sleep key that points to the script.

After this it behaves as it should. You can see the lock screen pop up briefly before it goes to sleep, which is reassuring.
Answer: It turns out the key is that it is a screensaver "problem", nothing to do with power management, suspend or resume!
So, go to Screensaver preferences, then the advanced tab. In the bottom-right is "Fading and Colormaps". Uncheck "Fade to Black when Blanking".
(I also have Grab Desktop Images unchecked, though I personally use the "Blank Screen Only" screensaver, so that is academic.)
This solution works equally well with lid-closing or using pm-suspend or using the suspend button from the power management menu; and equally well with opening the lid, or pressing the power button to resume. In a couple of my tests I did see the screen flash on briefly after a resume, when using power button to suspend and resume; one of those times it effectively crashed xfce, perhaps as I was testing too quickly. However using the lid-closing/lid-opening technique it has been always behaved correctly (so far).
Comment: It seems to work for me too !


Can not launch tlp

Question: I have installed tlp in Kubuntu 19.04.   I tried to launch it from the Discover application and a message appears:

cannot launch tlp

What do I need to do to confirm it's working?
Answer: TLP runs as a service. It is started from the terminal and it has no GUI.
After you install TLP, you run it for the first time using this command in the terminal:
sudo tlp start

Then you do not need to run it again. It will run automatically with each reboot.
You can check the status of the TLP service by running the following command in the terminal:
sudo systemctl status tlp.service

You will get an output like this:
● tlp.service - TLP system startup/shutdown
   Loaded: loaded (/lib/systemd/system/tlp.service; enabled; vendor preset: enabled)
   Active: active (exited) since Tue 2019-08-27 23:06:37 +03; 3 days ago
     Docs: https://linrunner.de/tlp
 Main PID: 2374 (code=exited, status=0)
    Tasks: 0
   Memory: 0B
   CGroup: /system.slice/tlp.service

enabled means it will run automatically every time the system starts.

To see TLP's extended status information, please run the following command in the terminal:
sudo tlp-stat

Comment: The answer was very good. I applied and it works.Thank you.
Comment: @AbhedaYoga I am glad it helped. You are most welcome.

Can not launch tlp


Brotherhood of Steel is now my enemy, what now?

Question: After I got my rank as a Knight, I was roaming in the big zeppelin untill I saw a couple molerats in a cage, i decided to shoot them, as i turned around the whole zeppelin was shooting at me. I killed their leader(maxus?) and a couple other Knights. Can i still join or work for the BoS or am I going to stay their enemy?
all the BoS quests are deleted from my Quest tab
Comment: If you killed the leader who gives you the quests why do you think you can still get him to give you quests? :)
Comment: maybe he'll spawn back :P so i got got 3 factions to choose from now?
Answer: Well that depends on what you want to do - if you want to be enemies with the Brotherhood of Steel you can go and speak to Preston Garvey at the Sanctuary and this should allow you to continue the story with the Minutemen.
If you don't want to be enemies with the Brotherhood of Steel then load an earlier save.


Solving a Simple Sorting Problem in MATLAB

Question: I have been given this problem in a MATLAB course I am doing. The instructor's solution provided there is wrong, and I have been struggling with the same problem for hours as I am a beginner who has just started coding (a science student here).

Consider a one-dimensional matrix A such as A = \[5 8 8 8 9 9 6 6 5 5 4 1 2 3 5 3 3 \]. Show the percentage frequencies of unique
elements in the matrix A in descending order.
Hint: Use the functions tabulate and sort.

How do I solve this problem using only tabulate, sort, and find functions (find is for eliminating zero frequency elements in tabulate table, which my instructor did not do)?
I tried first extracting the indices of non-zero elements in the percentage column of tabulating table using the find function, which I succeeded in doing using the following:
A = [5 8 8 8 9 9 6 6 5 5 4 1 2 3 5 3 3 ];
B = tabulate(A);
C = find(B(:,3) > 0)

But I am now struggling to return the values corresponding to the 3rd column of B using indices in C. Please help. Also please give me some alternative syntax where one can easily make a vector out of non-zero elements of a row or column easily by omitting the zeroes in that vector if it exists. Rest of the problem I'll do by myself.
Comment: `B = tabulate(A);` then `B = sortrows( B, 3, 'descend' );` or manually sort rows if you really need to use `sort` by doing `[~,idx]=sort(B(:,3)); B = B(idx,:);`?
Comment: Thanks brother for your help. But in the next question of my assignment this was easily answered by me itself as the question stated:

**"Write the equation which will delete the non zero elements form a single dimensional matrix A".**

And the answer to this question is so dumb I facepalmed myself in disappointment.

`A(find(A))`

So the solution to my question simply becomes:

`A = [5 8 8 8 9 9 6 6 5 5 4 1 2 3 5 3 3 ];
B = tabulate(A);
C = B(:,3);
D = sort(C(find(C)),'descend')`
Answer: With your find command, you are just finding the indices of the matrix and not the values themselves.
So you either will do something like this:
A = [5 8 8 8 9 9 6 6 5 5 4 1 2 3 5 3 3 ];
B = tabulate(A);

for i = 1:size(B,1)-1
    if B(i,3) == 0
        B(i,:) = [];
    end
end

sortrows(B,3,'descend')

where you remove the 0 value's row.
Or since you have all the numbers with none-zero frequency you can ask for their rows. Like this:
A = [5 8 8 8 9 9 6 6 5 5 4 1 2 3 5 3 3 ];
B = tabulate(A);
C = find(B(:,3) > 0);
sortrows(B(C(:),:),3,'descend')

in a bit more elegant way. B(C(:),:) calls all the rows with first indices the indices of matrix C. Which is exactly what you are asking for. While at the same time you sort your matrix based on row 3 at a descending order.


List view customization in android

Question: I am making an android app. I want to make List-view as above image. In this Listview I am fetching Items value from database using JSON webservice and how can change List-view Items border color and background image.  Items 1,3,5,7,9 = same color and same background and List-view Items 2,4,6,8,10 = same color and same background. How can i do. please help me.
Comment: might be similar to [this post](http://stackoverflow.com/questions/10305176/android-listview-with-2-different-colors)
Comment: can you put your getView() method so that I could edit it for you?
Answer: Perhaps this tutorial can help you: android.amberfog.com
Just 2 types of items: in getView you doing almost the same, that in  tutorial, but, instead of separator you setting your list item.
HTH.
Answer: I assume you know how to write an xml file with a dashed stroke. ask me if you need to know how to do it.

Use two separate background xml files: background_yellow_stroke.xml and background_back_stroke.xml put them in a new res folder and name it: colors
In your adapter's getView() method: use mod (%) operand to determine whether your position is even or odd.

public class MyCustomAdapter extends ArrayAdapter {
    private List data;
    private Activity context;
<code>public NoteArrayAdapter(Activity context, int resID,
        List<Note> data) {
    super(context, resID);
    this.data = data;
    this.context = context;
}

@Override
public int getCount() {
    return data.size();
}

@Override
public boolean isEmpty() {
    return data.size() == 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (convetView == null) {
        LayoutInflater inflater = context.getLayoutInflater();
        convertView= inflater.inflate(R.layout.custom_list_item, parent, false);
    }

    if (position % 2 == 0) {
            convertView.setBackgroundResource(R.colors.background_yellow_stroke.xml )
       }
    else
       {
           convertView.setBackgroundResource(R.colors.background_black_stroke.xml )
       }

    return convertView;
}
</code>
}
Done.
Comment: how can i put scissor in top right plach on dashed stroke.
Comment: @Amardeep: That's a complete question, but I'll answer it here:

 use two layouts, put the stroke to the inner layout and use layout_margin for it, put the sissor to the upper-right corner of the outer layout (use relative layout) and you are good to go :)

List view customization in android


Wifi selective proxy server

Question: I use Dropbox to backup files on my 12.04 laptop. Currently, whenever Dropbox has an internet connection it syncs. This is an issue when I am tethering with my mobile because of the cost of mobile data.
The Dropbox application doesn't let me choose which wifi networks to use but I can use a proxy server. So I was thinking I could setup a local proxy server with wifi rules.
Does anyone know of a proxy server which has network rules based on wifi? Or does anyone have a better option for limiting Dropbox to particular wifi networks? Apart from simply closing Dropbox ;)
Answer: I have no experience with the proxies, but you can use UFW (Uncomplicated Firewall) to redirect the outbound traffic. You can start here: https://help.ubuntu.com/community/UFW and here's how you can redirect inbound traffic: https://serverfault.com/questions/238563/can-i-use-ufw-to-setup-a-port-forward.
Comment: Cheers mate, I was hoping for a simpler solution but this will work :)

Wifi selective proxy server


Why does Docker not remove stopped containers?

Question: I am new to Docker and just getting started. I pulled a basic ubuntu image and started a few containers with it and stopped them. When I run the command to list all the docker containers (even the stopped ones) I get an output like this:
> docker container ls -a

CONTAINER ID   IMAGE           COMMAND       CREATED          STATUS                      PORTS     NAMES
099c42011f24   ubuntu:latest   "/bin/bash"   6 seconds ago    Exited (0) 6 seconds ago              sleepy_mccarthy
dde61c10d522   ubuntu:latest   "/bin/bash"   8 seconds ago    Exited (0) 7 seconds ago              determined_rosalind
cd1a6fa35741   ubuntu:latest   "/bin/bash"   9 seconds ago    Exited (0) 8 seconds ago              unruffled_lichterman
ff926b6eba23   ubuntu:latest   "/bin/bash"   10 seconds ago   Exited (0) 10 seconds ago             cool_rosalind
8bd50c2c4729   ubuntu:latest   "/bin/bash"   12 seconds ago   Exited (0) 11 seconds ago             cranky_darwin

My question is, is there a reason why docker does not delete the stopped containers by default?
Comment: For instance, because someone may want to restart it ...
Comment: Why would you want docker to delete the stopped containers? That would be like taking time to setup a new computer and then resetting it to factory settings any time you wanted to turn it off for the day.
Comment: If you want your container to be automatically removed, once stopped, you can start it with the `--rm` flag https://docs.docker.com/config/pruning/#prune-containers
Comment: @CWSites My assumption is that all the 'setup for a new computer' is what the docker image itself is about no? Why would I want to keep around an old container when I can spin up a new one using the docker image. Isn't a better analogy for keeping old containers around that you turn off your computer but you want the data in your RAM/cache to be safe?
Comment: @CWSites Note that "a container always starts from a clean slate" is actually one of the big advantages of using Docker.  It's a lot easier to set up a container when you know that it contains exactly what's in the image than to try to follow on a long stream of incremental updates.
Comment: You need to use `docker container prune -f` to remove all stopped container. You could make a script to stop all the containers and delete them.
Comment: @GinoMempin It answers what docker artifacts remain undeleted but not why they remain so.
Comment: @MarcoPolo It's not deleted *because* of all those artifacts that are kept after containers are stopped.
Answer: The examples you've provided show that you're using an Ubuntu container just to run bash. While this is fairly common pattern while learning Docker, it's not what docker is used for in production scenarios, which is what Docker cares about and is optimizing for.
Docker is used to deploy an application within a container with a given configuration.
Say you spool up a database container to hold information about your application. Then your docker host restarts for some reason, and that database disappears by default. That would be a disaster.
It's therefore much safer for Docker to assume that you want to keep your containers, images, volumes, and so on, unless you explicitly ask for them to be removed and decide this is what you want when you start them, with docker run --rm <image> for example.
Answer: In my opinion, it may have some reasons. Consider below condition:
I build my image and start the container (production environment, for some reason I stop the current container, do some changes to image and run another instance, so new container with new name is running.
I see new container does not work properly as expected, so as now I have the old container, I can run the old one and stop the new so the clients will not face any issues.
But what if containers were automatically deleted if they were stopped?
Simple answer, I would have lost my clients (even my job) simply:) And one person would be added to unemployed people :D
As @msanford mentioned, Docker assumes you want to keep your data, volumes, etc. so you'll probably re-use them when needed.
Since Docker is used to deploy and run applications (as simple as WordPress with MySQL but with some differences installing on Shared Hosting), usually it's not used for only running bash.
Surely it's good to learn Docker in the first steps by running things like bash or sh to see the contents of container.


Can I use individual wires from romex bundle?

Question: I am wiring three overhead florescent lights in my unfinished basement and I need 14/3 because of where the switch is located. The wiring already present between the fixtures is 14/2. I have a length of leftover 14/2 romex. Can I remove the sheathing and use each individual wire?
Comment: I've learned electrical codes are not just for the safety of the user, but also the safety of the tradesman or serviceman working on the system.  Things that have no use to the homeowner usually provide safety to someone else.
Comment: No. You do not want unsheathed wire carrying mains voltage anywhere in your house. - Exposed in an unfinished basement it could easily get damaged when moving furniture, cabinets, etc.
Comment: Just run the sheathed 14/2, use the black wire, and cap off the white and ground.
Comment: Either way, I'm buying more wire.
Comment: I recommend using Split Loom Tubing.
Comment: You can't use the wires inside NM cable individually, as they are not labeled as individual conductors.  NM cable is rated, listed, and labeled as a cable.
Comment: @A.I.Breveleri Code requires that all wire in a circuit be in the same cable assembly. Running a parallel cable for just one current carrying wire is not allowed.
Comment: @bib: What does the code have to say about a circuit that requires 4, 5, or more conductors? Must I haunt electrical warehouses questing for 12/4g, 14/5g, etc.?
Comment: @A.I.Breveleri Conduits and raceways are often used. But the most common multiwire situation is 14/3 or 12/3, both readily available.
Comment: Related: https://diy.stackexchange.com/questions/213713/can-i-run-stripped-romex-nm-through-conduit
Answer: Short answer: NO
You may be able to use individual wires taken from a non-metallic cable (Romex is a brand) within a fixture, but not between fixtures or switches.
NEC 300.3(B) requires that:

All conductors of the same circuit ... shall be contained within the same raceway, auxiliary gutter, cable tray, cablebus assembly, trench, cable, or cord [with certain exceptions that do not apply here].

If you give us a diagram of your fixtures and switches, we may be able to suggest a solution.
Comment: I appreciate the offer. Due to the current setup, I'll have to buy more wire.


How to specify label_attr for a model in a Flask-Admin ModelView using MongoEngine?

Question: I think I have a pretty common use case and am surprised at how much trouble it's giving me.
I want to use a key-value pair for a ReferenceField in the Flask-Admin edit form generated by the following two classes:
class Communique(db.Document):
    users = db.ListField(db.ReferenceField(User), default=[])

class User(db.Document):
    email = db.StringField(max_length=255, required=True)

    def __unicode__(self):
        return '%s' % self.id

I want the select to be constructed out of the ObjectId and the an email field in my model.
By mapping the   __unicode__
attribute to the id field I get nice things on the mongoengine side  like using the entire object in queries:
UserInformation.objects(user=current_user)

This has the unfortunate effect of causing the Flask-Admin form to display the mongo ObjectId in the edit form like so:

The docs say I have to provide the label_attr to the ModelSelectMultipleField created by Flask-Admin.  I've done so by overriding the get_form method on my ModelView:
def get_form(self):
     form = super(ModelView, self).get_form()
     form.users = ModelSelectMultipleField(model=User,
         label_attr='email',
         widget=form.users.__dict__['kwargs']['widget'])
     return form

I'm reusing the the widget used by the original form.users (which may be wrong). It works fine when editing an existing item, BUT throws an exception when creating a new one (perhaps because I'm reusing the widget).
All of this seems like way more work than should be needed to simply provide a label_attr to my SelectField.  Fixing up the listing view was a simple matter of adding an entry to the column_formatters dictionary.  Is there no simple way to specify the label_attr when creating my ModelView class?
I know I could make this problem go away by returning the email property in the __unicode__  attribute, but I feel like I shouldn't have to do that!  Am I missing something?
Answer: Oy, now I see how to do it, though it's not that obvious from the docs.  form_args is a dictionary with items keyed to the form models.  All I needed to do was...
form_args = dict(users=dict(label_attr='email'))

Which does seem about the right amount of effort (considering Flask-Admin isn't some sort of java framework).


My university network is changing resolv.conf. How do I prevent that?

Question: When I connect to the internet in my university, through a PEAP, MSCHAPv2 protected WPA2 wifi network, it changes my resolv.conf to this:
# Dynamic resolv.conf(5) file for glibc resolver(3) generated by resolvconf(8)
#     DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN
# 127.0.0.53 is the systemd-resolved stub resolver.
# run "systemd-resolve --status" to see details about the actual nameservers.

nameserver 127.0.0.53
search ufsc.br

However, when I get home, I can't access the website as it tries to reach a local address which obviously isn't there. I have to manually remove the nameserver/search lines to be able to access it again.
My question is: what process is actually doing this - changing the file as I connect to my university's network? How can I find out which process is doing it and tell it to stop? Or, if this is necessary - how do I automatically roll the file back to an empty version when I leave the university's network?
Comment: This seems to be the same problem as https://askubuntu.com/q/58781/696245
Comment: You should probably have a look at https://askubuntu.com/questions/907246/how-to-disable-systemd-resolved-in-ubuntu
Comment: I'll take a look at the second one but the first one seems to break VPN functionality for some users, something I also use (the University's VPN).
Answer: I'd recommend to set a static IP through Network Manager first. Once connected to the network of your university, modify the settings going to the IPv4 tab and choosing the Manual method. Press the Add  button and add your static IP.
Example:
IP 192.168.x.xxx
Netmask 255.255.255.0
Gateway 192.168.x.x
Save your new configuration
To know your Gateway digit the following command in a terminal:
route -n

The output of the command should be something like this:
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         192.168.2.1     0.0.0.0         UG    600    0        0 wlp2s0
169.254.0.0     0.0.0.0         255.255.0.0     U     1000   0        0 wlp2s0
192.168.2.0     0.0.0.0         255.255.255.0   U     600    0        0 wlp2s0

As you can see my Gateway is 192.168.2.1 and the IP you will choose will be a 192.168.2.xxx ( example 192.168.2.100 ).
Disable the systemd-resolved service and stop it:
sudo systemctl disable systemd-resolved.service
sudo service systemd-resolved stop

Put the following line in the [main] section of your /etc/NetworkManager/NetworkManager.conf:
dns=default

Install resolvconf:
sudo apt-get install resolvconf

and edit or create the file /etc/resolvconf/resolv.conf.d/tail
sudo nano /etc/resolvconf/resolv.conf.d/tail

Add Google nameservers (one per line) to the file
nameserver 188.8.131.52
nameserver 188.8.131.52

Save the file pressing Ctrl+O
RESTART YOUR SYSTEM and connect to your network
Comment: This will probably break wifi functionality if they're in a University environment that is not wired.
Comment: @Thomas Ward . Why it should?
Comment: @Thomas Ward. I mean, it's my daily wireless configuration and i have no problems at all with it.
Comment: I should be able to try that on Monday!
Comment: This didn't work - not because the file was still changed, but because the internet didn't work at all. Maybe Ward was right and it did break wifi functionality.


PHP racing like condition on string conversion

Question: I am having a very weird problem.
When I run my piece of code, I get an error saying <code>$carDay->date</code> is not an object. but when I run it in debug mode, it works fine. So I assume it is kind of a racing condition.
$trip is an object from ORM database (MySQL) and getStart-> is just a getter that gets the starting date in this format "20120929T024754". I convert that string to a date and then do stuff with the date. But like I said when I run it without debugging the date doesn't seem to be converted in time when I want to access it. Does anyone have anyone Idea why or what I can do about it ?
<code> private function calculateIntLate($trip) {
    $carDay = $trip->getStart();
    $carDay_date = $this->convertStringToDateTime($carDay);

    $carDate = $carDay_date->date;
  }

  public function convertStringToDateTime($string) {
    //012345678901234
    //20120929T024754
    $year = substr($string, 0, 4);
    $month = substr($string, 4, 2);
    $day = substr($string, 6, 2);
    $hour = substr($string, 9, 2);
    $minute = substr($string, 11, 2);
    $second = substr($string, 13, 2);
    $dateTime = new \DateTime($year . '-' . $month . '-' . $day . ' ' . $hour . ':' . $minute . ':' . $second);
    return $dateTime;
  }
</code>
Comment: `var_dump($carDay);` And according to your code it's a string, not an object.
Comment: Are you even using threads with shared data? (I don't believe this can happen in PHP without you doing so deliberately.)
Comment: I am not using threads. that is the strange part. Can it have something to do whit lazy loading ?
Answer: You probably want this:
<code>$carDate = $carDay_date->date;
</code>
not
<code>$carDate = $carDay->date;
</code>
Comment: Yes, sorry that was a typo when removing unnecessary code for stackoverflow.
Comment: @Nealv: `var_dump($carDay_date);`
Comment: + `var_dump($year . '-' . $month . '-' . $day . ' ' . $hour . ':' . $minute . ':' . $second);`
Answer: Ok,
I found the answer here.
Aparently you cant use the Datetime->date property


Is there a Wiki with a Web 2.0 UI (like StackOverflow's)?

Question: I need to use MediaWiki at work. It used to be okay, but with sites s.a. StackOverflow, there's some user interface issues that simply don't do any more.
Most importantly, I'd want to see the live preview when typing. There shouldn't be need for a preview mode.
What Wikis are you using? Which would be the best for a recent (easy) Web experience?
Can MediaWiki be updated to have more recent UI behaviour?
Addendum:
Two products seem to be above others, both "open source commercial" (= you get a skinny version free, standard and enterprise levels with more goodies cost).

MindTouch DekiWiki
Confluence

Judge for yourself. I sure found my liking in one of these. :)
Comment: http://www.mediawiki.org/wiki/Manual:Live_preview
Comment: http://www.mindtouch.com/Products/Demo_Gallery looks reeeeeally good.
Comment: MediaWiki 1.5 alpha 1 seems to have something for this itch:

* 'live preview' reduces preview reload burden on supported browsers
Comment: WikiWig has been mentioned here:
http://stackoverflow.com/questions/15871/getting-developers-to-use-a-wiki
Answer: There is a WYSIWYG extension for mediawiki. See Fckeditor:
Answer: Well there is StackExchange (which is the StackOverflow engine), but you have to pay for it.
Comment: Thanks! Only heard about that now. Will be glad to try out the beta.
Answer: A discussion  on Confluence vs Mediawiki: http://confluence.atlassian.com/display/DISC/Confluence+Vs+Mediawiki
Answer: It doesn't have the preview feature you talk about, but you asked for "favorite wikis", so here's mine (at least favorite for ease of use/setup):
http://en.wikipedia.org/wiki/ScrewTurn_Wiki
http://www.screwturn.eu/


How to disable or set to empty array model property $with to not eager load default model relations when needed?

Question: I have something like this:
class User
{
    protected $with = ['organisation'];
}

class Group
{
    public function members(): BelongsToMany
    {
        return $this->belongsToMany(User::class, 'groups_members', 'group_id', 'user_id', 'id', 'id')
                    ->select(['users.id', 'users.name', 'users.email']);
    }
}

How to prevent loading of organisation relation for group members?
Answer: You can use without():
public function members(): BelongsToMany
{
    return $this->belongsToMany(User::class, 'groups_members', 'group_id', 'user_id', 'id', 'id')
                ->select(['users.id', 'users.name', 'users.email'])
                ->without('organisation');
}