text:
Q: Code for -Python plot I have never used Python and I saw one piece of code from a manual and  I would love to know what does it mean.
This is the code from the manual:
    import h5py
    h5file = h5py.File('Output/ScottCreek250b/simulation.results.DY.hdf5')
    channel_flows = h5file['Channel/Qc_out'][...]
    plt.plot(channel_flows[:, 0])
    plt.ylim((-0.01,0.01))
    plt.title('Streamflow at outlet', fontweight='bold')
    plt.ylabel('Flow ($\mathbf{m^3/s}$)')
    plt.xlabel('Model time-steps (24 hours)')

I would like to know what this two line mean, especially [...] and what are [:, 0] and [:, :10] stands for.
    channel_flows = h5file['Channel/Qc_out'][...]
    plt.plot(channel_flows[:, 0])

    soil_stores = h5file['Soil/V_s'][...]
    plt.plot(soil_stores[:, :10])

A: The numpy documentation won't explain why the indices are used as they are, in particular the first ones on the h5file:
The [...] on the h5file lines are needed to actually copy the data; if not, a reference is passed, which may not always be what one wants. In this case, though, it looks like it's unnecessary and may have just been a force of habit.
After that, you're left with two dimensional data arrays (note: not 3D as you suggest), where the first dimension is indexed over the complete range (by use of the sole ':'), and the second inner dimension is indexed as a single value (0) or a range of the first ten values (:10, where the 0 in 0:10 is the default and can be omitted).


text:
Q: Android game score int add in access database through servlet I am not sure on how to go about this but I have a game which I want to expand further and let the user submit the score with their name.
This will submit the score and name to a servlet which will add the details into an access database.
The score is of an int type.
Would be great if someone could show me how to do this, or point me in the right direction.
Thanks

A: In Android, just pass score and name as request parameters in URL.
String url = "http://example.com/servlet?score=" + score + "&name=" + URLEncoder.encode(name, "UTF-8");
// Connect the URL.

In the servlet, just access them as request parameters.
int score = Integer.parseInt(request.getParameter("score"));
String name = request.getParameter("name");
// Save them in DB.

See also:

*

*Executing a HTTP GET request with HttpClient in Android

*Servlets info page

*JDBC tutorial

redpajama_set_name: RedPajamaStackExchange


text:
Q: 1 user session java app and mysql Well I'm learning mysql and java, and I'm trying to do a Login app, Server - client MySQL.
The problem is that the same user can login in more than 1 pc at time. I want just to let the user be logged in 1 pc at time, if he logs out he can get logged in other pc.
I thought to put an status column inside a table in the DB, but if the connection to the server is lost there's no way to change the status of the user.
So what could be a good way to solve it. I hope I explained clearly.

A: Add a timestamp on this status, update it on every user's action. If there's time out (simulates connection loss) or session logout, then update the status to 'not logged in'


text:
Q: Footer background-color is taking over my entire web page Help! My footer background-color is taking over my entire web page. This was supposed to be a blue backgrounded footer on a white page. When I take mention of the footer from my css the page looks correct, but my footer is lost. Help? I've tried everything! Here is the jsfiddle: https://jsfiddle.net/3eoxaqjt/1/   I thank you much for any help that you can give me!
html:

    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" type="text/css" href="css/responsive.css" />
    <link rel="stylesheet" type="text/css" media="print" href="css/print.css">

Project 2

About This Project

Unit Topics Covered

References

Tips

About This Project

This project is about responsive design. Resize the browser window (Viewport) to see how the content respond to the resizing.

Unit Topics Covered

HTML & CSS refresh

Browser to Debug

Responsive Design Media CSS

Responsive Design Mobile

Responsive Design Desktop & Tablet Hiding/Show

References

W3Schools: HTML

W3Schools: CSS

Browser: Chrome

Browser: Firefox

Browser: IE

W3Schools: Media Types

W3Schools: Media Queries

W3Schools: CSS Responsive Design

W3Schools: Responsive Design Images

W3Schools: CSS3 Responsive

Tips

Go Mobile First - Approximately 1 in every 7 people on earth use their mobile devices to access the internet

Get Acquainted with Media Queries - Media queries check for a device's resolution, height, width and orientation

Understand What Mobile Means for Your Users - Use analytics to figure out why a user is visiting your website on their phone

Use Percentages - Instead of designing breakpoints for every possible viewport, you set a maximum layout size

The Need for Speed - Smartphone users expect a site to load in under 4 seconds. Main reason behind a slow site are non-optimized images

Eliminate the Unnecessary - Get rid of excessive elements, not only for your user experience, but also for website's speed

To Hamburger or Not to Hamburger - Keep less popular links in the hamburger menu navigation

Make it Readable - Don't make your users squint to read or pinch-to-zoom. Make your text size large enough to read from a smaller screen

Use the Right Button Size - Avoid small button sizes. Padding increases the tappable area, but margins do not

Design for Screen Orientation - Landscape orientation wins over portrait orientation 59% to 41%

Time and Date

css:
* {
  box-sizing: border-box;
}

header,
footer,
nav,
section,
article,
aside {
  display: block;
}

[class*="col-"] {
  float: left;
  padding: 15px;
  width: 100%
}

.row::after {
  content: "";
  clear: both;
  display: block;
}

body {
  font-size: 14px;
  font-family: "Lucinda" Sans sans-serif;
}

@media screen and (min-width: 600px)and (max-width: 768px) {
  .col-m-1 {
    width: 8.33%;
  }
  .col-m-2 {
    width: 16.66%
  }
  .col-m-3 {
    width: 25%
  }
  .col-m-4 {
    width: 40%
  }
  .col-m-5 {
    width: 41.66%
  }
  .col-m-6 {
    width: 50%
  }
  .col-m-7 {
    width: 58.33%
  }
  .col-m-8 {
    width: 60%
  }
  .col-m-9 {
    width: 75%
  }
  .col-m-10 {
    width: 83.33%
  }
  .col-m-11 {
    width: 91.66%
  }
  .col-m-12 {
    width: 100%
  }
}

@media screen and (min-width: 768px) {
  .col-1 {
    width: 8.33%;
  }
  .col-2 {
    width: 16.66%
  }
  .col-3 {
    width: 25%
  }
  .col-4 {
    width: 33.33%
  }
  .col-5 {
    width: 40%
  }
  .col-6 {
    width: 50%
  }
  .col-7 {
    width: 58.33%
  }
  .col-8 {
    width: 60%
  }
  .col-9 {
    width: 75%
  }
  .col-10 {
    width: 83.33%
  }
  .col-11 {
    width: 91.66%
  }
  .col-12 {
    width: 100%
  }
}

h1 {
  background-color: #9933cc;
  color: white;
  padding: 15px;
  list-style: none;
}

#firstLine {
  background-color: #33b5e5;
  font: white;
  box-shadow: 1px 1px 1px #888888;
  padding: 8px;
}

#firstLine:hover {
  background-color: #0099cc;
}

#secondLine {
  background-color: #33b5e5;
  font: white;
  box-shadow: 1px 1px 1px #888888;
  padding: 8px;
}

#secondLine:hover {
  background-color: #0099cc;
}

#thirdLine {
  background-color: #33b5e5;
  font: white;
  box-shadow: 1px 1px 1px #888888;
  padding: 8px;
}

#thirdLine:hover {
  background-color: #0099cc;
}

#fourthLine {
  background-color: #33b5e5;
  font: white;
  box-shadow: 1px 1px 1px #888888;
  padding: 8px;
}

#fourthLine:hover {
  background-color: #0099cc;
}

img {
  max-width: 100%;
  height: auto;
}

#referencesHeading {
  color: white;
}

.references {
  text-align: left;
  font: 14px;
  box-shadow: 1px 1px 1px #888888;
  padding: 10px;
  background-color: #33b5e5;
}

a:link {
  text-decoration: none;
}

a:hover {
  text-decoration: underline;
}

span {
  color: orange;
}

.footer {
    background-color: #0099cc;
    color: #ffffff;
    text-align: center;
    font-size: 10px;
    padding: 15px;
}

A: Just add

before

Fiddle Updated here
Or as Praveen Kumar posted, add clear: both; to your .footer css.

A: Add clear: both to the footer:
.footer {clear: both;}

Updated Fiddle: https://jsfiddle.net/qqdtex78/

A: Most grid based frameworks require a column to be inside of a row.  But you have columns without any rows, and so you don't get the float clearing property that's built into the rows.  Wrap all of your column divs inside

 and that should take care of your footer problem.

A: @Andi is correct!
You should have a  and inside this row the responsive columns need to be coded. Your grid system has to define for full with , how many columns and base on that you need to apply the different col-m-* for different elements.
If this is not clear, mock the layout and share will do the sample code for layout.


text:
Q: Type name could not be resolved. Please check config file Trying to unit test my application using moq and unity, and I'm getting errors where my
service is an interface and cannot be resolved:
Error message:
    Test method Ecommerce_Test.Tests.LoginSuccessfulRedirectToActionLoad threw exception:
System.InvalidOperationException: The type name or alias Ecommerce_Test.AuthenticationMock could not be resolved. Please check your configuration file and verify this type name.

Error Stack Trace:
    Microsoft.Practices.Unity.Configuration.ConfigurationHelpers.TypeResolverImpl.ResolveType(String typeNameOrAlias, Boolean throwIfResolveFails) in e:\Builds\Unity\UnityTemp\Compile\Unity\Unity.Configuration\Src\ConfigurationHelpers\TypeResolverImpl.cs: line 110
Microsoft.Practices.Unity.Configuration.RegisterElement.GetMappedType() in e:\Builds\Unity\UnityTemp\Compile\Unity\Unity.Configuration\Src\RegisterElement.cs: line 128
Microsoft.Practices.Unity.Configuration.RegisterElement.ConfigureContainer(IUnityContainer container) in e:\Builds\Unity\UnityTemp\Compile\Unity\Unity.Configuration\Src\RegisterElement.cs: line 0
Microsoft.Practices.Unity.Configuration.ContainerElement.<>c__DisplayClass1.<ConfigureContainer>b__0(ContainerConfiguringElement element) in e:\Builds\Unity\UnityTemp\Compile\Unity\Unity.Configuration\Src\ContainerElement.cs: line 114
Microsoft.Practices.ObjectBuilder2.EnumerableExtensions.ForEach[TItem](IEnumerable`1 sequence, Action`1 action) in e:\Builds\Unity\UnityTemp\Compile\Unity\Unity\Src\ObjectBuilder\Utility\EnumerableExtensions.cs: line 36
Microsoft.Practices.Unity.Configuration.ContainerElement.ConfigureContainer(IUnityContainer container) in e:\Builds\Unity\UnityTemp\Compile\Unity\Unity.Configuration\Src\ContainerElement.cs: line 110
Microsoft.Practices.Unity.Configuration.UnityConfigurationSection.Configure(IUnityContainer container, String configuredContainerName) in e:\Builds\Unity\UnityTemp\Compile\Unity\Unity.Configuration\Src\UnityConfigurationSection.cs: line 151
Microsoft.Practices.Unity.Configuration.UnityContainerExtensions.LoadConfiguration(IUnityContainer container, UnityConfigurationSection section, String containerName) in e:\Builds\Unity\UnityTemp\Compile\Unity\Unity.Configuration\Src\UnityContainerExtensions.cs: line 35
Microsoft.Practices.Unity.Configuration.UnityContainerExtensions.LoadConfiguration(IUnityContainer container) in e:\Builds\Unity\UnityTemp\Compile\Unity\Unity.Configuration\Src\UnityContainerExtensions.cs: line 63
Ecommerce.Controllers.HomeController.Login(LoginModel model) in C:\Users\avmin!\Documents\Visual Studio 2010\Projects\Ecommerce_Mock\Ecommerce\Controllers\HomeController.cs: line 45
Ecommerce_Test.Tests.LoginSuccessfulRedirectToActionLoad() in C:\Users\avmin!\Documents\Visual Studio 2010\Projects\Ecommerce_Mock\Ecommerce_Test\Tests.cs: line 80

Config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
  </configSections>
  <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">

    <assembly  name="Ecommerce"/>
    <assembly  name="Ecommerce_Tests"/>

    <container>
      <register type="Ecommerce.Authentication.IAuthentication"
                mapTo="Ecommerce_Test.AuthenticationMock, Ecommerce_Test" />
    </container>
  </unity>
  <system.serviceModel>
      <bindings />
      <client />
  </system.serviceModel>
</configuration>

Usage:
public ActionResult Login(HomeModels.LoginModel model)
        {
            var unity = new UnityContainer().LoadConfiguration(); //error fired here!!!
            var proxy = unity.Resolve<IAuthentication>();

            if (ModelState.IsValid)
            {
                try
                {
                    Login log = new Login();
                    log.Username = model.Username;
                    log.Password = model.Password;
                    int result = proxy.Login(new Login { Username = log.Username, Password = log.Password });

                }
                catch (MemberAccessException e)
                {
                    ModelState.AddModelError("Login was not successful", e);
                }
            }
            return View("Login",model);
        }

A: The solution turned out to be appending the name of the assembly to the end of the
mapTo value. The config file is updated above to reflect this.
Assembly name found by right clicking on Ecommerce_Tests project > Properties.

A: also, if you're using separate dlls for the injected code, make sure that the target frameworks are the same and that the dll(s) containing the injected classes are copied to the run (debug) folder


text:
Q: redirect ethernet packets through sk_buff to localhost I am writing a Linux  kernel module which redirects a packet to the localhost webserver ,which was originally forwarded through this machine using bridge  . It also redirects to reply to the client . The client is oblivious of the redirection . So there are 2 parts
  1. all forwarded packets through bridge  to some webserver outside  are redirected to local webserver .

*The output of the localhost webserver is channelled to the original client

I am able to do the second part through nf_hook NF_INET_LOCAL_OUT
unsigned int snoop_hook_reply( unsigned int hooknum, struct sk_buff *skb,
    const struct net_device *in, const struct net_device *out,
    int(*okfn)( struct sk_buff * ) )
{
    int offset, len;
    struct ethhdr *ethh;
    struct iphdr *iph;
    struct tcphdr *tcph;
    bool flag = false;
    struct net_device *eth1_dev , *lo_dev;

    if (!skb) return NF_ACCEPT;
    iph = ip_hdr(skb);
    if (!iph) return NF_ACCEPT;
    skb_set_transport_header(skb, iph->ihl * 4);
    tcph = tcp_hdr(skb);
    /* skip lo packets */
    if (iph->saddr == iph->daddr) return NF_ACCEPT;
    if (tcph->dest == htons(80))
            flag=true;
    if(flag != true)
            return NF_ACCEPT;

    // correct the IP checksum
    iph->check = 0;
    ip_send_check (iph);

    //correct the TCP checksum
    offset = skb_transport_offset(skb);
    len = skb->len - offset;
    tcph->check = 0;
    if(skb->len > 60){
    tcph->check  = csum_tcpudp_magic((iph->saddr), (iph->daddr), len, IPPROTO_TCP, csum_partial((unsigned char *)tcph,len,0));
    }
    else{
    tcph->check  = ~csum_tcpudp_magic((iph->saddr), (iph->daddr), len, IPPROTO_TCP, 0);
    }

    //send to dev
    eth1_dev = dev_get_by_name(&init_net,"eth1");
    lo_dev = dev_get_by_name(&init_net,"lo");
    skb->dev = eth1_dev;
    ethh = (struct ethhdr *) skb_push(skb, ETH_HLEN);
    skb_reset_mac_header(skb);
    skb->protocol = ethh->h_proto = htons(ETH_P_IP);
    memcpy (ethh->h_source,eth1_dev->dev_addr , ETH_ALEN);
    memcpy (ethh->h_dest, d_mac, ETH_ALEN); // d_mac is mac of the gateway
    dev_queue_xmit(skb);

    return NF_STOLEN;
}

the above code works perfectly for me . One issue is that later on I will mangle the packet so need to create a new sk_buff, probably .
I am not able to do the 1st part through NF_INET_PRE_ROUTING, I am not able to push the packet/sk_buff to the webserver process through the TCP/IP stack. I tried using dev_queue_xmit() function with skb->dev as both eth1 and lo . I am seeing the packets hitting on the lo or eth1 through tcpdump . But the packets are not reaching the localhost webserver. Can anyone help me regarding this or point to some similar answered question . I believe instead of dev_queue_xmit() I need to call some receiving function . Also when packets arrive in NF_INET_PREROUTING, I the ethernet headers are already there so I am not forming it .
I have already accomplished the above tasks in variety of ways , first using raw sockets , then using nf_queue , now I want to see the performance through this method.
Thanks

A: If you want to receive the packet locally, you cannot call dev_queue_xmit() on eth1 as it will be sent out. You probably need to call netif_rx() after pointing the skb->dev to eth1/lo.
One more point is if the dest-ip is not your local host ip, then you need to avoid routing again otherwise, there will be no use of your interception.
To achieve this, either you need to modify packet's dest ip to eth1/lo IP or
fool the IP layer by using skb_dst_set() to set "rth->dst.input= ip_local_deliver" for packet to be accepted as local packet.


text:
Q: Eclipse IDE: How to automatically arrive at the end of the current line after typing into a green box? For example while writing a method with 3 arguments, pressing tab automatically shifts to each argument spaces, but how to jump to the end of the current line without having to press END key?
Is it possible to use tab to move to the far end?

A: Press INTRO...
The answer is to short... well, I tell you, when you press INTRO inside the green box, you reach to the end of the line :) .

A: Press 'Enter', that exits the 'linked mode' (or as you call the green boxes)


text:
Q: Integrating Solr with Nutch issue I am following a tutorial from here. i have got solr and nutch installed separately and they are both working all fine. The problem comes when i have to integrate them. From the earlier posts on this site i learned that there could some issue with the schema files. As mentioned in the tut i copied the schema.xml of nutch to the schema.xml of solr and restarted the solr. solr stoped because of configuration issues. So i simply copied the  contents of each file into the other along with the existing content. Now (and previously as well) i get this error:
Indexer: starting at 2014-08-05 11:10:21
Indexer: deleting gone documents: false
Indexer: URL filtering: false
Indexer: URL normalizing: false
Active IndexWriters :
SOLRIndexWriter
        solr.server.url : URL of the SOLR instance (mandatory)
        solr.commit.size : buffer size when sending to SOLR (default 1000)
        solr.mapping.file : name of the mapping file for fields (default solrindex-mapping.xml)
        solr.auth : use authentication (default false)
        solr.auth.username : use authentication (default false)
        solr.auth : username for authentication
        solr.auth.password : password for authentication

Indexer: java.io.IOException: Job failed!
        at org.apache.hadoop.mapred.JobClient.runJob(JobClient.java:1357)
        at org.apache.nutch.indexer.IndexingJob.index(IndexingJob.java:114)
        at org.apache.nutch.indexer.IndexingJob.run(IndexingJob.java:176)
        at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:65)
        at org.apache.nutch.indexer.IndexingJob.main(IndexingJob.java:186)

Can someone suggest what should be done?
I am using apache-nutch-1.8 and solr-4.9.0
 Here is how my hadoop.log file looks like:
2014-08-05 12:50:05,032 INFO  crawl.Injector - Injector: starting at 2014-08-05 12:50:05
2014-08-05 12:50:05,033 INFO  crawl.Injector - Injector: crawlDb: -dir/crawldb
2014-08-05 12:50:05,033 INFO  crawl.Injector - Injector: urlDir: urls
.
.
.
.
.
2014-08-05 13:04:21,255 INFO  solr.SolrIndexWriter - Indexing 1 documents
2014-08-05 13:04:21,286 WARN  mapred.LocalJobRunner - job_local1310160376_0001
org.apache.solr.common.SolrException: Bad Request

Bad Request

request: http://my-solr-url:8983/solr/update?wt=javabin&version=2
    at org.apache.solr.client.solrj.impl.CommonsHttpSolrServer.request(CommonsHttpSolrServer.java:430)
    at org.apache.solr.client.solrj.impl.CommonsHttpSolrServer.request(CommonsHttpSolrServer.java:244)
    at org.apache.solr.client.solrj.request.AbstractUpdateRequest.process(AbstractUpdateRequest.java:105)
    at org.apache.nutch.indexwriter.solr.SolrIndexWriter.close(SolrIndexWriter.java:155)
    at org.apache.nutch.indexer.IndexWriters.close(IndexWriters.java:118)
    at org.apache.nutch.indexer.IndexerOutputFormat$1.close(IndexerOutputFormat.java:44)
    at org.apache.hadoop.mapred.ReduceTask$OldTrackingRecordWriter.close(ReduceTask.java:467)
    at org.apache.hadoop.mapred.ReduceTask.runOldReducer(ReduceTask.java:535)
    at org.apache.hadoop.mapred.ReduceTask.run(ReduceTask.java:421)
    at org.apache.hadoop.mapred.LocalJobRunner$Job.run(LocalJobRunner.java:398)
2014-08-05 13:04:21,544 ERROR indexer.IndexingJob - Indexer: java.io.IOException: Job failed!
    at org.apache.hadoop.mapred.JobClient.runJob(JobClient.java:1357)
    at org.apache.nutch.indexer.IndexingJob.index(IndexingJob.java:114)
    at org.apache.nutch.indexer.IndexingJob.run(IndexingJob.java:176)
    at org.apache.hadoop.util.ToolRunner.run(ToolRunner.java:65)
    at org.apache.nutch.indexer.IndexingJob.main(IndexingJob.java:186)

2014-08-05 13:10:37,855 INFO  crawl.Injector - Injector: starting at 2014-08-05 13:10:37
.
.
.

A: may be because of some versioning differences the tutorial suggested to copy the conf/schema.xml whereas in this particular version of solr, the file schema-solr4.xml was supposed to be copied followed by addition of : <field name="_version_" type="long" indexed="true" stored="true"/> in line no 351. Restart the solr by java -jar start.jar and it works all normal! Hope this helps someone!


text:
Q: Entity Framework throwing exception while loading I'm trying to write my first app in Entity Framework.
In program.cs (where my main() is) I have line ProdContext ctx = new ProdContext();. The prodContext.cs is:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Entity;
using System.Text;

namespace Entity_Framework
{
    class ProdContext : DbContext
    {
        public DbSet<Category> Categories { get; set; }
        public DbSet<Product> Products { get; set; }
    }
}

While trying to run main I get exception at above line:

FileNotFoundException: Could not load file or assembly 'System.Configuration.ConfigurationManager, Version=4.0.2.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'.

I have fresh install of Visual Studio with C# and EF (I installed it with install-package entityframework -version 6.1.3.0). Why am I getting that exception?

A: I would suggest that you're using .NET Core application while still trying to install .NET library. EF 6 is ".NET" specific library. With .NET Core application type for your project you will have such crash (or similar) if installing .NET EF Version:

For .NET Core applications, you should install Core version. https://www.nuget.org/packages/Microsoft.EntityFrameworkCore/
Make sure you don't have this (or similar) error in your references:


text:
Q: How to prevent xlrd adding precison to float values My issue is little bit strange. I have an excel file in which some float values are mentioned e.g. 0.0079 but when I try to read it using my code it's giving me 0.007899999999999999.
 I'm not sure what's actually happening here(may be that's the original data which was entered in the excel sheet when it was originally created). I checked other questions on SO which are similar but they are all concerned about 'how to not loose the precision' and my case is opposite.
sample code:
sheet_hdl = open_workbook('file.xls')
sheet = sheet_hdl.sheet_by_index(0)
for row_idx in range(1, sheet.nrows):
    for col_idx in range(1):
        if(val == str(sheet.cell(row_idx,col_idx + 1).value)):
            accuracy_val = repr(sheet.cell(row_idx,col_idx + 7).value)
            print(accuracy_val)

Note: It's not a duplicate of this. The question in this link involves computation, but my data in excel doesn't involve any computations.


text:
Q: how I can return data as success message when I set data in firebase? I try to return orderId after I set this order in Realtime database using angularfirestore
what I should use after set() to return the orderId after sucess add this order to database
my order object is this:
const orderObj: Order = {
   payMethod: paymethod,
   arrivalHour: arrivalHour,
   tabel: this.tabel,
   itemsCount: Object.keys(this.handleCart.getCartData().items).length,
   state: { cook: false, serve: false, delete: false },
   items: this.handleCart.getCartData().items,
   orderId: new Date().toLocaleDateString(),
   addedOnDate: new Date().toLocaleDateString(),
   addedOnHour: new Date().toLocaleTimeString('en-US'),
   totalPrice: this.handleCart.getCartData().totalAmt,
};

and for set the data in database I use angular fire store as that :
 constructor(private store: AngularFirestore, private router: Router) {

store.collection('Orders').doc(this.data.Id).set(this.data)
  }

A: You can wrap the db operation with a try catch and handle accordingly.
try {
    store.collection('Orders').doc(this.data.Id).set(this.data)
    return {
      docId: this.data.id
    }
} catch (error) {
   return {
      error,
      errorMessage: 'something went wrong'
   }
}


text:
Q: Error: connect ECONNREFUSED in production for only one request caused unhandled rejection I have a site running in production. The backend connects to mongo atlas cloud.
Error: connect ECONNREFUSED 52.202.136.90:27017 caused an unhandled rejection in production. What does this error mean?
I found reports of a similar error, but for those reports the error prevented connection to mongo entirely. On the other hand, my backend was already running in production and had been making connections to my mongo atlas cloud database before I got this error. I have a lot of activity on my site, yet this only happened with one request.
Heroku uses a range of AWS IP addresses. So I have 0.0.0.0/0 (includes your current IP address) in my IP Access list for Network Access to account for their changing IP's.
I'm not sure what's causing this which also means I'm not sure where to look to add some error handling or what this concerns.
Backend logs
Jul 02 15:24:25 myexampleapp app/web.1 2022-07-02T20:24:25.105Z silly: OPTIONS: /api/posts/62c0a45ad56ea20004014196
Jul 02 15:24:25 myexampleapp app/web.1 2022-07-02T20:24:25.197Z silly: PATCH: /api/posts/62c0a45ad56ea20004014196
Jul 02 15:24:25 myexampleapp app/web.1 allowedOrigin https://www.example.com
Jul 02 15:24:25 myexampleapp app/web.1 node:internal/process/promises:279
Jul 02 15:24:25 myexampleapp app/web.1             triggerUncaughtException(err, true /* fromPromise */);
Jul 02 15:24:25 myexampleapp app/web.1             ^
Jul 02 15:24:25 myexampleapp app/web.1 Error: connect ECONNREFUSED 52.202.136.90:27017
Jul 02 15:24:25 myexampleapp app/web.1     at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1187:16) {
Jul 02 15:24:25 myexampleapp app/web.1   name: 'MongoNetworkError'
Jul 02 15:24:25 myexampleapp app/web.1 }
Jul 02 15:24:25 myexampleapp heroku/web.1 State changed from up to crashed
Jul 02 15:24:25 myexampleapp heroku/web.1 State changed from crashed to starting
Jul 02 15:24:25 myexampleapp heroku/router at=error code=H13 desc="Connection closed


text:
Q: NIS and autofs error I am trying to share the home directory of a NIS user using NFS and autofs. During testing, I get the following error message:
Could not chdir to home directory /home/guest/nis1: Permission denied
-bash: /home/guest/nis1/.bash_profile: Permission denied

How can I troubleshoot the above error?

A: Use getent passwd nis1 (where nis1 is the user in your example) to get the passwd entry the NFS client is seeing for 'nis1'. getent respects nsswitch.conf, which supplies ordering for nameservice lookups across multiple services (files, nis, ldap, etc...).
After you determine the UID in that response, compare it to the UID who owns the home directory, /home/guest/nis1 by running: stat /home/guest/nis1.
Your problem may be that the permissions on the home directory are restrictive such that there is no execute bit for other (o+x) and the UID that owns the directory is not actually the UID that the NFS client can resolve for that username.
It would be helpful if you provided the output of these commands, even if this answer is not correct so that we can continue to troubleshoot.


text:
Q: Extracting ADUser from a list of AD groups in different domain I have this code that extracts ADuser information from a list of AD groups, However there are some AD groups which are located on a different domain. The problem is that the code only extracts the ADuser information of the First Domain1 mentioned on the domain list, it does not go to the other domain and extract the information of the AD group that is in a different domain.
$outFile=".\Output.csv"
$report=@()
$ADGroups = Get-Content ".\ADGroups.txt"

$Domains = @("Domain1.com","Domain2.com","Domain3.com","Domain4.com","Domain5.com")

foreach ($ADGroup in $ADGroups)
{

   try{

Foreach ($Domain in $Domains)

           {
$ADGroupMem = Get-ADGroupMember -Identity $ADGroup  -server $Domain

ForEach ($Member in $ADGroupMem){

    $ADUser = $Member | Get-ADUser -Properties SamAccountName,Department,Title,Manager,l,Mobile
    [PSCustomObject]@{
            UserID = $ADUser.SamAccountName
            Group = $ADGroup
            City = $ADUser.l

                      }

     $localAdminsReport = new-object PSObject
     $localAdminsReport | add-member -membertype NoteProperty -name "UserID" -Value $ADUser.SamAccountName
     $localAdminsReport | add-member -membertype NoteProperty -name "Group" -Value  $ADGroup
     $localAdminsReport | add-member -membertype NoteProperty -name "City" -Value  $ADUser.l

    #Write output into .csv file
    #write-host  $report  -ForegroundColor cyan
     write-host   $Domain
    $report +=$localAdminsReport
    $report|Export-Csv -Path $outFile -NoTypeInformation

                                }
            }

         }
      Catch{}
}

When the report is extracted it has only extracted the information from the first Domain1 AD groups and leaves out other AD groups that are located in Domain2, Domain3.....

A: I've reworked your script. As mentioned in above comment you should use the -Append switch of the Export-Csv cmdlet. The other thing is that your catch clause is empty, so you won't recognize any errors. I would also recommend setting the $ErrorPreference to Stop otherwise cmdlets won't throw an error. Here is the reworked code:
    $outFile = ".\Output.csv"
    $report = @()
    $ADGroups = Get-Content ".\ADGroups.txt"

    $Domains = @("Domain1.com", "Domain2.com", "Domain3.com", "Domain4.com", "Domain5.com")
    $ErrorActionPreference = "Stop"
    foreach ($ADGroup in $ADGroups) {
        try {
            Foreach ($Domain in $Domains) {
                $ADGroupMem = Get-ADGroupMember -Identity $ADGroup -server $Domain
                ForEach ($Member in $ADGroupMem) {

                    $ADUser = $Member | Get-ADUser -Properties SamAccountName, Department, Title, Manager, l, Mobile
                    $localAdminsReport = new-object PSObject
                    $localAdminsReport | add-member -membertype NoteProperty -name "UserID" -Value $ADUser.SamAccountName
                    $localAdminsReport | add-member -membertype NoteProperty -name "Group" -Value  $ADGroup
                    $localAdminsReport | add-member -membertype NoteProperty -name "City" -Value  $ADUser.l

                    $report += $localAdminsReport
                    $report | Export-Csv -Path $outFile -NoTypeInformation -Append
                }
            }
        }
        Catch {
            Write-Error "Exception occurred $_"
        }
    }
    $ErrorActionPreference = "SilentlyContinue"
    $report | ForEach-Object { Write-Host $_}

At the of the code the content $report is dumped for debugging purposes. Check if the $report has a difference to the exported CSV file.
You can also debug your code via Visual Studio Code, via command line degguer, or via the Powershell ISE.
Hope that helps.

A: This worked for me. Thank you Moerwald
    $outFile = ".\Output.csv"
    $report = @()
    $ADGroups = Get-Content ".\ADGroupslist.txt"

    foreach ($ADGroup in $ADGroups) {

    $Domains = @("Domain1","Domain2","Domain3","Domain4","Domain5")

    foreach ($Domain in $Domains)
    {

        try
        {
            $ADGroupMem = Get-ADGroupMember -Identity $ADGroup -server $Domain
            ForEach ($Member in $ADGroupMem) {

                    $ADUser = $Member | Get-ADUser -Properties SamAccountName, l
                    [PSCustomObject]@{
                        UserID = $ADUser.SamAccountName
                        Group = $ADGroup
                        City = $ADUser.l

                                      }
                    $localAdminsReport = new-object PSObject
                    $localAdminsReport | add-member -membertype NoteProperty -name "UserID" -Value $ADUser.SamAccountName
                    $localAdminsReport | add-member -membertype NoteProperty -name "Group" -Value  $ADGroup
                    $localAdminsReport | add-member -membertype NoteProperty -name "City" -Value  $ADUser.l

                    $report += $localAdminsReport
                    $report | Export-Csv -Path $outFile -NoTypeInformation -Append
                    write-host   "$ADGroup : $Domain"   -ForegroundColor cyan

                    }
        }
        catch
        {
             Write-Error "Exception occurred $_"

        }

    }

}
$ErrorActionPreference = "Continue"
$report | ForEach-Object { Write-Host $_}


text:
Q: Concurrency issues in Android SQLite I am having issues when I am running an AsyncTask that performs a long delete action on the local SQLite database. If the user rotates the screen, then the Activity is recreated and a new connection to the database is created, while the AsyncTask is running.
I know that SQLite supports multiple reading and one writing at a time, and this will be the case, so I do not understand why it crashes when opening the database as readable while deleting is done...
The failure is the next:
04-26 12:54:21.839: I/Database(3925): sqlite returned: error code = 5, msg = database is locked
04-26 12:54:21.839: E/Database(3925): SELECT locale FROM android_metadata failed
04-26 12:54:21.839: E/Database(3925): Failed to setLocale() when constructing, closing the database
04-26 12:54:21.839: E/Database(3925): android.database.sqlite.SQLiteException: database is locked
04-26 12:54:21.839: E/Database(3925):   at android.database.sqlite.SQLiteDatabase.native_setLocale(Native Method)
04-26 12:54:21.839: E/Database(3925):   at android.database.sqlite.SQLiteDatabase.setLocale(SQLiteDatabase.java:1967)
04-26 12:54:21.839: E/Database(3925):   at android.database.sqlite.SQLiteDatabase.<init>(SQLiteDatabase.java:1835)
04-26 12:54:21.839: E/Database(3925):   at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:820)
04-26 12:54:21.839: E/Database(3925):   at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:197)
04-26 12:54:21.839: E/Database(3925):   at com.caumons.trainingdininghall.persistence.DatabaseManager.openReadableDatabaseWithForeignKeySupport(DatabaseManager.java:172)
04-26 12:54:21.839: E/Database(3925):   at com.caumons.trainingdininghall.persistence.DatabaseManager.openReadableDatabaseWithForeignKeySupport(DatabaseManager.java:180)
04-26 12:54:21.839: E/Database(3925):   at com.caumons.trainingdininghall.persistence.DatabaseManager.openReadableDatabaseWithForeignKeySupport(DatabaseManager.java:180)
04-26 12:54:21.839: E/Database(3925):   at com.caumons.trainingdininghall.persistence.DatabaseManager.openReadableDatabaseWithForeignKeySupport(DatabaseManager.java:180)
04-26 12:54:21.839: E/Database(3925):   at com.caumons.trainingdininghall.persistence.DatabaseManager.openReadableDatabaseWithForeignKeySupport(DatabaseManager.java:180)
04-26 12:54:21.839: E/Database(3925):   at com.caumons.trainingdininghall.persistence.DatabaseManager.openReadableDatabaseWithForeignKeySupport(DatabaseManager.java:180)
04-26 12:54:21.839: E/Database(3925):   at com.caumons.trainingdininghall.persistence.DatabaseManager.openReadableDatabaseWithForeignKeySupport(DatabaseManager.java:180)
04-26 12:54:21.839: E/Database(3925):   at com.caumons.trainingdininghall.persistence.DatabaseManager.openReadableDatabaseWithForeignKeySupport(DatabaseManager.java:180)
04-26 12:54:21.839: E/Database(3925):   at com.caumons.trainingdininghall.persistence.DatabaseManager.openReadableDatabaseWithForeignKeySupport(DatabaseManager.java:180)
04-26 12:54:21.839: E/Database(3925):   at com.caumons.trainingdininghall.persistence.DatabaseManager.openReadableDatabaseWithForeignKeySupport(DatabaseManager.java:180)
04-26 12:54:21.839: E/Database(3925):   at com.caumons.trainingdininghall.persistence.DatabaseManager.open(DatabaseManager.java:157)
04-26 12:54:21.839: E/Database(3925):   at com.caumons.trainingdininghall.persistence.DatabaseManager.<init>(DatabaseManager.java:147)
04-26 12:54:21.839: E/Database(3925):   at com.caumons.trainingdininghall.openerp.models.ConnectionProfile$ConnectionProfileManager.<init>(ConnectionProfile.java:138)
04-26 12:54:21.839: E/Database(3925):   at com.caumons.trainingdininghall.activities.SelectConnectionProfile.fillData(SelectConnectionProfile.java:71)
04-26 12:54:21.839: E/Database(3925):   at com.caumons.trainingdininghall.activities.SelectConnectionProfile.onResume(SelectConnectionProfile.java:66)
04-26 12:54:21.839: E/Database(3925):   at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1149)
04-26 12:54:21.839: E/Database(3925):   at android.app.Activity.performResume(Activity.java:3833)
04-26 12:54:21.839: E/Database(3925):   at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2085)
04-26 12:54:21.839: E/Database(3925):   at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2110)
04-26 12:54:21.839: E/Database(3925):   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1643)
04-26 12:54:21.839: E/Database(3925):   at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:2796)
04-26 12:54:21.839: E/Database(3925):   at android.app.ActivityThread.access$1600(ActivityThread.java:117)
04-26 12:54:21.839: E/Database(3925):   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:932)
04-26 12:54:21.839: E/Database(3925):   at android.os.Handler.dispatchMessage(Handler.java:99)
04-26 12:54:21.839: E/Database(3925):   at android.os.Looper.loop(Looper.java:123)
04-26 12:54:21.839: E/Database(3925):   at android.app.ActivityThread.main(ActivityThread.java:3647)
04-26 12:54:21.839: E/Database(3925):   at java.lang.reflect.Method.invokeNative(Native Method)
04-26 12:54:21.839: E/Database(3925):   at java.lang.reflect.Method.invoke(Method.java:507)
04-26 12:54:21.839: E/Database(3925):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
04-26 12:54:21.839: E/Database(3925):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
04-26 12:54:21.839: E/Database(3925):   at dalvik.system.NativeStart.main(Native Method)

I coded the following workaround, but I think this is not very polite:
private void openReadableDatabaseWithForeignKeySupport() {
    try {
        mDatabase = mDatabaseHelper.getReadableDatabase();
        mDatabase.execSQL("PRAGMA foreign_keys = ON");
    } catch (SQLiteException e) {
        /*
         * If there is an exception because the database is locked,
         * we will retry until it is free and can be opened.
         * */
        Log.d(getClass().getName(), e.toString());
        openReadableDatabaseWithForeignKeySupport(); // Recursive call
    }
}

The most curious is that what seems to fail is the setLocale() method called automatically by Android, but the docs says that:

setLocale() Sets the locale for this database. Does nothing if this database has the NO_LOCALIZED_COLLATORS flag set or was opened read only.

Any help will be much appreciated! :)

A: It's not a great idea to be opening and closing the database regularly like this. Open it once on application startup, and reuse this connection throughout your app's lifetime. You don't even need to bother closing it. SQLite manages the concurrency by itself, so you don't need to worry about multiple threads either.
This will make all your "database is locked" errors go away, as well as make your code tidier and simpler.


text:
Q: Python, transpose nested values adding None for Missing One of those days, Can't get me head around this tiny solution.
I am looking for generic solution as the length of the key value pairs in parent and child leg could vary.
so data source looks like following
data = {
    "New York": [
    { "Name": "John", "QTY": 56 },
    { "Name": "Richard", "QTY": 76 }   ],
    "Texas": [
    { "Name": "John", "QTY": 34 },
    { "Name": "Stephanie", "QTY": 23 }   ],
    "Florida": [
    { "Name": "Rebecca", "QTY": 28 },
    { "Name": "Richard", "QTY": 43 }   ],
    "Arizona": [
    {"Name": "Charles", "QTY": 23},
    {"Name": "Anne", "QTY": 31},
    {"Name": "William", "QTY": 44}   ],
    "New Mexico": [
    {"Name": "Rebecca", "QTY": 56},
    {"Name": "Charles", "QTY": 76},
    {"Name": "Stephen", "QTY": 21},
    {"Name": "William", "QTY": 63}   ],
    "New Jersey": [
    {"Name": "John", "QTY": 56},
    {"Name": "Richard", "QTY": 76},
    {"Name": "Stephen", "QTY": 45}   ] }

Now I want to re-arrange the the dictionary by Name and add values for each state and add None for missing. here is my code
output = {}

for x, y in data.items():
    for i in y:
        key = i['Name']
        try:
            output[key].update({x: i['QTY']})
        except:
            output[key] = {x: i['QTY']}

print(output)

This gives me result as following
{
  "John": {
    "New York": 56,
    "Texas": 34,
    "New Jersey": 56
  },
  "Richard": {
    "New York": 76,
    "Florida": 43,
    "New Jersey": 76
  },
  "Stephanie": {
    "Texas": 23
  },
  "Rebecca": {
    "Florida": 28,
    "New Mexico": 56
  },
  "Charles": {
    "Arizona": 23,
    "New Mexico": 76
  },
  "Anne": {
    "Arizona": 31
  },
  "William": {
    "Arizona": 44,
    "New Mexico": 63
  },
  "Stephen": {
    "New Mexico": 21,
    "New Jersey": 45
  }
}

What I will like to have is something like following, order is indeed important
{
  "John": {
    "New York": 56,
    "Texas": 34,
    "Florida": None,
    "Arizona": None,
    "New Mexico": None,
    "New Jersey": 56
  },
  .......
  .......
  "Stephen": {
    "New York": None,
    "Texas": None,
    "Florida": None,
    "Arizona": None,
    "New Mexico": 21,
    "New Jersey": 45
  }
}

I was wondering if defautldict from collections can be used. But I am not that savvy with it. Folks, remember I need generic solution as the number of states and number os Names can vary.. Any help is much appreciated.

A: In your code, instead of:
try:
    output[key].update({x: i['QTY']})
except:
    output[key] = {x: i['QTY']}

do
try:
    output[key].update({x: i['QTY']})
except KeyError:
    output[key] = defaultdict(none_generator, {x: i['QTY']})

Here, none_generator is a function that takes no arguments and returns `None:
def none_generator(): pass

Note: You shouldn't be using a bare except: clause anyway. You know your output[key].update(...) line will produce a KeyError if all is working as expected, so only catch a KeyError (See What is wrong with using a bare 'except'? for more details)

Now, each value of your output dictionary is itself a defaultdict, and getting a non-existent key of these defaultdicts will return `None:
output = {'John': defaultdict(<function none_generator at 0x12256d6c20>, {'New York': 56, 'Texas': 34, 'New Jersey': 56}), 'Richard': defaultdict(<function none_generator at 0x12256d6c20>, {'New York': 76, 'Florida': 43, 'New Jersey': 76}), 'Stephanie': defaultdict(<function none_generator at 0x12256d6c20>, {'Texas': 23}), 'Rebecca': defaultdict(<function none_generator at 0x12256d6c20>, {'Florida': 28, 'New Mexico': 56}), 'Charles': defaultdict(<function none_generator at 0x12256d6c20>, {'Arizona': 23, 'New Mexico': 76}), 'Anne': defaultdict(<function none_generator at 0x12256d6c20>, {'Arizona': 31}), 'William': defaultdict(<function none_generator at 0x12256d6c20>, {'Arizona': 44, 'New Mexico': 63}), 'Stephen': defaultdict(<function none_generator at 0x12256d6c20>, {'New Mexico': 21, 'New Jersey': 45})}

print(output["John"]["Florida"]) prints None

If you want there to be None values explicitly at the keys in the dictionary that do not exist, you're going to have to populate the output dictionary first. Then, remake all dictionaries with their missing values set to None:
output = {}
for x, y in data.items():
    for i in y:
        key = i['Name']
        all_states.add(x)
        try:
            output[key].update({x: i['QTY']})
        except KeyError:
            output[key] = {x: i['QTY']}

for person, person_vals in output.items():
    output[person] = {state: person_vals.get(state, None) for state in data}

{'John': {'New York': 56,
  'Texas': 34,
  'Florida': None,
  'Arizona': None,
  'New Mexico': None,
  'New Jersey': 56},
 'Richard': {'New York': 76,
  'Texas': None,
  'Florida': 43,
  'Arizona': None,
  'New Mexico': None,
  'New Jersey': 76},
 'Stephanie': {'New York': None,
  'Texas': 23,
  'Florida': None,
  'Arizona': None,
  'New Mexico': None,
  'New Jersey': None},
 'Rebecca': {'New York': None,
  'Texas': None,
  'Florida': 28,
  'Arizona': None,
  'New Mexico': 56,
  'New Jersey': None},
 'Charles': {'New York': None,
  'Texas': None,
  'Florida': None,
  'Arizona': 23,
  'New Mexico': 76,
  'New Jersey': None},
 'Anne': {'New York': None,
  'Texas': None,
  'Florida': None,
  'Arizona': 31,
  'New Mexico': None,
  'New Jersey': None},
 'William': {'New York': None,
  'Texas': None,
  'Florida': None,
  'Arizona': 44,
  'New Mexico': 63,
  'New Jersey': None},
 'Stephen': {'New York': None,
  'Texas': None,
  'Florida': None,
  'Arizona': None,
  'New Mexico': 21,
  'New Jersey': 45}}

A: Here's a straightforward way to do what your question asks:
nameList = []
nameSet = set()
for state, nameQtyList in data.items():
    for nameQty in nameQtyList:
        name = nameQty["Name"]
        if name not in nameSet:
            nameSet.add(name)
            nameList.append(name)
out = {name:{state:None for state in data} for name in nameList}
for state, nameQtyList in data.items():
    for nameQty in nameQtyList:
        out[nameQty["Name"]][state] = nameQty["QTY"]

Explanation:

*

*walk through the input, compiling names in the sequence of first occurrence in names

*initialize the result out to have the desired structure, with an initial value of None for each QTY

*walk through the input again, updating out with each QTY encountered in the input.


text:
Q: Possible to enumerate a collection to an array in just one line? In Ruby, can this be reduced to just one line?
results = []
Object.all.each { |o| results <<  o if o == 1 }
results

I am thinking it is with enum_for, but can't figure it out.

A: Take a look at the wealth of methods in Enumerable:
Object.all.select { |o| o == 1 }

A: Maybe this?
Object.all.select{|o| o == 1}


text:
Q: How to customize the color and fonts for microsoft Adaptivecards Input.choiceset I'm using v1.2 of the AdaptiveCard SDK in BotFramework Webchat. I need to customize the color of the values of the Input.Choiceset of the Microsoft adaptive cards.
I need to use it in the AdaptivecardhostConfig.
Input choice list which is being used in my code


text:
Q: How to convince team members not to use singletons? I'm a member of team which has grown considerably during the last two years. Three members of "the old team" have been working for more than two years on a library, which now the rest of the team has to use. They have invested a lot of ego into that library. Unfortunately it turned out to be littered with singletons.
The singletons are making it impossible for us to write testable code. TDD is important for some of the team members, but only tolerated by the three library creators. So far we have tried the following to convince them to get rid of the singletons:

*

*Pointed out problems with singletons (global state, tight coupling, difficult to test)

*

*Objections were rejected, because current code works.

*Demonstrated that our tests (which use the library/singletons) fail from time to time

*

*Rejected, because we obviously "do not know how to work with singletons"

*Provided alternative implementation

*

*Rejected, because their current code already works

*Talked together with superior about problems

*

*Superior is not a software developer and has to choose between two "valid" views onto the problem. Trusts older team members more.

We have to use that library, because it has already replaced a central part of our program. Do you see any other way to tackle the situation?

A: (You haven't stated your language or platform, so I'll use C# as an example. I'd expect the same principles to apply for others though.)
Do you get to create your own interfaces and implementations of those interfaces which delegate appropriately? Even if the library designers are unwilling to implement an interface, you can always delegate:
// Existing code
public class FooSingleton
{
    public static FooSingleton Instance { get { ... } }

    public void Bar()
    {
        ...
    }
}

public interface IFoo
{
    void Bar();
}

public class SingletonDelegatingFoo : IFoo
{
    public void Bar()
    {
        FooSingleton.Instance.Bar();
    }
}

Then you use normal dependency injection (or whatever) to make your own code testable, only relying on IFoo - and you inject a SingletonDelegatingFoo when running the full system.
(As an aside, are these singletons even implemented correctly? You may get more buy-in if you can show that the singleton pattern is not only sucky from a testing point of view, but can also be implemented badly...)

A: The usual approach of an experienced developer is to update their CV/resume and start looking around for another job before it is realized that the system cannot be made reliable enough for delivery, is delivered anyway and becomes a never-ending crock of not-gold that someone has to continually maintain.  The 'someone' should be one of the older developers with 40 years of pension-entitlement to protect - 'an offer he/she can't refuse'.
Maybe I'm being over-cynical because my latest project has itself turned into a crock of not-gold overnight after an innocuous change, or maybe I remember what happened decades ago when I stood up in a review meeting and stated 'This job cannot possibly work as it's designed', (ever since that experience, I've just got out early, or done it as a contract job).

A: Your problems with the code base of the library will not be solved with technical arguments or technical approaches. To solve your issues with the singletons a pure technical solution will work for now. But if you want to convince the "old" team to not use singletons and to work together with the rest of the team, to take your concerns seriously you'll definitely need more than tech.
Try to see the whole situation from their point of view. They were working hard for two years to implement that library the knowledge base they had and hopefully liked that work. And now your "new" team is coming and telling them that the implementation, they invested two years of their live, is technical bullshit. How would you react in that situation? Say, uh thanks, these singletons are really the worst pattern we used? No, not really...
I'd recommend you to read Driving Technical Change and try to find a strategy how to convince them. In the meanwhile my best advice is: Honor their work, try to see the situation from their perspective, try to convince one by one - not the team and build a wrapper around that "legacy" code.

A: In my view, you have to treat that library as an external dependency of your code (like a 3rd party library) and code accordingly.
That means, as Jon Skeet mentioned, design your code to be isolated and testable without the external library. Design a couple of interfaces (pure virtual classes) that capture the required contracts that you expect them to fulfill, and also write a couple of integration tests that exercise the communication between your code and that library. Ideally, the communication surface should be kept as small as possible, maybe only relegated to a couple of adapters or bridges that implement your interfaces.
Then it becomes a problem of "contract" negotiation, where you'd point out parts of the library that don't work as expected and (hopefully) wait for a fix or adapt your code accordingly. You might surface bugs and semantic mismatches this way, which might prompt parallel evolution of your code and the library.
If your code is the only consumer of that library, you should get to dictate what is expected of it, and it should adapt to your needs, not the other way around. If they then provide the service you expect, the fact that they use singletons or whatnot becomes irrelevant.


text:
Q: How to authenticate users using restangular? I'm trying to create web application using MEAN in which i'm trying to authenticate users with the passwords they have created during signup. Below is how my signin.html looks like

  UserName

  <input type="text" ng-model="movie.username" placeholder="Username">

Password

  <input type="password" ng-model="movie.password" placeholder="Password">

  <input type="button" value="Login" ng-click="signFunction()">

I'm using restangular to connect my angularjs and node api
Below is my angularjs controller
angular.module('clientApp')
  .controller('MovieEditCtrl', function (
    $scope,
    $routeParams,
    Movie,
    $location
  ) {
    $scope.movie = {};
    Movie.one($routeParams.id).get().then(function(movie) {
      $scope.movie = movie;
      $scope.signFunction = function() {
        if($scope.movie.username.then(function() {
          $location.path('/movie/' + $routeParams.id);
        });
      };
    });
  });

But i know the above logic is wrong , can someone explain me how to check if the user exists in the database or not and then check if the password matches with the one in database.

A: Your logic is unclear. What you actually need to do is send a userAuthorization object to your backend, which contains a username and password. You then check whether the username/password sent match what's in the db. If they do match, you send back whatever you wanted from the call to the front end, if they don't match, you send back an unauthorized error and handle it in the error part of the promise on the front end.
So, send three things to the backend - movie (your endpoint), movieId (your standard id for a REST get call), userAuthorization object (object holding username and password).
Overall, this is a poor way to do security in general, but I won't get into that since I understand that you are trying to handle it in a basic manner.


text:
Q: Python3 PyQt5. How can I run the PyQt window method from the main process? How can I run the PyQt window method MainWindow.load_url() from the main process?
from multiprocessing import Process
import sys
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QMainWindow
from PyQt5.QtCore import *
from PyQt5.QtWebKitWidgets import *

class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)

        self.desktop_size = QtWidgets.QDesktopWidget().screenGeometry()
        self.__browser = QWebView(self)
        # todo
        self.init_ui()

    def init_ui(self):
        self.__browser.resize(self.desktop_size.width(), self.desktop_size.height())
        self.load_url('https://stackoverflow.com/')

        self.showFullScreen()

    def load_url(self, url: str):
        self.__browser.load(QUrl(url))

def run_qt():
    app = QtWidgets.QApplication(sys.argv)
    x = MainWindow()
    sys.exit(app.exec_())

class QtGui:
    process = None

    @staticmethod
    def read_process():
        if QtGui.process is None:
            QtGui.process = Process(target=run_qt)
        return QtGui.process

    @staticmethod
    def stop_process():
        if QtGui.process is not None:
            if QtGui.process.is_alive():
                QtGui.process.terminate()
                QtGui.process = None

    @staticmethod
    def start_process():
        if QtGui.read_process().is_alive() is False:
            QtGui.read_process().start()

if __name__ == '__main__':
    qtGui = QtGui()
    qtGui.start_process()

    """
        how to run method MainWindow.load_url() from here
    """

I tried to create an instance of QWebKit in the main process and pass it as an argument to have access to it in two processes, but PyQt does not accept it, which I understand. Unfortunately I don't know how I can do it.
Thanks


text:
Q: Why does '\x01\x1A' (Start-of-Header and Substitute control characters) in a textfile line stop a for-loop prematurely? I'm using Python 2.7.15, Windows 7
Context
I wrote a script to read and tokenize each line of a FileZilla log file (specifications here) for the IP address of the host that initiated the connection to the FileZilla server. I'm having trouble parsing the log text field that follows the > character. The script I wrote uses the:
    with open('fz.log','r') as rh:
       for lineno, line in rh:
          pass

construct to read each line. That for-loop stopped prematurely when it encountered a log text field that contained the SOH and SUB characters. I can't show you the log file since it contains sensitive information but the crux of the problem can be reproduced by reading a textfile that contains those characters on a line.
My goal is to extract the IP addresses (which I can do using re.search()) but before that happens, I have to remove those control characters. I do this by creating a copy of the log file where the lines containing those control characters are removed. There's probably a better way, but I'm more curious why the for-loop just stops after encountering the control characters.
Reproducing the Issue
I reproduced the problem with this code:
if __name__ == '__main__':
    fn = 'writetest.txt'
    fn2 = 'writetest_NoControlChars.txt'

    # Create the problematic textfile
    with open(fn, 'w') as wh:
        wh.write("This line comes first!\n");
        wh.write("Blah\x01\x1A\n"); # Write Start-of-Header and Subsitute unicode character to line
        wh.write("This comes after!")

    # Try to read the file above, removing the SOH/SUB characters if encountered
    with open(fn, 'r') as rh:
        with open(fn2, 'w') as wh:
            for lineno, line in enumerate(rh):
                sline = line.translate(None,'\x01\x1A')
                wh.write(sline)
                print "Line #{}: {}".format(lineno, sline)
    print "Program executed."

Output
The code above creates 2 output files and produces the following in a console window:
Line #0: This line comes first!

Line #1: Blah
Program executed.

I step-debugged through the code in Eclipse and immediately after executing the
for lineno, line in enumerate(rh):

statement, rh, the handle for that opened file was closed. I had expected it to move onto the third line, printing out This comes after! to console and writing it out to writetest_NoControlChars.txt but neither events happened. Instead, execution jumped to print "Program executed".
Picture of Local Variable values in Debug Console

A: You have to open this file in binary mode if you know it contains non-text data: open(fn, 'rb')


text:
Q: Shallow Copy and Move in rust Is is possible for rust to have shallow copies, because it would appear that a move replaces a shallow copy?

A: You have to differentiate based on the underlying type.
You can't do a shallow copy of struct Foo(String); because two instances of Foo would point at the very same String, which would violate the strict aliasing rule .
However, if you are having a reference counter, e.g. struct Foo(Rc<String>); it is possible, because Rc will prevent you from doing unsafe things, e.g. having a mutable reference, when there are others references on the String.
It is also possible for types that implement [Clone] to make a "shallow" copy, because Copy implies, that the type can be copied by using memcpy (e.g. a u32 or a &T).
What is the difference between Copy and Clone? is also very worth reading.

So, in general no: Exceptions are reference counted structs (Rc or Arc) , Cloneables, or references (&T), because they don't violate the strict aliasing rule.


text:
Q: How to set up GitLab CI to run multiple build steps efficiently while indicating at which step it is? I am pretty new to GitLab. I've set up pipelines and stages via .gitlab-ci.yml and they seem to work but I've just discovered that some of my assumptions were wrong.
I have a large, multi-project Gradle setup, producing many artifacts. We are in the process of setting up GitLab and I really wanted to make use of the GitLab UI to show the progress of the build. The idea was to nicely indicate to developers and reviewers how far the build got before it failed, something like:

*

*Got its dependencies

*Compiled main code, YAY!

*Compiled test code, yippie!

*Passed unit tests, we rock!

*Passed integration tests, awesome!

*Passed various static code analysis tests. We're almost good to go!

*Generated documentation - can we ship it?

I've set up each of these as individual jobs of their individual stages, (incorrectly) assuming that Gradle will be able to do its incremental build magic and that this will be almost as quick as running it as a single step.
Then I noticed that each stage causes what seems to be a Docker container reinitialization. This also means that the Gradle daemon has to restart and has no knowledge of the past. It has to get all the dependencies. I think I could cache these, but it seems that they would be separately cached for each job. Finally, these some jobs end up repeating what jobs before them already did because their output isn't available to them. My thinking that serialized jobs would execute inside the same container instance was proven wrong. Each of the subsequent jobs generally have to repeat what jobs before them already did, significantly increasing the build time.
I think I understand that I could declare artifacts of each job and make them available to dependent jobs that way, but that does not eliminate all of the overhead and adds some of its own - copying the artifacts out to "somewhere" and then back, while also hitting the limits of how much I can pass on. In fact, my unit test job is now failing and I can't see why because of the log size limit, but it seems it has to do only with artifacts (the report) as the unit test pass nicely when I run them outside GitLab.
I also think I understand that the idea behind jobs was to be able to run them in parallel on separate runners. That is a very fine feature and I probably can use them for later stages, but not for (1)-(5) as they heavily rely on a lot of output of at least some of the previous jobs.
I could merge (1)-(5) into a single job (and a single stage) for performance reasons, but then there is no indication in the UI (that I know of) as to how far the build got ... and the logs would be even longer and nastier to figure out even if the log limit got lifted.
Do any of you have any suggestions as to what am I missing / should do here?

A: After further research, I found that this is not possible (yet). Jobs are meant to be units of (potentially) concurrent execution and can only communicate by copying artifacts, obviously.
What I would be interested in is steps lesser than jobs that would be indicated in the UI and that could post their artifacts when they (steps) complete but before the entire job is done. This would eliminate 1-2 minutes of job startup overhead that I am facing now.


text:
Q: Java missing hk2.jar I have project using spring boot with maven, when i run it it works perfectly fine, but when i try to use debuger it stops in URLClassPath with FileNotFoundException, the path to file that was not found is "user/.m2/repository/org/glassfish/ha/ha-api/3.1.12/class-model.jar".
Am i missing some dependency? I tried to add glassfish dependency to my pom file, but this does not fix my issue, and not being able to use Debug mode is quite difficult sometimes.
My pom file:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId></groupId>
    <artifactId></artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name></name>
    <description></description>

    <properties>
        <java.version>11</java.version>
        <log4j2.version>2.17.0</log4j2.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.1</version>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.14</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>2.0.12</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.6</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.sendgrid/sendgrid-java -->
        <dependency>
            <groupId>com.sendgrid</groupId>
            <artifactId>sendgrid-java</artifactId>
            <version>4.6.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.ws</groupId>
            <artifactId>spring-ws-core</artifactId>
            <version>3.0.4.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.sun.xml.ws</groupId>
            <artifactId>jaxws-rt</artifactId>
            <version>2.3.3</version>
            <type>pom</type>
        </dependency>
        <dependency>
            <groupId>com.sun.xml.ws</groupId>
            <artifactId>rt</artifactId>
            <version>2.3.3</version>
        </dependency>
        <dependency>
            <groupId>com.opencsv</groupId>
            <artifactId>opencsv</artifactId>
            <version>5.6</version>
        </dependency>
        <dependency>
            <groupId>io.github.jonathanlink</groupId>
            <artifactId>PDFLayoutTextStripper</artifactId>
            <version>2.2.3</version>
        </dependency>
        <dependency>
            <groupId>org.locationtech.proj4j</groupId>
            <artifactId>proj4j</artifactId>
            <version>1.1.5</version>
        </dependency>
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>2.0.1.Final</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.6</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.hk2</groupId>
            <artifactId>hk2-core</artifactId>
            <version>3.0.3</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.jvnet.jaxb2.maven2</groupId>
                <artifactId>maven-jaxb2-plugin</artifactId>
                <version>0.13.3</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>generate</goal>
                        </goals>
                    </execution>
                </executions>

                <configuration>
                    <schemaLanguage>WSDL</schemaLanguage>
                    <generatePackage>big.wsdl</generatePackage>
                    <schemas>
                        <schema>
                            <url>https://wasstt.infomonitor.pl/bigApi/v1/LiabilitiesManagementService/WEB-INF/wsdl/wsBigApi1v1.wsdl</url>
                        </schema>
                    </schemas>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.22.1</version>
                <configuration>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <version>0.8.3</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>prepare-agent</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>default-report</id>
                        <phase>test</phase>
                        <goals>
                            <goal>report</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>


text:
Q: How to optimize static elements`s performance in three.js? In my scene. I painted a large map by plane and line. This map is static.
And then I need mount many moving cars in my scene.
But the performance is readly bad because the map.
So do we have a solution to optimize static elements in threejs?
I have tried set matrixautoupdate to false, but it still has bad performance.


text:
Q: Saving Photos (CameraCaptureTask) to Isolated Storage - OutOfMemoryException I would like to save a photo, taken within my App(using CameraCaptureTask), to the isolated storage. The current Problem is the consumption of RAM, which always leads to an OutOfMemoryException. This also happens when I am loading the picture into an Image-Control.
My App should finally be able to take 10 pictures, save them to isolated storage, show them in an Image Control and if necessary delete the picture for good.
Lowering the resolution of the pictures logically fixed the exception, but that's not the way I wanted to go.
Maybe you can give me a hint.
Here is my code:
private CameraCaptureTask ccTask = new CameraCaptureTask();
WriteableBitmap[] imgList = new WriteableBitmap[10];
Random rnd = new Random();

private void addPicture_button_Click(object sender, EventArgs e)
{
    ccTask.Show();
    ccTask.Completed += ccTask_Completed;
}

void ccTask_Completed(object sender, PhotoResult e)
    {
        if (e.TaskResult == TaskResult.OK)
        {
            WriteableBitmap writeableBitmap = new WriteableBitmap(1600,1200);
            writeableBitmap.LoadJpeg(e.ChosenPhoto);

            string imageFolder = "Unfaelle";
            string datetime = DateTime.Now.ToString().Replace("/","");
            datetime = datetime.Replace(":","");
            string imageFileName = "Foto_"+datetime+".jpg";
            using (var isoFile = IsolatedStorageFile.GetUserStoreForApplication())
            {

                if (!isoFile.DirectoryExists(imageFolder))
                {
                    isoFile.CreateDirectory(imageFolder);
                }

                string filePath = System.IO.Path.Combine(imageFolder, imageFileName);
                using (var stream = isoFile.CreateFile(filePath))
                {
                    writeableBitmap.SaveJpeg(stream, writeableBitmap.PixelWidth, writeableBitmap.PixelHeight, 0, 100);
                }
            }

            //now read the image back from storage to show it worked...
            BitmapImage imageFromStorage = new BitmapImage();

            using (var isoFile = IsolatedStorageFile.GetUserStoreForApplication())
            {
                string filePath = System.IO.Path.Combine(imageFolder, imageFileName);
                using (var imageStream = isoFile.OpenFile(
                    filePath, FileMode.Open, FileAccess.Read))
                {
                    imageFromStorage.SetSource(imageStream);
                }
            }

            Rectangle b = new Rectangle()
            {
                Width = 100,
                Height = 100,
            };

            Thickness margin = b.Margin;
            margin.Left = 10;
            margin.Top = 10;
            b.Margin = margin;

            ImageBrush imgBrush = new ImageBrush();
            imgBrush.ImageSource = imageFromStorage;
            b.Fill = imgBrush;
            b.Tag = System.IO.Path.Combine(imageFolder, imageFileName);
            b.Tap += OnTapped;

            pictures_wrapPanel.Children.Add(b);
        }
    }

private void OnTapped(object sender, System.Windows.Input.GestureEventArgs e)
        {

            Rectangle r = sender as Rectangle;
            BitmapImage imageFromStorage = new BitmapImage();

            using (var isoFile = IsolatedStorageFile.GetUserStoreForApplication())
            {
                string filePath = r.Tag.ToString();
                using (var imageStream = isoFile.OpenFile(
                    filePath, FileMode.Open, FileAccess.Read))
                {
                    imageFromStorage.SetSource(imageStream);
                }
            }
            img.Source = imageFromStorage;
        }

Thanks a lot, if there is anything unclear, feel free to ask. Maybe there is a much easier way to save a photo, I am just beginning with app development
Greetings Daniel
Btw: 1600x1200 are 2MP, I lowered the resolution to avoid the exception, unfortunately it was just delayed

A: 10 pictures with a resolution of 1600 * 1200 use about 80MB of ram. The memory limit is 90 MB on Windows Phone 7 and 150 MB on Windows Phone 8, there's no way what you're trying to do could work.

My App should finally be able to take 10 pictures, save them to isolated storage, show them in an Image Control and if necessary delete the picture for good.

This approach is correct, however you are loading the full-sized picture to display in the thumbnails, which is a total waste of RAM. When you're saving the picture to the isolated storage, save a copy with a lower resolution and display that copy in the thumbnail. Then, when the user tap on a thumbnail, load the full-res picture from the isolated storage to display it.


text:
Q: Getting error when trying to update Product Prices index in Magento I'm getting the following error after attempting to index Product Prices in Magento: Invalid backend model specified: catalog/product_attribute_backend_startdate_specialprice
Screenshot here: http://grab.by/DRzK
Any advise what the issue is and how to resolve?

A: You have a product with an invalid special pricing startdate, most likely from a bad import, updating using the api without error checking your values, or some query that put the value in the db without any error checking or requiring it to re-index after saving the product.
When I ran into this, I was heavily using the api, so I used the api to create a report of all products and their promotion start and end dates.  I was able to identify the ones in the wrong format, and after correcting those values I could re-index again.  You could also look in the db if you aren't using the api.  For me, finding and correcting the bad values was all it took to get it to run again without error.  Just be sure to build more error checking into however you load this data or it will happen again.

A: This error happens when the backend model is failed to load. The error appears to be with the model Mage_Catalog_Model_Product_Attribute_Backend_Startdate_Specialprice.
Validate that this file exists as I think it should be, at least in my version 1.9 it is there, if it is not there than simply download it and add it to you Magento install. It might also be worth checking if other files are missing.


text:
Q: How do I get the notification icons I want in Unity? I now have Unity 2D running on my laptop, and the jury is still out as to whether or not I keep it or go back to Gnome.
One thing that is throwing me off is that I don't have the same notification icons in the top panel that I like to have.
One is a CPU monitor. My laptop is a little older, so I keep an eye on the CPU usage to know when one process is done and I can start a new one without slowing things down.
The other is UIM. I switch between Japanese and English input, and the UIM indicator applet in Gnome let me know which input mode I was in.
Right now, only my Dropbox icon has carried over (I upgraded from 10.10).
How do I add/remove indicators in my top panel? Right clicking seems to do nothing.

A: There's a new system load indicator. see here: What Application Indicators are available?

A: To enable it open a terminal and type:
       gsettings set com.canonical.Unity.Panel systray-whitelist "['all']"

or use dconf-tools, but you need to isntall it.
After the changes, log out and then back in.


text:
Q: Cant understand an ab amplifier diagram
I been trying to figure out this diagram, and Can't understand what happens from the beginning of the input , how the voltage changes in a way that "shuts off" one transistor. Also cant understand the direction in which it goes in the input signal .
Does the voltage goes off completely on one transistor at a time whle there is a signal ?
How does the signal works in the preamplifier transistor?
What path does the current takes when the signal changes in the input?
(A hobbyist about electricity , learned only the basics)

A: I provide some analysis of a very similar design here on EE.SE regarding this quite similar circuit:

simulate this circuit – Schematic created using CircuitLab
However, if you read through the text there you will see that there are some measurements you need to take and that the circuit actually needs some tweaking to get it functioning correctly. This isn't something you can do for production. But it's often fine for a hobbyist or builder who wants minimal parts and is willing to tinker.
Still, you can compare the circuit you have presented with the one above, discussed in the above link, to see some slight differences and where I've actually talked about how to adjust it, given arbitrary BJTs, to get it centered and working reasonably as intended.
I also provide a better, more designable approach at that link, as well. It has more parts but it is also doesn't ask the end user (hobbyist) to have to tinker with it to make it work, correctly. The schematic shown at the link above is this one:

simulate this circuit
Both of the above circuits are for \$5\:\textrm{V}\$, though. And so they would need to be redesigned for \$9\:\textrm{V}\$. But the concepts are similar and I think if you read the above link it will go a long way towards helping you follow the schematic you presented.
It's important for your understanding of your circuit to take note that your circuit includes a large-value bootstrapping capacitor. If you look near the bottom part of my answer to a different question here, you will see some discussion about how that works. It's purpose is to provide a fixed voltage across your \$R_1\$ resistor so that there is a near-constant current flowing through the diodes and to the VAS (your \$Q_3\$.) There are other ways to provide this (and for example the LM380 power amplifier IC I'll mention in a moment uses such different methods.) But these other ideas take extra parts.
Since I just brought it up, I think it would be instructive to you to read another answer of mine about the LM380 power amplifier. Schematic follows here, too:

simulate this circuit
Here, you will see that they don't use the bootstrapping capacitor trick but instead use a different method of providing a constant current for the two diodes used to separate the bases of power output section. You should be able to notice that they also use an output driver section that uses three BJTs instead of two. However, that's not an important difference, as the basic idea remains quite similar to your circuit (\$Q_{12}\$ is just a helper BJT.) Note that they include the VAS, as well. But that it is driven by a differential amplifier section. This is much better than your case, which... well.... uses NOTHING at all to help out. It's just an exposed VAS, in effect.
A final note worth mentioning, assuming you are willing to take the time to follow those links and what I've said here, is that in the LM380 and in the second schematic I've exposed here, above, there is a negative feedback resistor. In your circuit, this negative feedback resistor is \$R_2\$ and in my first schematic above it is \$R_5\$. In the LM380 and the second schematic above, that's its main purpose. But in your schematic (and my first one above), it also does double-duty in order to bias the VAS. This is part of what complicates such a design.
So, to understand your specific schematic a little better, go to the first link I mentioned at the outset. Read it carefully and it may help somewhat in trying to understand your schematic better.

A: It's better to think in terms of each output transistor conducting current.
D1 and D2 set up a voltage drop of 2 diodes across the two bases of the output transistors, just enough to put them both at the edge of conduction.
When Q3 pulls the bases down, or R1 pulls them up, the voltage on the bases shifts slightly so that one output transistor conducts more strongly, to be an emitter follower for the signal, and the other one conducts less strongly, and supplies no current.
This amplifier would sound quite rough, there's a lot more knowhow goes into to getting the output to bias up stably, over temperature, and to reduce the inevitable distortion (crossover distortion) that happens when the load current shifts from one transistor to the other.


text:
Q: How do I delete a cloned HTML element with JQuery? A couple of days ago I had placed a question regarding the cloning of an HTML element. I got the JQuery function to work, but I'd also like the element(, in this case a textarea) to be deleted if a user requires it. I've tried to legally steal several solutions from the net, but I cannot get this to work. I'm sure I'm doing something horribly wrong. Please have a look at this bit of code to try and help me get to know what exactly is incorrect.
HTML

    #parse("inc/Demo.html")

            <form>

                    Email Form
                    Save Form
                    Change Form
                    new
                    Portal

                            <input autofocus name="title" type="text"
                                id="title" value="Titel" onfocus="
                                    if(this.value==this.defaultValue)this.value='';" onblur="
                                    if(this.value=='')this.value=this.defaultValue;"/>

                            <textarea name="Content[]" type="text" id="Content[]"
                            onfocus="if(this.value==this.defaultValue)this.value='';"
                            onblur="if(this.value=='')this.value=this.defaultValue;">
                            </textarea>

                        <button id="AddTextarea">Add</button><button id="remove">Remove</button>

                        Delete
                        Save
                        Edit

                        Question type

                            <select id="Select">
                                <option value="Text">Text</option>
                                <option value="Date">Date</option>
                                <option value="Scale">Scale</option>
                                <option value="Tekstarea">Textarea</option>
                                <option value="Checkboxes">Checkboxes</option>
                                <option value="multiple_Choice">Multiple-Choice</option>
                                <option value="Choose from a list">Choose from a list</option>
                                onder require>masker dd,mm,jjjj
                            </select>

                        Mask

                            <select id="Select" >
                                <option value="date">{Date}DD-MM-JJJJ</option>
                                <option value="mobile_number">{M-nummer}__-________</option>
                                <option value="house_number">{H-nummer}___-_______</option>
                                <option value="ponskaart nummer">Ponskaart nummer</option>
                                <option value="klanten nummer">Klanten nummer</option>
                            </select>

                        Question title
                        <input type="text" name="Vraag Titel" id="list" value="..." onfocus="
                            if(this.value==this.defaultValue)this.value='';" onblur="
                            if(this.value=='')this.value=this.defaultValue;"/>

                        Help text
                        <input type="text" name="Help_tekst" id="list" value="..." onfocus="
                            if(this.value==this.defaultValue)this.value='';" onblur="
                            if(this.value=='')this.value=this.defaultValue;"/>

                        Required

                            <input id="checkboxes"type="checkbox" name="Required" value="Required"/>

                #parse("Form/Textarea.html")

                        +

                    <button  id="Button_Done" class="buttons_Done green square" type="submit">Done</button>

                <button  id="button_Complete" class="buttons_Complete_Add green square" type="submit">Complete form</button>

            </form>

        #parse("inc/footer.html")

JS
   $(document).ready(function() {
    $('#AddTextarea').click(function() {
        $clone=$('textarea[name="Content[]"]:first').clone();
        console.log($clone);
        $('#form_Content').append($clone);
        return false;
    });

    $("#remove").click(function(e) {
        $(this).closest('textarea[name="Content[]"]:first').remove();
        e.preventDefault();
    });
});

And also a link to the JSFiddle:
JSFiddle

A: The problem lies in the line:
$(this).closest('textarea[name="Content[]"]:first').remove();

replace it with:
$('textarea[name="Content[]"]:last').remove();

This way it will remove the last added textarea.
From jQuery docs: (http://api.jquery.com/closest/)

Given a jQuery object that represents a set of DOM elements, the
  .closest() method searches through these elements and their ancestors
  in the DOM tree and constructs a new jQuery object from the matching
  elements.

In your case, it searches this, and hence is unable to find a textarea in the set or in ancestry of the remove button.
Updated fiddle: http://jsfiddle.net/hcJGk/9/

A: JSFiddle: http://jsfiddle.net/hcJGk/11/
$(document).ready(function() {
    $('#AddTextarea').click(
        function() {
            $clone=$('textarea[name="Content"]:first').clone();
            console.log($clone);
           $('#form_Content').append($clone);
            return false;
    });

    $("#remove").click(function(e) {
        $(this).closest('div').find('textarea[name="Content"]:last').remove();
        e.preventDefault();
    });
});

There are several problems with your example. Don't use a name like "Content[]" and don't expect duplicated ID's to work on all browsers (dump the id on the textArea).
You were also applying closest to the button and expecting to find the textarea, but closest only searches back up the parents of the element.
I changed the example to find the parent DIV then remove the last textarea so that you could have multiples of these on the same page.


text:
Q: SonarQube Test coverage issue when using sonar-maven-plugin with jacoco We have a multi module maven project where the sonar-maven-plugin and jacoco maven-plugin are defined in the parent pom:
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <source>1.7</source>
                <target>1.7</target>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.jacoco</groupId>
            <artifactId>jacoco-maven-plugin</artifactId>
            <version>${jacoco.version}</version>
            <configuration>
                <destFile>${sonar.jacoco.reportPath}</destFile>
                <append>true</append>
                <excludes>
                    <exclude>**/generated/**</exclude>
                </excludes>
            </configuration>
            <executions>
                <execution>
                    <id>agent</id>
                    <goals>
                        <goal>prepare-agent</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>sonar-maven-plugin</artifactId>
            <version>2.5</version>
        </plugin>

Now we have a submodule common, containing again other submodules:

In the submodule common, the maven structure is as follows:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
   <parent>
       <groupId>be.groupname</groupId>
       <artifactId>artifactname</artifactId>
       <version>1.0-SNAPSHOT</version>
   </parent>

   <modelVersion>4.0.0</modelVersion>
   <groupId>be.groupname</groupId>
   <artifactId>common-master</artifactId>
   <name>Common - Master</name>
   <packaging>pom</packaging>
   <modules>
       <module>bindings</module>
       <module>core</module>
       <module>tools</module>
   </modules>
</project>

The submodule core has the following maven structure:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <groupId>be.groupid</groupId>
        <artifactId>common-master</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>common-core</artifactId>
    <name>Common - Core</name>
    <packaging>jar</packaging>
    ...
</project>

Now my question, in my SonarQube report, I see the uncovered lines:

The common master project contains all the uncovered lines from the submodules (common-core,...). I would expect that only the common core module would contain those lines.
In the filesystem, I see a jacoco.exec is generated under the common/target folder.
In the subdirectory common, I don't see this file being created but instead I see a file common/core/target/sonar/jacoco-overall.exec


text:
Q: Can I use lucene for full text search in a file , but without creating indexes. I want to do full text search in my application (where at a time I have around 1000 documents). But almost everytime these documents will be different. I want to use lucene for full text search, however without creating indexes. I do not want to maintain a separate secondary/primary memory for Indexes.
Is this possible ?And if Yes, Then what impact will I have on performance (say I will be having 1000 docs, and maximum doc of around 10-15 MB).
Also, Is there any other replacement for Lucene ?

A: Yes, you can create a memory-resident index using RAMDirectory.  It should perform well in general, as long as your indexes aren't too large.  Note the warning in the docs:

This class is not intended to work with huge indexes. Everything beyond several hundred megabytes will waste resources (GC cycles), because it uses an internal buffer size of 1024 bytes, producing millions of byte[1024] arrays. This class is optimized for small memory-resident indexes. It also has bad concurrency on multithreaded environments.

Also, yes, there are other full-text search tools out there...


text:
Q: Cannot create new Object within Schema Builder, while doing Trailhead Tutorial The Error Message:

The value of the "le" parameter contains a character that is not allowed or the value exceeds the maximum allowed length. Remove the character from the parameter value or reduce the value length and resubmit. If the error still persists, report it to our Customer Support team. Provide the URL of the page you were requesting as well as any other related information.

Sometimes it's also The value of the "to" parameter [...].
Why is this error happening and how can I proceed in my trailhead lesson?
I have tried several times with different naming conventions, same error.
I did find this Forum Thread on Salesforce, but it didn't provide any help. The only thing that seemed to work was, to create the object inside the Setup > Object Manager. Before I do that I figured to ask for help.
Error Image:

My new Object: