text:
Q: Unable to install Maven on ubuntu 16.04 I'm not able to install maven on my system I have tried using below command:
sudo apt-get install maven

It giving me below errors:
Reading package lists... Done
Building dependency tree
Reading state information... Done
You might want to run 'apt-get -f install' to correct these:
The following packages have unmet dependencies:
  libperl5.22 : Depends: perl-modules-5.22 (>= 5.22.1-9ubuntu0.2) but 5.22.1-9 is to be installed
  maven : Depends: libmaven3-core-java (= 3.3.9-3) but it is not going to be installed
  perl : Depends: perl-modules-5.22 (>= 5.22.1-9ubuntu0.2) but 5.22.1-9 is to be installed
E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).

I have no clue what happening here and how do I install it.

A: As the error message suggests "run apt-get -f install with no packages":
sudo apt-get install -f

If that doesn't help, your packages may be (partially) out of date. Update them while fixing dependency issues again (-f):
sudo apt-get update
sudo apt-get upgrade -f

(You can also append maven to the latter command to try to install it in one go together with the upgrades and dependency fixes.)
If apt-get update leads to errors itself, please try to fix them before you proceed. Search on Ask Ubuntu for the error message1 or ask a new question.

1 Sometimes Google is a better search engine than the one integrated into Stack Exchange. You can limit a Google search to one domain with the site: operator, e. g. site:askubuntu.com Unmet dependencies.

A: It might looks dummy but did you run sudo apt-get -f install as it recommend?


text:
Q: Relay two SSH connections together I have three machines:

*

*I have physical access to localhost

*I want to ssh into host1. However, it is behind carrier-grade NAT, so I can't ssh directly to it from localhost

*relayhost is set up to help me connect from localhost to host1
I want to ssh from each localhost and host1 to relayhost, then have relayhost relay my ssh connection from localhost to host1.
This answer suggests I can create a tunnel on relayhost using ssh -L if I know the URI or IP address of host1. However, I don't know that because of the carrier grade NAT. So I can imagine a process to relay it like this:

*

*On host1, ssh user@relayhost

*relayhost is watching for this connection and when it sees it says "I'm going to create a tunnel from my port 9999 to this connection"

*On localhost, ssh 9999:relayhost
Is this the right way to go about this? How do I do step 2?

A: You don't need any specialized triggers on relayhost. All you need to do is use remote port forwarding with ssh -R instead of local port forwarding with ssh -L.
Now if i understand it correctly - your problem is that neither localhost nor host1 have publicly accessible IP - both are behind NAT. Otherwise it would be easier create tunnel from host1 to localhost with ssh -R and then run second SSH connection inside this tunnel.
If we have to use the relay, it can be done in following steps. For clarity let's rename your localhost machine to myhost now.

*

*Run this on host1:
ssh -R 12345:localhost:22 user@relayhost

This will open port 12345 on relayhost and when anyone connects to it, the data will be forwarded to SSH port 22 on host1.

*Now you can connect to port 12345 on relayhost from myhost.
ssh user@relayhost -p 12345

In case that you have restrictive firewall on relayhost that prohibits external access to port 12345, you can use local port forwarding to open the port locally on myhost:
ssh -N -L 56789:localhost:12345 user@relayhost

And then connect to host1 from myhost:
ssh user@localhost -p 56789

However don't expect to build any permanent networking solution on remote port forwarding (see: https://serverfault.com/q/595323 for future possible problems). You should consider using VPN with server on relayhost for long term setup instead.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the preferred way (better style) to name a namespace in Ruby? Singular or Plural? What are for you the pros and cons of using:
FooLib::Plugins
FooLib::Plugins::Bar

vs.
FooLib::Plugin
FooLib::Plugin::Bar

naming conventions? And what would you use or what are you using? What is more commonly used in the comunity?

A: Assuming Plugin is a base class:

*

*class FooLib::Plugin::Bar < FooLib::Plugin
This is the one I use and recommend. Bar is a Plugin in FooLib and it inherits from FooLib::Plugin. It also keeps the plugins provided by the FooLib library nested under the namespace of the general class, which reads naturally:
# Assign the Bar Plugin of the FooLib library to p.
p = FooLib::Plugin::Bar

If I were to develop a third party plugin for your library, I would create the following structure:
# Baz is a Plugin for the FooLib library provided by BarLib.
class BarLib::FooLib::Plugin::Baz < ::FooLib::Plugin

Note that I mirror the FooLib hierarchy, but under BarLib's namespace. I would not extend it directly.

*class FooLib::Plugins::Bar < FooLib::Plugin
I have also used this one, and I think it makes the most sense. Bar extends FooLib::Plugin and is one of the Plugins provided by FooLib. However, it creates a potentially needless module.
I think this would be a great choice if Plugins was a central plugin repository that implements methods like Plugins.add, Plugins.all and Plugins.loaded.
Use it if you can justify the extra module.

*class FooLib::Plugins::Bar < FooLib::Plugins
Doesn't make a lot of sense to me. Bar is one of the Plugins in FooLib, that part looks fine. However, it inherits from Plugins. Is it inheriting from more than one plugin? It sounds strange to me; the class name shouldn't suggest something that is impossible.

A: Use:
module FooLib end
module FooLib::Plugins end
class  FooLib::Plugins::Plugin; end #the base for plugins
class  FooLib::Plugins::Bar < FooLib::Plugins::Plugin; end
class  FooLib::Plugins::Bar2 < FooLib::Plugins::Plugin; end

or in a different words:
module FooLib
  module Plugins
    class Plugin; end #the base for plugins
    class Bar < Plugin; end
    class Bar2 < Plugin; end
  end
end

Also arrange the files like this:
- foo_lib/
  - plugins/
    - plugin.rb
    - bar.rb
    - bar2.rb

This is how Rails does it (so this is the Rails Way). I.e. look at the Associations namespace and the Associations::Association class from which all of the classes form the Associations namespace inherits (i.e. Associations::SingularAssociation).

A: I would second the approach outlined by @jtrim.
Given that the module (i.e. Plugin) is being used for namespacing only, I typically override the new method in the module:
module Foo
  module Plugin

    def self.included(base)
      raise "cannot be included"
    end

    def self.extended(base)
      raise "cannot extend"
    end

    def self.new(*args)
      Base.new(*args)
    end

    class Base;end
  end
end

base_plugin_obj = Foo::Plugin.new(...)

A: To me FooLib::Plugins appears like a module, used as a namespace which various plugin classes are kept in. FooLib::Plugin looks like a superclass for FooLib plugins.
In FooLib::Plugins::Bar, Bar definitely seems like the name of a plugin. With FooLib::Plugin::Bar, I would be doubtful whether Bar was a helper class used by Foo::Plugin, or the name of a plugin.

A: Generally, the approach I tend to take is:
module Foo
  module Plugin
    class Base; end
  end
end

class Foo::Plugin::Bar < Foo::Plugin::Base; end

The Base class for plugins is a convention found all over the place in the RubyOnRails codebase as well as many others. (e.g. ActiveRecord::Base, ActionController::Base, etc.)
I disagree with @Matheus Moreira's approach where Foo::Plugin is used both as the base class and the namespace for plugins.
The only functional reason why this shouldn't be done has to do with convention - in the Ruby community one will find many less instances of classes as namespaces than modules. The only time I really see classes used as a namespace for another class is when the purpose of said class is private to the namespace class and is not used externally.


text:
Q: ERROR: Content Element with uid "61" and type "mask_container" has no rendering definition! (Typo3, Mask) I transfered a Typo3 website from the dev server to the live server. I can log into the backend, I cleared all caches, activated all necessary extensions. In backend everything seems to run fine.
However, in frontend everything is rendered correctly except the Mask-elements. In place of the mask-elements I get this output:
"ERROR: Content Element with uid "61" and type "mask_container" has no rendering definition!"
Can anyone help?

A: Perhaps you forgot to include the "Fluid Styled Content" and the "Mask" templates in your site template under "include static from extension".

A: I was able to fix it. Static templates were included. I had copied all folders in /fileadmin and /typo3conf. I also had copied the database, imported an export of the dev server database.
But still the paths in the Mask configuration were wrong. I had to correct the paths manually. That fixed it.


text:
Q: Replace 3d model (json) I found an example online and in this example that shows a 3D model (a Ferris wheel) placed on a parking lot with a Google Street View Panorama as the background.
Now I want to replace the Ferris wheel with another 3d object — an asteroid — that I download as a 3DS and OBJ. file. I converted the 3DS file to JSON through Blender but when I replace the file it just shows a blank screen.
How can I do it? Here is my code:
<!DOCTYPE html>

        <title>Street View Overlay - EINA</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">

A: So here's the thing.. you can covert to three.json format, and that's fine, but the version of your conversion tools have to match the version of three you're using.. you also want to be on close to the most recent three.js version..
but a large issue is that the three.json format is still somewhat in flux between versions, so I have had situations in the past where previously exported models go stale.
If I we're you .. I would use the OBJLoader and load your OBJ directly, or use a format like GLTF or Collada, and their respective loaders. Those formats are less likely to age. Especially GTLF looks like its heading toward being widely supported and has a lot of nice features that make it very efficient for realtime 3d.
r.e. your specific problem: First I would ask if you see any errors in the console from when you load your model. Second, I would put a debug breakpoint on the line inside the loader, and visually inspect the scene and its .children,
OR log it in the code with a scene.traverse((elem)=>{console.log(elem.type,elem);});
If that doesn't show at least one "Mesh" it means your conversion may have had problems.. if it does show, it could mean the mesh is too tiny to see, too Huge to see, or maybe the material is accidently transparent or many other possibilities. At that point, you can look at the mesh.geometry and make sure it has vertices and elements within it...
Failing all that:
If you try with OBJLoader or some other loader, and still can't get it to work.. check back with us. :)


text:
Q: StartActivityForResult, but activity finishes I am trying to use Adobe Image Edit SDK to edit a photo then redirect to another activity, from my custom camera activity.
This works from another activity, simply by creating the Image edit Intent, using startActivityForResult, then treating the "Done" callback in said activity, in the method onActivityResult.
Intent imageEditorIntent = new AdobeImageIntent.Builder(mContext)
                        .setData(selectedImageUri)
                        .withToolList(tools)
                        .withOutput(new File(mLastSavedFilePath))
                        .build();
startActivityForResult(imageEditorIntent, 2);

and then
public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == 2) { // i get here

However, when I do this from my Custom Camera Activity, the activity ends when I click "done" in the image edit sdk (its onDestroy is called) before it gets to the result
Intent intent = FileUtils.getInstance().SavePhoto(data, mContext); //this returns an AdobeImageIntent
startActivityForResult(intent, 1);

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        //this never gets called, because activity finishes, but why?
super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {

So why is the activity finishing, if the other one does not?

A: Turns out this was my fault, I did not notice I had             android:noHistory="true"
in the manifest for the second activity


text:
Q: WPF ListBox loads lots of pics will got System.IO.IOException occured in PresentationCore.dll? My ItemTemplate is very Simple, One TextBlock to show Name, Another Image to show Net Image:
<ListBox.ItemTemplate>
    <DataTemplate>
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>
            <Image VerticalAlignment="Center" Source="{Binding Url, Mode=OneWay, Converter={StaticResource cvtImage}}" Width="30" Height="30"/>
            <TextBlock Grid.Column="1" Text="{Binding Name, Mode=OneWay}" Margin="5" VerticalAlignment="Center"/>
        </Grid>
    </DataTemplate>
</ListBox.ItemTemplate>

Here is my pictrues array:
private int[] numArr =
{
    20333581,
    65476272,
    65494751,
    67810732,
    72685857,
    73794129,
    74292128,
    78448608,
    89297529,
    109457648,
    128775798,
    136864278,
    140889893,
    155315730,
    155707244,
    158590544,
    160382605,
    162265810,
    167648987,
    170883246,
    175708510,
    181177782,
};

private List<ImageItem> imagesList = new List<ImageItem>();
private int imageCount = 22;

private void initialImageList()
{
    for (int i = 0; i < imageCount; i++)
    {
        imagesList.Add(new ImageItem {
            Name = "item " + (i + 1).ToString(),
            Url = String.Format("https://p.qlogo.cn/gh/{0}/{0}_1/40", numArr[i], numArr[i])
        });
    }
}

Net Images above are all valid.
Class ImageItem is simple with two Properties: Name and Url
Here is my converter class:
class GcToNetImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var url = (string)value;
        Console.WriteLine("url is " + url);
        try
        {
            return new BitmapImage(new Uri(url));
        }
        catch (Exception ex)
        {
            Console.WriteLine("ex message: {0}", ex.Message);
            return new BitmapImage();
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Aftet setting lb.ItemsSource = this.imagesList;,
when you slide down the ListBox, you will definitely got IOException.
I guess it's something about with memory leak


text:
Q: Image not visible when merging one word doc into another I am trying to merge 2 docx documents and have succeeded in achieving most of my use case. I am able to merge the text and the tables successfully but in case of images in the docx file, it shows the placeholder but not the image itself.
Here is my code snippet for reference:
def document
Integer i
Integer j

void mergeDocx(FileInputStream test1, FileInputStream test2, FileOutputStream dest) {
    i = 0
    j = 0
    XWPFDocument doc1 = new XWPFDocument(test1)
    XWPFDocument doc2 = new XWPFDocument(test2)
    document = new XWPFDocument()
    parseElement(doc1)
    parseElement(doc2)
    parseStyle(doc1, doc2)
    OutputStream out = dest
    document.write(out)
    out.close()
}

This is the base version of parseElement(XWPFDocument doc) I started with
void parseElement(XWPFDocument doc) {
    for (IBodyElement e : doc.getBodyElements()) {
        if (e instanceof XWPFParagraph) {
            XWPFParagraph p = (XWPFParagraph) e
            if (p.runs.embeddedPictures.flatten()) {
                p.runs.each { r ->
                    r.embeddedPictures.each { pic ->
                        document.addPictureData(pic.pictureData.data, pic.pictureData.pictureType)
                    }
                }
            } else {
                if (p.getCTP().getPPr() != null && p.getCTP().getPPr().getSectPr() != null) {
                    continue
                } else {
                    document.createParagraph()
                    document.setParagraph(p, i)
                    i++
                }
            }
        } else if (e instanceof XWPFTable) {
            XWPFTable t = (XWPFTable) e
            document.createTable()
            document.setTable(j, t)
            j++
        }
    }
}

This is the alternate version of parseElement(XWPFDocument doc) I used
void parseElement(XWPFDocument doc) {
    for (IBodyElement e : doc.getBodyElements()) {
        if (e instanceof XWPFParagraph) {
            XWPFParagraph p = (XWPFParagraph) e
            if (p.runs.embeddedPictures.flatten()) {
                p.runs.each { r ->
                    r.embeddedPictures.each { pic ->
                        XWPFParagraph title = document.createParagraph()
                        XWPFRun run = title.createRun()
                        run.setText("Fig.1 A Natural Scene")
                        run.setBold(true)
                        title.setAlignment(ParagraphAlignment.CENTER)
                        run.addBreak()
                        run.addPicture(new ByteArrayInputStream(pic.pictureData.data), XWPFDocument.PICTURE_TYPE_JPEG, pic.pictureData.fileName, Units.toEMU(200), Units.toEMU(200))
                    }
                }
            } else {
                if (p.getCTP().getPPr() != null && p.getCTP().getPPr().getSectPr() != null) {
                    continue
                } else {
                    document.createParagraph()
                    document.setParagraph(p, i)
                    i++
                }
            }
        } else if (e instanceof XWPFTable) {
            XWPFTable t = (XWPFTable) e
            document.createTable()
            document.setTable(j, t)
            j++
        }
    }
}

The problem here is that whenever an Image is encountered it considers it as an instance of Paragraph and then it tries to do setParagraph() which I know I should not use here for Images.
Here is how my word docx looks like after merge

I am using ApachePOI for this but I am open to a solution using docx4j as well. Any guidance would be appreciated.
P.S: The programming language is groovy.

A: Updating my parseElement() method to this worked for me:
void parseElement(XWPFDocument doc) {
    for (IBodyElement e : doc.getBodyElements()) {
        if (e instanceof XWPFParagraph) {
            XWPFParagraph p = (XWPFParagraph) e
            if (p.runs.embeddedPictures.flatten()) {
                p.runs.each { r ->
                    r.embeddedPictures.each { pic ->
                        XWPFParagraph p1 = document.createParagraph()
                        XWPFRun r1 = p1.createRun()
                        int width = pic.getCTPicture().getSpPr().getXfrm().getExt().getCx() as int
                        int height = pic.getCTPicture().getSpPr().getXfrm().getExt().getCy() as int
                        int imgFormat1 = getImageFormat(pic.pictureData.fileName)
                        r1.addPicture(new ByteArrayInputStream(pic.pictureData.data), imgFormat1, pic.pictureData.fileName, width, height)
                        i++
                    }
                }
            } else {
                if (p.getCTP().getPPr() != null && p.getCTP().getPPr().getSectPr() != null) {
                    continue
                } else {
                    document.createParagraph()
                    document.setParagraph(p, i)
                    i++
                }
            }
        } else if (e instanceof XWPFTable) {
            XWPFTable t = (XWPFTable) e
            document.createTable()
            document.setTable(j, t)
            j++
        }
    }
}

One thing that I was missing was the i++ whenever I encountered an image within a paragraph.


text:
Q: Cross correlation detection in binary Hamming distance Given two long binary strings of length N, it's easy to find the Hamming distance between them.  If you're allowed to cyclically shift one of the strings, you'll get N different Hamming distances when comparing the two.  What is an efficient way to find the maximum Hamming distance over all N shifts?
This question is motivated by a sensor which tends to emit streams of "random" bits. There's potential slight correlations at unknown delays of millions of bits, a kind of slight bias of a ghost echo. I'm looking for a test to see if these correlations can be detected.
I think the problem can be solved with application of the discrete Fourier transform, but I'm not sure if there's a "binary" Fourier transform analogue and how it could identify the maximum Hamming over all the circular shifts.
Thanks!

A: I'd suggest that you start by encoding your signal in terms of the symbols +1 and -1 rather than 0 and 1.  If you have two signals x and y, then take elementwise products of x and y and sum to get a measure of the distance between x and y.  If the signals are identical, then the sum will be n.  If the signals differ in each position, the sum will be -n.  If there are matches in k positions, then the sum will be k-(n-k)=2k-n.
e.g. (using MATLAB notation)
x=[1; 1; 1];
y=[-1; 1; -1];
sum(x.*y)=-1
Once you know this, then you can consider taking the circular convolution of two signals x and y.  The elements of the circular convolution of x and y are these sums for various circular shifts of z.    e.g.
x=[+1, -1, +1]
y=[+1, +1, -1]
let
z=circconv(x,y)=ifft(fft(x).*fft(y))
z=[3, -1, -1]
This tells us that shifting y circularly to the left by one position results in a perfect match, and that the other two circular shifts of y result in largest mismatches.
This algorithm takes O(n*log(n)) time to compute z and then O(n) time to find the max (and/or min) elements of z.


text:
Q: Use multiple Powershell commands in C# In the method shown here, I would like to use multiple PowerShell cmdlets. How can I do that? Like in a PowerShell window, I do a Import Module and then run a command Start-Db. How can I do the same in this method? I am able to run Import-module command successfully, but how can I add another command?
[Fact]
public void TestGetRecordings()
{
    PowerShell ps = PowerShell.Create();
    ps.AddCommand( "Import-Module" ).AddArgument( "C:\\ProgramFiles\\Azure Cosmos DB Emulator\\PSModules\\Microsoft.Azure.CosmosDB.Emulator" );
    ps.Invoke();
    ps.Commands.Clear();
}

A: Use AddStatement to add multiple commands:
ps
  .AddCommand("Import-Module").AddArgument("C:\\ProgramFiles\\Azure Cosmos DB Emulator\\PSModules\\Microsoft.Azure.CosmosDB.Emulator")
  .AddStatement() // <= this is equivalent to writing ";" in PowerShell
  .AddCommand("Start-Db").AddArgument("...")
  .Invoke();

A: This is an extremely lazy hack to the issue and you will likely get a far better answer before I will even be near a PC...but why not just write the script to a powershell file?
You can then execute it and keep it for future use...or if need be for any reason, delete it after the command to execute the script returns using a function that waits for it to complete?


text:
Q: Is it okay to allow "While Using the App" instead of "ALWAYS ALLOW" while foreground service is used? Is there any difference between location permission ALWAYS_ALLOW and Only While Using the App option when using foreground service. I'm developing an SDK which use location permission all time, I'm using foreground service and is it okay to allow "Only While Using the App" permission instead of ALWAYS_ALLOW

A: There is no problem in using the Only While Using the App option, if the location acquisition process in the application will only be performed when the application is open on the screen.
If you want to get location while in background, you should use ALWAYS_ALLOW option.


text: Q: ways of automatic capitalizing format in emails (webpage/outlook version) Is there a way to automatically capitalize the 1st letters, 'I', special terms etc in emails? For lazy people not wanting to press 'shift' all the time.


text:
Q: Show xticks which are function of x-axis, not directly the data it self. Example with dates (pandas, matplotlib) While working with seaborn, I tried to set x-ticks to be different from my data unsuccessfully. I'll give concrete example in a moment, but I also generalized my question. If there is a canonical answer to the general question that will be great.
Is it possible to set x-ticks to be a function of the data what I used for plotting? When I can't plot function of data directly.

*

*Assume I've a method which receive x and returns f(x). Is it possible to plot data by x, but showing f(x) in x axis? Like returning a string for each number, and I want to show the string.

*If I have a dataframe which I plot as x-axis his column name "col_x", and I want instead of that x-ticks to show data of "col_f_x". Can I make somehow a "match" between two columns?

Questions are similar of course, while the first assumes I have a function, the second asks directly about two columns in dataframe.
Now for concrete example. My initial goal was to use seaborn.displot on dates. Unfortunately, it seems it does not support working with dates. I decided to do some bypass and plot data by days difference. I explained what I did here: How to plot Pandas datetime series in Seaborn distplot?
, that is the origin of my question.
Let's use this simple example:
import pandas as pd
import datetime as dt

original_dates = ["2016-03-05", "2017-03-05", "2016-02-05", "2016-02-05", "2016-02-05", "2015-03-05"]
dates_list = [dt.datetime.strptime(date, '%Y-%m-%d').date() for date in original_dates]

df = pd.DataFrame({"Date":dates_list})

df["NewDate"] = df["Date"] - dt.date(2015,3,5)
df["NewDate"] = df["NewDate"].apply(lambda x: x.days)

import seaborn as sns
sns.set()
ax = sns.distplot(df['NewDate'])

Output:

I used numerical different of days instead of plotting Date column directly. But I want my xticks to be dates, not numerical difference. How can I do this?
I hope my two general questions are now more clearer: I can supply to the plot a function (date - starting_date) or different column (Date), by I'm still not sure how to set x-ticks accordingly.
During my small research on that I tackled across matplotlib's major_locator and major_formatter. I guess I suppose to use them, but couldn't figure out how to do it on my own. Some of related posts in stack overflow I found during my search:
Manipulating Dates in x-axis Pandas Matplotlib
Set the labels between xticks
matplotlib set xticks to column, labels to corresponding index
plot_date function set xticks for hourly data

A: Run the following at the end of your code
import matplotlib.pyplot as plt

def my_func(x):
    return dt.date(2015,3,5) + dt.timedelta(days=x)

ticks = plt.xticks()[0]
dates = [my_func(x) for x in ticks]
plt.xticks(ticks, dates)


text:
Q: Boxplot colour mismatch I would like to color the dots of the plot with the legend Episode values. What I am missing?

I replaced fill with color still is not the plot that I would like to have

Sample code:
(p <- ggplot(df, aes(x=Type, y=Value, fill=Episode, group=Type)) +

    geom_boxplot()+
    geom_line()+
    geom_dotplot(binaxis='y', stackdir='center',
                 position=position_dodge(0.8))+
    theme_bw())

Sample data:
 df<-structure(list(Type = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 2L,
    2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L,
    4L, 5L, 5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L, 6L, 7L, 7L, 7L,
    7L, 7L, 7L), .Label = c("A", "B", "C", "D", "E", "F", "G"), class = "factor"),
        Episode = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 1L, 2L, 3L,
        4L, 5L, 6L, 1L, 2L, 3L, 4L, 5L, 6L, 1L, 2L, 3L, 4L, 5L, 6L,
        1L, 2L, 3L, 4L, 5L, 6L, 1L, 2L, 3L, 4L, 5L, 6L, 1L, 2L, 3L,
        4L, 5L, 6L), .Label = c("t1", "t2", "t3", "t4", "t5", "t6"
        ), class = "factor"), Value = c(32, 36, 57, 83, 88, 40, 40,
        44, 67, 77, 66, 45, 88, 46, 56, 99, 65, 0, 66, 46, 59, 77,
        74, 79, 38, 45, 60, 78, 66, 75, 45, 55, 68, 77, 88, 35, 36,
        118, 80, 73, 71, 0)), row.names = c(NA, -42L), class = "data.frame")

A: I am not entirely sure if I understand your question correctly, but for me, the cleanest plot would be:
library(ggplot2)
df<-structure(list(Type = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 2L,
                                      2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L,
                                      4L, 5L, 5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L, 6L, 7L, 7L, 7L,
                                      7L, 7L, 7L), .Label = c("A", "B", "C", "D", "E", "F", "G"), class = "factor"),
                   Episode = structure(c(1L, 2L, 3L, 4L, 5L, 6L, 1L, 2L, 3L,
                                         4L, 5L, 6L, 1L, 2L, 3L, 4L, 5L, 6L, 1L, 2L, 3L, 4L, 5L, 6L,
                                         1L, 2L, 3L, 4L, 5L, 6L, 1L, 2L, 3L, 4L, 5L, 6L, 1L, 2L, 3L,
                                         4L, 5L, 6L), .Label = c("t1", "t2", "t3", "t4", "t5", "t6"
                                         ), class = "factor"), Value = c(32, 36, 57, 83, 88, 40, 40,
                                                                         44, 67, 77, 66, 45, 88, 46, 56, 99, 65, 0, 66, 46, 59, 77,
                                                                         74, 79, 38, 45, 60, 78, 66, 75, 45, 55, 68, 77, 88, 35, 36,
                                                                         118, 80, 73, 71, 0)), row.names = c(NA, -42L), class = "data.frame")

p <- ggplot(df, aes(x=Type, y=Value, group = Type)) +
    geom_boxplot() +
    geom_line() +
    geom_point(aes(col=Episode))
p

Created on 2021-04-15 by the reprex package (v0.3.0)


text:
Q: An unexpected version directory `Assets` was encountered for Private Pod I have built a private CocoaPods repo that is  used in my company. This repo can be pushed to gitlab.com. The procedure is like this:
//1
pod lib create PZResources

//2 change podspec
//3 add directory and images to PZResources.
//4 push these changes to gitlab.com. Then add tag and push tags to server.

//5 vertify spec
pod spec lint --sources=https://zlanchun@gitlab.com/zlanchun/PZResources.git

//6 pod repo add
pod repo add PZResources https://zlanchun@gitlab.com/zlanchun/PZResources.git

//6 pod repo push
pod repo push PZResources PZResources.podspec --sources=https://zlanchun@gitlab.com/zlanchun/PZResources.git

Then I open a new project, pod it, and add new library to the Podfile:
# Uncomment the next line to define a global platform for your project
platform :ios, '7.0'
source 'https://zlanchun@gitlab.com/zlanchun/PZResources.git'
source 'https://github.com/CocoaPods/Specs.git'

target 'PZDemo' do
# Uncomment the next line if you're using Swift or would like to use dynamic frameworks
# use_frameworks!
pod "PZResources"
# Pods for PZDemo

end

After the above steps, this error occurs:
[!] An unexpected version directory `Assets` was encountered for the `/Users/z/.cocoapods/repos/PZResources/PZResources` Pod in the `PZResources` repository.

I think my procedure is correct, but this error occurred. I don't know what is wrong.

A: With times go, I found this answer for it.
Because the repo is private for me, I need a Specs repo to collect these private repos. But I don't have one. So the error occur.
Then follow below steps, I solved this error.
1.Create a gitlab repo called Specs that used to collect private repo.
2.add repo and push private repo to Specs.
3.In Podfile, add source url.
4.pod install

For example:
1.delete pod repo in your computer cache
$ pod repo list

If you have PZResources repo ,then you should delete it.
$ pod repo remove PZResources

2.add lib repo to remote Specs repo
$ pod repo add PZResources https://zlanchun@gitlab.com/zlanchun/Specs.git

3.push lib repo to remote Specs repo. You can use --sources for it.
$ pod repo push PZResources PZResources.podspec --sources=https://zlanchun@gitlab.com/zlanchun/Specs.git

Maybe it need an username and password, just complete it.
4.Create a test project and pod init, then in Podfile add the info below:
//search private Specs. If this Specs cann't have repo, then seacrch github Specs.
source 'https://zlanchun@gitlab.com/zlanchun/Specs.git'
source 'https://github.com/CocoaPods/Specs.git'

target 'TestPrivateLibRepo' do
    pod 'PZResources'
end


text:
Q: Applications open on login when they shouldn't be My MacBook will open applications (even when no applications were open on shutting down or restarting it) when it boots up. I checked the login items on system preferences and nothing should be opening.

A: Yes - this can be disconcerting when you don't realize that the majority of the Apple apps save their system state and don't even need to be told to start or stop. You can have an app in the dock when it's not running and you can have an app running when it's not in the dock. (or the task switcher interface)
The simple way to reset this is to choose log out from the Apple menu and turn off the check mark below.

Then log out, log in and log out again and verify the status if the check is disabled and the apps do not relaunch.
In some rare cases, this setting / preference could get corrupt, so I then turn it on (which is the opposite of what you want)- log out / log in - then turn it off  (what you want) and before contacting support. Most of the time, just exercising the button a couple times is all that's needed if someone isn't aware to uncheck the button when they log out.


text:
Q: What is actually $e$ ? Why $e$ is so significant over other real numbers ? I had this question for a long time.
We always use it in differentiation,Integration , Logarithms ..etc.
What is its origin ?
What unique qualities does it have over other real numbers?


text:
Q: Inserir Option com javaScript Tenho um formulário dinâmico. Com um campo radiobutton e um select. De acordo com o valor que seleciono na opção eu populo o campo lista com valores selecionados.
Exemplo.
Opção 1
Opção 2
Ao selecionar a opção 1, o campo select é populado com
Item A
Item B
Item C
Ao selecionar a opção 2, o campo select é populado com
Item X
Item W
Maior maior problema é como faço para inserir options dentro do select com JavaScript.

A: Segue um exemplo amigo.. Após você selecionar uma opção, os options são criados dinamicamente. A cada alteração do radio os options mudam, refletindo somente os valores desejados para aquela seleção.

function populateOptions(opt) {
  let select = document.querySelector("select[name='selecao']");

  while (select.children.length) {
    select.removeChild(select.lastChild);
  }

  // Cria option "default"
  let defaultOpt = document.createElement('option');
  defaultOpt.disabled = true;
  defaultOpt.selected = true;
  defaultOpt.textContent = 'Selecione uma opção';
  select.appendChild(defaultOpt);

  opt.forEach(function(option) {
    let optEl = document.createElement('option');
    optEl.value = option.value;
    optEl.textContent = option.text;

    select.appendChild(optEl);

  });
}

document.querySelectorAll("input[type='radio']")
  .forEach(function(radio) {
    radio.addEventListener('change', function(evt) {

      switch (parseInt(this.value)) {
        case 1:
          populateOptions([{
              value: "A",
              text: "Opção A"
            },
            {
              value: "B",
              text: "Opção B"
            }
          ]);
          break;

        case 2:
          populateOptions([{
              value: "C",
              text: "Opção C"
            },
            {
              value: "D",
              text: "Opção D"
            }
          ]);
          break;
      }
    });
  });

  Opção 1
  <input type="radio" name="opt" value="1">

  Opção 2
  <input type="radio" name="opt" value="2">

<select name="selecao">
  <option disabled selected>Selecione uma opção</option>
</select>

A: Fiz um pequeno exemplo aqui utilizando somente JavaScript. Veja:

[...document.getElementById('form').elements].forEach((field) => {
  field.addEventListener('change', () => {
    if (field.value === 'opcao2') {
      createOptions(2);
    } else {
      createOptions(3);
    }
  });
});

function createOptions(quantidade) {
  let fieldSelect = document.getElementById('select');
  cleanOptionsSelect(fieldSelect);
  for (let i = 0; i < quantidade; i++) {
    let option = document.createElement('option');
    option.text = 'Opção ' + i;
    fieldSelect.append(option);
  }
}

function cleanOptionsSelect(fieldSelect) {
  fieldSelect.innerHTML = '<option value="valor1">Selecione uma opção</option>';
}
<form id="form">
    <input type="radio" id="opcao1" name="opcao" value="opcao1" />
    Opção 1
    <input type="radio" id="opcao2" name="opcao" value="opcao2" />
    Opção 2
</form>

<fieldset>
  <legend>Campo select</legend>
  <select name="select" id="select">
    <option value="valor1">Selecione uma opção</option>
  </select>
</fieldset>

Observações:

*

*O algoritmo possui compatibilidade com a maioria dos navegadores, mas provavelmente não funcionará no IE por usar ES6.


text:
Q: Using LIKE with apostrophes I have been running a server side trace in order to find out how a specific stored procedure is called within my database.
I am running the following query in order to get data from the trace file generated:
select TextData,
db_name(databaseid)
from fn_trace_gettable( 'R:\Profiler\udpProductTaxRateGet4.trc', default) fn
join sys.trace_events te
 on fn.EventClass = te.trace_event_id
where --
1=1
--and EventClass = 42
and textdata like '%udpProductBulletPointSelectByTier1NoteTypeCode%'
--and db_name(databaseid) = 'US16AUTPProduct'
order by starttime desc

But as you can see on the picture below, there are too many rows like this one:
declare @p5 int  set @p5=86400 exec dbo.udpProductBulletPointSelectByTier1NoteTypeCode @Tier1=N'AR763',@LanguageID=2,@SeasonItemID=N'16AUT',@ListNoteTypeCode=N'',@CacheDuration=@p5 output  select @p5

more specifically the procedure was called with an empty parameter value for @ListNoveTypeCode

@ListNoteTypeCode=N''

How can I filter out all those rows where @ListNoteTypeCode=N''??

A: The single quote character has no special significance to LIKE
You need to double them up to escape them inside any string literal.
So the two consecutive single quotes in the string you are trying not to match become four as below.
And textdata not like '%@ListNoteTypeCode=N''''%'

A: From the image, it looks like the BulletPoint is what you need to look for as well. Change the Like statement to
like '%udpProductBulletPointSelectByTier1NoteTypeCode%BulletPoint%'
This should reduce the results.


text:
Q: Formating JSON data from firestore I am using a cloud function to download my db collection as a JSON file.
The code is
exports.csvJsonReport = functions.https.onRequest((request, response) => {
  const db = admin.firestore()
  const userAnswers = db.collection('/surveys/CNA/submissions')
  return (
    userAnswers
      .get()
      .then(querySnapshot => {
        let answers = []
        querySnapshot.forEach(doc => {
          const answer = doc.data()
          answers.push({ ...answer.answers, ...answer.anonUser })
        })

        response.setHeader('Content-disposition', 'attachment; filename=cna.json')
        response.set('Content-Type', 'application/json')
        response.status(200).send(answers)
      })
      .catch(error => {
        console.log(error)
      })
  )
})

Most of the time I only care about value, but sometimes value is nested inside..and when it is nested, I will need value and name
current output
[{
"2": {
      "loopIndex": null,
      "questionType": "multiChoice",
      "value": "Farm owner",
      "id": 1
    },
"7": {
      "1": {
        "name": "Enviroment management",
        "questionType": "responsiveMultiCheckBox",
        "valueId": 4,
        "value": "My top priority right now",
        "id": 1
      },
      "2": {
        "questionType": "responsiveMultiCheckBox",
        "valueId": 3,
        "value": "One of my top priorities",
        "id": 2,
        "name": "Financial management"
      },
      "3": {
        "value": "My top priority right now",
        "id": 3,
        "name": "People management",
        "questionType": "responsiveMultiCheckBox",
        "valueId": 4
      },
      "4": {
        "name": "Reproduction management",
        "questionType": "responsiveMultiCheckBox",
        "valueId": 4,
        "value": "My top priority right now",
        "id": 4
      },
      "5": {
        "name": "Feed management",
        "questionType": "responsiveMultiCheckBox",
        "valueId": 4,
        "value": "My top priority right now",
        "id": 5
      }
    },
}]

desired output:
[{
    "2": {
          "value": "Farm owner",
        },
    "7": {
          "1": {
            "name": "Enviroment management",
            "value": "My top priority right now",
          },
          "2": {
            "value": "One of my top priorities",
            "name": "Financial management"
          },
          "3": {
            "value": "My top priority right now",
            "name": "People management",
          },
          "4": {
            "name": "Reproduction management",
            "value": "My top priority right now",
         },
          "5": {
            "name": "Feed management",
            "value": "My top priority right now",
          }
        },
    }]

I have tried
answer.answers.map(questionId => {
            return console.log('value', questionId.value)
          })

but answers.answers.map is not a function

A: here is a working fiddle: https://jsfiddle.net/uekbhta6/2/
let result = {};
// I am assuming that your answers array always contains one object with the rest of data
for (let id in answers[0])
{
    // If the value is present on the 1st level, push it to the buffer
    if (answers[0][id].value)
    {
        result[id] = answers[0][id].value;
    }
    // otherwise, iterate through the second level and push name/value to result buffer
    else
    {
       result[id] = {};
       for(let id2 in answers[0][id])
       {
          result[id][id2] = {
                name:answers[0][id][id2].name,
              value:answers[0][id][id2].value
          };
       }
    }
}
// wrap result in an array and print
console.log([result])

It could be done more elegantly with Array.reduce(), however it is getting late and I need some sleep.


text:
Q: Failed to install virtualbox 6.1 to Ubuntu 20.04 I'm trying with no success to install VirtualBox on Ubuntu 20.04. It keeps failing with every try. I think I may have possibly created files that I no longer have permissions to remove. I'm using my personal PC and don't know how to elevate permissions.  I'm new to Ubuntu.
This is my script when I try to install VirtualBox:
emsys@emsys:~/Downloads$ sudo su
[sudo] password for emsys:
root@emsys:/home/emsys/Downloads# ls
virtualbox-6.1_6.1.16-140961~Ubuntu~eoan_amd64.deb
root@emsys:/home/emsys/Downloads# dpkg -i virtualbox-6.1_6.1.16-140961~Ubuntu~eoan_amd64.deb
Selecting previously unselected package virtualbox-6.1.
(Reading database ... 182383 files and directories currently installed.)
Preparing to unpack virtualbox-6.1_6.1.16-140961~Ubuntu~eoan_amd64.deb ...
Unpacking virtualbox-6.1 (6.1.16-140961~Ubuntu~eoan) ...
dpkg: dependency problems prevent configuration of virtualbox-6.1:
 virtualbox-6.1 depends on libqt5core5a (>= 5.12.2); however:
  Package libqt5core5a is not installed.
 virtualbox-6.1 depends on libqt5gui5 (>= 5.4.0) | libqt5gui5-gles (>= 5.4.0); however:
  Package libqt5gui5 is not installed.
  Package libqt5gui5-gles is not installed.
 virtualbox-6.1 depends on libqt5opengl5 (>= 5.0.2); however:
  Package libqt5opengl5 is not installed.
 virtualbox-6.1 depends on libqt5printsupport5 (>= 5.0.2); however:
  Package libqt5printsupport5 is not installed.
 virtualbox-6.1 depends on libqt5widgets5 (>= 5.12.2); however:
  Package libqt5widgets5 is not installed.
 virtualbox-6.1 depends on libqt5x11extras5 (>= 5.6.0); however:
  Package libqt5x11extras5 is not installed.
 virtualbox-6.1 depends on libsdl1.2debian (>= 1.2.11); however:
  Package libsdl1.2debian is not installed.
 virtualbox-6.1 depends on python (<< 2.8); however:
  Package python is not installed.
 virtualbox-6.1 depends on python (>= 2.7); however:
  Package python is not installed.
 virtualbox-6.1 depends on python:any (>= 2.6.6-7~); however:

dpkg: error processing package virtualbox-6.1 (--install):
 dependency problems - leaving unconfigured
Processing triggers for systemd (245.4-4ubuntu3.2) ...
Processing triggers for gnome-menus (3.36.0-1ubuntu1) ...
Processing triggers for desktop-file-utils (0.24-1ubuntu3) ...
Processing triggers for mime-support (3.64ubuntu1) ...
Processing triggers for hicolor-icon-theme (0.17-2) ...
Processing triggers for shared-mime-info (1.15-1) ...
Errors were encountered while processing:
 virtualbox-6.1
root@emsys:/home/emsys/Downloads# apt-get -f install
Reading package lists... Done
Building dependency tree
Reading state information... Done
Correcting dependencies... Done
The following packages will be REMOVED
  virtualbox-6.1
0 to upgrade, 0 to newly install, 1 to remove and 0 not to upgrade.
1 not fully installed or removed.
After this operation, 216 MB disk space will be freed.
Do you want to continue? [Y/n] y
(Reading database ... 183132 files and directories currently installed.)
Removing virtualbox-6.1 (6.1.16-140961~Ubuntu~eoan) ...
Processing triggers for mime-support (3.64ubuntu1) ...
Processing triggers for hicolor-icon-theme (0.17-2) ...
Processing triggers for gnome-menus (3.36.0-1ubuntu1) ...
Processing triggers for shared-mime-info (1.15-1) ...
Processing triggers for desktop-file-utils (0.24-1ubuntu3) ...
root@emsys:/home/emsys/Downloads# sudo apt purge virtualbox
Reading package lists... Done
Building dependency tree
Reading state information... Done
Package 'virtualbox' is not installed, so not removed
0 to upgrade, 0 to newly install, 0 to remove and 0 not to upgrade.
root@emsys:/home/emsys/Downloads#

If I type ls, I get the following:
-virtualbox-6.1_6.1.16-140961~Ubuntu~eoan_amd64.deb

My folder computer /etc/apt/sources.list.d has 4 files they contain the following:
folder oracle.virtualbox.list=# deb http://download.virtualbox.org/virtualbox/debian focal contrib

folder oracle.virtualbox.list.save=# deb http://download.virtualbox.org/virtualbox/debian focal contrib

folder virtualbox.list=# deb [arch=amd64] http://download.virtualbox.org/virtualbox/debian focal contrib

folder virtualbox.list.save=# deb [arch=amd64] http://download.virtualbox.org/virtualbox/debian focal contrib

Do I need to delete these multiple files? Are they preventing the download? I cant amend these text files. I see the files say debian focal but when I type ls in the terminal its looking for eoan?!!

A: You've definitely done something incorrectly.
All you need to do to install VirtualBox is two simple commands:
sudo apt update
sudo apt install virtualbox

That's it!
That being said, if your actions have degraded your sources and if you've been attempting other installation methods and failing, these simple commands might not work anymore if the package in Ubuntu repositories conflicts with whatever else you've done.

At this point it's unclear what you've done to break your package management system, but it looks like you've spawned more than one problem in your attempts to stab at this.
Do you remember or did you document every single change?  If not, your best path may be a system reinstall at this point.


text:
Q: Using SELECT statement inside an IF Else condition in JasperReports SQL query in JasperReports Server I have the following sample query:
     IF(1=1)
      Select  top 10 * from Person

     ELSE
      Select top 10 * from Person where Id < 20

When i create a report with above query using iReport, the report works fine.
But when i upload the same report to JasperReports Server and try to run the report, it is throwing the below  error.
ERROR Validator,report1 subreports #1:493 - Invalid SQL:An error has occurred.
Please contact your system administrator. (6632),
SQL: IF(1=1)Select  top 10 * from PersonELSESelect top 10 * from Person where Id < 20.

Does JasperReports Server supports IF..Else conditions outside the SELECT statement?
Do any one know about this error?

A: After searching for around 4 days, i found a solution.
Jasper Server allows the SQL queries that starts with only "SELECT" keyword. So in order to make other queries work, we have to modify a regular expression of "Validator.ValidSQL" that is present in "webapps/jasperserver/WEB-INF/classes/esapi/security-config.properties/validation.properties" location.
I have modified this regular expression to support 'IF' conditions and made it work.
Got this solution from jasper community forum:
http://community.jaspersoft.com/questions/800208/stored-procedures-works-ireport-does-not-work-jasperserver.


text:
Q: ggplot2 plot title based on an iterating for loop variable I would like to title each plot with the variable (k) I am using to iterate within a for loop:
> MyData
     Name Stat Year value
1  Site01  Max 2013 29.88
2  Site01  Med 2013 29.67
3  Site01  Min 2013 29.16
4  Site01  Max 2020 31.21
5  Site01  Med 2020 30.38
6  Site01  Min 2020 29.38
7  Site01  Max 2040 35.50
8  Site01  Med 2040 33.17
9  Site01  Min 2040 29.60
10 Site02  Max 2013 53.70
11 Site02  Med 2013 53.49
12 Site02  Min 2013 53.20
13 Site02  Max 2020 53.10
14 Site02  Med 2020 53.01
15 Site02  Min 2020 52.55
16 Site02  Max 2040 52.04
17 Site02  Med 2040 51.74
18 Site02  Min 2040 50.98

pdf("plots.pdf")
for (k in unique(MyData$Name)){
subdata <- subset(MyData, Name == k)

     print(ggplot(subdata, aes(x = Year, y = value, colour = Stat))
          + geom_line() + expand_limits(y=c(0,100)) + ggtitle(k))

}
dev.off()

The plots are generated just fine when using a string for ggtitle() (for example: ggtitle("Name")) or after removing ggtitle() completely.
Any suggestions for how to include the value of the iterator variable (k) as the title on each plot?

A: What class are the data in MyData$Name ?
Try replacing ggtitle(k) with ggtitle(as.character(k)) to ensure you're passing ggtitle a string.

A: You could use paste(), example:
ggtitle(paste(your_value))


text:
Q: How to make wxPython StaticText selectable The other day I found out, much to my surprise, that static text on a wxPython panel is not selectable/highlightable. I'd need that so the user could copy the content.
I didn't find a flag or the like to make the StaticText component selectable.
import wx
app = wx.App(False)
frame = wx.Frame(None, wx.ID_ANY, "Hello, World!")
panel = wx.Panel(frame)
panel.SetBackgroundColour("#FFB6C1")
st = wx.StaticText(panel, wx.ID_ANY, "Hello, World!")
frame.Show(True)
app.MainLoop()

A: I can't find a way to make StaticText selectable/copyable but here are 2 hacks to get around the problem.
1. Copy to clipboard on right mouse click
2. TextCtrl masquerading as a StaticText
import wx
class MyFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1)
        self.panel = wx.Panel(self)
        self.st = wx.StaticText(self.panel, wx.ID_ANY, "Hello, World! Copy me with right click",pos=(5,5))
        self.st.Bind(wx.wx.EVT_RIGHT_DOWN,self.ShowPopup)
        self.tc = wx.TextCtrl(self.panel, wx.ID_ANY, "Paste here", pos=(5,30),size=(300,20))
        self.tc2 = wx.TextCtrl(self.panel, wx.ID_ANY,"TextCtrl masquerading as StaticText - Select me",style=wx.TE_READONLY|wx.NO_BORDER,pos=(5,60),size=(300,20))
        self.tc2.SetBackgroundColour(self.panel.GetBackgroundColour())
        self.Show()

    def ShowPopup(self,event):
        popmenu = wx.Menu()
        popmenu.Append(1, "Copy this text to clipboard")
        popmenu.Bind(wx.EVT_MENU, self.Copy)
        self.panel.PopupMenu(popmenu)
        popmenu.Destroy()

    def Copy(self,event):
        clipdata = wx.TextDataObject()
        text = self.st.GetLabelText()
        clipdata.SetText(text)
        wx.TheClipboard.Open()
        wx.TheClipboard.SetData(clipdata)
        wx.TheClipboard.Close()

app = wx.App()
frame = MyFrame()
app.MainLoop()

A: After a few experiments I settled for creating my custom HTML-enabled tooltip window. Here's the current version from the gist (wish SO allowed to embed rather than copy this):
import wx
import wx.html
import webbrowser

class HtmlPopupTransientWindow(wx.PopupTransientWindow):
    def __init__(self, parent, style, html_body_content, bgcolor, size):
        wx.PopupTransientWindow.__init__(self, parent, style)
        panel = wx.Panel(self)
        panel.SetBackgroundColour(bgcolor)

        html_window = self.HtmlWindow(panel, wx.ID_ANY, size=size)
        html_window.SetPage('<body bgcolor="' + bgcolor + '">' + html_body_content + '</body>')

        sizer = wx.BoxSizer(wx.VERTICAL)
        sizer.Add(html_window, 0, wx.ALL, 5)
        panel.SetSizer(sizer)

        sizer.Fit(panel)
        sizer.Fit(self)
        self.Layout()

    class HtmlWindow(wx.html.HtmlWindow):
        def OnLinkClicked(self, link):
            # get a hold of the PopupTransientWindow to close it
            self.GetParent().GetParent().Dismiss()
            webbrowser.open(link.GetHref())

See https://frightanic.com/software-development/create-an-info-icon-with-wxpython/ for further explanations.


text:
Q: Getting image data out of base64 I would like to get the image data part out of a base64 image, to alter it.
I tried this :
(origin : How can I strip the data:image part from a base64 string of any image type in Javascript)
let originalImage = myBase64Image
let strImage = originalImage.replace(/^data:image\/[a-z]+;base64,/, "");

The problem with the snippet is that when you alter strImage that you don't alter the originalImage.
Does anyone now a way of converting the strImage back to a base64 image or a way to directly alter the image data of the originalImage?


text:
Q: ndf file missing error shown while attaching the "mdf" file There was a space issue for a database in our server. So we added a secondary file (ndf file) for that DB in another drive. (ndf file- 'c' drive, mdf,ldf file- 'e' drive). When we formatted the 'C' drive, the ndf file got deleted. When we try to get that DB back again by attaching the 'mdf' file, we are getting error that "ndf file is missing".
SO what can we do next to get that DB back again to its old state?

A: This is a totally bad move all the way round. First its a bad practice to put database files on the C: drive. Secondly, in the attempt to format C: drive which basically includes rebuilding the server; why would you not perform a backup of entire server or at least files on the server.
Your resolution in this scenario is very very limited and sorry if it comes out harsh but take this as a IT/life lesson. Some data is so much very important that I cant imagine having to lose it.Okay now these are the options that I see:

*

*Use a data recovery tool to try and retrieve the formatted disk data. This is not a guaranteed process anyways.

*Once you have your .ndf file, you should be able restore file - hopefully is not corrupted.

*If retrieved .NDF file is corrupted or cannot be retrieved; then be ready to accept data loss. You can attempt DBCC CHECKDB with REPAR_ALLOW_DATA_LOSS. Note this command is not a guaranteed fix for the database

*If all the above options do not work. There is a great third party tool called Stellar Phoenix SQL Database Repair that can repair .MDF and .NDF files. It will repair and recovery data from corrupted database files which can then be exported into other formats including a newly created database. I really think this would be your best solution if you need to stand up this database again.

Good luck and let us know how it goes.

A: ndf file contains the data and ndf file is copy where your file is


text:
Q: Why is linear time reducible important When proving the lower bound of a new problem by reducing an existing problem of known complexity to it the emphasis is on linear time reduction. I kind of guess that for greater than linear time (say omega n^2 which is greater than linear omega n) we can not compare the two problems. But how to say it formally.
Also, say the known problem is omega n^3. Will now a omega n^2 reduction safely prove that the unknown problem has n^3 complexity?

A: Here is a formal statement.
Suppose that problem type A can be solved in time O(f(n).
Suppose that problem B can be reduced in time O(g(n)) to a problem of size h(n).
Then we can solve problem B in time O(g(n) + f(h(n))).
Ideally we want the reduction to be fast and for the problem to not blow up too much.  You generally can't do better than a linear time reduction since it takes linear time just to enter the problem.  That is why that is the ideal.
Note that if f(n) has a polynomial upper bound then "a problem of size h(n)" can be relaxed to, "a problem of size O(h(n))."  This is often true, and saves a lot of effort.  However an example where that kind of simplification fails is with f(n) = 2^n and h(n) = n+log(n)).


text:
Q: Json.net format I am having trouble with json formation for an api call. I need something like this
{
    "token": "87dd8f93-27ad-493c-8ab1-e75c50b8fb71",
    "answers": [
        {
            "question": "Where are you from",
            "ans": "t"
        },
        {
            "question": "I am from tts",
            "ans": "f"
        }
    ]
}

i have array of hashes named answers which i made separately with something like
string json = JsonConvert.SerializeObject(account, Formatting.Indented);

after that i have to make with the token but then using the same process i got
{
    "token": "87dd8f93-27ad-493c-8ab1-e75c50b8fb71",
    "answers": [
        "{\r\n
            \"question\": \"Where are you from\",
            \"ans\": \"t\"
        }",
        "{\r\n
            \"question\": \"I am from tts\",
            \"ans\": \"f\"
        }"
    ]
}

 public class Account
    {
       public string question { get; set; }
       public string ans { get; set; }
    }

and after that
if (ansNo.IsChecked == true)
                    {
                        Account account = new Account
                        {
                            question = quizText.Text,
                            ans = "f"
                        };
                        string json = JsonConvert.SerializeObject(account, Formatting.Indented);
                        Globals.answers[counter] = json;
                    }
                    else
                    {
                        Account account = new Account
                        {
                            question = quizText.Text,
                            ans = "t"
                        };
                        string json = JsonConvert.SerializeObject(account, Formatting.Indented);
                        Globals.answers[counter] = json;
                    }

need help please
Thanks

A: I think what you are after can be achieved by a rejig of your data. Create a new object to serialise to return
public class MyJson{
    public string token {get;set;}
    public List<Account> answers {get;set;}

    public MyJson(){
        answers = new List<Account>();
    }
}

Create a new MyJson object and add the token
MyJson o = new MyJson { token = "87dd8f93-27ad-493c-8ab1-e75c50b8fb71" }

Then like you already have add to the answers to the list
Account account = new Account{
     question = quizText.Text,
     ans = "t"
};
o.answers.Add(account);

Then serialise the whole thing and return it
return JsonConvert.SerializeObject(o, Formatting.Indented);


text:
Q: How to set a value of a sparse matrix to 0 without discarding the index so I have the following scenario for a sparse matrix $X$:
for k = 1 : long_loop
    X(indexA{k}) = stuff;
end
X(indexB) = 0;

where some indices in indexA{k} and indexB overlap. The situation is, if I set indexB to 0, then MATLAB throws out the indexes in indexB from the definition of X, and then when those indices come up again in the loop, they are reallocated, and it makes the loop run very very slowly. What I would like to do is to set the values X indexed by indexB to 0 without discarding the indices. I currently set it up by using
X(indexB) = eps;

but I don't think that's a great solution, since eps is going to be a source of error later.
Any way to set the values of a sparse matrix to 0 without discarding the index?
Thanks!


text:
Q: Update a collections view dynamically after removing the models from it I have the following code:
// Create the Backbone view to display a list of vehicles

var Vehicle = Backbone.Model.extend({
  idAttribute: "registrationNumber",
  urlRoot: "/api/vehicles",
  validate: function(attrs) {
    if (!attrs.registrationNumber)
        return "Registration number is required!";
  }
});

var Vehicles = Backbone.Collection.extend({
  model: Vehicle
});

// View for the model
var VehicleView = Backbone.View.extend({
  tagname: "li",
  attributes: {
    "data-color" : "Rainbow"
  },
  events: {
    "click .deleteButton" : "deleteVehicle"
  },

  render: function() {
    var template = _.template($("#vehicleTemplate").html());
    var html = template(this.model.toJSON());
    this.$el.html(html);
    return this;
  },

  deleteVehicle: function() {
    console.log("Model destroyed");
    this.model.destroy();
  }
});

var VehiclesView = Backbone.View.extend({
  tagName : "ul",

  initialize: function () {
    this.model.on("change", this.render, this);
    this.model.on("add", this.render, this);
    this.model.on("remove", this.render, this);
  },

render: function() {
    var self = this;

    this.model.each(function(vehicle){
        var vehicleView = new VehicleView({model: vehicle});
        self.$el.append(vehicleView.render().$el);
    });
}

});

// Add cars to the collection
var car1 = new Vehicle({registrationNumber: "XLI887", color: "blue"});
var car2 = new Vehicle({registrationNumber: "ZNP123", color: "blue"});
var car3 = new Vehicle({registrationNumber: "XUV456", color: "grey"});

var vehicles = new Vehicles([car1, car2, car3]);

var vehiclesView = new VehiclesView({el: "#container", model: vehicles});
vehiclesView.render();

The rendering looks good, but when I click delete, the new collection (with one less element) is appended to the existing view of the older collection. How do I replace the old collection view with the new one?

A: I modified the "remove" handler as below and it dynamically removed the "li" element from the list and showed the new collection.
initialize: function () {
    this.model.on("change", this.render, this);
    this.model.on("add", this.render, this);
    this.model.on("remove", this.onDelete, this);
},

onDelete : function(vehicle) {
    console.log("Vehicle deleted");
    this.$el.find("li#" + vehicle.id).remove();
}


text:
Q: If request comes on the same day, Object remains same otherwise compare and create new Object Today, If i run the program first time then create the object otherwise we use the previous object.
public class ObjectRestriction {

static SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
static String date = "00000000";
public static void main(String[] args) {

    if( date.equals(formatter.format(new Date())))
    {
        System.out.println("already create object");
    }
    else
    {
        Reconcilation rc = new Reconcilation();
        date = formatter.format(new Date());
        System.out.println(date);
    }
}

}

But when I run again then it initialize date variable to "00000000" and create new object. so, please help to restrict object creation on the basis of date.

A: A static variable does not survive the run of your app. Nor does any other kind of variable. After your main method completes its run, and you've not spawned any other threads, your app is done, complete, fini. All your variables are gone, wiped out, no longer in existence, cleared from memory.
Persistent storage
To save a value between runs of your app, you must persist the value, write the data to storage. For example in a file, or send to a database.
java.time
You are using troublesome old date-time classes, now legacy, supplanted by the java.time classes. For a date-only value without time-of-day and without time zone, use the LocalDate class.
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );

ISO 8601
The ISO 8601 standard defines sensible practical formats for text representing date-time values. Use these formats when writing your date-time objects to text files.
For date-only value that format is YYYY-MM-DD. The java.time classes use these standard formats by default. So you simply call toString.
String output = today.toString();

LocalDate ld = LocalDate.parse( "2017-01-23" );


text:
Q: How can i initialize JsonObject items in DataModel in android I want use Retrofit for load data from server, and I use DataModel for set and get data.
My dataModel such as this : (this is not mine dataModel, jus like this)
public class Movie {
    @SerializedName("poster_path")
    private String posterPath;
    @SerializedName("adult")
    private boolean adult;
    @SerializedName("overview")
    private String overview;
    @SerializedName("release_date")
    private String releaseDate;
    @SerializedName("genre_ids")
    private List<Integer> genreIds = new ArrayList<Integer>();
    @SerializedName("id")
    private Integer id;
    @SerializedName("original_title")
    private String originalTitle;
    @SerializedName("original_language")
    private String originalLanguage;
    @SerializedName("title")
    private String title;
    @SerializedName("backdrop_path")
    private String backdropPath;
    @SerializedName("popularity")
    private Double popularity;
    @SerializedName("vote_count")
    private Integer voteCount;
    @SerializedName("video")
    private Boolean video;
    @SerializedName("vote_average")
    private Double voteAverage;

    public Movie(String posterPath, boolean adult, String overview, String releaseDate, List<Integer> genreIds, Integer id,
                 String originalTitle, String originalLanguage, String title, String backdropPath, Double popularity,
                 Integer voteCount, Boolean video, Double voteAverage) {
        this.posterPath = posterPath;
        this.adult = adult;
        this.overview = overview;
        this.releaseDate = releaseDate;
        this.genreIds = genreIds;
        this.id = id;
        this.originalTitle = originalTitle;
        this.originalLanguage = originalLanguage;
        this.title = title;
        this.backdropPath = backdropPath;
        this.popularity = popularity;
        this.voteCount = voteCount;
        this.video = video;
        this.voteAverage = voteAverage;
    }

    public String getPosterPath() {
        return posterPath;
    }

    public void setPosterPath(String posterPath) {
        this.posterPath = posterPath;
    }

    public boolean isAdult() {
        return adult;
    }

    public void setAdult(boolean adult) {
        this.adult = adult;
    }

    public String getOverview() {
        return overview;
    }

    public void setOverview(String overview) {
        this.overview = overview;
    }

    public String getReleaseDate() {
        return releaseDate;
    }

    public void setReleaseDate(String releaseDate) {
        this.releaseDate = releaseDate;
    }

    public List<Integer> getGenreIds() {
        return genreIds;
    }

    public void setGenreIds(List<Integer> genreIds) {
        this.genreIds = genreIds;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getOriginalTitle() {
        return originalTitle;
    }

    public void setOriginalTitle(String originalTitle) {
        this.originalTitle = originalTitle;
    }

    public String getOriginalLanguage() {
        return originalLanguage;
    }

    public void setOriginalLanguage(String originalLanguage) {
        this.originalLanguage = originalLanguage;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getBackdropPath() {
        return backdropPath;
    }

    public void setBackdropPath(String backdropPath) {
        this.backdropPath = backdropPath;
    }

    public Double getPopularity() {
        return popularity;
    }

    public void setPopularity(Double popularity) {
        this.popularity = popularity;
    }

    public Integer getVoteCount() {
        return voteCount;
    }

    public void setVoteCount(Integer voteCount) {
        this.voteCount = voteCount;
    }

    public Boolean getVideo() {
        return video;
    }

    public void setVideo(Boolean video) {
        this.video = video;
    }

    public Double getVoteAverage() {
        return voteAverage;
    }

    public void setVoteAverage(Double voteAverage) {
        this.voteAverage = voteAverage;
    }
}

My json is below image : (this mine json)

I want add medium from thumbnail_images into above DataModel, but I don't know how can I it?! Thanks all <3
I want add medium from thumbnail_images into above DataModel, but I don't know how can I it?! Thanks all <3

A: Inside your model add:
@SerializedName("thumbnail_images")
private ThumbnailImages thumbnailImages;

Create the class ThumbnailImages and add inside it:
@SerializedName("medium")
private Medium medium;

And create the class Medium with the fields url, width and height.
You can remove the constructor if you want


text:
Q: Как вызвать функцию в JavaScript событии onclick к коде, не в HTML? Все просто, есть кнопка, по её нажатию должна вызываться определенная ранее функция 'firstrButtonActive(). Событие onclick прописано в коде javascript не в HTML. Как вызвать функцию таким образом? Я уже всё перепробовал...
//Беру кнопку
var buttonFirstTabComments = document.getElementById("buttonFirstTabComments");

//Как я уже пробовал:
buttonFirstTabComments.onclick='firstrButtonActive();'

buttonFirstTabComments.onclick='firstrButtonActive();';

buttonFirstTabComments.onclick=firstrButtonActive();

buttonFirstTabComments.onclick(firstrButtonActive());

buttonFirstTabComments.onclick('firstrButtonActive()');

buttonFirstTabComments.onclick("firstrButtonActive()";);

A: http://javascript.ru/tutorial/events/comparison
element.addEventListener( имя_события, обработчик, фаза)

A: Попробуйте так:
buttonFirstTabComments.onclick = firstrButtonActive;

или так:
buttonFirstTabComments.addEventListener('click', firstrButtonActive, false);

И да, не забудьте назначать обработчики после загрузки DOM страницы, иначе будут ошибки.
A:
document.getElementById('buttonFirstTabComments').setAttribute('onclick','firstrButtonActive()');

Рекомендация от меня, а меня лучше не слушать //И пожалуйста, на используйте такие длинные имена. Лучше but1Com. Если таких несколько, то для понятности при объявлении первого напишите //1 - 1st tab
Кстати, мини лекция. У объекта из тега таким образом (.%attribute%) можно пробраться только для style. Остальное только так(см. "Смотрите также" снизу)


text:
Q: Issue with filename containing spaces There is a bug in an OpenCart Framework version 3.0.2.0,
If there are files with the filename containing spaces between them, it takes too long to process and execute
For Eg: Consider

img = https://DomainNameServer/image/catalog/pimages/SKU 081985
  P80.jpg

<?php

set_time_limit(0);
ignore_user_abort(true);

public  function addSubImages($images){
      $Image =array();

      foreach($images['img'] as $key => $img){

          $headers[] = 'Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg';
          $headers[] = 'Connection: Keep-Alive';
          $headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8';
          $user_agent = 'php';
          $process = curl_init($img); // http://localhost/bluemb/image/catalog/pimages/SKU 081985 P80.jpg
          curl_setopt($process, CURLOPT_HTTPHEADER, $headers);
          curl_setopt($process, CURLOPT_HEADER, 0);
          curl_setopt($process, CURLOPT_USERAGENT, $user_agent);
          curl_setopt($process, CURLOPT_TIMEOUT, 1800);
          curl_setopt($process, CURLOPT_CONNECTTIMEOUT, 0);
          //curl_setopt($process, CURLOPT_CONNECTTIMEOUT, 1700);
          curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
          curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);
          $return = curl_exec($process);
          curl_close($process);
          //return $return;

          $filepath  = pathinfo($img);
          $dirname  = DIR_IMAGE.'catalog/prod/';

          if (!file_exists($dirname)) {
            mkdir($dirname, 0755, true);
          }

          if (!empty($dirname)) {
            $srcfile = $img;
            $dstfile = DIR_IMAGE.'catalog/prod/'.$filepath['basename']; // /var/www/html/opencart/image/catalog/prod/SKU 081985 P80.jpg
            $Image[] = 'catalog/prod/'.$filepath['basename'];  //catalog/prod/SKU 081985 P80.jpg
            copy(str_replace(" ","%20",$srcfile), $dstfile);
            //file_put_contents($dstfile,$return);
          }
          else {
            $Image = "";
          }

      }
  return $Image;
}

With these below functions:

*

*The images were saved in Corrupted/RAW format with more latency without a throughput file_put_contents($dstfile, $return);

*The images were saved perfectly with more latency with proper throughput copy(str_replace(" ", "%20", $srcfile), $dstfile);

*The images were saved in Text format with more latency with improper throughput
@copy($srcfile, $dstfile);
$content = file_get_contents($srcfile);
$fp = fopen($dstfile , "w+");
fwrite($fp, $content);
$Image = 'catalog/prod/'.$filepath['basename'];
fclose($fp);
curl_close($process);

*copy(urlencode($srcfile), $dstfile);
Results:

Warning: copy(https%3A%2F%2Fwww.DomainNameServer.in%2Fimage%2Fcatalog%2Fpimages%2FSKU093126+%281%29.jpg):
  failed to open stream: No such file or directory in
  /var/www/html/opencart3/admin/model/account/apisync.php on line
  264

*copy(urldecode($srcfile), $dstfile);
Results:

Warning: copy(https://www.DomainNameServer.in/image/catalog/pimages/SKU093126 (1).jpg): failed to open stream: HTTP request failed!  in /var/www/html/opencart3/admin/model/account/apisync.php on line 264

*copy(str_replace('_','%20',$srcfile), $dstfile);
Results:

Warning:copy(https://www.DomainNameServer.in/image/catalog/pimages/SKU093126 (1).jpg):
  failed to open stream: HTTP request failed!  in
  /var/www/html/opencart3/admin/model/account/apisync.php on line
  265

*copy(str_replace('%20',' ',$srcfile), $dstfile);OR
copy(str_replace('%20','_',$srcfile), $dstfile);OR
copy(str_replace('%20','',$srcfile), $dstfile);
Results:

Warning:
  copy(https://www.DomainNameServer.in/image/catalog/pimages/SKU093126 (1).jpg):
  failed to open stream: HTTP request failed!  in
  /var/www/html/opencart3/admin/model/account/apisync.php on line
  265

When building the API functionality, out of 10,000 products only 1091 products are saving into a database and rest of 8909 products took 7 - 10 hours
long to execute. Since I have set the execution time limit to Infinite. When I checked after 10 hours, all the products were successfully saved.
Total Time Taken is directly proportional to no. of Image File name containing spaces
Exporting the no. of the product varies according to Image File name containing spaces.
While when I was debugging for three products having the image file name with spaces, it was taking 20 mins in order complete without the addSubImages() function it took not even a single second to execute
If there are any other approaches for the solutions in order to get around this scenario?

A: Use this code
Dont use space
copy(str_replace("%20", "", $srcfile), $dstfile);
OR
copy(str_replace("%20", "_", $srcfile), $dstfile);

See https://www.w3schools.com/php/func_string_str_replace.asp

A: Modifying Prasannas answer this worked for me:
$string_without_space = str_replace(" ", "_", $string_with_space);


text:
Q: How to use media queries in flexbox? I'm using flexbox to do the layout of my website to facilitate the responsiveness but when the width of the screen gets to less than 800px, rows get on top of each other. I'm trying to solve this with media queries but don't know exactly what to do here. I've tried using flex-shrink but I'm not sure how to use it as well. Can anyone help me with this?
I'm putting here the whole code for the page that I've done so far.
html
<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>A.J. Machado</title>
    <meta name="author" content="Joana Oliveira" />
    <link href="./style.css" rel="stylesheet" />
    <link
      href="https://fonts.googleapis.com/css?family=Fjalla+One|Amiri|Prata|Lato:300|Cormorant+Garamond|Francois+One|Inter|Josefin+Sans:100|Montserrat|Playfair+Display|Ibarra+Real+Nova:400,700|Sen:700&display=swap"
      rel="stylesheet"
    />

                ana

                joão

home

about

work

                    contact

shop

                Find magic in the

                smallest of things.

                I'm Ana and I will help you with any design solution you might
                be looking for. I'll build the identity of your new, creative
                and exciting projects and restore ones that already exist.

About me

                    Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean
                    commodo ligula eget dolor. Aenean massa. Cum sociis natoque
                    penatibus et magnis dis parturient montes, nascetur ridiculus
                    mus. Donec quam felis, ultricies nec, pellentesque eu, pretium
                    quis, sem.

                      Nulla consequat massa quis enim. Donec pede justo, fringilla
                      vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus
                      ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis
                      eu pede mollis pretium. Integer tincidunt. Cras dapibus.

                    Vivamus elementum semper nisi. Aenean vulputate eleifend tellus.
                    Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac,
                    enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a,
                    tellus.

                        Let's connect

CONNECT

                    Still here? I would love

                    to hear you story!

                    Tell me your story and how you business begun,

                    I would love to hear and help you achieve your goals.

                    Get in touch

                        ana

                        joão

home

about

work

                        contact

shop

Joana Oliveira© All Rights Reserved

css
body {
  padding: 0;
}
* {
  padding: 0;
  box-sizing: border-box;
}

/*--------rows----------*/
.row {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  width: 100%;
}

/*-------columns-------*/
.column {
  display: flex;
  flex-direction: column;
  flex-basis: 100%;
  flex: 1;
}

/*--------------------HEADER---------------------*/

.header-container {
  width: 100%;
  height: 370px;
  flex-direction: row;
  background-color: rgba(234, 203, 193, 0.4);
  display: flex;
  margin: 0 auto;
  padding-bottom: 200px;
}

.logo {
  font-family: "Francois One", sans-serif;
  letter-spacing: 3px;
  padding-left: 80px;
}

.header {
  height: 280px;
  justify-content: space-between;
}
/* ------- nav --------- */

nav {
  height: 50px;
  flex-direction: row;
  justify-content: space-between;
  padding: 10px 50px 0 0;
}
nav ul {
  list-style: none;
  display: flex;
  padding: 5px;
}
nav li {
  margin-left: 45px;
  font-family: "Josefin Sans", sans-serif;
  display: list-item;
}

nav a {
  color: #343335;
  text-decoration: none;
  font-size: 16px;
  font-weight: 500;
  text-transform: uppercase;
}

/* ------- Containers --------- */

.wrap-container {
  flex-wrap: wrap;
  width: 100%;
  height: 100%;
}

.welcome-section {
  width: 400px;
}

.welcome-section h1 {
  font-family: "Ibarra Real Nova", serif;
  font-size: 50px;
}
.intro-text {
  font-family: "Lato", sans-serif;
  line-height: 1.8;
  letter-spacing: 0;
  font-weight: 300;
  font-size: 20px;
}

.work-together {
  font-family: "Ibarra Real Nova", serif;
  align-items: center;
  color: rgba(40, 44, 48, 1);
  font-weight: bold;
  text-align: center;
  justify-content: center;
  font-size: 40px;
  padding-top: 180px;
}

.connect-title {
  font-family: "Lato", sans-serif;
  color: white;
  line-height: 1.8;
  letter-spacing: 0.15em;
  text-align: center;
  justify-content: center;
  transform: rotate(90deg);
  font-size: 18px;
  font-weight: 700;
  padding-left: 200px;
}

.connect-text {
  font-family: "Lato", sans-serif;
  color: rgba(40, 44, 48, 1);
  font-size: 14px;
  padding: 30px 0 20px 0;
  text-align: center;
  line-height: 1.4;
  letter-spacing: 0.05em;
}
.inquire {
  justify-content: center;
}
.connect-button {
  font-family: "Lato", sans-serif;
  color: rgba(198, 211, 222, 1);
  text-align: center;
  letter-spacing: 0.15em;
  font-size: 13px;
  line-height: 1.4;
  text-decoration: none;
  cursor: pointer;
  background-color: rgb(48, 51, 54);
  padding: 10px 17px;
  justify-content: center;
  align-content: center;
  border-style: solid;
  border-radius: inherit;
}

/* ------- FOOTER --------- */

.footer {
  height: 250px;
  background-color: #3d3d3d;
}

.logo-footer h1 {
  font-family: "Francois One", sans-serif;
  letter-spacing: 3px;
  color: rgb(255, 255, 255);
  padding: 20px 0 0 0;
  text-align: center;
}

.menu-footer {
  flex-direction: column;
  padding-top: 50px;
}

.menu-footer ul {
  list-style: none;
  display: flex;
}
.menu-footer li {
  margin-left: 45px;
  font-family: "Josefin Sans", sans-serif;
  display: list-item;
  list-style-type: none;
  padding: 5px 0 5px 0;
}

.menu-footer a {
  color: rgb(255, 255, 255);
  text-decoration: none;
  font-size: 16px;
  font-weight: 500;
  text-transform: uppercase;
}

.social-media ul {
  list-style: none;
  display: flex;
  justify-content: center;
}

.social-media li {
  margin-left: 30px;
  display: list-item;
  list-style-type: none;
  padding: 40px 0 10px 0;
  color: rgb(255, 255, 255);
  font-size: 1.3rem;
}

.rights {
  padding-top: 30px;
  justify-content: center;
}
.rights h3 {
  font-family: "Lato", sans-serif;
  color: rgb(255, 255, 255);
  font-size: 10px;
  text-align: center;
  letter-spacing: 0.15em;
  line-height: 1.4;
}

/* ---------------- ABOUT PAGE---------------- */

.header-container-2 {
  width: 100%;
  height: 370px;
  background-color: rgba(221, 226, 220, 1);
  display: flex;
  padding-bottom: 100px;
}

.section-1-about {
  justify-content: space-around;
  padding-bottom: 100px;
}

.section-1b-about {
  height: 550px;
}

.section-2-about {
  height: 800px;
  justify-content: center;
  background-color: rgba(234, 203, 193, 0.3);
}

.bookpicture {
  padding: 50px 50px 0 0;
}

.about-me-title {
  font-family: "Ibarra Real Nova", serif;
  align-items: center;
  color: rgba(40, 44, 48, 1);
  font-weight: bold;
  text-align: left;
  font-size: 40px;
  padding: 250px 0 0 50px;
}

.about-me-text {
  width: 400px;
  padding-left: 50px;
  font-family: "Lato", sans-serif;
  line-height: 1.8;
  letter-spacing: 0;
  font-weight: 300;
  font-size: 13px;
}

.connect-button-about {
  font-family: "Lato", sans-serif;
  color: rgba(198, 211, 222, 1);
  text-align: center;
  letter-spacing: 0.15em;
  font-size: 13px;
  line-height: 1.4;
  text-decoration: none;
  cursor: pointer;
  background-color: rgb(48, 51, 54);
  padding: 10px 17px;
  border-width: 0px;
  border-style: solid;
  border-radius: inherit;
}

.section-3-about {
  height: 200px;
}

.section-4-about {
  background-color: rgba(198, 211, 222, 1);
  height: 300px;
}

.inquire-about {
  padding: 20px 0 0 50px;
}

.section-5-about {
  height: 300px;
}

https://codepen.io/joanaoli09/pen/YzXoEmm
As you're not going to be able to see how it looks because of the images, here is what it looks like:

A: You want flex-direction: column:

.flex{display:flex}

.flex.m{
    flex-direction:column
}

I'm desktop

1

2

3

4

5

I'm mobile

1

2

3

4

5


text:
Q: Render json with a condition in rails I am working on serializers. I want to display some jobs with attribute cancelled=true. I tried render json: @jobs, :only => [:cancelled], but its only displaying the jobs with cancelled attribute. How can I filter the jobs? I also tried json: @jobs, :only => [:cancelled =="true"], but it's not working.
I tried it in serializer too. This is my serializer:
module V1
  module Jobs
    class CancelledJobSerializer < ActiveModel::Serializer
      attribute :id, if: :id?
      attribute :cancelled, if: :cancelled?
      def cancelled?
        true if object.cancelled
      end
      def id?
        true if object.cancelled
      end
    end
  end
end

and it returns
{},
{},
{},
{},
{},
{},
{},
{},
{},
{"cancelled":true }

Is there anyway to remove those parentheses?

A: Add a scope to the Job model so it can return canceled (cancelled) jobs
scope :cancelled, -> { where(cancelled: true) }

And then in your controller
@cancelled_jobs = Job.cancelled
render json: @cancelled_jobs


text:
Q: Visual Studio Immediate window "Internal error in the expression evaluator" Disclaimer: I already checked this question but this is about the Immediate window.
I'm using Entity Framework to fetch some results, so I have a list of logging:
var result = ctx.Logging.Where(*filtering*).ToList();

But I want to know the distinct Datatypes of the list (an enumeration, underlying type byte and Datatype is nullable, if I make it not nullable it works for some reason). When I try to do it in the immediate window:
result.Select(r => r.Datatype).Distinct().ToList();

I get the message:

Internal error in the expression evaluator.

However it works fine when I do it in code, for example var test = result.Select(r => r.Datatype).Distinct().ToList();. I already tried using 'managed compatibility mode' and 'legacy expressions' from the debugging options but then I get another message:

Expression cannot contain lambda expressions

Am I missing something or is this a bug in Visual studio 2015?
Minimal, Complete, and Verifiable example:
class Program
{
    static void Main(string[] args)
    {
        List<Test> tests = new List<Test>();
        for(int i = 0; i<100; i++)
        {
            if (i % 2 == 0)
                tests.Add(new Test { ID = i, Enum = TestEnum.Value1 });
            else
                tests.Add(new Test { ID = i, Enum = TestEnum.Value2 });
        }
        var distinct = tests.Select(t => t.Enum).Distinct().ToList();
    }
}

public enum TestEnum : byte
{
    Value1 = 1,
    Value2 = 2
}
public class Test
{
    public int ID { get; set; }
    public TestEnum? Enum { get; set; }
}

In code tests.Select(t => t.Enum).Distinct().ToList(); works, in immediate window it doesn't.

A: I think it is a bug in the expression evaluator as it seems to work with a workaround like this:
tests.Select(t => t.Enum).ToList().Distinct().ToList()

Here is the same result using this:
? tests.Select(t => t.Enum).ToList().Distinct().ToList()
Count = 2
    [0]: Value1
    [1]: Value2

I noticed that 'quickwatching' the expression in your code also results in the error:
Internal error in the expression evaluator.

At least it is consistent in that area :-)

A: Your expression does not work:
tests.Select(t => t.Enum).Distinct().ToList();
'Internal error in the expression evaluator.'

But thats because Enum is a nullable type.
tests.Select(t => t.Enum.Value).Distinct().ToList();
    'Count = 2
        [0]: Value1
        [1]: Value2'

And in fact, native functions used in EF does not work with lambda expressions in the immediate window.


text:
Q: Why is my apache server address ::1 and not 127.0.0.1 I am using bitnami wamp on windows 7 running apache 2.4 and I am having a problem. The server address of the apache server shows ::1 instead of the expected 127.0.0 1
Is apache using ipv6 by default or what?
In the wamp readme file, it says go to
http://127.0.0.1:80

or
http://localhost

When I do the 127.0.0.1 the browser tells me connection rejected but that is not the case for localhost. Localhost seems to work fine but I think it is using the ipv6 address ::1.
So why is my apache server address ::1 and not 127.0.0.1 and how do I resolve the issue.
Thanks.

A: I have myself never had issues with Apache listening on any IPv6 address, but this is what the apache docs say:
On some platforms, such as Linux and Tru64, the only way to handle both IPv6 and IPv4 is to use mapped addresses. If you want Apache to handle IPv4 and IPv6 connections with a minimum of sockets, which requires using IPv4-mapped IPv6 addresses, specify the --enable-v4-mapped configure option.
--enable-v4-mapped is the default on all platforms except FreeBSD, NetBSD, and OpenBSD, so this is probably how your Apache was built.
If you want Apache to handle IPv4 connections only, regardless of what your platform and APR will support, specify an IPv4 address on all Listen directives, as in the following examples:
Listen 0.0.0.0:80
Listen 192.0.2.1:80

You can read more here:
http://httpd.apache.org/docs/2.2/bind.html


text:
Q: Collapse SearchView (in ActionBar) on Back button press I have implemented SearchView in ActionBar, But the problem with it is, whenever am typing something and press submit, the SearchView doesn't collapse back into that Search icon, it stays expanded, neither when I press Back button, SearchView doesn't collapse back.
My implementation is like this:
menu_search.xml
<item
    android:id="@+id/app_bar_search"
    android:icon="@drawable/ic_search_white_24dp"
    android:title="Search"
    app:actionViewClass="android.widget.SearchView"
    app:showAsAction="always" />

MainActivity.java
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu_search, menu);
    item = menu.findItem(R.id.app_bar_search);
    searchView = (SearchView) item.getActionView();
    searchView.setMaxWidth(Integer.MAX_VALUE);

    int searchBarId = searchView.getContext().getResources().getIdentifier("android:id/search_bar", null, null);
    searchBar = searchView.findViewById(searchBarId);
    searchBar.setLayoutTransition(new LayoutTransition());

    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {

            item.collapseActionView();

            searchView.setQuery("", false);
            searchView.clearFocus();
            searchBar.clearFocus();

            .
            .
            .
            .
            .

            return true;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            return false;
        }
    });

    return super.onCreateOptionsMenu(menu);
}

Things I have tried:
@Override
public void onBackPressed() {
    super.onBackPressed();
    if (item.isActionViewExpanded()) {
        item.collapseActionView();
    } else {
        super.onBackPressed();
    }
}

and
   @Override
   public void onBackPressed() {
       super.onBackPressed();
       if (searchView != null) {
           searchView.onActionViewCollapsed();
           searchView.setQuery("", false);
           searchView.clearFocus();
           searchBar.clearFocus();
           hideSoftKeyboard(MainActivity.this);
       } else {
           super.onBackPressed();
       }
   }

   public static void hideSoftKeyboard(Activity activity) {
       InputMethodManager inputMethodManager =
               (InputMethodManager) activity.getSystemService(
                       Activity.INPUT_METHOD_SERVICE);
       inputMethodManager.hideSoftInputFromWindow(
               activity.getCurrentFocus().getWindowToken(), 0);
   }

SearchView expands from left to right to type but doesn't collapse back form right to left.
Please advice.

A: Try below code and let me know if it works.
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
                    searchView.setSearchableInfo(searchManager.getSearchableInfo(new ComponentName(this, ResultActivity.class)));
    searchView.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
            searchView.setOnSuggestionListener(new SearchView.OnSuggestionListener() {
                @Override
                public boolean onSuggestionSelect(int position) {
                    return false;
                }

                @Override
                public boolean onSuggestionClick(int position) {
                    searchView.clearFocus();
                    item.collapseActionView();
                    return false;
                }
            });
            searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                @Override
                public boolean onQueryTextSubmit(String query) {
                    searchView.clearFocus();
                    item.collapseActionView();
                    return false;
                }

                @Override
                public boolean onQueryTextChange(String newText) {
                    return false;
                }
            });

A: I was going through the second page of Google search and found this.
It worked for me.
searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    searchView.setIconified(true);
                }
            }
        });


text:
Q: Use AWS::EC2::Instance in AWS::CloudFormation::Init I have some LaunchConfig for AS group
   "LaunchConfig": {
     "Type" : "AWS::AutoScaling::LaunchConfiguration",

     "Metadata" : {
        "AWS::CloudFormation::Init" : {
          "configSets" : {
            "InstallAndRun" : [ "Install" ]
          },

          "Install" : {

            "files" : {

              "/var/www/html/index.html" : {
                "content" : { "Fn::Join" : ["", [
                "<html\n",
                "
Apache HTTP Server
\n",
                "\n"
              ]]},
              "mode"    : "000644",
              "owner"   : "apache",
              "group"   : "apache"
              },
            ......

It's possible or what the best approach add to index.html some data, like, for example, instance-id from AWS::EC2::Instance using "files" sections?
If I add { "Ref" : "AWS::StackId" } or { "Ref" : "AWS::Region" }, it works fine, but its from Pseudo Parameter.
              "/var/www/html/index.html" : {
                "content" : { "Fn::Join" : ["", [
                "<html\n",
                "
Apache HTTP Server
\n",
                { "Ref" : "AWS::StackId" },
                "\n"
              ]]},

Thanks!

A: I don't believe it's possible to do this directly, but you should be able to accomplish this by placing a file, and then afterwards running a command to update it:
(Disclaimer: I haven't explicitly tested this.)
{
    "AWS::CloudFormation::Init": {
        "configSets": {
            "InstallAndRun": [
                "Install",
                "UpdateIndexHtml"
            ]
        },
        "Install": {
            "files": {
                "/var/www/html/index.html": {
                    "content": {
                        "Fn::Join": [
                            "",
                            [
                                "<html\n",
                                "
Apache HTTP Server
\n",
                                "---INSTANCE_ID---\n",
                                "\n"
                            ]
                        ]
                    },
                    "mode": "000644",
                    "owner": "apache",
                    "group": "apache"
                }
            }
        },
        "UpdateIndexHtml": {
            "commands": {
                "UpdateIndexHtml": {
                    "command": "sed -i \"s|---INSTANCE_ID---|$(curl -s http://169.254.169.254/latest/meta-data/instance-id)|\" /var/www/html/index.html"
                }
            }
        }
    }
}


text:
Q: In TextField when type @@ open the date-picker angular 2+ I have a one text box when type the @ get the usersList when type the # get the tagsList and when type the @@ open the date picker I'm using ngx-bootstrap datepicker.
-I'm tried to add dynamically bsDatepicker it added successfully but datepicker dialog not get. I think it not registered in DOM perfectly.
HTML
        <div *ngIf="addCard" class="mx-2">
        <input type="text" class="form-control" (keyup)="getVal()" id="input_2" [formControl]="cardName" >
           <ng-container *ngIf="drpBind">
            <div class="searchresults" *ngFor="let i of lstbindData; let index = index" (click)="selectVal(i)">{{i}}
            </div>
           </ng-container>
       </div>

TS
  lstbindData: any = [];
  addCard: boolean = false;
  drpBind: boolean = false;
  getDatePicker: boolean = false;
  cardName = new FormControl();

 getVal() {
  const val = this.cardName.value;
  console.log('val', val);
  const value = val == '@' ? 1 : val == '#' ? 2 : val == '@@' ? 3 : 4;
   if (value == 1) {
     this.drpBind = true;
     this.lstbindData = this._cS.getAtkeywords();
   }
   else if (value == 2) {
     this.drpBind = true;
     this.lstbindData = this._cS.getHaskeywords();
   }
   else if (value == 3) {
     this.drpBind = false;
     var getEle1 = document.getElementById('input_2');
     getEle1.setAttribute('bsDatepicker', ''); //I'm trying to setAttribute it added successfully but datepicker it not getting.
   }
    else {
      this.drpBind = false;
    }
 }

Anyone have Idea please share it.
Thanks.


text:
Q: How do I align elements in adjacent columns of a UL? How do I align elements in adjacent columns of a ?
How it is not working:

Have tried specifying a fixed height to ul li {} which does the aligning; however, when the height needed is very small, this leaves huge white space.
HTML = standard
CSS =
ul {
    -webkit-column-count: 2;   /* Chrome, Safari, Opera */
    -moz-column-count:    2;   /* Firefox */
    column-count:         2;
}

ul li {
    color:         red;     /* bullet color */
    padding-right: 2.0em;   /* not too close */
}

A: you haven't written your html code but try to put ul tag in a div tag. you can play with div's height and width