text:
Q: i have a list in my customer.txt how to create a search function to print out the whole customer information using python Hi i have a list in my customer.txt file:
[1, 'Amin Milani Fard', 'Columbia College', 778]
[33, 'Ali Sulemanji', 'Langara College', 4324442211]
[32, 'Ali Sulemanji', 'Langara College', 4324442211]
[325, 'Ali Sulemanji', 'Langara College', 4324442211]
[2, 'Yuvin Ng','Dougles College',77839922003]
[3, 'Ali Sulemanji', 'Langara College', 4324442211]

my job is to create a search function that can track the customer name.
for eg.
type in the customer name:Yuvin Ng
and it will return the whole list from Yuvin Ng's line
how can i do that? using python.
def search(n):
    name=input('Customer Name:')
    x=open('customerlist.txt','r')
    i=0
    while i<1000: # anyway this is out of desperation to make the function work...
        z=x.readline()
        print(z)
        i+=1

im stuck... pleease help a.s.a.p thx you..

A: A simple approach would be to iterate over the lines in the file using in to check for a match, and if a match is found use eval to return the line as a list.
def search(file_name, name):
    with open(file_name) as f:
        for line in f:
            if name in line:
                return eval(line)
    return []

>>> search('customer.txt', 'Yuvin Ng')
<<< [2, 'Yuvin Ng', 'Dougles College', 77839922003]

A: Think that you have to look at the pickle module. You code than will look the following way:
data = [[1, 'Amin Milani Fard', 'Columbia College', 778],
[33, 'Ali Sulemanji', 'Langara College', 4324442211],
[32, 'Ali Sulemanji', 'Langara College', 4324442211],
[325, 'Ali Sulemanji', 'Langara College', 4324442211],
[2, 'Yuvin Ng','Dougles College',77839922003],
[3, 'Ali Sulemanji', 'Langara College', 4324442211]]

import pickle

pickle.dump(data, open('c:\\file.txt','w'))

# than you can retrieve data the following way

data = pickle.load(open('c:\\file.txt','r'))

# And now it is very easy to find data you need.
data[1]
>>> [33, 'Ali Sulemanji', 'Langara College', 4324442211]

# OR
for x in data:
   if 'Ali Sulemanji' in x:# or look for any other property/ies
        print x

A: Why not use a database instead of a flat file for storing the information? For example if you wanted to use a database called 'users', you could have something like
import _mysql
conn = _mysql.connect('localhost','root','','users')
with open(filename) as fp:
    for line in fp:
         then fill your query with the information like:
         "..." % dict(zip([id,name,college,number],eval(line)))

Future queries can then be done with like
def search(name):
    cursor = conn.cursor()
    cursor.execute("Select * from users.users where name = %(name)"%locals())
    data = cursor.fetchone()
    cursor.close()
    return data


text:
Q: Setting up 4 containers with 4 IPs and 2 interfaces on EC2 I am trying to set up 4 containers(with nginx) in a system with 4 IPs and 2 interfaces. Can someone please help me? For now only 3 containers are accessible. 4th one is timing out when tried to access from the browser instead of showing a welcome page. I have given the ip routes needed
Host is Ubuntu.
So when this happened I thought it had something to do with the ip routes. So in the same system I installed apache and created 4 virtual hosts each listening to different IPs and with different document routes.
When checked all the IPs were accessible and showed the correct documents.
So now I am stuck, what do I do now!
Configuration:
4 IPs and 2 interfaces. So I created 2 IP aliases. All IPs are configured by the /etc/network/interfaces except the first one. eth0 is is set to dhcp mode.
auto eth0:1
iface eth0:1 inet static
address 172.31.118.182
netmask 255.255.255.0

auto eth1
iface eth1 inet static
address 172.31.119.23
netmask 255.255.255.0

auto eth1:1
iface eth1:1 inet static
address 172.31.119.11
netmask 255.255.255.0

It goes like this. The IPs are private IPs, so I guess there is no problem sharing it here.
eth0   - 172.31.118.249
eth0:1 - 172.31.118.182
eth1   - 172.31.119.23
eth1:1 - 172.31.119.11

Now the docker creation commands
All are just basic nginx containers, so when working it will show the default nginx page.
sudo docker create -i -t -p 172.31.118.249:80:80 --name web1 web_fresh
sudo docker create -i -t -p 172.31.118.182:80:80 --name web2 web_fresh
sudo docker create -i -t -p 172.31.119.23:80:80 --name web3 web_fresh
sudo docker create -i -t -p 172.31.119.11:80:80 --name web4 web_fresh
sudo docker start web1
sudo docker start web2
sudo docker start web3
sudo docker start web4

--
Now here web1 & web2 become immediately accessible. But the containers running on eth1 and eth1:1 are not. So I figured iproutes must be the issue and went ahead and added some routes.
ip route add 172.31.119.0/24 dev eth1 src 172.31.119.23 table eth1
ip route add default via 172.31.119.1 table eth1
ip route add 172.31.119.0/24 dev eth1 src 172.31.119.11 table eth11
ip route add default via 172.31.119.1 table eth11
ip rule add from 172.31.119.23 lookup eth1 prio 1002
ip rule add from 172.31.119.11 lookup eth11 prio 1003

This made web3 also accessible. But not the one from eth1:1. So here is where I am stuck at the moment.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why French word of url cannot be parsed by Node.js V6? I meet one issue, this url 'localhost:4020/share/Fr?chars=ECYCÉDN' with French word can NOT be parsed in Node V6.10.0, however it could be parsed correctly under Node V0.10.42.
Here are more details for my codes

*

*The middleware for Express
app.use bodyParser.urlencoded({ extended: false })
app.use bodyParser.json({ limit: '20mb' })
app.use bodyParser.urlencoded({ limit: '20mb', extended: false })

*And output the chars in the above url router
router = express.Router()
router.get '/share/:lang', (req, res, next) ->
     console.log(req.query.chars)

I test this server with curl 'localhost:4020/share/Fr?chars=ECYCÉDN', and the results are

*

*Node v0.10.42
{"chars":"ECYCÉDN"}

*Node v6.10.0
{"chars":"ECYCÃ DN"}
The express version is 4.15.2
I want to know why this French word cannot be parsed correctly under Node V6.10.0?
I think it could be the character encode issue. However, I try to use querystring.unescape or querystring.escape of querystring, it does not work well.

Update
When I try to output console.log(JSON.stringify(req.query)) in the router '/share/:lang', the result is {"chars":"ECYCÃ DN"} and the length of chars is 8.


text:
Q: What is the most effective way to filter this array? I have two arrays. My goal is to get a third array with users that exist in usersUpdated but do not exist in oldUsers. I know i have to apply multiple filters, but I do not know how.
   const oldUsers = [
     { name: 'Fede', id: 1 },
     { name: 'Marce', id: 2 },
  ];

   const usersUpdated = [
   { name: 'Fede', id: 1 },
   { name: 'Marce', id: 2 },
   { name: 'Ale', id: 3 },
   { name: 'Julian', id: 4 },
];

const expectedValue = [
  { name: 'Ale', id: 3 },
  { name: 'Julian', id: 4 }
 ];

A: Convert arrays to objects, use names as keys & ids as values,  delete keys of old obj from updated obj then convert the updated obj back to array.


text:
Q: JDeveloper ADF: CreateInsert auto committing? I'm currently starting with ADF Faces technology as well as with JDeveloper. I have a .jspx page where I open a popup in which exists an ADF Form binded with a View Object. Whenever the popup opens it calls a createInsert action, but then some error messages popup as if somewhere a validation is being executed.
Things I've considered or tried so far:

*

*The "SKIP VALIDATION" property of the page is set to TRUE. I don't
know what else to try.

*Auto Submit property of each input are set to FALSE.

Consideration
I think the createInsert action is auto submitting but like I said I just started using these technologies a few days ago. So perhaps this "weird behaviour" is being caused by other settings I haven't considered yet.

Here's the code I use when the popup opens (PopUpFecthListener)
public void createInsert(PopupFetchEvent popupFetchEvent) {
    try {

        System.out.println("Inside function");

        ADFUtil.invokeEL("#{bindings.CreateInsertVariable.execute}");
        Util.getAppModuleImpl().getFurVariableView1().getCurrentRow().setAttribute("Estado", "I");

        System.out.println("Function has been executed");
    } catch (Exception e) {

        Util.logErrorJava("Error", e.getMessage());
    }
}

Here's the method in which I get the AppModuleImpl
    public static AppModuleImpl getAppModuleImpl() {
        FacesContext context = FacesContext.getCurrentInstance();
        ValueBinding vb = context.getApplication().createValueBinding("#{data}");
        BindingContext bc = (BindingContext)vb.getValue(context);
        DCDataControl dc = bc.findDataControl("AppModuleDataControl");
        AppModuleImpl module = (AppModuleImpl)dc.getDataProvider();
        return module;
}

A: I think you should try to use immediate attribute for you input controls.
For best understanding of immediate and validation mechanism read this article


text:
Q: How do I find the number of ACTIVE MEMBERS on a forum? I am putting together a Forum Stats website and I need to find the number of Active Members on several forums.
Many have "Total members" listed but that doesn't help me.
I'm considering "Active" as someone that has posted at least 5 times within 6 the last months.
I'm really perplexed as to how this might be done. Any suggestions?

A: If you don't have access to the database, scraping the html pages, following links, and determining post-date & post-user from the HTML itself seems to only way to gp. (HTTPRequest or cURL for fetching, in combination with DOMDocument / DOMXpath for reliable HTML parsing & finding explicit nodes), storing it in your own database. All in all, depending on the exact HTML layout of the forums, not exactly complicated, but a lot of work, and possibly work you have to repeat again and again with small variations for each different forum.
If the forums have RSS feeds or other means of getting more structured content / data the amount of work needed could be greatly reduced.


text:
Q: Why are Starfleet computers so noisy? Starfleet computer consoles are rather noisy.  I can understand — especially with 24th Century touchscreen LCARS consoles — why they might be designed to emit sounds when pressed.  (This way, you'll know if you have inadvertently initiated a photon torpedo launch when you were resting your hand on the tactical console...)
But the consoles also make plenty of noise while they are retrieving information, for instance at 00:16s in this compilation:

Present-day computers make unavoidable hard-drive whirring sounds while accessing data, but do not purposely make sound effects to indicate that data is being accessed (at least not typically).
Why are Starfleet computer consoles so noisy?
I perfectly understand the out-of-universe reasons for this — it makes sense from a production point of view, as it helps to create the atmosphere.  I'm asking for in-universe reasons.  Why would Starfleet engineers add so many sound effects to consoles?
Speculation is fine, but something official — such as a statement from Michael Okuda or a technical manual entry — is preferable.

A: What, you've never heard anyone's touchscreen cell phone making artificial clicking as they type? It works by the same principle - a touchscreen, with "buttons" that don't really exist, right next to each other, easy to miss letting you accidentally not press any input at all. Usually those sounds are a little quieter, maybe using tactile vibration instead of sound.
Heck, nearly every ATM and credit card point of sale terminal does exactly this too. And for the same reason - to reduce errors.
In fact, watching this, it's kind of weird that there aren't a lot of "dammits" and frantic backspacing. ;)

A: I am going to echo what others have said about the in-universe justification of sounds indicating a part of the system state.
I would like to add, however, that this principle is as a real thing and it goes well beyond having pre-defined sound clips play upon particular events (as it has been supported since at least Windows 95). The generic technique is called sonification, and it is a subject of active research (e.g. one recent research paper, another recent research paper).
The idea is that human (and certainly, other humanoid :-) ) users can easily detect anomalies even in a somewhat complex pattern of sounds. While many of the sound effects we see on Star Trek seem to be pre-recorded (they always play out the same), that data processing one you pointed out might very well be the indication of something being loaded successfully - I speculate that, had there been any errors, a few of the beeps might have been replaced with something else, thereby immediately giving users a hint that there is a problem with X percent of the data.

A: My speculation: it's so you can perform multiple tasks at once, without looking at every single screen.
Think about the little beeps as auditory progress bars.
I can start a planetary scan on one console, turn around and start a shield modulation on another console, and then start writing up a log on a third console. (Or do all three on the same console.) By listening to the noises made by the first two processes, I can know exactly what the first two processes are doing without turning away from my third task to look at them.
The "real" answer is probably a combination of all of the answers, but this is the first thing that occurred to me.

A: Probably as acknowledgement for input and processes occurring...for the user and (!) for his or her colleagues
In all the instances shown in the above video, it seems to me that every time a noise is made by the computer, it is when someone has pressed a button on the screen somewhere.  Rather than just touching the screen and having no acknowledgement, it is probably useful to know that they have pressed what they thought they had.
Focusing in on the main question about why it makes so much noise when retrieving data we have the out-of-universe reason for 'rule of cool' and informing people that a system is coming online.  The latter is also a valid in-universe reason though; if you want to access data it's nice to have some acknowledgement of that.  So, by having the sound output acknowledging that, yes a system is coming online to access the data you requested, you know something is working.  From a troubleshooting perspective this is particularly useful.  I press a button and I don't hear the system coming online tells me what the problem is - there must be a problem with the system connections.
Bear in mind (and I know this is going from a bit of an out-of-universe perspective) that when TNG was made, keyboards and mice were quite noisy and so the idea of not having a sound confirmation of making an action would be alien.
This then raises the question of why audio notifications are better than visual ones; wouldn't audio notifications just annoy everyone around you?  Well, it could be argued that this is part of the reason.  When you consider when people use LCARS, generally they are in a group environment.  So, when they do something, there is a little sound notification, not only alerting the user, but also the people around them.  I don't know about you, but if I was aboard the Enterprise-D, I'd want to make sure that other people could tell what Wesley was doing with the anti-matter containment field to ensure he wasn't messing it up without spending all their time looking over his shoulder!

A: Most likely the sounds serve as a reminder of a carried out function. Also the sounds have different pitches. A negative connotation often has a buzz or lower pitch sound. Confirmation have a high pitch or beeping sound. the sound of pressed buttons is probably a affect to remind the audience they're working with technology. It's also probably a means to indicate a button has been pressed. Keyboards today often make sounds, since we don't look at them when we type the sound is indicative of knowing we pressed it.


text:
Q: Trouble starting a AVD (Android Virtual Device) in Android Studio (on Mac) I have prior experience (rusty) with Eclipse and I recently downloaded Android Studio for Mac (El Capitan).  I'd like to run my "hello world" program on virtual machine.  I picked (Nexus 7 2012 API 23) but in Android Virtual Device Manager I'm getting "Failed to Load" message and Details gives:
Name: Nexus_7_2012_API_23
CPU/ABI: Google APIs ARM (armeabi-v7a)
Path: /Users/user/.android/avd/Nexus_7_2012_API_23.avd
Error: Unknown target 'Google Inc.:Google APIs:23' in
/Users/user/.android/avd/Nexus_7_2012_API_23.ini

In Android SDK, I have the following loaded:
    null
null    23  2   Installed
null    23  2   Not installed
null    23  2   Not installed
null    23  1   Not installed
null    23  1   Installed
null    23  3   Installed
null    23  7   Installed
null    23  7   Installed
null    23  1   Installed
null    23  7   Installed
null    23  11  Installed
null    23  11  Installed
null    23  1   Installed

Basically all the 23 packages including Google APIs.  Just not the TV stuff.
When I hit the arrow to run my program, it builds fine, but no emulator launches.  This is not surprising given the message in the AVD.  It would be nice if when you ran it, there was some sort of message saying the image won't work.
Any ideas?
Thanks,
Dave

A: I had this issue when I had Docker for Mac running. I quit Docker for Mac and it works. It seems to be due to an issue with conflicting virtual machines.

A: Wow, what a pain.  After all that, it turns out that just closing and reopening Android Studio did the trick.  Also, beware that Virtual Device seems to take forever (minutes?) to come up.  At least on my MacBook Air Mid 2012. Processor: 1.8 GHz i5 Memory 4 GB 1600 MHz DDR3.
Thanks Morrison Chang for ideas.
-Dave


text:
Q: How to access remote desktop from two machines in windows azure I published the cloud service from VS2010 with Remote Desktop enabled. I downloaded the remote desktop connection for that instance. I just logged in to cloud server using Remote Desktop. Now i published same application from another computer. When i want to connect Remote Desktop from new machine its unable to connect to server. Even i tried from previous machine i am getting the same thing.
Application has 1 role & 1 instance. help me with this thing.

A: You must allow the RDP while publishing it to the cloud...Check the publish settings once...


text:
Q: Accessing row data from Kendo Grid ClientTemplate I am trying to embed a chart in a Kendo Grid Cell, following this example: http://docs.telerik.com/kendo-ui/aspnet-mvc/helpers/grid/faq#how-do-i-use-a-kendo-ui-widget-inside-a-grid-client-column-template
I have managed to embed the graph in the grid, but I am unable to find a way to bind to row data.
The ViewModel has properties for each bar value - but how do I bind to those properties (maybe some #= ... # expression?).
I expect something similar to this:
@(Html.Kendo().Grid<ViewModel>()
    .Name("grid")
    .Columns(columns =>
    {
        columns.Bound(p => p.DataID).Filterable(false);
        columns.Template(@<text></text>).ClientTemplate(
            Html.Kendo().Chart()
                .Name("chart#=DataID#")
                .Series(series =>
                {
                    series.Bar("\\#= FirstBarValue \\#");
                    series.Bar("\\#= SecondBarValue \\#");
                })
                .ToClientTemplate().ToHtmlString()
        );
    })
.DataSource(dataSource => dataSource.Ajax().PageSize(20).Read(read => read.Action("Read", "Grid"))))

But the FirstBarValue and SecondBarValue are not properly evaluated, although DataID is. Maybe a different scope? I can only make it work with hard coded values.
Any suggestions?


text:
Q: append html content to html using ajax I have html code like this :

I want to append html if the data-date come's in between startdate and enddate.
$(document).ready(function(){
    var d = $(".fc-day").data('date');
    $.ajax({
        url : '<?php echo base_url()."admin/utilities/get_task_assign_staff" ?>',
        dataType : 'json',
        success : function(responce){
            $(".fc-day").each(function(){
                var d = $(".fc-day").data('date');
                if(d == responce[0].startdate)
                {
                    this.append(""+responce[0].name+"");
                }
            });
        }
    });
});

For Example, my startdate is 2016-07-05 and enddate is 2016-07-09 than append responce[0].name to the given  that data-date come's in between startdate and enddate.
So what jQuery should I have to write?

A: $(document).ready(function(){
  $.ajax({
    url : '<?php echo base_url()."admin/utilities/get_task_assign_staff" ?>',
    dataType : 'json',
    success : function(responce){
        $('.fc-day').each(function(){
            var data_date = $(this).attr('data-date'),
               response = $.parseJSON(responce);
            if(data_date == response.startdate){
                $(this).html(""+response.name+"");
            }
        });
      }
   });
});

*

*You want to get the attribute date_date from the elements that contain the class fc-day. This is how you get this attribute.
$('.fc-day').each(function(){var data_date = $(this).attr('data-date');});

*You have indicated that you expecting JSON as response, so you want to probably use parseJSON for the responce you got.
I hope i helped to solve your issue. Cheers


text:
Q: Level-sensitive SR Latch behavior I am looking into the difference between a regular SR latch and a level sensitive SR Latch.
Level - sensitive SR Latch
I am aware that what we want to avoid in an SR latch is the configuration (1,1) because it can cause an oscillation and when it finally settles on a 0 or 1 we can't be certain which one due to the oscillation. Thus, we use a level sensitive SR latch. But can someone elaborate on the behavior of this level-sensitive SR latch. Because if S,R, and C(usually a clock) are all 1, it seems to me that we can still end up with the same (1,1) configuration that we are trying to avoid.
I have found this post and it talks about the difference between a latch and a flip-flop. But just to re-iterate, my main question is if clk = 1 and if S =1, R =1, then can't we still end up in a loop of oscillations.

A: The SR flipflop is designed so that C is only 1 when S and R are stable. It is designed very carefully as to prevent C from being 1 when S=R=1. However, this is not apparent at all given the basic diagram of the flip flop.
An improvement to this is the D flipflop. It inverts one of the signals from the SR flipflop. This ensures that S and R are never the same. This can be seen in the image below.


text:
Q: How to map Json String to POJO? I am getting below json response from third party web services.
    {
  "Values":[
    {
      "Date":"2013-08-01",
      "Value":1451674.0
    },
    {
      "Date":"2013-09-01",
      "Value":1535645.0
    },
    {
      "Date":"2013-10-01",
      "Value":1628753.0
    },
    {
      "Date":"2013-11-01",
      "Value":1279856.0
    },
    {
      "Date":"2013-12-01",
      "Value":1471991.0
    },
    {
      "Date":"2014-01-01",
      "Value":1571008.0
    },
    {
      "Date":"2014-02-01",
      "Value":1863232.0
    },
    {
      "Date":"2014-03-01",
      "Value":2126469.0
    },
    {
      "Date":"2014-04-01",
      "Value":2146069.0
    },
    {
      "Date":"2014-05-01",
      "Value":2735564.0
    },
    {
      "Date":"2014-06-01",
      "Value":1977808.0
    },
    {
      "Date":"2014-07-01",
      "Value":1932503.0
    }
  ]
}

Now what should be the pojo properties and how to map it with pojo?
class Value{

    @JsonProperty("Values")
    List<DateValuePair> values;

//setter getter
}

class DateValuePair{
    @JsonProperty("Date")
    String date;

    @JsonProperty("Value")
    String value;
//setter getter
}

//mapping
Value visits = new Value();
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(SerializationConfig.Feature.WRAP_ROOT_VALUE, true);
        mapper.configure(DeserializationConfig.Feature.UNWRAP_ROOT_VALUE, true);

    HttpClient client = HttpClientBuilder.create().build();
    HttpGet request = new HttpGet("http://api.8df1fc");
    HttpResponse response = client.execute(request);
    BufferedReader rd = new BufferedReader (new InputStreamReader(response.getEntity().getContent()));
    String line = "";
    while ((line = rd.readLine()) != null) {
      System.out.println(line);
      mapper.readValue(line, Value.class);
    }

got below exception:
{"Values":[{"Date":"2013-08-01","Value":1451674.0},{"Date":"2013-09-01","Value":1535645.0},{"Date":"2013-10-01","Value":1628753.0},{"Date":"2013-11-01","Value":1279856.0},{"Date":"2013-12-01","Value":1471991.0},{"Date":"2014-01-01","Value":1571008.0},{"Date":"2014-02-01","Value":1863232.0},{"Date":"2014-03-01","Value":2126469.0},{"Date":"2014-04-01","Value":2146069.0},{"Date":"2014-05-01","Value":2735564.0},{"Date":"2014-06-01","Value":1977808.0},{"Date":"2014-07-01","Value":1932503.0}]}
Exception in thread "main" org.codehaus.jackson.map.JsonMappingException: Root name 'Values' does not match expected ('Value') for type [simple type, class com.domain.Value]
 at [Source: java.io.StringReader@e9a398d; line: 1, column: 2]

Thanks!

A: you can have Pojo which looks something like this
class Value{

    @JsonProperty("Values")
    List<DateValuePair> values;
}

class DateValuePair{
    @JsonProperty("Date")
    String date;

    @JsonProperty("Value")
    String value;
}

and getters/setteres as well
we have jackson libraries which will help you to de-serialize the json string to above POJO object
Just a pointer you need to take it forward
Hope this helps!

A: Root name 'Values' does not match expected ('Value') for type [simple type, class
com.domain.Value] at [Source: java.io.StringReader@e9a398d; line: 1, column: 2]

Try with setting UNWRAP_ROOT_VALUE to false
//mapper.configure(DeserializationConfig.Feature.UNWRAP_ROOT_VALUE, true);
mapper.configure(DeserializationConfig.Feature.UNWRAP_ROOT_VALUE, false);


text:
Q: What "idiomatic Kotlin" does the library billing.ktx facilitate? In researching answers for my question here I found (after several days of very frustrating work) references to the kotlin billing library "billing.ktx" which a couple of Developer pages claim

contains Kotlin extensions and coroutines support that enable you to
write idiomatic Kotlin when using Google Play's billing system

but gives neither details nor links for more information. The Play billing examples, "Classy Taxi" and "TrivialDrive" have been rewritten to use Kotlin but hardly "idiomatic Kotlin", and certainly not using coroutines, nor do they use this library. They are now two years old and showing their age in this fast moving arena.
My question is specifically what does this library offer in terms of idiomatic Kotlin or even coroutine support? I am making some headway with some billing client functions (as can be seen in the referenced question) before using this library, but I can't see what difference using it makes. To be even more specific, "launchBillingFlow" looks impossible to convert, but is it?
Just links to somewhere to find information would be enough. Why is it so hard to find more than class definitions for the billing client?

A: I can find no documentation. Everything in this answer comes from looking through the billing-ktx aar that appears when I add a dependency on this library to my project.
This library looks pretty minimal. It provides three new "result" classes as well as four extension funtions on BillingClient to replace callback-based code with suspend funs.
package com.android.billingclient.api

public suspend fun BillingClient.acknowledgePurchase(params: AcknowledgePurchaseParams): BillingResult { /* compiled code */ }
public suspend fun BillingClient.consumePurchase(params: ConsumeParams): ConsumeResult { /* compiled code */ }
public suspend fun BillingClient.queryPurchaseHistory(skuType: String): PurchaseHistoryResult { /* compiled code */ }
public suspend fun BillingClient.querySkuDetails(params: SkuDetailsParams): SkuDetailsResult { /* compiled code */ }

With these in place, inside a coroutine you can write:
val result = billingClient.querySkuDetails(params.build())
// you can now access result.billingResult or result.skuDetailsList

Rather than something like what appears in the documentation:
billingClient.querySkuDetailsAsync(params.build()) { billingResult, skuDetailsList ->
    // Process the result.
}


text:
Q: nuget.exe ignores inheritance for packageSourceCredentials Is it possible to configure Nuget so the package sources are configured in the nuget.config file in the solution dir, while the credentials for those sources are configured in the nuget.config file located at the user level (%appdata%\NuGet\NuGet.Config)?
Reading how settings are applied for nuget operations, seems like nuget.config has some sort of inheritance. I was trying to use this inheritance to configure nuget for my team in the following way.

*

*Each developer will have a personal set of credentials to the Nuget repository.

*Each visual studio solution will contain a Nuget.config file in the solution directory.
2.1. The Nuget.config file will contain two package sources: nuget.org, and a private credential required source.

*Each developer will configure the credentials to the private Nuget source within the file located in the user profile (%appdata%\NuGet\NuGet.Config). In this way, those credentials are not committed to source control.
here are some examples of the nuget.config files I am trying to use:
Solution level file
<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <packageSources>
        <add key="nuget.org" value="https://api.nuget.org/api/v3/index.json" />
        <add key="Private" value="url_for_the_private_feed" />
    </packageSources>
    <activePackageSource>
        <add key="All" value="(Aggregate source)" />
    </activePackageSource>
</configuration>

User level file
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
  </packageSources>
  <packageSourceCredentials>
    <Private>
      <add key="Username" value="user_name_here" />
      <add key="Password" value="encrypted_password_here" />
    </Private>
  </packageSourceCredentials>
</configuration>

For some reason, I am not able to get this to work.

A: I finally figured out that if the NuGet command includes the argument -configFile <path to nuget.config> then the behavior described in how settings are applied does not apply, and instead, the NuGet CLI will only consider the configuration file passed as a parameter.
This is not clear in the documentation. For some reason, I thought that I could pass a nuget.config file to the NuGet CLI, and it would use that file in conjunction with the user-level configuration and the computer-level configuration.


text:
Q: Should I close the session before closing the resource resolver I have simple service, lets use resourceResolver and session for some logic:
@Component(immediate = true)
@Service(value = ServiceInterface.class)
public class ServiceInterfaceImpl implements ServiceInterface {

     //Some fields

     @Reference
     private ResourceResolverFactory resolverFactory;

     private void someMethod() {
          ResourceResolver resourceResolver = null;
          try {
               resourceResolver = resolverFactory.getServiceResourceResolver(null);
               Session session = resourceResolver.adaptTo(Session.class)
               someMethod2(resourceResolver);
               someMethod3(session);
          } catch (LoginException e) {
              log.error(e.getMessage(), e);
          } finally {
              if (resourceResolver != null && resourceResolver.isLive()) {
                  resourceResolver.close();
              }
          }
     }

     //Some implementation
 }

Should I close the session, or it will be closed in automatically resourceResolver.close()?

A: The session will be automatically closed, when you close the ResourceResolver, so resourceResolver.close() is enough. You can dig into the code to find the place where this happens. If you get a session repo.loginAdministrative(), you should logout the session at the end, but this is not the recommended way to obtain a jcr session.


text:
Q: Windows server 2008 R2 - time limit for locked session? Question on Windows Server - if I remote desktop into a server, and then proceed to the lock the screen (rundll32.exe user32.dll, LockWorkStation), and close the window...because I wanted to keep a process running on that machine...
Is there a time when that locked session expires or fizzles out and becomes disconnected?
If the session became disconnected, that process I was running earlier may not function.
Or....does it stay good for as long as no one logs into that account again?

A: That would depend if any policy settings that have been set to limit the time.
Both the User & Computer sections of policy offer several kinds of time limits at the following path:
...\Policies\Administrative Templates\Windows Components\Remote Desktop Services\Remote Desktop Session Host\Session Time Limits

*

*End a disconnected session

*Active session limit

*Idle session limit

*When a session limit is reached or connection is broken

More here: https://technet.microsoft.com/en-us/library/cc754272(v=ws.11).aspx


text:
Q: How to do a whereKey so it querys posts ___ km+ AWAY from currentuser? var limitlocation = 5 as Double

if let usergeo = currentuser.objectForKey("location") as? PFGeoPoint {
    query.whereKey("location",
          nearGeoPoint: usergeo,
          withinKilometers: limitlocation)
}

currently have that but it gets users that are within 5 km. how do i make it so it is 5 km+ AWAY.

A: By default this type of query will only allow you to query geoPoints that are within 100 miles of the geoPoint you are querying for : https://www.parse.com/docs/ios/guide#geopoints-caveats.
What you can do is filter the results and remove any results that are within 5km.
This is how it would look in objective-c - you'll have to translate this into swift
NSMutalbeArray* mutableObjects = [[NSMutableArray alloc] init];
PFGeoPoint* userGeoPoint = user[@"geoPoint"];
for (PFObject* object in objects) {

    PFGeoPoint* objectGeoPoint = object[@"geoPoint"];
    CLLocation *locA = [[CLLocation alloc] initWithLatitude:userGeoPoint.latitude longitude:userGeoPoint.longitude];
    CLLocation *locB = [[CLLocation alloc] initWithLatitude:objectGeoPoint.latitude longitude:objectGeoPoint.longitude];
    CLLocationDistance distance = [locA distanceFromLocation:locB]; // Distance in meters
    if (distance >= 5000) {
        [mutableObjects add:object];
    }

}


text:
Q: Validate an integer and integer range in java I've been working on this simple issue for hours and not getting anywhere.  I'm trying to validate that a number inputted into my program is between 1 and 12. I've tried several kinds of loops but get various errors and problems which I've detailed in the comments at the top of the sample code:
//This gives me an error saying that the local variable deptMonth may not have
//been initialized

boolean monthCorrect;
int deptMonth;
Scanner input = new Scanner(System.in);

    do
    {
        System.out.print("Please input the month (1-12): ");
        if (input.hasNextInt())
        {
            if ((input.nextInt()) <= 12 && (input.nextInt()) >=1)
            {
                deptMonth = input.nextInt();
                monthCorrect = true;
            }
            else
            {
                System.out.println("I don't understand try again.");
                monthCorrect = false;
                input.next();
            }
        }
        else
        {
            System.out.println("I don't understand try again.");
            monthCorrect = false;
            input.next();
        }

    }while (!(monthCorrect));

Is there an easier and correct way to do this?
Thank you.

A: You're calling the method nextInt repeatedly. Isn't that going to eat up multiple input tokens? Try this: call nextInt just once and assign that to a variable, let's call it foo. Then test foo to see if it is in the correct range, and if so, assign foo to deptMonth.

A: Like Robert said, you need to assign the
    input.nextInt()
to a variable inside of the do loop. Calling this method multiple times results in you having to enter a value multiple times. So, in order for your code to work, it should like more like this:
boolean monthCorrect;
int deptMonth;
Scanner input = new Scanner(System.in);

do
{
    System.out.print("Please input the month (1-12): ");
    if (input.hasNextInt())
    {
        int tmp = input.nextInt();
        if ((tmp) <= 12 && (tmp) >=1)
        {
            deptMonth = tmp;
            monthCorrect = true;
        }
        else
        {
            System.out.println("I don't understand try again.");
            monthCorrect = false;
        }
    }
    else
    {
        System.out.println("I don't understand try again.");
        monthCorrect = false;
    }

}while (!(monthCorrect));

Also, I don't know if you are continuing input or not, but it is good practice to close the Scanner once you are done with it, to prevent memory issues and such.
So,
if ((tmp) <= 12 && (tmp) >=1)
        {
            deptMonth = tmp;
            monthCorrect = true;
        }

Should look like:
if ((tmp) <= 12 && (tmp) >=1)
        {
            deptMonth = tmp;
            monthCorrect = true;
            input.close();//This keeps everything tidy! Also eclipse should give you a warning message if you forget to include it!
        }


text:
Q: Spyder 4.1.5 disable selected pycodestyle warnings After updating Spyder to 4.1.5 my script is covered with a whole bunch of taste-specific alerts like:

Code analysis:
E261 at least two spaces before inline comment (pycodestyle E261)

or

Code analysis:
E266 too many leading '#' for block comment (pycodestyle E266)

While many of the warnings improve my code, I would like to disable the ones that I disagree with (like for example the two listed above).
How can I do it?

A: OK, I have found it
Tools -> Preferences -> Completion and linting -> Code Style then mark the checkbox Enable code style linting and then list all the unwanted warnings, separate them with commas.


text:
Q: Failed when connecting: Connection closed (code: 1000)
As per above screenshot I'm getting VNC Disconnected.
This is hosted on remote server using docker. This is "Docker in Docker implementation"
this is my docker-compose file
version: "3"
networks:
  selenoid:
    external:
      name: selenoid
services:
  selenoid:
    networks:
        selenoid: null
    image: "aerokube/selenoid:latest-release"
    restart: always
    ports:
        - "4444:4444"
    volumes:
        - /var/run/docker.sock:/var/run/docker.sock
        - "$PWD/selenoidconfig:/etc/selenoid/:ro"
        - $HOME/Projects/videos:/opt/selenoid/video
        - "$PWD/logs:/opt/selenoid/logs"
    environment:
        - OVERRIDE_VIDEO_OUTPUT_DIR=$HOME/Projects/videos
    command: ["-video-output-dir", "/opt/selenoid/video", "-log-output-dir", "/opt/selenoid/logs","-container-network", "selenoid","-timeout","8h","-service-startup-timeout","10m","-session-attempt-timeout","10m", ]
  selenoid-ui:
      networks:
          selenoid: null
      image: "aerokube/selenoid-ui"
      restart: always
      depends_on:
          - selenoid
      ports:
          - "8081:8080"
      command: ["--selenoid-uri", "http://selenoid:4444"]

I can't watch video live. But I can watch old videos when I clicked Videos link.
And I can see this console error --> Failed when connecting: Connection closed (code: 1000) rfb.js:668
I managed to get below error from --> docker-compose logs --follow
[VNC ERROR] [dial tcp 172.18.0.5:5900: connect: connection refused

I managed to catch some error outputs as well.
I can see below errors
95439231.695][INFO]: Waiting for pending navigations...
[1595439231.695][DEBUG]: DevTools WebSocket Command: Runtime.evaluate (id=355) 907E8B9EDE154FC01AEB8BC2D449BDD9 {
"expression": "1"
}
[1595439231.695][DEBUG]: DevTools WebSocket Response: Runtime.evaluate (id=355) 907E8B9EDE154FC01AEB8BC2D449BDD9 {
"result": {
"description": "1",
"type": "number",
"value": 1
}
}
[1595439231.695][INFO]: Done waiting for pending navigations. Status: ok
[1595439231.695][INFO]: [5193d46ce8e3cb8ce787f4e283b3e674] RESPONSE ClickElement
--- x11vnc loop: waiting for: 413

error opening logfile: /home/selenium/x11vnc.log
open: Permission denied

--- x11vnc loop: sleeping 500 ms ---

--- x11vnc loop: 8 ---

[1595439232.699][INFO]: [5193d46ce8e3cb8ce787f4e283b3e674] COMMAND ExecuteAsyncScript {
"args": [ "" ],
"script": "try { return (function anonymous(\n) {\nfunction getNg1Hooks(selector, injectorPlease) {\n function tryEl(el) {\n try {\n if (!injectorPlease && angular.getTestability) {\n var $$testabil..."
}
[1595439232.699][DEBUG]: DevTools WebSocket Event: DOM.childNodeCountUpdated 907E8B9EDE154FC01AEB8BC2D449BDD9 {
"childNodeCount": 15,
"nodeId": 23
}
[1595439232.699][DEBUG]: DevTools WebSocket Event: DOM.attributeModified 907E8B9EDE154FC01AEB8BC2D449BDD9 {
"name": "class",
"nodeId": 23,
"value": " ng-scope "
}

A: I removed the image. then pulled as the normal user. I must have pulled the selenoid/vinc:chrome image as root user. Now it works


text:
Q: Зависимость проходимого расстояния от скорости Unity C# Ведем пальцем по тачпаду, получаем разницу от точки касания до текущей точки пальца.
Относительно размера экрана приводим это значение к промежутку от -1 до +1
 if(th.phase == TouchPhase.Began && (th.phase != TouchPhase.Moved))
                {
                    StartTouchPos = th.position;
                }
if (th.phase == TouchPhase.Moved)
                {
                    currentpositiony = (((CurrentTouchPos.y - StartTouchPos.y) / Screen.height)) + savey;
                }
if(th.phase == TouchPhase.Ended)
                {
                    savey = currentpositiony;
                }

Как к этому прикрутить зависимость от скорости движения пальца по тачу?
Чтобы, когда пальцем ведёшь быстрее, значение currentpositiony менялось быстрее.
Для наглядности - так же работает мышка. Ведёте медленно - за 10 см движение мышки на столе её курсор двигается на часть экрана. Дернете быстро - за 10 см на столе курсор пробежит весь экран.
Скорость у нас вычисляется так
 distance = th.deltaPosition.magnitude;

 speed = distance / Time.deltaTime;

Вроде простая математика, а никак решение в голову не приходит.

A: У тебя есть расстояние. Почему бы не засекать время еще в момент старта тача?
А расстояние/время = скорость.
Далее закидаешь эту скорость в некую функцию (Скорей всего пол параболы как правая чать параболы на картинке) ( если что, подберешь какую более удачную)

(источник: wordsland.ru)
И эта функция будет возвращать скорость движения твоего персонажа в игре так как тебе нужно.
Чем ответ не подходит?


text:
Q: Nginx: how to add /something to a uri and still keep it working I have a nginx instance running. My config is something like the following.
server {
    listen 80;
    listen 443;

    location / {
        ...
        proxy_pass http://127.0.0.1:8080;
        ...
        proxy_redirect http://127.0.0.1:8080 example.com;

    }
}

I have some software running in 8080 and I want that the user enters example.com/somepath and be able to be redirected to the root 127.0.0.1:8080 through my domain. The software should receive all urls without /somepath but the browser should still show /somepath in the name.
I am quite new so sorry for the basic question I could not find any relevant info on how to do this exactly: I tried rewrite rules and setting location /mysoftware { tests with no luck.

A: The client browser uses /somepath/... to access /...in the application. This means that nginx must rewrite the URI before passing it upstream.
The proxy_pass directive has a basic rewrite capability. See this document for details. For example:
location /somepath/ {
    proxy_pass http://127.0.0.1:8080/;
    ...
}

Alternatively, you might use a rewrite ... break statement. See this document for details. For example:
location /somepath {
    rewrite ^/somepath/?(.*)$ /$1 break;
    proxy_pass http://127.0.0.1:8080;
    ...
}

The difficult part is preventing your application from breaking out of /somepath. The proxy_redirect directive can handle the 3xx responses from your application. But the location of resource files (.css and .js) and the target for hyperlinks, can cause problems for applications that are not aware that they need to stay inside a subdirectory.


text:
Q: Sort Ascending - Linked List I'm having a little trouble with getting my head around how this function would work and what I need to do. I have int number as my data type and  node* next in my node class. I also have node pointers head, current and temp. My question is how would I go about getting my list of integers into order? Also how does ascending and decending work in a single linked list?
My header file:
#ifndef SDI_LL
#define SDI_LL

namespace SDI
{

    class LinkedList
    {
        class Node
        {
        public:
            int number;                                 //data element
            Node* next;                                 //pointer to next, node inside each node
        private:

        };

    private:

        Node *head;
        Node *current;                                  //head, current and temp node pointers
        Node *temp;

    public:
        LinkedList();                                   //constructor to access nodes from above
        ~LinkedList();                                  //destructor

        void insert(int add);
        void remove(int remove);                        //functions that access private data nodes above
        void display();
        void reverse();
        void search(int searchNum);
        void sortAscending();
        void sortDecending();
        void saveAll();
        void restoreAll();

    };

}
#endif

My ascending function so far where it starts from the beginning and searches through the list:
void LinkedList::sortAscending()
{
    current = head;
    for (current = head; current;)
    {
        temp = current;
        current = current->next;

    }
}

A: In general, you should use containers available in the standard libraries, which provide efficient sorting methods where applicable.
That said, if you want to do it for learning purposes - as you probably "should at least once" - then it is not too difficult to implement.
for (current = head; current;)

That's a funny for loop, personally I'd prefer:
current = head;
while(current)  // or current != nullptr to be more explicit

Note also that you (unnecessarily, of course) assign head to current twice - immediately before the for loop, and in the initialisation of it.
A simple scheme (but not at all efficient!) might be to just swap 'out of order' elements as you iterate through the list, until no swaps were necessary:
bool changeMade;
do{
    changeMade = false;
    current = head;
    while( current ){
        temp = current;
        current = current->next;

        if( current && current->data < temp->data ){
            changeMade = true;
            swap( temp->data, current->data );
        }
    }
} while( changeMade );

This assumes a data field is the only other in the node - since it doesn't actually swap the nodes, just the data. (Doing the former is not really any more difficult - but without seeing your node type declaration I'd be making up names and risk confusing the issue.)

A: I don't see any declarations for current, head, and temp, but I assume they are pointers to node. Have you decided on a sort algorithm? Does the sort algorithm need to be efficient or is something with the performance of a bubble sort ok? With logic similar to a bubble sort, you can repeatedly move the node with the largest value to the end of the list. Or to save a bit of time, you could remove the node with the largest value from the original list and insert it into the front of a new list that would end up in sorted order. More efficient algorithms use logic based on merge sort.
To remove or swap nodes, using a pointer to pointer can avoid special handling for the first node of a list (the one pointed to by pList in this example):
NODE * SortList(NODE * pList)
{
NODE * pNew = NULL;                     /* sorted list */
NODE **ppNode;                          /* ptr to ptr to node */
NODE **ppLargest;                       /* ptr to ptr to largest node */
NODE * pLargest;                        /* ptr to largest node */
    while(pList != NULL){               /* while list not empty */
        ppLargest = &pList;             /*  find largest node */
        ppNode = &((*ppLargest)->next);
        while(NULL != *ppNode){
            if((*ppNode)->data > (*ppLargest)->data)
                ppLargest = ppNode;
            ppNode = &((*ppNode)->next);
        }
        pLargest = *ppLargest;          /* move node to new */
        *ppLargest = pLargest->next;
        pLargest->next = pNew;
        pNew = pLargest;
    }
    return(pNew);
}


text:
Q: I'm trying to convert this PtrSafe to 64 bit and I've added the Win64 and LongPtr but it still is highlighted in red. Any suggestions? I'm trying to convert this PtrSafe to 64 bit and I've added the Win64 and LongPtr but it still is highlighted in red.  Any suggestions?
Option Compare Database
Option Explicit

Public lngRefNum As LongPtr
Public blnSetupCK As Boolean

#If Win64 Then

    Private Declare PtrSafe Function ShellExecute Lib "shell32.dll" _
            Alias "ShellExecuteA" _
           (ByVal hWnd As LongPtr, _
            ByVal lpOperation As String, _
            ByVal lpFile As String, _
            ByVal lpParameters As String, _
            ByVal lpDirectory As String, _
            ByVal nShowCmd As LongPtr) As Long

#Else
        Private Declare Function ShellExecute Lib "shell32.dll" _
            Alias "ShellExecuteA" _
           (ByVal hWnd As LongPtr, _
            ByVal lpOperation As String, _
            ByVal lpFile As String, _
            ByVal lpParameters As String, _
            ByVal lpDirectory As String, _
            ByVal nShowCmd As LongPtr) As Long


text:
Q: Drawing area using cairo I am developing a simple interface which simulates a led using GTK3 and C. When I receive a command the "led" turn on or turn off according to command. I am using Cairo in drawing area to draw a circle representing my led and I am using gtk_widget_queue_draw_area to update screen in my timeout function. After a while my CPU usage increase to 100% in my application.
When I receive a command I call the function below
void update_status_led(int led, int status_led)
{

    g_signal_connect(G_OBJECT(darea[led]), "draw", G_CALLBACK(on_draw_event_leds), GINT_TO_POINTER(status_led));

}

so the callback function "on_draw_event_leds" is called
gboolean on_draw_event_leds(GtkWidget *widget, cairo_t *cr,
    gpointer user_data)
{
  set_status_led(cr, GPOINTER_TO_INT(user_data));
  return FALSE;
}

So it calls the function "set_status_led"
void set_status_led(cairo_t *cr, int status)
{
    printf("update status led: %d\n", countref++);
    cairo_reference(cr);
    cairo_set_line_width(cr, 2);
    cairo_set_source_rgb(cr, 0, 0, 0);
    cairo_arc(cr, 9, 9, 7, 0, 2 * M_PI);
    if (status>0)
    {
      cairo_set_source_rgb(cr, 1, 0, 0); //red
    }
    else
    {
      cairo_set_source_rgb(cr, 0, 0, 0); //black
    }
    cairo_fill(cr);
    cairo_stroke(cr);
    cairo_destroy(cr);
}

I am using "printf("update status led: %d\n", countref++);" to know how many times my function is called and my log is printed below
New Connection from 127.0.0.1:34589
1 Command Received
update status led: 6
update status led: 7
1 Command Received
update status led: 8
update status led: 9
update status led: 10
1 Command Received
update status led: 11
update status led: 12
update status led: 13
update status led: 14
1 Command Received
update status led: 15
update status led: 16
update status led: 17
update status led: 18
update status led: 19
1 Command Received
update status led: 20
update status led: 21
update status led: 22
update status led: 23
update status led: 24
update status led: 25
1 Command Received
...

As can be seen, I receive only one command and my callback function on_draw_event_leds is called many times and always increase 1 more call
each received command as previous cairo was not deleted and gtk_widget_queue_draw_area render them all again.
Can someone help me?
Thanks,

A: The g_signal_connect() function just says "when this event happens, do this function". You were likely confusing it for gtk_widget_queue_draw(), which is the function that actually causes a widget to be redrawn.
Somewhat counter-intuitively, signal connections are many-many. This means that any number of functions can connect to the same signal, and all of them will be called when that signal is emitted. Because you call g_signal_connect() repeatedly, you get multiple connections to your drawing function, and that drawing function will thus be called multiple times.
So what you want to do is move the g_signal_connect() to your initialization code instead, as that's usually where signals are connected anyway, and have gtk_widget_queue_draw() (or a similar function) in update_status_led().


text:
Q: Два раза показывается реклама Воспользовавшись предложенным в другом вопросе ответом решил отображать рекламу с задержкой в 10 секунд. Написал так, но после закрытия рекламы (межстраничное), через некоторое время опять появляется. Почему так?
Вот код, в методе onCreate прописал его
public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    //Для adMob
    private InterstitialAd adMob;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_note);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (!isShow) {
                    createAds();
                    isShow = false;
                }
            }
        }, 10000);
    }

    /*Проверка загрузки объявления adMob*/
    public void displayAdMob() {
        if (adMob.isLoaded()) {
            adMob.show();
            isShow = true;
        }
    }
    /*Проверка загрузки объявления adMob*/

    private void createAds() {
        /*Создаем межстраничное объявление adMob*/
        adMob = new InterstitialAd(this);
        adMob.setAdUnitId("идентификатор");
        // Создаём запрос к AdMob
        AdRequest adRequesti = new AdRequest.Builder().build();
        // Начинаем загружать объявление
        adMob.loadAd(adRequesti);
        adMob.setAdListener(new AdListener() {
            @Override
            public void onAdLoaded() {
                super.onAdLoaded();
                displayAdMob();
            }
        });
        /*Создаем межстраничное объявление adMob*/
    }
}

A: В onCreate надо добавить проверку переменной, которая принимает значение true или false, в зависимости от того, была уже показана реклама или нет.
Видел код на одном сайте, которую эту проблему обходил созданием в onCreate таймера.


text:
Q: Extra parameters added to webmethods I'm reading some MethodInfo from a proxy generated from a wsdl.
One of the methods has three (int) parameters and a int return type, but when I explore the ParameterInfo[] I actually see eight parameters:

*

*Int32,

*Boolean,

*Int32,

*Boolean,

*Int32,

*Boolean,

*Int32&,

*Boolean&
Where do these extra parameters originate?
UPDATE
To elaborate a bit more, the code in the generated proxy looks as following:
  /// <remarks/>
[System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://tempuri.org/IInleerAppService/AddThreeNumbers", RequestNamespace="http://tempuri.org/", ResponseNamespace="http://tempuri.org/", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
public void AddThreeNumbers(int one, [System.Xml.Serialization.XmlIgnoreAttribute()] bool oneSpecified, int two, [System.Xml.Serialization.XmlIgnoreAttribute()] bool twoSpecified, int three, [System.Xml.Serialization.XmlIgnoreAttribute()] bool threeSpecified, out int AddThreeNumbersResult, [System.Xml.Serialization.XmlIgnoreAttribute()] out bool AddThreeNumbersResultSpecified) {
    object[] results = this.Invoke("AddThreeNumbers", new object[] {
                one,
                oneSpecified,
                two,
                twoSpecified,
                three,
                threeSpecified});
    AddThreeNumbersResult = ((int)(results[0]));
    AddThreeNumbersResultSpecified = ((bool)(results[1]));
}

Why is this?
UPDATE
If you're bugged by this, as I am, you cane easily avoid displaying those extra parameters by simply applying the following snippet of code:
if (!parameterInfo[i].Name.EndsWith("Specified") && !parameterInfo[i].IsRetval && !parameterInfo[i].Name.EndsWith("Result"))
{
    // magic
}

A: I recently found this out for myself. In some cases it has todo with minoccurs=0 in the XSD. The WCF proxy class doesn't use nullable types, so it's not possible for the XmlSerializer to determine whether you want or don't want to send a certain field.
You can set one, but it won't be sent. You also have to set oneSpecified to true to make the serializer serialize the value of one and send it.
Some more info here.


text:
Q: Problem with PSTricks graph I get the error:
    ! Undefined control sequence.<recently read> \c@lor@to@ps }

when trying the following graph
\documentclass[11pt]{article}
\usepackage[usenames,dvipsnames]{pstricks}
\usepackage{epsfig}
\usepackage{pst-grad} % For gradients
\usepackage{pst-plot} % For axes
\usepackage{mathtext}

\begin{document}

\psscalebox{1.0 1.0} % Change this value to rescale the drawing.
{
\begin{pspicture}(0,-2.4101124)(5.36,2.4101124)
\psline[linecolor=black, linewidth=0.04, arrowsize=0.05291666666666667cm     2.0,arrowlength=1.4,arrowinset=0.0]{->}(0.8,-2.3398876)(0.8,2.4601123)
\psline[linecolor=black, linewidth=0.04, arrowsize=0.05291666666666667cm                 2.0,arrowlength=1.4,arrowinset=0.0]{->}(0.4,-1.9398876)(5.2,-1.9398876)
\psline[linecolor=red, linewidth=0.04](1.2,-1.5398877)(4.8,2.0601122)(4.8,2.0601122)
\rput[bl](0.0,2.0601122){\textcolor{red}{f(x)}}
\rput[bl](5.2,-2.3398876){\textcolor{red}{x}}
\end{pspicture}
}

\end{document}

It should be something easy, but I'm not a pro. Please, help me!

A: % compile it with
% pdflatex -shell-escape filename

\documentclass[border=12pt,12pt]{standalone}% change it back to article or whatever you want to use
\usepackage{filecontents}
\begin{filecontents*}{diagram.tex}
\documentclass[pstricks,border=12pt,12pt]{standalone}
\usepackage{pst-plot}
\begin{document}
\begin{pspicture}(-4,-1)(4.5,8.5)
    \psaxes(0,0)(-4,-1)(4,8)[$x$,0][$y$,90]
    \psplot[algebraic]{-2.5}{2.5}{x^2}
\end{pspicture}
\end{document}
\end{filecontents*}

\usepackage{pgffor,graphicx}
\foreach \compiler/\ext in {latex/tex,dvips/dvi,ps2pdf/ps}{\immediate\write18{\compiler\space diagram.\ext}}

\begin{document}
\includegraphics{diagram.pdf}
\end{document}

A: When using PSTricks, you have to use latex or xelatex to compile the image.
If you use TikZ/PGFPlots, you can also use pdflatex:

\documentclass[11pt]{article}
\usepackage{pgfplots}

\begin{document}

\begin{tikzpicture}
\begin{axis}[
    axis lines=middle,
    xmin=0, xmax=10,
    ymin=0, ymax=10,
    enlargelimits,
    xtick=\empty, ytick=\empty,
    axis equal image,
    xlabel=$x$, ylabel=$f(x)$
]
\addplot [red, very thick, domain=1:10] {x};
\end{axis}
\end{tikzpicture}
\end{document}


text:
Q: Bilinear form and cross product in hyperbolic geometry I'm reading Patrick J. Ryan's Euclidean and non-Euclidean geometry, page 152. There is a bilinear form defined by $b\left( {x,y} \right) = {x_1}{y_1} + {x_2}{y_2} - {x_3}{y_3}$ on ${\mathbb{R}^3}$ and a norm defined by $\left| v \right| = {\left| {b\left( {v,v} \right)} \right|^{\frac{1}{2}}}$. Vectors $v,w$ are orthogonal if $b\left( {v,w} \right) = 0$. He uses standard definitions for a normal vector and orthonormal set.
Vector is space-like if $b\left( {v,v} \right) > 0$, time-like if $b\left( {v,v} \right) < 0$ and light-like if $b\left( {v,v} \right) = 0$. Let $\left\{ {{e_1},{e_2},{e_3}} \right\}$ be an orthonormal basis. We want to show that two of those are space-like and one is time-like. It's easy to see that at least one is time-like and at least one is space-like, let those be ${e_1},{e_3}$.
Now, $\left( {{e_1} \times {e_3}} \right) \times {e_2} = 0$ so ${e_2}$ is a multiple of ${{e_1} \times {e_3}}$ and obviously $ - b\left( {{e_1},{e_1}} \right)b\left( {{e_3},{e_3}} \right) = 1$.
However, it is claimed that $b\left( {{e_1} \times {e_3},{e_1} \times {e_3}} \right) =  - b\left( {{e_1},{e_1}} \right)b\left( {{e_3},{e_3}} \right)$.
My question: How do I see that $b\left( {{e_1} \times {e_3},{e_1} \times {e_3}} \right) =  - b\left( {{e_1},{e_1}} \right)b\left( {{e_3},{e_3}} \right)$. I've tried direct algebraic manipulation, the statement is equivalent to $ - 2{x_2}{y_3}{x_3}{y_2} - 2{x_3}{y_1}{x_1}{y_3} + 2{x_1}{y_2}{x_2}{y_1} =  - x_1^2y_1^2 - x_2^2y_2^2 - x_3^2y_3^2$ for $\left| {b\left( {x,x} \right)} \right| = \left| {b\left( {y,y} \right)} \right| = 1$.
Is there an easier way to see this holds?
EDIT: I've just realized by skipping to the text ahead that the cross product with respect to the bilinear form $b$ is not the same as the standard cross product on ${\mathbb{R}^3}$. How would, in general, one find a cross product with respect to the given bilinear form?

A:
I've just realized by skipping to the text ahead that the cross product with respect to the bilinear form b is not the same as the standard cross product on R3. How would, in general, one find a cross product with respect to the given bilinear form?

It's not too hard to answer this, provided one doesn't mind a little abstract linear algebra.
Given a right-handed orthonormal basis $(e_1, e_2, e_3)$ of $\mathbb{R}^3$, we can form the dual basis $(\theta^1, \theta^2, \theta^3)$, and then by construction $\epsilon := \theta^1 \wedge \theta^2 \wedge \theta^3$ is a volume form for the bilinear form $b$, and $\epsilon$ is independent of the basis chosen (if we instead use a left-handed basis, we get the negative of that volume form). We can regard $\epsilon$ as a map $E: \mathbb{R}^3 \times \mathbb{R}^3 \to (\mathbb{R}^3)^*$, namely,
$$(X, Y) \mapsto \epsilon(X, Y, \,\cdot\,)$$
that is, the map that sends the pair $(X, Y)$ of vectors in $\mathbb{R}^3$ to the linear functional $Z \mapsto \epsilon(X, Y, Z)$. Now, we can regard the bilinear form $b$ as an isomorphism $B: \mathbb{R}^3 \to (\mathbb{R}^3)^*$, namely,
$$X \mapsto B(X, \,\cdot\,),$$
that is, the map that sends the vector $X$ to the functional $Z \mapsto B(X, Z)$. Then, the composition $B^{-1} \circ E$ is a map $\mathbb{R}^3 \times \mathbb{R}^3 \to \mathbb{R}^3$, and we can show using these definitions that map this is a cross product compatible with the bilinear form $b$.
Note that this construction works both for the usual cross product and for the cross product you mention (sometimes called a "split" cross product).
Remark There's another natural way to view your (split) cross product, by the way. We can identify $\mathbb{R}^3$ with the space of tracefree $2 \times 2$ matrices (which in this context is sometimes called the algebra of "split quaternions"), namely, those of the form
$$A = \begin{pmatrix} x & y\\ z & -x\end{pmatrix},$$
and this space has a natural nondegenerate quadratic form, namely $$Q(A) := - \det A,$$ and polarizing this quadratic form gives a bilinear form $b$. This form is compatible with the cross product
$$A \times B := -\text{tf}(AB),$$
where $\text{tf}$ denotes the tracefree part; in terms of components, this is
$$\begin{pmatrix} x & y\\ z & -x\end{pmatrix} \times \begin{pmatrix} x' & y'\\ z' & -x'\end{pmatrix} = \begin{pmatrix} -yz' + zy' & - xy' + yx'\\ - zx' + xz' & -(-yz' + zy')\end{pmatrix}.$$

A: Found it on page 137. For given vectors ${u,v}$ and a bilinear form $b$ there exists a unique vector $w$ such that for all $z$ we have
$b\left( {w,z} \right) = \sqrt {\det B} \det \left( {z,u,v} \right)$, where $B$ is a matrix representation of $b$ in any base.
Then we say that $w = u{ \times _b}v$.
For the given bilinear form from the question, we get $u{ \times _b}v = \left| {\begin{array}{*{20}{c}}
  {\mathbf{i}}&{\mathbf{j}}&{ - {\mathbf{k}}} \\
  {{u_1}}&{{u_2}}&{{u_3}} \\
  {{v_1}}&{{v_2}}&{{v_3}}
\end{array}} \right|$.


text:
Q: SAS merging multiple tables I would like to know what is the best way to merge multiple tables. I have a unique identifiers across all the tables. Should I join all the tables in one step after sorting the tables OR should I should do stepwise one by one table merging.
Does this matter ?

A: You can do multiple merges at single step. However, this is not the safest way. If there is possibility that your data is subject to imperfections, it is best to do this step by step. Imho, it is best do merge a step at the time, but it's your call.
proc sort data=data1; by id; run;
proc sort data=data2; by id; run;
proc sort data=data3; by id; run;

data combo;
    merge data1(in=a) data2(in=b) data3(in=c);
    by id;
    if a and b and c; /*Inner join. Change as needed. */
run;

This is equivalent to:
data partial;
    merge data1(in=a) data2(in=b);
    by id;
    if a and b;
run;

data combo;
    merge partial(in=a) data3(in=b);
    by id;
    if a and b;
run,

A: There's no particular reason to do it step-by-step, unless you've got conflicting variable names that you're concerned about resolving, or if your combination logic is complicated and you're worried about confusing something.  There's no functional reason why not, in any event.  merge in SAS is actually somewhat simpler than join in SQL, in particular as the syntax is simpler, so it's somewhat different than the SQL case.


text:
Q: Quasar SSR app, "window is not defined" from vue-router I'm taking a fairly simple Vue app built with Quasar, and adding ssr.
I'm using the Quasar CLI, and added ssr with quasar mode add ssr.  This created the src-ssr/ folder and files as expected.
When I launch it with quasar dev -m ssr, I get:
 App • Opening default browser at http://localhost:9100/

/Users/stevex/src/myapp/node_modules/vue-router/dist/vue-router.cjs:478
    const { history, location } = window;
                                  ^

ReferenceError: window is not defined
    at useHistoryStateNavigation (/Users/stevex/src/myapp/node_modules/vue-router/dist/vue-router.cjs:478:35)
    at createWebHistory (/Users/stevex/src/myapp/node_modules/vue-router/dist/vue-router.cjs:570:31)
    at Module.eval [as default] (/src/router/index.ts:14:14)
    at __vite_ssr_exports__.default (/.quasar/app.js:91:44)
    at async eval (/Users/stevex/src/myapp/.quasar/server-entry.js:86:9)

Node.js v18.7.0

A: Found the problem, it was the history mode.
I was using createWebHistory in routes/index.ts, but for SSR the history mode must be createMemoryHistory.  With that change, the server-side-rendered page loads.
Details here:
https://router.vuejs.org/guide/essentials/history-mode.html#memory-mode
The default createHistory checks for the environment and picks a compatible one; I'd replaced that.  Here's the default, which works:
  const createHistory = process.env.SERVER
    ? createMemoryHistory
    : process.env.VUE_ROUTER_MODE === 'history'
    ? createWebHistory
    : createWebHashHistory;


text:
Q: What do these arp commands mean? Now and then my router displays the following error message in the browser:

This function is to prevent the attack was interrupted when you use the Internet.
Please install to download ARP binding.
This feature will be automatically discharged after you shut down.

And then asks me to run the following commands:
arp -d
arp -s 192.168.1.1 00-17-16-03-37-21

I've checked man arp but I can't quite tell what it does. Any idea what the commands above mean, and whether I should actually run then?

A: This message looks suspicious.
The two commands are asking you to flush the ARP cache (arp -d), and to set as your IP address 192.168.1.1 a pc whose MAC address is 00:17:16:03:37:21
ARP (Address Resolution Protocol) is a key protocol in LANs, helping to associate a MAC address to an IP address (who has 192.168.1.17? Tell 192.168.1.1...). Technically, it translates the network addresses into link layer addresses. This is of utmost importance in networks with many clients (Multiple Access Networks), like LANs.
The commands are asking to throw away what your router has learned, in favor of a new association between MAC address and IP number. It might very well be a trap.
One thing first: is this the exact error message you have seen? Or is it somehow your rough recollection? I am asking this because this error message is extremely poor English, and, if it is the exact message, then the chances of it being bogus are really very high.
Second, the vendor associated with this MAC address (00:17:16) is QnoTechn, a Chinese manufacturer without a proper Web page, according to a Google Search. It may be legitimate.
Third, you can establish whether the message is bogus by checking the MAC address of known, legitimate pcs and routers on your LAN. The commands ipconfig (Windows) and ifconfig (Linux+Mac) [notice the small, critical difference between the two commands] will give you, among other things, the MAC address of all NICs (=Network Interface Card) on your pcs. You ought to check them against 00-17-16-03-37-21, and see who has it.
If no one does, then the message is surely bogus, and you have an unseen client to your network (wireless, most likely, if you are at home). If a pc has it, then that pc has been infected. If the router has it (you can check it from the router's GUI), then it might be genuine.
In any case, I would not follow the advice. Turning the router on and off will instead clear the problem, for the moment at least. You should then start to read about securing your network, because the problem will not simply vanish.


text:
Q: How do I create a function that does a different mathematical operation at different levels of a variable I am creating an R function that needs to adjust the income values for specific years to the 2018 USD value. The previous years are 1972, 1980, 1990, 2000, and 2010. I have a variable in my dataset that is called "year" and a variable called "income".
In the function, I need to use loops to cycle through the years and adjust the income value for each observation within each year to the 2018 USD value. I have the conversion rates for each year, but I am not sure how to create a loop that cycles through each year and does the specific conversion for each year.
This is my first time creating a function and my first time really using loops. I tried to do this but it is not producing any values in my dataframe:
incomeadj=NA
uslop2 <- cbind(uslop, incomeadj)
  adjust_income <- function(uslop2){
    if (uslop2$year == 1972){
      uslop2$incomeadj <- uslop2$income*(251.23/41.8)
    } else {NA}
  }
uslop2$incomeadj

I feel like I can eventually grasp what I need to do, but I am struggling right now. Any help is greatly appreciated.


text:
Q: what is the point of queryBuilder.appendWhere()? android what's the point here to use  queryBuilder.appendWhere()? isn't it much simpler to set the where clause in Cursor cursor = queryBuilder.query()? or the two ways to set the "where" clause are different from each other?
  public Cursor query(Uri uri, String[] projection, String selection,
      String[] selectionArgs, String sortOrder) {

    // Uisng SQLiteQueryBuilder instead of query() method
    SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();

    // Check if the caller has requested a column which does not exists
    checkColumns(projection);

    // Set the table
    queryBuilder.setTables(TodoTable.TABLE_TODO);

    int uriType = sURIMatcher.match(uri);
    switch (uriType) {
    case TODOS:
      break;
    case TODO_ID:
      // Adding the ID to the original query
      queryBuilder.appendWhere(TodoTable.COLUMN_ID + "="
          + uri.getLastPathSegment());
      break;
    default:
      throw new IllegalArgumentException("Unknown URI: " + uri);
    }

    SQLiteDatabase db = database.getWritableDatabase();
    Cursor cursor = queryBuilder.query(db, projection, selection,
        selectionArgs, null, null, sortOrder);
    // Make sure that potential listeners are getting notified
    cursor.setNotificationUri(getContext().getContentResolver(), uri);

    return cursor;
  }

A: You might use appendWhere() if you are building up the pieces of a WHERE clause based on conditions.


text:
Q: How to enable Google map controllers (right,right..etc arrows) I have build an application to search my location.
Here is the code
var map;
var gdir;
var geocoder = null;
var addressMarker;

function initialize() {
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map_canvas"));
        gdir = new GDirections(map, document.getElementById("directions"));
        GEvent.addListener(gdir, "load", onGDirectionsLoad);
        GEvent.addListener(gdir, "error", handleErrors);
        map.setCenter(new GLatLng(51.519853,-0.122566), 14)
        var point = new GLatLng(51.519853,-0.122566); //CHANGE THESE COORDINATES
        map.addOverlay(new GMarker(point));
        map.openInfoWindow(map.getCenter(),html)
    }
}

function setDirections(fromAddress) {
    gdir.load("from: " + fromAddress + " to: 51.519741,-0.122596 ");
}

function handleErrors(){
    if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS) {
        alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
    } else if (gdir.getStatus().code == G_GEO_SERVER_ERROR) {
       alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
    } else if (gdir.getStatus().code == G_GEO_MISSING_QUERY) {
       alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
    } else if (gdir.getStatus().code == G_GEO_BAD_KEY) {
       alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
    } else if (gdir.getStatus().code == G_GEO_BAD_REQUEST) {
       alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
    } else {
       alert("An unknown error occurred.");
    }
}

function onGDirectionsLoad(){}

it is working fine. but there is no navigation keys.
could any one tell me that how can I activate it please

A: If you are trying to put different pan controls on the screen (e.g. the four directional icons commonly found on google maps), you may want to take a look at this control tutorial for version 2 of the Google Maps Javascript API.
Basically, that link describes under what circumstances which controls automatically appear. But, if you want to force controls into your google map, you can do it as follows:
function initialize() {
    //assuming 'map' already exists...
    //add a large pan / zoom control to the map
    map.addControl(new GLargeMapControl());
}


text:
Q: I can't start Cassandra Server in Eclipse( Unknown Commitlog version 4) I'm trying to run Cassandra in eclipse, but I'm getting this exception
java.lang.IllegalStateException: Unknown commitlog version 4Exception encountered during startup: Unknown commitlog version 4

at org.apache.cassandra.db.commitlog.CommitLogDescriptor.getMessagingVersion(CommitLogDescriptor.java:81)
at org.apache.cassandra.db.commitlog.CommitLogReplayer.recover(CommitLogReplayer.java:118)
at org.apache.cassandra.db.commitlog.CommitLogReplayer.recover(CommitLogReplayer.java:93)
at org.apache.cassandra.db.commitlog.CommitLog.recover(CommitLog.java:146)
at org.apache.cassandra.db.commitlog.CommitLog.recover(CommitLog.java:126)
at org.apache.cassandra.service.CassandraDaemon.setup(CassandraDaemon.java:305)
at org.apache.cassandra.service.CassandraDaemon.activate(CassandraDaemon.java:461)
at org.apache.cassandra.service.CassandraDaemon.main(CassandraDaemon.java:504)

What am I doing wrong?

A: Sounds like a version mismatch - possibly from downgrading Cassandra[?]
What version of Cassandra are you using in eclipse? Also, did you have another version running and sharing the same commitlogs? It is likely you have commitlogs from one version of cassandra being read from another. (That was my experience.)
Adding the solution, as provided by @LyubenTodorov in the comments:

To solve this either change your commitlog_directory or empty your current commitlog dir (default is /var/lib/cassandra/commitlog)


text:
Q: How do i delay or buffer the stream of a programs output for a few seconds before it pipes to another program? I want to run a program that will after a few seconds display a generated url in the stderr. I want to then take this url and pass it to my browser. I also want to leave the output of the terminal unchanged, so I use the tee command.
I have already solved all the parsing and piping path by taking the output into a file. But still need to figure out how to link it to the program itself.
michael@DESKTOP-OI3AOU6:~$ ./anaconda3/bin/jupyter lab ~ 2> 1.txt
michael@DESKTOP-OI3AOU6:~$ cat 1.txt
[I 12:02:11.619 NotebookApp] JupyterLab extension loaded from /home/michael/anaconda3/lib/python3.7/site-packages/jupyterlab
[I 12:02:11.620 NotebookApp] JupyterLab application directory is /home/michael/anaconda3/share/jupyter/lab
[I 12:02:11.622 NotebookApp] Serving notebooks from local directory: /home/michael/anaconda3/bin
[I 12:02:11.622 NotebookApp] The Jupyter Notebook is running at:
[I 12:02:11.622 NotebookApp] http://localhost:8888/?token=e48288141f435ebe3008ba9209d2c6d4f456a664bf6aed34
[I 12:02:11.622 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
[C 12:02:11.631 NotebookApp]

    To access the notebook, open this file in a browser:
        file:///home/michael/.local/share/jupyter/runtime/nbserver-2069-open.html
    Or copy and paste one of these URLs:
        http://localhost:8888/?token=e48288141f435ebe3008ba9209d2c6d4f456a664bf6aed34

Then I can pipe it through my chain like so:
michael@DESKTOP-OI3AOU6:~$ cat 1.txt > >(grep ^[[:blank:]].*http.* | tr -d " \t\n\r")
michael@DESKTOP-OI3AOU6:~$ http://localhost:8888/?token=e48288141f435ebe3008ba9209d2c6d4f456a664bf6aed34

And it works wonderfully to pipe the url into my browser with a custom profile set up:
cat 1.txt > >(grep ^[[:blank:]].*http.* | tr -d " \t\n\r" | xargs firefox.exe -P jupyterlab 2> /dev/null)
Putting it all together I get the behaviour I want with the browser launching and the error log showing with:
michael@DESKTOP-OI3AOU6:~$ cat 1.txt > >(tee >(grep ^[[:blank:]].*http.* | tr -d " \t\n\r"| xargs firefox.exe -P jupyterlab 2>/dev/null))
michael@DESKTOP-OI3AOU6:~$ [I 12:02:11.619 NotebookApp] JupyterLab extension loaded from /home/michael/anaconda3/lib/python3.7/site-packages/jupyterlab
[I 12:02:11.620 NotebookApp] JupyterLab application directory is /home/michael/anaconda3/share/jupyter/lab
[I 12:02:11.622 NotebookApp] Serving notebooks from local directory: /home/michael/anaconda3/bin
[I 12:02:11.622 NotebookApp] The Jupyter Notebook is running at:
[I 12:02:11.622 NotebookApp] http://localhost:8888/?token=e48288141f435ebe3008ba9209d2c6d4f456a664bf6aed34
[I 12:02:11.622 NotebookApp] Use Control-C to stop this server and shut down all kernels (twice to skip confirmation).
[C 12:02:11.631 NotebookApp]

    To access the notebook, open this file in a browser:
        file:///home/michael/.local/share/jupyter/runtime/nbserver-2069-open.html
    Or copy and paste one of these URLs:
        http://localhost:8888/?token=e48288141f435ebe3008ba9209d2c6d4f456a664bf6aed34

The problem occurs when I attatch my program to the pipe. It takes a few seconds to initialize the server and feed the output. The tr command ends up just pushing forward an empty string to the browser before the correct line is recieved by grep.
michael@DESKTOP-OI3AOU6:~$ ./anaconda3/bin/jupyter lab ~ 2> >(tee >(gre
p ^[[:blank:]].*http.* | tr -d " \t\n\r"| xargs firefox.exe -P jupyterlab 2>/dev/null))
It works up to grep, but the url will only show after a few seconds once it loads:
michael@DESKTOP-OI3AOU6:~$ ./anaconda3/bin/jupyter lab ~ 2> >(grep ^[[:blank:]].*http.*)
        http://localhost:8888/?token=6988d45b9baa2e9f07c5a91a9a91457d6119e9884bdbcb10

Nothing shows up after I tr it.
michael@DESKTOP-OI3AOU6:~$ ./anaconda3/bin/jupyter lab ~ 2> >(grep ^[[:blank:]].*http.* | tr -d " \t\n\r")
How do I make the command (grep) wait a few seconds before it sends it to the next command in the stream chain (tr)?

A: I was able to solve the problem by making it simpler, and saving the output to a temp file instead of trying to pipe it all at once.
michael@DESKTOP-OI3AOU6:~$ ~/anaconda3/bin/jupyter lab ~ 2> >(tee /tmp/jlab ) & sleep 4 ; cat /tmp/jlab | grep ^[[:blank:]].*http.* | tr -d " \t\n\r" | xargs firefox.exe -P jupyterlab ; rm /tmp/jlab; %
Going through each section line by line for others reference:

~/anaconda3/bin/jupyter lab ~  →  Run a jupyter lab session in the home directory (~).

2>  →  Pipe the standard error into the file follows it.

>()  →  Allow pipes going into files to be directed into standard input of command enclosed.
tee /tmp/jlab   →  Redirect the input to a temporary file jlab and copy it to the standard output. This is how I retain the behavior of the original program showing the information in the terminal. More info https://en.wikipedia.org/wiki/Tee_(command)
>(tee /tmp/jlab )  →  The output is piped into the tee command

&  →  Allow process to continue running in the background.

sleep 4  →  Wait 4 seconds for the server to spin up.

;  →  After command executes next command

cat /tmp/jlab  →  Catenate the contents of the temporary file /tmp/jlab into the standard output.

|  →  Pipe the standard output of the program to the left to the standard input of the pogram to the right. In this case cat /tmp/jlab into grep ^[[:blank:]].*http.*.

grep ^[[:blank:]].*http.*   →  Extracts the lines that have space a space in the beginning and has http contained on the line. It will allow any amount of charachters in between and after. In this case it workes out really nicely, but if by chance an update to jupyter changes the output this is where it would break and a more appropriate regex will be chosen.

| output of grep piped to tr

tr -d " \t\n\r"  →  Removes all tabs spaces and line breaks from the line.

| Pipes output of tr to xargs. This is the complete url unique to the jupyter session.

xargs firefox.exe -P jupyterlab  →  Xargs takes its standard input and feeds it as an argument to the following command.

In this case firefox.exe which is a soft link which i stored in /usr/local/bin/firefox.exe the soft link points to the mounted windows location /mnt/c/ which resides at /mnt/c/Program Files/Mozilla Firefox/Firefox.exe. The reason i mount it this way is just my convention as windows executables have better rendering than programs executed in the WSL and ran through an xming.
-P jupyterlab  →  launches a profile I made which removes the tabs and navigation bar from firefox. I also accessed the customize option in firefox so the titlebar is showing.
The profile is set up by setting a custom css in the specific profile directory %APPDATA%\Mozilla\Firefox\Profiles\
The full path of the file is %APPDATA%\Mozilla\Firefox\Profiles\8vv7gs2r.jupyterlab\chrome\userChrome.css
This file will set firefox so it will have no tabs or navigation cluttering the window.
The contents of the file are as follows:
/*
 * Do not remove the @namespace line -- it's required for correct functioning
 */
@namespace url("http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"); /* set default namespace to XUL */

/*
 * Hide tab bar, navigation bar and scrollbars
 * !important may be added to force override, but not necessary
 * #content is not necessary to hide scroll bars
 */
#TabsToolbar {visibility: collapse;}
#navigator-toolbox {visibility: collapse;}

;  →  After command executes next command

rm /tmp/jlab  →  Boiler plate line which remove the temporary file. It usually should be deleted on reset of the linux system, but it does not work in all implementations. I have not checked about whether wsl does it.

;  →  After command executes next command

%  →  Moves the last job moved in the background with & to the foreground. The program now executes will now take interrupts as it did before it was moved to the background.

A: You could easily do a trick like this :
$ echo "hello world" | { read test && sleep 2 && echo $test; } | xargs echo


text:
Q: Perl Shell Wrapper for piping scripts and commands I'm working on a bioinformatics project that involves piping together different scripts and input parameters for the analysis of Next-Gen Sequencing Illumina data. I need help with the wrapper script. Recall that a wrapper is a shell script that embeds a system command or utility, that accepts and passes a set of parameters to that command. Wrapping a script around a complex command-line simplifies invoking it.
Here's a minimal representation of the code:
#!/usr/bin/perl
use strict; use warnings;

my $barcode_file= shift;
unless($barcode_file){
    die "missing barcode file location, aborting.\n";
}

my $raw_data_location = '/data/local/samples/';
my $components_location= '~/read_cleanup/';
my $tmp_dir= '/tmp/';

open (FILEIN, $barcode_file) or die "couldn't open $barcode_file for read: $!\n";

while(<FILEIN>){
# input file format (tab delimited):
# Sample_Name    barcode    enzyme    size    paired    seq_file

    /^$/ and next; chomp;

    my ($sample, $barcode, $enzyme, $size, $pe, $seq_file)= split;

    $raw_file_data = "${raw_data_location}$seq_file"; #/data/local/samples/301.fq for instance

    # final output file
    my $final_output_file = "${tmp_dir}${sample}_reconciled_ends.fq"; # /tmp/D1_reconciled_ends.fq for instance

    # if the sample is paired ( 1 - paired, 0 - unpaired)
    if ($pe) {
        my $pipe_cmd= "${components_location}script01.pl $raw_data_file $barcode | ${components_location}script02.pl $enzyme | ${components_location}script03.pl  $size > $final_output_file";
    }
    system($pipe_cmd);

# at this point, $final_output_file should be saved in the
# tmp folder and contain the paired fastq data output

}
close (FILEIN);

Basically the wrapper reads the barcode.txt file and loops through each line (sample name) of the file. For each sample name, it generates the input parameters for each script in the the piped run. If the sample is paired data, then we do a piped run. The piping scheme goes like this:
# the input parameters are "fed" into the script and the output is piped
# as STDIN to the next script.
script01.pl [input parameters] | script02.pl [input parameters] | script03.pl [input parameters] > file.txt

system($piped_cmd) executes the piped run in the terminal.
Here's where I'm getting trouble, when I try to run the wrapper script from the terminal:
./wrapper_example.pl barcode.txt
It returns the following error message:
sh: 1: /home/user/read_cleanup/script01.pl: not found
Does anyone know what's wrong or how to fix this? thanks. Any suggestions are greatly appreciated.

A: Well, system() syntax is system("$command","$args1","$args2") OR system(@command) where @command=("$command","$arg1","$arg2"). I would rather use back ticks to run the whole chain of commands like-
if ($pe) {
    `perl ${components_location}script01.pl $raw_data_file $barcode | perl ${components_location}script02.pl $enzyme | perl ${components_location}script03.pl  $size > $final_output_file`;
}

A: Most likely, /home/user/read_cleanup/script01.pl is not an executable, OR its shebang (first line starting with #!) points to the wrong Perl. It's kind of difficult to troubleshoot further without a bit more details.


text:
Q: How change a string looks like array to a real aray I have a string, it looks like a array but not a real array. So my question is how to make it to a real array.
let string = "["abc", "cde"]";
// how to make string become an array

change string to an array

A: First you need to make sure your string is invalid format
"["abc", "cde"]" // invalid
"[abc, cde]" // invalid
"[11, 22]" // valid,if you do not want to use quote to wrap it,then the elements need to be number
"['abc', 'cde']" // valid

let string = `["abc", "cde"]`
const array = JSON.parse(string)
console.log(array)

A: You can do something like this

let data = "['abc', 'pqr', 'xxx']";
data = data.replace(/'/g, '"');
console.log(data)
const convertedArray = JSON.parse(data);
console.log(convertedArray)

A: Observation : Your input string is not a valid JSON string.
Solution : Double quotes besides the array items should be escaped to parse it properly. Your final string should be.
let string = "[\"abc\", \"cde\"]";

Now you can parse it using JSON.parse() method.
Live Demo :

let string = "['abc', 'cde']";
string = string.replace(/'/g, '"');
console.log(string); // "[\"abc\", \"cde\"]"
console.log(JSON.parse(string)); // ["abc", "cde"]


text:
Q: Why doesn't it work to append information in the exception message? Why doesn't this work?
try:
    1/0
except ZeroDivisionError as e:
    e.message += ', you fool!'
    raise

The modified message is not used, even though it remains on the exception instance.  Is there a working pattern for the above?  Behaviour should be like my current workaround below:
try:
    1/0
except ZeroDivisionError as e:
    args = e.args
    if not args:
        arg0 = ''
    else:
        arg0 = args[0]
    arg0 += ', you fool!'
    e.args = (arg0,) + args[1:]
    raise

I'm aware of exception chaining in python3, it looks nice but unfortunately doesn't work in python2.  So what is the usual recipe for re-raising an exception in python2?
Note:  Because of the warnings and caveats mentioned here, I don't want to dig up the traceback and create a new exception but rather re-raise the existing exception instance.

A: Changing e.args is the only way to do this.  The implementation for BaseException.__str__ only considers the args tuple, it doesn't look at message at all:
static PyObject *
BaseException_str(PyBaseExceptionObject *self)
{
    PyObject *out;

    switch (PyTuple_GET_SIZE(self->args)) {
    case 0:
        out = PyString_FromString("");
        break;
    case 1:
        out = PyObject_Str(PyTuple_GET_ITEM(self->args, 0));
        break;
    default:
        out = PyObject_Str(self->args);
        break;
    }

    return out;
}

This shouldn't be too unexpected, since BaseException.message is deprecated since Python 2.6.

A: I don't think there's going to be a better solution than your workaround. ZeroDivisionError doesn't use the message property to build its output, so modifying that will have no effect.
If you're specifically catching a ZeroDivisionError it should always have a single argument so the following more succinct version will work:
try:
    1/0
except ZeroDivisionError as e:
    e.args = (e.args[0] + ', you fool!',)
    raise

If you check the properties of ZeroDivisionError, all it has are args and message and it doesn't use message so short of creating a new error, modifying args is pretty much the only possible solution.


text:
Q: Can't get PHP script to run when launched from Aptana Studio I've been using notepad++ for web development (currently html, css, and some php and mysql). I decided to dive into an IDE to see if I could cut down on development time and have more power than notepad++.
I grabbed Aptana yesterday and, after harassing it for a few hours, have finally gotten everything up and running. The only problem is that my web pages, which are .php's, do not execute any of their included .php code in the browser.
as an example:
<?php
echo "IT WORKS WOOO";
?>

ought to print IT WORKS WOOO smack in the middle of my blank test page, and yet it does not. I checked to see if I had somehow forgotten how to do an echo statement and ran it on my desktop, using notepad++, and it worked just fine.
I have the php plugin, have used the php perspective to write it and have launched it as a php web page, but nothing makes it execute the php within.
Any ideas?

A: You're going to want to run through the setup for the PHP Plugin again, to make sure you configured everything correctly.
I use an external WAMP server, as I can better mirror the environment I am developing for. They have a guide on how to set that up, too.


text:
Q: Windows 10 running slow Windows 10 running slow sometimes or hang. Task managers shows disk 100% usage.
My laptop configuration;
1) Operating System
Windows 10 Home Single Language 64-bit

2) CPU
Intel Core i7 5500U @ 2.40GHz
Broadwell-U 14nm Technology

3) RAM
16.0GB Dual-Channel DDR3 @ 798MHz (11-11-11-28)

4) Motherboard
Dell Inc.

5) Graphics
Generic PnP Monitor (1600x900@60Hz)
Intel HD Graphics 5500 (Dell)
4095MB NVIDIA GeForce 920M (Dell)
ForceWare version: 353.62
SLI Disabled

6) Storage
1863GB Seagate ST2000LM003 HN-M201RAD (SATA)

7) Optical Drives
PLDS DVD+-RW DU-8A5LH

8) Audio
Realtek High Definition Audio

A: Run a tool named Sysinternals Process Explorer.
After you have started Process Explorer, click on the View menubar item and then Select Columns.

Click on the Process I/O tab and check:

*

*Read Bytes

*Write Bytes

*History

Hit OK.
You will see a separate chart of I/O activity for each process under I/O History column and amount of data read and written. It is not only disk activity, see here, but most of it should be disk or network activity, so you can try to disconnect from network to see only disk activity.
There you should determine, which process is eating your disk performance. Usually that process would also consume some significant processor time.

Some services are reported that can cause 100% disk usage. You can try to stop them one by one using following commands and see if it helps:
net.exe stop WSearch
net.exe stop Superfetch
net.exe stop Bits

You should also scan your PC with MBAM Antimalware.


text:
Q: how to insert Hex as argument to gdb? (as arg, not as stdin) I want to do the next bash command, but actually in gdb (so i can debug it):
myProgram "`echo -en '\x41\x41\x41\x41'`"

I'm trying to do this (in gdb):
(dbg) run "`echo -en "\x41\x41\x41\x41"`"

i DON'T mean the stdin redirect:
echo -en "\x41\x41\x41\x41" > command_output.txt
gdb myProgram
(gdb) run < command_output.txt

how to insert Hex values as an agrument to a program in gdb?

A: you may try
(dbg) run $(echo -en "\x41\x41\x41\x41")

A: The gdb set args command can set the arguments. Using eval, which runs its arguments through printf, we can insert almost arbitrary characters using hex escapes. (We're limited by the fact that gdb will typically invoke the target using a shell, so it helps to add single quotes around each argument).
(gdb) eval "set args '%s'", "\x41\x41\x20\x41"
You can't do that without a process to debug.

That's another gdb limitation. An alternative that doesn't make gdb want to allocate memory in the target is to give eval only %c conversions and integer arguments, like this:
(gdb) eval "set args '%c%c%c%c'", 0x41, 0x41, 0x20, 0x41

But having to put the exact number of %c conversions into that format string is tedious, so let's stick with the single %s. We need to start the process, even though we're going to restart it right after we set the args using eval.
(gdb) start
Starting program: /home/mp/argprint

Temporary breakpoint 1, main (argc=1, argv=0x7ffffffee2b8) at argprint.c:4
4               for(int i=0; i < argc; i++) {

(gdb) eval "set args '%s'", "\x41\x41\x20\x41"
(gdb) run
The program being debugged has been started already.
Start it from the beginning? (y or n) y
Starting program: /home/mp/argprint 'AA A'
arg 0 is <</home/mp/argprint>>
arg 1 is <<AA A>>

If you have an old gdb that doesn't have the eval command but does have Python, you can do this:
(gdb) python gdb.execute("set args '\x41\x41\x20\x41'")


text:
Q: Need help constructing json with PHP I want the following json data created with php.
I'am getting the required values from my database.
JSON i want to output(I created it manually to show):
{
   "room":[
      {
         "id":"1",
         "temp":"20"
      },
      {
         "id":"2",
         "temp":"30"
      }
   ]
}

Current PHP:
 $rows = array();
    if(!$allData->count()) {
        echo 'No results!';
    } else {
        foreach ($allData->results() as $allData) {
            $rows['id'] = $allData->id;
            $rows['data'] = $allData->temp;
        }
    }

// echo out as json data
    echo '{"rom":'.json_encode($rows).'}';

This is what my current PHP script outputs:
{"rom":{"id":"2","data":"20"}}

JSON formatted:
{
   "rom":{
      "id":"2",
      "temp":"30"
   }
}

As you can see it outputs only the last id and temp values..
I can't seem to find out what I'am doing wrong, any help is greatly appreciated.

A: You are missing one dimension in your array:
$rows = array();
if(!$allData->count()) {
    echo 'No results!';
} else {
    foreach ($allData->results() as $allData) {
        $rows[] = [
           'id' => $allData->id,
           'data' => $allData->temp,
        ];
    }
}

A: Consider this:
$rows[] = ["id"=>$allData->id, "data"=>$allData->temp];

I n this way you never overwrite previous data