text:
Q: Cannot run Bamboo build specs on Docker in Windows 10 When I run process Bamboo build specs in Docker container, I have error about missing/invalid path.
I have local installation of Bamboo 6.9.1 in Windows 10 machine.
Docker 18.09.2 with Hyper-V containers (default option)

docker settings:
-expose daemon on port 2375 without TLS
-local drive C: shared to container
In Bamboo - repository Stored Specs security settings :
Enable Repository Stored Specs - checked
Process Bamboo Specs in Docker -checked
Docker image(required) : 'atlassian/bamboo-specs-runner:6.9.1'.
When i'm trying to process build specs, I have error:
Processing Specs within Docker containerUnable to scan repository bamboo-specs gh (753665) for Bamboo Specs
com.atlassian.bamboo.repository.RepositoryException: Unable to scan repository bamboo-specs gh (753665) for Bamboo Specs
    at com.atlassian.bamboo.configuration.external.RepositoryStoredSpecsServiceImpl.lambda$runSpecsWithDocker$9(RepositoryStoredSpecsServiceImpl.java:864)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at com.atlassian.bamboo.utils.BambooRunnables$1.run(BambooRunnables.java:48)
    at com.atlassian.bamboo.security.ImpersonationHelper.runWith(ImpersonationHelper.java:26)
    at com.atlassian.bamboo.security.ImpersonationHelper.runWithSystemAuthority(ImpersonationHelper.java:17)
    at com.atlassian.bamboo.security.ImpersonationHelper$1.run(ImpersonationHelper.java:41)
    at java.lang.Thread.run(Thread.java:748)
Caused by: com.spotify.docker.client.exceptions.DockerRequestException: Request error: POST http://localhost:2375/containers/create?name=bamboo-specs-685e946f-716d-4b1d-a92e-35c3aa66aa42: 400, body: {"message":"the working directory '\\mnt\\input' is invalid, it needs to be an absolute path"}

A: Please verify with the development team that Docker on Windows is supported. While Windows does support windows, it requires different images and the Bamboo server code needs to be adapted as well.


text:
Q: Passing time from TIBCO to Salesforce Classic We have passed a time 17:40:12 from TIBCO to Salesforce Classic, but Salesforce Classic received it as 17:40:12.000 (When checked on Edit Mode) but not 17:40:12 and displays 5:40 PM.
Our locale  English (Australia) - AUD. Our Default Timezone is (GMT+10:00) Australian Eastern Standard Time (Australia/Sydney).
Why does Salesforce change the time format? Any explanation on this?
Note: I have tested this on Salesforce Lightning when typed in 17:40:12 it does accept and display 17:40:12 (HH:MM:SS) format.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to write a shell script that shows just the content of the files with more than 8 lines from the current directory? I'm new in shell scripting. How can I write a shell script that shows just the content of the files with more than 8 lines from the current directory (in Ubuntu)?
I know that I must use the command head and take a for that goes through all the files and also a counter that will increase every time when a file have more than 8 lines, but something is going wrong. When I execute the script, this doesn't produce the output it is supposed to produce.
 #!/bin/bash
 for fis in *
 do
    cat $fis
    head -8 $fis
 done

   contor=0
   while [ contor -le 100 ]
   do
        echo $contor
        contor=`expr $contor + 1`
   done

A: Here is a very simple solution:
for f in *
do
    if [ $(wc -l "$f" | awk '{print $1}') -gt 8 ]; then
        cat "$f" # print the file content
        #echo $f # print the filename
    fi
done

The command wc -l $f | awk '{print $1}' returns the number of lines of the file and the conditional validates if it is greater than 8. If you're just going to print the content of the file, consider use the command 'more' instead of cat.


text:
Q: Process returned -1073741571 (0xC00000FD) on my c++ code The c++ code below works fine for some inputs, but it is stuck at test 9 (number of inputs here is 6000) where it gives me this message "Process returned -1073741571 (0xC00000FD)".
This code reads information for n babies (their gender and name). Next it counts the appearances of each name then sorts the list of structures according to the appearances. Finally, it removes the duplicates and prints the top m female names and top m male names.
What does this error mean and what do I need to change to eliminate this error?
#include <iostream>
#include <fstream>
#include <algorithm>
#include <string.h>

using namespace std;
ifstream fin("input.txt");
struct baby
{
    string gender,name;
    int cnt;
};
bool cmp(baby a,baby b)
{
    if (a.cnt>b.cnt)
        return true;
    else if (a.cnt==b.cnt && a.name<b.name)
        return true;
    return false;
}
int howmany(baby babies[],int n,int i)
{

    int cnt=0;
    for (int j=0; j<n; j++)
    {
        if (babies[i].name==babies[j].name && babies[i].gender==babies[j].gender)
        {
            cnt++;
        }
    }
    return cnt;
}
void getData(baby babies[],int n)
{
    for (int i=0; i<n; i++)
    {
        fin>>babies[i].gender>>babies[i].name;

    }
}
int removeDuplicates(baby babies[],int n)
{
    int j=0;
    for (int i=0; i<n-1; i++)
    {
        if (babies[i].name!=babies[i+1].name)
            babies[j++]=babies[i];
    }
    babies[j++]=babies[n-1];
    return j;
}
int main()
{
    int n,i,top,j;
    fin>>n>>top;
    baby babies[50000];
    getData(babies,n);
    for (i=0; i<n; i++)
    {
        babies[i].cnt=howmany(babies,n,i);
    }
    sort(babies,babies+n,cmp);
    j=removeDuplicates(babies,n);
    int cnt=0;
    for (int i=0; i<j; i++)
    {
        if (cnt<top)
        {
            if (babies[i].gender=="F")
            {
                cout<<babies[i].name<<" ";
                cnt++;
            }
        }
    }
    cout<<endl;
    cnt=0;
    for (int i=0; i<j; i++)
    {
        if (cnt<top)
        {
            if (babies[i].gender=="M")
            {
                cout<<babies[i].name<<" ";
                cnt++;
            }
        }
    }
    return 0;
}

A: As you can see in Window's NT status reference, error code 0xC00000FD means stack overflow (usually caused by infinite recursion). In your case, it seems that you simply allocate a far too large array on the stack (line 57, baby babies[50000];), which is an array of size 50000*20=1000000. The simplest solution will be a dynamic allocation
baby* babies = new baby[50000];
// Your code here
delete[] babies;

A better solution would be to use std::vector which is a dynamic array that can grow and shrink. The simplest thing to do is to take a vector of size 50000, this way:
#include <vector>
...
std::vector<baby> babies(50000);

However, this is a poor solution as your pre-allocate 50000 elements even though you probably need much much less, and a better solution would be to add an element on-demand, using .push_back(element) method, or in your case, allocate n elements to the vector (impossible in a stack-allocated array).
I added your code with some modifications of mine:
#include <vector>
#include <iostream>
#include <fstream>
#include <algorithm>

using namespace std;
ifstream fin("input.txt");

struct baby
{
    string gender;
    string name;
    int cnt = 0;
};

bool cmp(const baby& a, const baby& b)
{
    if (a.cnt > b.cnt) {
        return true;
    }
    return a.cnt == b.cnt && a.name < b.name;
}

bool are_equal(const baby& lhs, const baby& rhs)
{
    return lhs.gender == rhs.gender && lhs.name == rhs.name;
}

int howmany(const std::vector<baby>& babies, int i)
{

    int cnt = 0;
    for (int j = 0; j < babies.size(); j++)
    {
        if (babies[i].name == babies[j].name && babies[i].gender == babies[j].gender)
        {
            cnt++;
        }
    }
    return cnt;
}

void getData(std::vector<baby>& babies)
{
    for (int i = 0; i < babies.size(); i++)
    {
        fin >> babies[i].gender >> babies[i].name;
    }
}

int removeDuplicates(std::vector<baby>& babies)
{
    int j = 0;
    for (int i = 0; i < babies.size() - 1; i++)
    {
        if (babies[i].name != babies[i + 1].name) {
            babies[j++] = babies[i];
        }
    }
    babies[j++] = babies.back();
    return j;
}

void remove_duplicates_improved(std::vector<baby>& babies)
{
    babies.erase(babies.begin(), std::unique(babies.begin(), babies.end(), are_equal));
}

int main()
{
    int n;
    int top;
    fin >> n >> top;
    std::vector<baby> babies(n);
    getData(babies);
    for (int i = 0; i < n; i++)
    {
        babies[i].cnt = howmany(babies, i);
    }
    sort(babies.begin(), babies.begin() + n, cmp);

    remove_duplicates_improved(babies);
    int cnt = 0;
    for (int i = 0; i < babies.size(); i++)
    {
        if (cnt < top)
        {
            if (babies[i].gender == "F")
            {
                cout << babies[i].name << " ";
                cnt++;
            }
        }
    }
    cout << endl;
    cnt = 0;
    for (int i = 0; i < babies.size(); i++)
    {
        if (cnt < top)
        {
            if (babies[i].gender == "M")
            {
                cout << babies[i].name << " ";
                cnt++;
            }
        }
    }
    return 0;
}

Good luck


text:
Q: Getting to the data before your browser :) Is it possible to write a program to retrieve data coming in on a socket change it and then send it to the browser and vice versa.

A: What it sounds like is what fiddler does. I don't know if you can get the source code for it, but it might give you a place to start looking as to how it works.
Looks like you can use Fiddler Core to do what you want. If you want to totally write it from scratch this might give some insight, if not you maybe able to leverage this.

A: what you want is a squid proxy.
AdZap uses squid to do this.


text:
Q: How can I override quarkus.security.users.embedded.users on docker run command line? I have a quarkus based webapp that uses Basic Authentication with Embedded Realm Configuration. The webapp runs in a docker container. The authentication properties are specified in application.properties like this:
quarkus.http.auth.basic=true

quarkus.security.users.embedded.enabled=true
quarkus.security.users.embedded.plain-text=true
quarkus.security.users.embedded.users.test=mypass
quarkus.security.users.embedded.roles.test=admin

I would like to override quarkus.security.users.embedded.users.test to specify a password at docker runtime.
I tried to do this by overriding the quarkus property using an environment variable at docker runtime.
docker run -p 9999:9999 -e QUARKUS_SECURITY_USERS_EMBEDDED_USERS_TEST=newpasswd mywebapp

This does not work. When I access mywebapp using http://locahost:9999 I must login using test/mypass. I expected to login using test/newpasswd.
Any help greatly appreciated.

A: I suggest you report an issue for this problem. While Quarkus won't be able to "enumerate" any new users from environment variables (the correct property names cannot be deduced), I think it should still be possible to override the password of a user that has already been specified in application.properties using an environment variable like you try to do.


text:
Q: Unable to read repository at http://download.oracle.com/otn_software/oepe/juno/content.xml. Received fatal alert: protocol_version Tried to install glassfish server tools in eclipse juno but i was unable to and got this error message Unable to read repository at http://download.oracle.com/otn_software/oepe/juno/content.xml.
Received fatal alert: protocol_version
Help
i use java 6
Thanks


text:
Q: Infinite scroll with puppeteer I am trying to scrape the data from this page. The page has infinite scroll within an element in the DOM. I have the following puppeteer script to scroll all the way to the bottom to reveal all data so that I can scrape it. The first page.evaluate call is working as expected, scrolling to the bottom and revealing the further contents. However, subsequent calls are not working. I have tried using await page.waitFor(2000); to wait before I can scroll further but it does not seem to work. Kindly help someone!
// this script parses the data from http://covid.rcmedicrew.org/ using their /scripts/getSearch.php API
// install nodejs then npm install axios
const puppeteer = require('puppeteer');

const siteURL = "https://www.powerbi.com/view?r=eyJrIjoiOTcyM2JkNTQtYzA5ZS00MWI4LWIxN2UtZjY1NjFhYmFjZDBjIiwidCI6ImQ1ZmE3M2I0LTE1MzgtNGRjZi1hZGIwLTA3NGEzNzg4MmRkNiJ9";

async function callPowerBiApi(apiUrl) {
  const browser = await puppeteer.launch({headless: false, args: ['--auto-open-devtools-for-tabs']});
  // const browser = await puppeteer.launch({headless: false});
  const page = await browser.newPage();
  page.setDefaultNavigationTimeout(0);
  await page.goto(apiUrl, {waitUntil: 'networkidle0', timeout: 0});
  await page.waitForSelector('.innerContainer');

  await page.evaluate(() => document.querySelectorAll(".innerContainer")[1].querySelector(".bodyCells>div>div div:last-child").scrollIntoView());
  //await page.waitFor(2000);
  await page.evaluate(() => document.querySelectorAll(".innerContainer")[1].querySelector(".bodyCells>div>div div:last-child").scrollIntoView());
  await page.evaluate(() => document.querySelectorAll(".innerContainer")[1].querySelector(".bodyCells>div>div div:last-child").scrollIntoView());
  await page.evaluate(() => document.querySelectorAll(".innerContainer")[1].querySelector(".bodyCells>div>div div:last-child").scrollIntoView());
  await page.evaluate(() => document.querySelectorAll(".innerContainer")[1].querySelector(".bodyCells>div>div div:last-child").scrollIntoView());
  await page.evaluate(() => document.querySelectorAll(".innerContainer")[1].querySelector(".bodyCells>div>div div:last-child").scrollIntoView());
}()

A: I was scrolling to the wrong element, fixed it by using:
await page.evaluate(() => document.querySelectorAll(".innerContainer")[1]
    .querySelector(".bodyCells>div div:last-of-type div:last-of-type div:last-of-type")
    .scrollIntoView()
);

However, it seems that the previous results are getting cleared when you scroll down so will need another strategy to scrape it all.


text:
Q: Where are importScripts files loaded from? The MDN definition is pretty short:

The importScripts() method of the WorkerGlobalScope interface imports one or more scripts into the worker's scope.

When using importScripts("foo.js"), where is foo.js loaded from? I would like to know what happens in the following cases:

*

*foo.js is not cached and not loaded on page by someone else. Is foo.js loaded from disk?

*foo.js is cached. Probably it's loaded from cache, right?

*foo.js is loaded on page already (using <script src="foo.js"></script>). Is foo.js loaded from memory? If not, where is it loaded from?


text:
Q: VBA Code for Saving a workbook on to a networked drive Hi i am using this VBA code to save a Excel Workbook:
Sub Button10_Click()
    Dim SaveName As String
       SaveName = ActiveSheet.Range("N2").Text
       ActiveWorkbook.SaveAs Filename:="z:\" & _
           SaveName & ".xlsm"
End Sub

This code works once i open the template and commit the first save but when i make changes to that workbook and try to save it wont allow me to overwrite and gives me a 1004 Error.
But when i open the template again and put the same FileName it lets me overwrite by giving me a prompt box.
Is there a way i can get it to overwrite?
Oh and cel N2 is the concatenate of B2 and B3 which is the site name and the date with a "-" in between if this is causing the problem.
Thanks in advance for your help
What i have done to resolve the problem for myself:
Adapted the workbook to remove any spaces in the fileName
SaveName is nowWeeklyTakingsv9 but gets changed from siteName(B2)-WeekendingDate(B3) Site name takes white spaces out putting "_"
I tried trimming But client whats the fileName to be a specific SiteName to the date of the week end.
Attempted to create a work around so the dialog box would open giving the fileName and the Networked drive location but this would not work on clients machines
Further details of what its doing
I have 26 Client sites (Library's)
each site has its own networked drive connected to SharePoint
What i have done is set up each networked drive connected to there sharepoint library
i Set the drive letter to Z as to not Interfere with they're own network set up
So that i dont have to create 26 workbooks i have got to this point where it will save once but they need to go into the workbook every day and make changes.
So when the workbook is opened B2-B3 arent changed so the fileName is the same but it does not let me overwrite what is there
SharePoint is NOT the problem here its the overwrite problem i am having on Excel

A: I use network saving all the time within the organisation i work for.
Only use SaveAs when saving as a new file.
When you want a workbook to save itself over itself i have found the following code successful:
Application.DisplayAlerts = False
ThisWorkbook.Save

Note that this code is executed every 30 seconds or so each time the user clicks (file is used 24 hours a day!), and it hasnt failed since it was implemented (oct 2013).
Good Luck.


text:
Q: StreamBuilder does not listen / update I have one widget which has a public stream. In another widget, I want to update my UI depending on the stream's data. So I wrapped the stream with a StreamBuilder as usual.
In this case, the StreamBuilder doesn't update but I can see the print output.
My code looks like this (the original code is more complex):
class WidgetA extends StatefulWidget {
  final _WidgetAState _state = _WidgetAState();

  Stream<String> get stream => _state?._subject?.stream;

  @override
  _WidgetAState createState() => _state;
}

class _WidgetAState extends State<WidgetA> {
  final BehaviorSubject<String> _subject = BehaviorSubject<String>();

  @override
  Widget build(BuildContext context) {
    return Container(
      child: FlatButton(
        child: const Text('click'),
        onPressed: () => _subject.add(DateTime.now().toString()),
      ),
    );
  }

  @override
  void dispose() {
    _subject.close();
    super.dispose();
  }
}

class WidgetB extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final WidgetA widgetA = WidgetA();
    widgetA.stream.listen((value) => print('value: $value'));

    return Column(
      children: <Widget>[
        widgetA,
        StreamBuilder<Object>(
          stream: widgetA.stream,
          builder: (_, snapshot) => Text('data: ${snapshot.data}'),
        ),
      ],
    );
  }
}

When I wrap the stream with another stream, it works.
class WidgetB extends StatefulWidget {
  @override
  _WidgetBState createState() => _WidgetBState();
}

class _WidgetBState extends State<WidgetB> {
  final WidgetBBloc bloc = WidgetBBloc();

  @override
  Widget build(BuildContext context) {
    final WidgetA widgetA = WidgetA();
    bloc.init(stream: widgetA.stream);
    bloc.stream.listen((value) => print('value: $value'));

    return Column(
      children: <Widget>[
        widgetA,
        StreamBuilder<Object>(
          stream: bloc.stream,
          builder: (_, snapshot) => Text('data: ${snapshot.data}'),
        ),
      ],
    );
  }
}

class WidgetBBloc {
  Stream<String> get stream => _subject.stream;
  final BehaviorSubject<String> _subject = BehaviorSubject<String>();

  void init({@required Stream<String> stream}) {
    assert(stream != null);
    stream.listen((String s) => _subject.add(s));
  }

  void dispose() {
    _subject.close();
  }
}

Why is the StreamBuilder of the first version not updating?


text:
Q: An error occurred while updating the entries I'm strugglish with adding feature for my controller. While adding new item, receving the error like: "An error occurred while updating the entries. See the inner exception for details."
I debugged it, and understood ProductDetailIs is null and here is the issue. But, can not figure out how to mend the problem.
Here is the DTO models:
public class WishlistItemDto
    {
        public int Id { get; set; }

        public string CustomerId { get; set; }

        public ProductDetailsDtoWithPrimaryImage ProductDetails { get; set; }

        public int Quantity { get; set; }
    }

public class WishListItemCreationDto
    {
        public string CustomerId { get; set; }

        public int ProductDetailId { get; set; }

        public int Quantity { get; set; }
    }

Controller:
[HttpPost]
public async Task<IActionResult> Add(WishListItemCreationDto wishListItemDto)
{
    var itemAdd = _mapper.Map<WishlistItemDto>(wishListItemDto);
    var itemCreated = await _wishListItemService.AddAsync(itemAdd);

    return CreatedAtAction(nameof(GetId), new { id = itemCreated.Id }, wishListItemDto);
}

Service:
public async Task<WishlistItemDto> AddAsync(WishlistItemDto item)
{
    var entity = _mapper.Map<WishlistItem>(item);
    await _wishListItemRepository.AddAsync(entity);

    return _mapper.Map<WishlistItemDto>(entity);
}

Repository:
public async Task<WishlistItem> AddAsync(WishlistItem item)
{
    await _context.Set<WishlistItem>().AddAsync(item);
    await _context.SaveChangesAsync();

    return item;
}

A: This line here:
var itemAdd = _mapper.Map<WishlistItemDto>(wishListItemDto);

your "wishListItemDto" is passed in as a 'WishListItemCreationDto' which contains only a ProductDetailsId. Automapper will have no way of knowing how to convert that into a ProductDetailsDtoWithPrimaryImage.
Typically for something like this where you pass an reference ID you would compose your entity by either populating a FK or loading the referenced entity. Your existing service and repository patterns will complicate your final solution. From what I can see from your example I'd look at creating an AddAsync method that accepts the WishListItemCreationDto:
public async Task<WishlistItemCreationDto> AddAsync(WishlistItemCreationDto item)
{
    var entity = _mapper.Map<WishlistItem>(item);
    var productDetails = _productDetailsRepository.GetById(item.ProductDetailsId);
    entity.ProductDetails = productDetails;
    await _wishListItemRepository.AddAsync(entity);

    return _mapper.Map<WishlistItemDto>(entity);
}

Without the added abstraction complexity of the Service and Repository the add operation can be a whole lot simpler:
[HttpPost]
public async Task<IActionResult> Add(WishListItemCreationDto wishListItemDto)
{
    // or better, use an injected dependency to the Context...
    // TODO: add applicable exception handling.
    using(var context = new AppDbContext())
    {
        var item = _mapper.Map<WishlistItem>(wishListItemDto);
        var productDetails = context.ProductDetails.Single(x => x.ProductDetailsId == wishListItemDto.ProductDetailsId);
        item.ProductDetails = productDetails;
        context.SaveChanges();

        return CreatedAtAction(nameof(GetId), new { id = itemCreated.Id }, wishListItemDto);
    }
}


text:
Q: ubuntu dual boot on mac goes to black screen I have been trying to dual boot Ubuntu on my 2009 Mac desktop running 10.10. The problem is it starts into refind, then I click on the cd and Ubuntu starts to load. It goes to a purple screen with a keyboard at the bottom then cuts to colored lines, then to black. I dont know why it is doing it? I know the download works as I am running inside virtualbox. It also does the same thing if I put in kali linux cd and try to run it live. It starts to boot gives me the ok ok, ok, then goes to colored lines and then black. I don't know if its graphics? or what??

A: I figured it out, its not a long term patch but it gets you there. It has something to do with the graphic card in the Mac desktop and the linux trying to run differently. So I installed kali-linux-2.0-amd64.iso as a dual boot. After reboot choose kali, in the boot menu. Then hole E key down, it comes to a blue kali screen. Mid way down there is a line that says "linux ..." (its long) go to the end of that line and enter nomodeset press ctrl x and it should boot with the log in screen appearing. Thank you guys for your help and hints!


text:
Q: barplot failure in R 3.1.0. read.csv converting what should be numerics to factors I have a little problem with the bar plot function of R 3.1.0. (it works fine in older versions).
nd_p_a<- read.csv("nd_p_a.csv")
barplot(nd_p_a$y, col="blue", names.arg=nd_p_a$x, xlab="k", ylab="P(k)")

has worked without any warnings or errors. But i version 3.1.0 i got an error:
Error in barplot.default(nd_p_a$y, col = "blue", names.arg = nd_p_a2$x,  :
  'height' must be a vector or a matrix

So, why did this do not work in this version? And how can i convert a factor to a vector? I tried as.numeric() and so on, but with no proper result.
The CSV File contains data like this:
"x","y"
1.0,48.947791826110596
2.0,6.317211620667564
3.0,14.982593438237588
4.0,3.4443873302013475
5.0,9.760934831763135
6.0,1.7191829918211519
7.0,3.9200958456693455
8.0,1.0765813450714172
9.0,2.290369697396343
10.0,0.6342337460169456
11.0,1.1210994624619959
12.0,0.5291701034830391

As wished more informations:
sessionInfo()
3.0.3
R version 3.0.3 (2014-03-06)
Platform: x86_64-unknown-linux-gnu (64-bit)

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C
 [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8
 [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8
 [7] LC_PAPER=en_US.UTF-8       LC_NAME=C
 [9] LC_ADDRESS=C               LC_TELEPHONE=C
[11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

3.1.0
R version 3.1.0 beta (2014-03-28 r65330)
Platform: x86_64-pc-linux-gnu (64-bit)

locale:
 [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C               LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8     LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8
 [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                  LC_ADDRESS=C               LC_TELEPHONE=C             LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

loaded via a namespace (and not attached):
[1] tools_3.1.0

str(nd_p_a)
3.0.3
'data.frame':   1449 obs. of  2 variables:
 $ x: num  1 2 3 4 5 6 7 8 9 10 ...
 $ y: num  48.95 6.32 14.98 3.44 9.76 ...

3.1.0
'data.frame':   1449 obs. of  2 variables:
 $ x: num  1 2 3 4 5 6 7 8 9 10 ...
 $ y: Factor w/ 221 levels "0.0010183159621912567",..: 194 201 171 184 220 173 187 167 178 166 ...

A: There seems to be an issue with the new version (3.1.0) of type.convert() which gets called by read.table() which gets called by read.csv() in R.  The most recent version of type.convert() assumes that the representation in your file is more accurate than R's internal numeric storage format (double-precision floating point values) and thus casts it to a FACTOR.  This behavior appears very surprising to a bunch of people, so I would bet it will go away, or there will be a parameter that will be able to be passed to type.convert() through the chain.  It seems sufficiently painful for people (including myself) that rely on the old-standing behavior of the automatic field type detection algorithm.
This question should be cross-linked somewhere upstream to something like "Why doesn't read.csv() work reliably with floating point values anymore?"
http://r.789695.n4.nabble.com/type-convert-and-doubles-td4688616.html

A: Here is a work around.  The new behavior is annoying
read.csv("nd_p_a.csv", colClasses=c("numeric", "numeric"))


text:
Q: Metric graphs and curvature Consider a positively weighted connected simple graph with bounded degree $X$ . Denote by $d(x,y)$ the weight on the edge with endpoints $x$ and $y$. Suppose we have the following compatibility axioms:

*

*If $x_0,x_1,\ldots,x_{n-1},x_n$ and $y_0,y_1,\ldots,y_{n-1},y_n$ are two shortest paths in the unlabeled graph connecting the same points (i.e. $x_0=y_0$ and $x_n=y_n$), then
$$
\sum d(x_{i-1},x_i)=\sum d(y_{i-1},y_i)
$$

*If $x_0,x_1,\ldots,x_{n-1},x_n$ is a shortest path in the unlabeled graph connecting $x$ to $y$ and $y_0,y_1,\ldots,y_{m-1},y_m$, with $m>n$, is another path connecting $x$ to $y$, then
$$
\sum d(x_{i-1},x_i)<\sum d(y_{i-1},y_i)
$$
Define a metric on the set of vertices just adding the various weights that you encounter moving along a shortest path. Suppose this metric is locally finite. The two axioms above say that this metric is well-defined and that it is in some sense compatible with the graph structure: the shortest-paths are geometrically the same and the distance is additive only along shortest paths.

General question: Has somebody studied these objects?

In particular, I am interested in the following questions:

Question: Suppose that our graph (without labels) is a tree with positive isoperimetric constant. Is it still true that it does not have bi-lipschitz embeddings (with the new metric) into a Hilbert space?

Also, let $\delta_1(X)$ be the best nonnegative constant, if exists, such that every side of a geodesic triangle is contained in the $\delta_1$-neigborhood of the other two sides. (If you like quasi-isometry, let $\delta$ be the infimum of all $\delta_1(Y)$ when $Y$ runs over the quasi-isometric class containing $X$). I am very tempted to say that $X$ has curvature bounded above by $-\frac{1}{\delta(X)}$.

Question: Has been this notion studied before? More specifically, what happens if I take, as graph, the 1-skeleton of a very good triangulation of a compact negatively curved metrizable manifold with labels given by the induced metric?

Thank you in advance,
Valerio

A: I suspect there is some terminology confusion here. Without the axioms 1 and 2, what you define is just a 1-dimensional polyhedral space (they are usually called metric graphs). Or, more precisely, the set of vertices of a metric graph with the induced distance. The "weights" are usually referred to as "edge lengths".
The axioms impose an additional requirement that the shortest paths of the "weighted" metric are the same as those of the "unweighted" one. This is a very unusual requirement, and I wonder where it comes from. By the way, it is not satisfied in the triangulation example from your last question.
Concerning bi-Lipschitz embeddings: if the edge lengths are bounded away  from 0 and infinity, then there is no difference from the unit lengths (the two metrics are bi-Lipschitz equivalent). And if they are not bounded, then any tree (I mean the set of vertices) can be bi-Lipschitz embedded into $\mathbb R$. Assign the $k$-th edge the length $10^k$, then the distance between any two vertices is dominated by the longest edge between them. Now mark one of the vertices as the origin and, for every vertex $x$, let $f(x)$ be the distance from $x$ to the origin. Then $f$ is a bi-Lipschitz map to $\mathbb R$.
I wonder what you mean by quasi-isometry (in your curvature bound definition). The notion of quasi-isometry I am used to allows arbitrary bi-Lipshitz rescaling, so the supremum and infimum of $\delta$ do not make sense. What you define is Gromov's $\delta$-hyperbolicity. This property is preserved under quasi-isometries, but the actual value of $\delta$ is not.
As for you last question, I presume that you are talking about the lift of the triangulation to the universal cover of the manifold (otherwise it is just a finite graph). In this case the graph is certainly Gromov-hyperbolic because it is quasi-isometric to the universal cover itself (with its negatively curved metric).


text:
Q: Is there a settings manager available for Mutter? Is there a GUI settings manager for Mutter? Something where I can adjust the window shadow size, or the hot corners, or opacity, etc...

A: Mutter is lean and mean by design, and is for sure way less configurable than Compiz. That's a choice made by the GNOME designers, who place simplicity and maintainability above configurability.

*

*If deep customization is your thing, the best answer is probably "don't use Metacity/Mutter". Compiz is one of your possible alternatives, but there is a bajillion of more customizable X window managers that could do the job for you. Try some of them! From what you say, maybe you could start with Enlightenment and Openbox. And Compiz, yes.

*If for some other reason you really want mutter, the grand total of settings you can adjust is 5, managed through the GConf infrastructure (soon migrated to DConf) and declared in a XML schema located at /usr/share/gconf/schemas/mutter.schemas. To edit them, fire gconf-editor and go to /apps/mutter/.
Also, this Fedora Gnome 3 Tips page has a few interesting paths to explore in gconf, and you might find a few interesting not exactly mutter-related but still interesting in gnome-tweak-tool

A: On Ubuntu 20.10, GConf is no longer used, but you can query the available dconf schemas:
➜  ~ gsettings list-schemas | grep mutter
org.gnome.mutter.wayland
org.gnome.mutter.keybindings
org.gnome.mutter.wayland.keybindings
org.gnome.mutter.x11
org.gnome.mutter

Here are the available settings:
➜  ~ gsettings list-schemas | grep mutter | xargs -n 1 -I % sh -c "echo %: && gsettings list-keys % && echo"
org.gnome.mutter.wayland:
xwayland-allow-grabs
xwayland-disable-extension
xwayland-grab-access-rules

org.gnome.mutter.keybindings:
tab-popup-cancel
tab-popup-select
toggle-tiled-right
toggle-tiled-left
rotate-monitor
switch-monitor

org.gnome.mutter.wayland.keybindings:
switch-to-session-4
switch-to-session-10
switch-to-session-3
switch-to-session-9
switch-to-session-2
switch-to-session-8
switch-to-session-1
restore-shortcuts
switch-to-session-7
switch-to-session-12
switch-to-session-6
switch-to-session-11
switch-to-session-5

org.gnome.mutter.x11:
fractional-scale-mode

org.gnome.mutter:
workspaces-only-on-primary
overlay-key
focus-change-on-pointer-rest
draggable-border-width
experimental-features
dynamic-workspaces
center-new-windows
auto-maximize
attach-modal-dialogs
edge-tiling
locate-pointer-key
check-alive-timeout
no-tab-popup

You can set a setting via gsettings set:
➜  ~ gsettings set
Usage:
  gsettings [--schemadir SCHEMADIR] set SCHEMA[:PATH] KEY VALUE

Set the value of KEY to VALUE

Arguments:
  SCHEMADIR A directory to search for additional schemas
  SCHEMA    The name of the schema
  PATH      The path, for relocatable schemas
  KEY       The key within the schema
  VALUE     The value to set


text:
Q: Create array whose keys and values depend of other arrays There are some topics narrowing my problem, but no one permits me to solve it.I have a csv file of terms from which i would like to count the number in a table of my db and to write the result in a new csv file.
I need to create a new array, where each key would be a term of the first array and the value would be the related number of records in my database.
Here are some examples of the input :
Lactose
Serine
And i would like to get something like this:
lactose, 25
serine, 3
So i have created an array whose values are the terms in the csv file.
Then i input the values of this array in a sql query.
And then, i have been unable to find the right way on the Internet or in the php documentation. The last line completely fails, but i tried it because it seemed to be the narrower mean to manage my task.
Could someone help me ?
Thanks in advance !
$termslist= array();

$file = fopen('fileterms.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
//$line is an array of the csv elements
  foreach ($line AS $molindice => $molvalues)
  {
    if ( ! in_array( $molvalue, $termslist ) )
            {array_push($termslist, $molvalues);}
  }
}

fclose($file);

//print_r ($termslist);

$molnumbers = array();

foreach ($termslist as $ancientkey => $ancientvalue)
{
    echo $ancientvalue;
    $sql3 = "SELECT content from mols WHERE content like '% $ancientvalue %'";
    $result3 = mysql_query($sql3)or die(mysql_error());
    $count3 = mysql_num_rows($result3);
    echo $count3;
    $molnumbers [$ancientvalue['molnames']] = $count3['quantities'];
}

A: Change:
$molnumbers [$ancientvalue['molnames']] = $count3['quantities'];

To:
$molnumbers[$ancientvalue['molnames']] = $count3['quantities'];

Or:
$molname = $ancientvalue['molnames'];
$molnumbers[$molname] = $count3['quantities'];

A: In the line:
if ( ! in_array( $molvalue, $termslist ) )

You have a small error as it should be:
if ( ! in_array( $molvalues, $termslist ) )

Then in this line:
$molnumbers [$ancientvalue['molnames']] = $count3['quantities'];

$ancientvalue is already the value (or molname) itself and not an array by itself.
Thus the line only needs to be:
    $molnumbers [$ancientvalue] = $count3['quantities'];

then it should put the number into the correct part of the array.
For the sql itself:
$sql3 = "SELECT content from mols WHERE content like '% $ancientvalue %'";

Here it seems to me that you are searching for %BLANKancientvalueBLANK% if that is not what
you want to do there but instead to look for %ancientvalue%, you should modify the line to:
$sql3 = 'SELECT content from mols WHERE content like \'%'.$ancientvalue.'%\'';


text:
Q: PHP file() error, invalid argument I have what should be a fairly straightforward operation, which gives me an error that doesn't seem very helpful.  The code is this:
<?php
$strLines = file('//tardis/htdocs/apps/freespace/FreeSpace-Servers.txt');
.
.
.
?>

But in php-errors.log, I get this:

[28-Aug-2013 16:31:30] PHP Warning:  file(//tardis/htdocs/apps/freespace/FreeSpace-Servers.txt) [function.file]: failed to open stream: Invalid argument in C:\Program Files (x86)\Apache Software Foundation\Apache2.2\htdocs\apps\freespace\freespace.php on line 2

The txt file is definitely there.  Any ideas what else an "Invalid argument" might suggest?  The documentation doesn't seem to hint at much of anything else.  Or, should I be doing this a different way?  My goal is to read the file in as an array of things.  All help is appreciated.

A: If you're using UNC, then the address should be
file('\\\\tardis\\htdocs\\apps\\freespace\\FreeSpace-Servers.txt');

You may also need to check that your PHP configuration allows you to open remote files.

A: I have a somewhat more correct answer than any of the above.  While all of the above is completely right, the actual problem (and solution) is detailed on question 18748985: PHP fails to read files.
The short answer is:  The Apache user password was changed, but Apache didn't know about it.  Update the password and restart the service.  The overall problem is slightly more colorful than that, but that's how the issue is most succinctly reduced.


text:
Q: Exibir variavel JS no HTML Fala pessoal, tenho uma variável js que conta o numero de pontos baseado em um questionário, ela conta os pontos corretamente, só não sei como posso exibir esse valor da variável no meu html, alguém pode ajudar por favor?
Aqui esta meu js
function contarPontos() {
    if (!localStorage.pontos) {
        localStorage.pontos = 0;
    }
    localStorage.pontos = parseInt(localStorage.getItem("pontos")) + 10;
}

E aqui meu HTML onde quero exibir

                        Sua pontuação foi pontos!

A: No seu caso basta usar o innerHTML para mostrar a pontuação. Basta recuperar a pontuação e atribuir ela ao elemento com o id=contarPontos.
function contarPontos() {
    if (!localStorage.pontos) {
        localStorage.pontos = 0;
    }
    localStorage.pontos = parseInt(localStorage.getItem("pontos")) + 10;
    document.getElementById("contarPontos").innerHTML = localStorage.pontos;
}

Caso esteja usando jQuery, pode fazer dessa forma
$("#contarPontos").text(localStorage.pontos)


text:
Q: Pass function outputs as arguments to another function I need to pass the output of a function in Python as an argument to another function. The only catch is that the 1st function returns a tuple and the entire tuple needs to be passed to the second function.
For ex:
I have a library function:
def some_function(some_string, some_number):
    # does something
    return (text,id)

Now I want to pass text and id returned from the some_function as arguments to another function. The catch is that the function has other arguments as well. I also need need to retrieve many texts and ids that will be generated by different values of some_string and number.
Depending on the condition met, I want to call another function which will look something like this
 if abcd:
     other_function(name,phone,**some_function("abcd","123")**,age)
 elif xyz:
     other_function(name,phone,**some_function("xyz","911")**,age)
 else:
     other_function(name,phone,**some_function("aaaa","000")**,age)

So what should I replace some_function("abcd","123") with so that it expands the tuple and sends both the text and id as arguments?
The other_function is defined like this
def other_function(name, phone, text, id, age):
   ...
    return

Will simply passing some_function("aaaa","000") as an argument work?

I am asking this because I wrote a simple code to test my hypothesis and it was giving me a blank output.
def f(id,string):
    return ("123", "hello")

def a(name, age, id, words, phone):
     print name + age + id + words + phone

def main():
    a("piyush", "23", f("12", "abc"), "123")

A: You have two options*; either explicitly unpack the function result first:
id, words = f('12', 'abc')
a('piyush', '23', id, words, '123')

or use tuple unpacking within the call to a, and supply the last parameter by keyword:
a('piyush', '23', *f('12', 'abc'), phone='123')

If this syntax is unfamiliar, see What does ** (double star) and * (star) do for parameters?

Note that if you try to pass phone as a positional argument (rather than a keyword argument as above) after the unpacked results from f, i.e.
a('piyush', '23', *f('12', 'abc'), '123')

you will get SyntaxError: only named arguments may follow *expression. You can't have positional arguments after * unpacking, you must use the keywords for any additional arguments.

* Unless you either:

*

*rearrange the order of the parameters, as Oz123 suggests; or

*wait for Python 3.5's release, as noted by abarnert.

A: You could also change the order of arguments in the signature:
def a(name, age, id, words, phone):
     name = name
     age=age
     id=id
     words=words
     phone=phone
     print name+age+id+words+phone

a("piyush", "23", 123, *f("12","123"))
piyush23123123hello

This way you can unpack the returned values directly when calling the function.
Note, however, that this makes readability very poor and debugging harder.
Also if you don't want to use unpacking and change the you call your function you can change the code like this:
def a(name, age, id_words, phone):
     name = name
     age=age
     id=id_words[0]
     words=id_words[1]
     phone=phone
     print name+age+id+words+phone

a("piyush", "23", f("12","123"), "123")
piyush23123hello123

This has the advatage of keeping all the functions call the same as they were. Only the interal works of the function change, not the signature.

A: Assuming you live in the future, the right way to do this is to just unpack the tuple into the middle of the argument list, like this:
a('piyush', '23', *f('12', 'abc'), '123')

Unfortunately, you, the OP, probably don't live in the future, so this is largely only helpful for people who find this answer after September 2015 (or are willing to require a pre-release version of Python before that). This functionality was added as PEP 448, which doesn't go in until Python 3.5 (and, as of 13 April 2015, doesn't even have a patch in trunk yet—but if you really want to live dangerously, you can download the latest patch at #2292, apply it to a local fork of the repo, and build it yourself…).
So, for the time being, you have to fake it, e.g., as in jonrsharpe's answer.


text:
Q: Правильный подсчет значений Есть код, который формирует словарь из данных json
Пример данных из json:
ссылка
Сам код
 import os
        import re
        import json
        import collections

   # Initialization collection for all lvl
    rule0 = collections.defaultdict(int) #
    rule1 = collections.defaultdict(int) #
    rule2 = collections.defaultdict(int) #
    rule3 = collections.defaultdict(int) #
    rule4 = collections.defaultdict(int) #
    rule5 = collections.defaultdict(int) #

    MY_RULE = {}

    # run comandline for create json
    # MY_PAT = os.system(r'pmd -d C:\Users\vsi\int\sfdevops_metrics\.project\na_gold\force-app\main\default\classes -R C:\Users\vsi\int\sfdevops_metrics\.project\na_gold\__PMD\GOLD_ruleset.xml -f json > C:\Users\vsi\int\sfdevops_metrics\.project\SM-774\output.json')

    #open json
    with open(r'C:\Users\vsi\int\sfdevops_metrics\.project\SM-774\output.json') as json_file:
        MY_PATH = json.load(json_file, object_hook=None)

    #refactor json
    for values in MY_PATH['files']:
        for i in values['violations']:
            if i['priority'] == 1:
                rule1[i['priority']] += 1
            elif i.get('priority') == 2:
                rule2[i['priority']] += 1
            elif i.get('priority') == 3:
                rule3[i['priority']] += 1
            elif i.get('priority') == 4:
                rule4[i['priority']] += 1
            elif i.get('priority') == 5:
                rule5[i['priority']] += 1
            rule0[i['priority']] += 1
        for key1 in values.items():
            key1 = str(key1)
            key1 = re.findall(r'C:.*', key1)
            key1 = str(key1)
            key1 = key1.replace(r'"C:\\\\Users\\\\vsi\\\\int\\\\sfdevops_metrics\\\\.project\\\\na_gold\\\\force-app\\\\main\\\\default\\\\classes\\\\', '')
            key1 = key1.replace("')\"", '')
            rule6 = str(rule0).replace("defaultdict(<class 'int'>, ", '')
            rule7 = str(rule1).replace("defaultdict(<class 'int'>, ", '')
            rule8 = str(rule2).replace("defaultdict(<class 'int'>, ", '')
            rule9 = str(rule3).replace("defaultdict(<class 'int'>, ", '')
            rule10 = str(rule4).replace("defaultdict(<class 'int'>, ", '')
            rule11 = str(rule5).replace("defaultdict(<class 'int'>, ", '')
        # MY_RULE[a] = values

            MY_RULE[key1] = MY_RULE.get(key1, []) + [( rule7, rule8, rule9, rule10, rule11)]
    del MY_RULE['[]']

            # print(a)
    # for i in values['violations']:
    #     print(i[''])

        # print(rule0)
    print(MY_RULE)

Я собирался посчитать кол-во приоритетов для каждого файла, но в итоге он считает все приоритеты для всех файлов и соотвественно суммирует их между собой по номеру критерию и в конце получается {4: 3965, 2: 6572, 3: 1285, 1: 129, 5: 65}
Как мне изменить код, чтобы приоритеты считались только в рамке одного файла

A: Для корректного отчета коллекции достаточно было обнулять ее после записи
import os
import re
import json
import collections

# Initialization collection for all lvl
rule0 = collections.defaultdict(int) #
rule1 = collections.defaultdict(int) #
rule2 = collections.defaultdict(int) #
rule3 = collections.defaultdict(int) #
rule4 = collections.defaultdict(int) #
rule5 = collections.defaultdict(int) #

MY_RULE = {}

# run comandline for create json
# MY_PAT = os.system(r'pmd -d C:\Users\vsi\int\sfdevops_metrics\.project\na_gold\force-app\main\default\classes -R C:\Users\vsi\int\sfdevops_metrics\.project\na_gold\__PMD\GOLD_ruleset.xml -f json > C:\Users\vsi\int\sfdevops_metrics\.project\SM-774\output.json')

#open json
with open(r'C:\Users\vsi\int\sfdevops_metrics\.project\SM-774\output.json') as json_file:
    MY_PATH = json.load(json_file, object_hook=None)

#refactor json
for values in MY_PATH['files']:
    for key1 in values.items():
        # print(key1)
        key1 = str(key1)
        priority = re.findall(r'priority....', key1)
        # priority = str(priority)
        for i in values['violations']:
            if i['priority'] == 1:
                rule1[i['priority']] += 1
            elif i.get('priority') == 2:
                rule2[i['priority']] += 1
            elif i.get('priority') == 3:
                rule3[i['priority']] += 1
            elif i.get('priority') == 4:
                rule4[i['priority']] += 1
            elif i.get('priority') == 5:
                rule5[i['priority']] += 1
            rule0[i['priority']] += 1
        # # rule0[i['priority']] += 1
        # print(key1)
        key1 = re.findall(r'C:.*', key1)
        key1 = str(key1)
        key1 = key1.replace(r'"C:\\\\Users\\\\vsi\\\\int\\\\sfdevops_metrics\\\\.project\\\\na_gold\\\\force-app\\\\main\\\\default\\\\classes\\\\', '')
        key1 = key1.replace("')\"", '')
        # print(key1)
        rule6 = str(rule0).replace("defaultdict(<class 'int'>, ", '')
        # rule7 = str(rule1).replace("defaultdict(<class 'int'>, ", '')
        # rule8 = str(rule2).replace("defaultdict(<class 'int'>, ", '')
        # rule9 = str(rule3).replace("defaultdict(<class 'int'>, ", '')
        # rule10 = str(rule4).replace("defaultdict(<class 'int'>, ", '')
        # rule11 = str(rule5).replace("defaultdict(<class 'int'>, ", '')

        MY_RULE[key1] = MY_RULE.get(key1, []) + [(rule6)]
        rule0 = collections.defaultdict(int)  #
        # rule1 = collections.defaultdict(int)  #
        # rule2 = collections.defaultdict(int)  #
        # rule3 = collections.defaultdict(int)  #
        # rule4 = collections.defaultdict(int)  #
        # rule5 = collections.defaultdict(int)  #
del MY_RULE['[]']
MY_RULE['FULL ATTENTIONS ON BRANCH'] = rule6

# print(a)
# for i in values['violations']:
#     print(i[''])

    # print(rule0)
print(MY_RULE)
# print(rule1)


text:
Q: Cross domain ajax request to a json file using JSONP I want to access a JSON file which is in domain1 (example.com) from domain2 (example2.com). For example,
$.ajax({
    type:'get',
    url: 'http://example.com/vigneshmoha.json',
    success: function(data) {
        console.log(data);
    },
    statusCode: {
        404: function() {
            console.log('Status code: 404');
        }
    }
});

I want to make this ajax request to example.com from some other domain (ie) example2.com.
I have tried JSONP. I couldn't understand how it works. Can someone please explain the way its work?

A: Your service has to return jsonp, which is basically javascript code.
You need to supply a callback function to the service from your ajax request, and what is returned is the function call.
Below is a working example.
ajax request:
$.ajax({
            crossDomain: true,
            type:"GET",
            contentType: "application/json; charset=utf-8",
            async:false,
            url: "http://<your service url here>/HelloWorld?callback=?",
            data: {projectID:1},
            dataType: "jsonp",
            jsonpCallback: 'fnsuccesscallback'
        });

server side code returning jsonp (c#):
public void HelloWorld(int projectID,string callback)
    {

        String s = "Hello World !!";
        StringBuilder sb = new StringBuilder();
        JavaScriptSerializer js = new JavaScriptSerializer();
        sb.Append(callback + "(");
        sb.Append(js.Serialize(s));
        sb.Append(");");
        Context.Response.Clear();
        Context.Response.ContentType = "application/json";
        Context.Response.Write(sb.ToString());
        Context.Response.End();
    }

Refer What is JSONP all about?.

A: Have you tried calling it as:
$.getJSON('http://example.com/vigneshmoha.json?callback=foo', null, function(data) {
          console.log(data);
});

And see what happens?


text:
Q: JavaFX update textArea I have a simple JavaFX application which has a TextArea. I can update the content of the textArea with the code below inside the start() method:
new Thread(new Runnable() {

    public void run() {

        for (int i = 0; i < 2000; i++) {

            Platform.runLater(new Runnable() {
                public void run() {
                    txtarea.appendText("text\n");
                }
            });
        }
    }
}).start();

The code just write the text string into the TextArea 2000 times. I want to update this textArea from a function which is implemented outside of the start() method.
public void appendText(String p){
    txtarea.appendText(p);
}

This function can be called from arbitrary programs which use the JavaFX application to update the TextArea. How can I do this inside the appendText function?

A: You could give the class which needs to write to the javafx.scene.control.TextArea an reference to your class which holds the public void appendText(String p) method and then just call it. I would suggest you also pass an indication from which class the method was called, e.g.:
public class MainClass implements Initializable {
    @FXML
    private TextArea txtLoggingWindow;
    [...more code here...]
    public void appendText(String string, String string2) {
       txtLoggingWindow.appendText("[" + string + "] - " + string2 + "\n");
    }
}

public class SecondClass {
    private MainClass main;
    public SecondClass(MainClass mClass) {
        this.main = mClass;
    }
    public void callMainAndWriteToArea() {
        this.main.appendText(this.getClass().getCanonicalName(), "This Text Goes To TextArea");
    }
}


text:
Q: @angular/schematics: Typescript failing to compile I am trying to create a custom schematics.
I have created a template file which is to be generated by schematics.
This should create file with classname specified by inputs at command.
 export class <%= classify(name) %> {

}

But when I run using "npm run build", it throws error
    export class <%= classify(name) %> {
               error TS1109: Expression expected.

I understand this is typescript error, But I am using "typescript": "~3.1.6" which should compile this.
I might be missing something basic. This is my first attempt with @angular/schematics.


text:
Q: How to write a switch statement that compares multiple variables? I'm a beginner in JS, I was hoping this code worked but it doesn't, what would be an alternative way of accomplishing the result I'm expecting here? basically want to return something based on the combination of 3 variables/arguments. (btw, in some case statements I'm not mentioning the 'roomSize' value because I'm expecting the code to know that it's the same as the original value)
const roombaMovement = (direction , initialRoombaLocation, roomSize) => {
    const roombaLocation = initialRoombaLocation
    let wallHit = 0;
    switch (roombaLocation && direction && roomSize) {
      case [4,0] && "S" && [4,0]:
        wallHit +=1;
        break;
      case [0,0] && "W":
        wallHit +=1;
        break;
      case [1,0] && "S":
        wallHit +=1;
        break;
      case [0,1] && "W":
        wallHit +=1;
        break;
      default:
    }
    return wallHit;
  }

A: Don't use switch for this - it's quite verbose and will be tedious to get the syntax to work properly for the logic you want. Since all the resulting statements to execute are the same (increment wallHit), all you need is a single (but large) if statement:
const arrsEqual = (a, b) => a.length === b.length && a.every((num, i) => num === b[i]);
const roombaMovement = (direction , initialRoombaLocation, roomSize) => {
  const roombaLocation = initialRoombaLocation
  let wallHit = 0;
  if (
    (direction === 'S' && arrsEqual(roombaLocation, [4, 0]) && arrsEqual(roomSize, [4, 0])) ||
    (direction === 'W' && arrsEqual(roombaLocation, [0, 0])) ||
    (direction === 'S' && arrsEqual(roombaLocation, [1, 0])) ||
    (direction === 'W' && arrsEqual(roombaLocation, [0, 1]))
  ) {
    wallHit +=1;
  }
  return wallHit;
}

A: you can also use JSON.stringify()
and compose a character string gathering all of your values:
const roombaMovement = (direction , initialRoombaLocation, roomSize) =>
  {
  let wallHit = 0
    , testVal = `${JSON.stringify(initialRoombaLocation)} && "${direction}"`
    ;
  if (testVal==='[4,0] && "S"')
    {
    testVal += ` && ${JSON.stringify(roomSize)}`;
    }
  switch (testVal)
    {
    case '[4,0] && "S" && [4,0]':
    case '[1,0] && "S"':
    case '[0,0] && "W"':
    case '[0,1] && "W"':
      ++wallHit;
      break;
    }
  return wallHit;
  }

which is gives a little more readable code ;)

A: Taking a guess at the actual intent of the code…

*

*Define what a wall is. For example:
const isWall = ([x, y], [roomWidth, roomHeight]) =>
  x === -1
  || y === -1
  || x === roomWidth + 1    // check which of roomWidth or roomWidth + 1 is correct
  || y === roomHeight + 1;  // same here

*Check whether the movement brings you into one:
const roombaMovement = (direction, initialRoombaLocation, roomSize) => {
  const [x, y] = initialRoombaLocation;
  const [dx, dy] = direction;
  const newLocation = [x + dx, y + dy];

  return isWall(newLocation, roomSize);
};

A: here are some pointers for you:

*

*don't change the order of your parameters. (direction , initialRoombaLocation, roomSize) vs (roombaLocation && direction && roomSize). It's just better coding to be consistent.

*There's no reason to assign a variable into another variable: const roombaLocation = initialRoombaLocation, just use initialRoombaLocation.

*This is not valid syntax: && "S". maybe you meant: && direction == "S"

*roombaLocation == [1, 0] is not valid syntax. you will need to find a better was to check that condition.

*There's no reason to use a case statement if there's only one possible result. just use a simple if statement.
good luck!


text:
Q: Creating an associative table in Prisma Schema I'm trying to model the following using Prisma for a personal project I'm working on.

The following schema for this I have put together is the following (I've removed some of the unnecessary session tables):
// learn more about it in the docs: https://pris.ly/d/prisma-schema

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

generator client {
  provider = "prisma-client-js"
}

model User {
  id            String     @id @default(cuid())
  name          String?
  email         String?    @unique
  emailVerified DateTime?
  image         String?
  accounts      Account[]
  sessions      Session[]
  SpotList      SpotList[]
}

// SpotSpot tables

model SpotList {
  id               Int                @id @default(autoincrement())
  userId           String
  name             String?
  description      String?
  public           Boolean
  createdAt        DateTime           @default(now())
  updatedAt        DateTime           @updatedAt
  User             User               @relation(fields: [userId], references: [id])
  SpotListLocation SpotListLocation[]
}

model SpotListLocation {
  list       SpotList     @relation(fields: [listId], references: [id])
  listId     Int
  location   SpotLocation @relation(fields: [locationId], references: [id])
  locationId Int

  @@id([listId, locationId])
}

model SpotLocation {
  id               Int                                  @id @default(autoincrement())
  name             String?
  description      String?
  coords           Unsupported("geometry(Point, 4326)")
  createdAt        DateTime                             @default(now())
  updatedAt        DateTime                             @updatedAt
  SpotListLocation SpotListLocation[]
}

My question was basically two things:

*

*Does my initial db design look sensible?

*Is my schema a faithful representation of my design?

Bearing in mind, it's just a personal project for learning backend and DB mostly. I don't need it to be the most performant thing in the world. I just don't want it to be completely wrong :)


text:
Q: How do I fully forward traffic from wlan0 to eth0 on Raspbian 10? I'm posting here because this seems like a general Debian/Ubuntu issue, and not a Raspberry pi-specific issue.
I want to bridge my wlan0 and eth0 ports on my Raspberry Pi (Raspbian 10/Buster), so that I can share my internet via my raspberry pi to a portable device that can only receive internet via ethernet.
While I know that creating a bridge with wlan0 is technically impossible, I know that I can reach similar results.
Edit: What I've tried so far (as recommended on many pages, for example here and here):
sudo sysctl -w net.ipv4.ip_forward=1
sudo iptables -A FORWARD --in-interface eth0 -j ACCEPT
sudo iptables --table nat -A POSTROUTING --out-interface wlan0 -j MASQUERADE

iw dev wlan0 set 4addr on
brctl addbr mybridge
brctl addif mybridge eth0
brctl addif mybridge wlan0

This does not work or help.
The only thing that does help is installing network-manager-gnome and activating the Shared to other computers-setting. This is very simple and works like a charm. However - I want my device (that I connected to the RPi with an ethernet cable) to also have an IP-address in the same network/subnet as the wlan0-interface is, so that other devices on the network will be able to reach it. Right now, it's getting addresses in the 10.42.0.1-range (which, according to this is a built-in feature..).
I've tried setting static IP-addresses on the Pi and the device, but that didn't help (they could only reach each other).
What is the best solution to this?


text:
Q: Question about Shockley's equation for JFETs I'm currently studying JFETs (Junction Field Effect Transistors) in Navy school. What I know so far is that in JFETs, \$V_{gs}\$ is reversed biased, creating a depletion zone. What this means in plain English is that the more negative the gate is with respect to the source, the more narrower the channel becomes, leading to more resistance in the drain to the source, so the drain to source acts like a resistor. There is a point when current flows constant and we call this the saturation point and denote this as \$v_{gs(off)}\$
We are introduced to this equation and I have no idea where it comes from:
$$I_d = I_{dss} \left(1 - \frac{V_{gs}}{v_{gs(off)}} \right)^2$$
Here \$I_d\$ is the current of the drain and \$I_{dss}\$ is the drain to source saturation. Can someone shed some light as to how we can get this equation?

A: OK first a little on notation. Your Vgs(off) is also called the Threshold voltage (Vt) and the pinch-of voltage (Vp), I think they all mean the same thing.  The voltage where the device is off.
So I cracked open "Art of electronics" (2nd ed.),  They talk about two regions of operation.
A linear region where the the drain current is proportional to the gate source voltage.
Id ~  (Vgs-Vt) and a saturation region where the current is proportional to the square of that voltage.
Id ~ (Vgs-Vt)^2.
The details are involved.  You might read some here.. and then look up the references.


text:
Q: How to get the Compute Engine logs to end up in the structured jsonPayload instead of the textPayload? I'm running an API on a Linux VM as a Compute Instance in the Google Cloud. The API is being run with systemd, and it's logging to syslog. I run the StackDriver logging agent to transfer the logs to StackDriver.
From this API I'm logging Json messages to the standard output. If I read /var/log/syslog (or do systemctl status), I see such messages:
May  9 14:10:25 test-rulesapi-core-473n dotnet-example[4021]: {"customfield": "value"}

What I'd like to achieve is to make this Json payload end up in the jsonPayload field of the log entries to be able to run custom queries. What I tried to do is to modify the StackDriver config so that it ignores the prefix prepended to the log messages (with the date and the name of the app, etc), so that only the raw Json is sent to StackDriver. The config looks like this (the default one is commented out):
# format /^(?<message>(?<time>[^ ]*\s*[^ ]* [^ ]*) .*)$/
format /^(?<time>[^ ]*\s*[^ ]* [^ ]*)[^{]*(?<message>.*)$/

This seems to properly extract only the json part of the message, but my problem is that in the log entries it still ends up in the textPayload field.
For example if I retrieve one specific log entry with gcloud, it looks like this:
$ gcloud logging read "logName=projects/my-project/logs/syslog AND insertId=ajooj1g318gl2l"
---
insertId: ajooj1g318gl2l
labels:
  compute.googleapis.com/resource_name: myapi-473n
logName: projects/travix-production/logs/syslog
receiveTimestamp: '2018-05-09T14:00:03.877941542Z'
resource:
  labels:
    instance_id: '3565608832621021979'
    project_id: travix-production
    zone: europe-west1-c
  type: gce_instance
textPayload: '{"customfield": "value"}'
timestamp: '2018-05-09T14:00:03Z'

How can I get StackDriver to put the Json object into jsonPayload as a proper object to be able to use custom queries?

A: I see that you would want to print a Json object into the jsonPayload field for Logging.
After reading though some documents, here's what I think. You should look into a parser [1], also I wanted to share with you how syslog parser plugin parses the logs [2].

[1] https://cloud.google.com/logging/docs/structured-logging#writing_your_own_parser
[2] https://docs.fluentd.org/parser/syslog


text:
Q: How to find the limit of $\frac{\tan(2x)}{\sin(3x)}$ as $x$ approaches $0$ analytically? I'm taking a calculus 1 course, and I'm running into issues when trig gets added into the mix. I keep trying to simplify $\frac{\tan(2x)}{\sin(3x)}$ so that I can either plug in $0$ or find one of the special limits, but I always end up at a dead end.
I've looked for existing help, but everything seems to use L'Hopital's rule. We haven't gotten to derivatives yet, so that wouldn't be an acceptable answer to turn in.

A: The computation can be done simply as follows
\begin{eqnarray*}
\frac{\tan 2x}{\sin 3x} &=&\frac{\sin 2x}{\sin 3x\cos 2x} \\
&=&\frac{2\sin x\cos x}{\left[ \sin x\color{red}{(2\cos 2x+1)}\right] \cos 2x} \\
&=&\frac{2\cos x}{\color{red}{(2\cos 2x+1)}\cos 2x}\rightarrow \frac{2\cdot 1}{(2\cdot
1+1)\cdot 1}=\dfrac{2}{3}.
\end{eqnarray*}
No L'Hospitale's rule, no Taylor series, no limit of  $\dfrac{\sin x}{x}$  too!
(Thanks to P.S. :) )
$\bf EDIT$ The  misprint is now corrected. Thanks to Blue who pointed out to $\color{red}{it}$.

A: We just need to recall that
$$ \lim_{x\to 0}\frac{\sin(ax)}{x} = a, $$
hence:
$$ \lim_{x\to 0}\frac{\tan(2x)}{\sin(3x)} = \lim_{x\to 0}\frac{1}{\cos(2x)}\cdot\frac{x}{\sin(3x)}\cdot\frac{\sin(2x)}{x} = \frac{2}{3}.$$

A: Hint:
$$\frac{\tan2x}{\sin3x}=\frac23\frac{\sin2x}{2x}\frac{1}{\cos2x}\Big/
  \frac{\sin3x}{3x}\ .$$
You should see some known "special limits" here.

A: when trying to find the limit of $\dfrac{\tan 2x}{\sin 3x} = \dfrac{\sin 2x}{\cos 2x\sin 3x}$  one can see that the $\cos 3x $ in the numerator is harmless can be evaluated to $1.$ finding the original limit is reduced to finding the limit of $\dfrac{\sin(2x)}{\sin(3x)}$ here we make further simplification that $\sin(small) = small + \cdots$ so that when the argument to $\sin$ is small, you can erase the word $\sin$ leaving the small argument. in this case finding the limit is reduced to finding $\lim_{x \to 0}\dfrac{2x}{3x}.$ that is clearly $\dfrac{2}{3}$

A: With equivalents: $\, \sin ax\sim_0 ax,\enspace \cos ax\sim_01$, hence $\tan ax \sim_0 \dfrac{ax}1=ax$. Hence:
$$\frac{\sin 2x}{\tan 3x}\sim_0\frac{2x}{3x}=\frac23,$$
which proves the limit is $\dfrac23$.


text: Q: Live streaming using chromecast with H.264 frames and TCP or UDP protocol I want to build an app where I can feed H.264 frames directly to chromecast via UDP or TCP protocol. From documentation its given that is supports H.264 video codex. Is it possible to use it directly?


text: Q: How to duplicate the entire gatsbyjs app into an additional directory on compile for theming I'm trying to have two versions of the gatsby generated application so that I can theme one dark and one light. The best way that I can think to do this is with a /dark/ in the url to point to the dark themed app. I considered doing a query param to set a class, but query params get lost when navigating around and I don't want to have to pass it around. I also considered the react router but feel like there has to be a way to just duplicate it. Does anyone have any suggestions on how to do this?


text:
Q: unable to create or update a belongs_to record in Rails 4 I'm new to Rails and struggling to get my belongs_to association right. I have an app where a painting belongs to an artist and an artist can have_many paintings. I can create and edit my paintings, however I can not edit or create artists except through the console. Through much Googling I feel I have got myself turned around. Any help would be much appreciated!
Here's my routes.rb file:
MuseumApp::Application.routes.draw do
  resources :paintings

  resources :paintings do
  resources :artists
  resources :museums
end
  root 'paintings#index'

end

Here's my paintings Controller
   def show
    @painting = Painting.find params[:id]
  end

  def new
    @painting = Painting.new
    #@artist = Artist.new
  end

  def create
    safe_painting_params = params.require(:painting).permit(:title, :image)
    @painting = Painting.new safe_painting_params
    if @painting.save
      redirect_to @painting
    else
      render :new
    end
  end

  def destroy
    @painting = Painting.find(params[:id])
    @painting.destroy
    redirect_to action: :index
  end

  def edit
    @painting = Painting.find(params[:id])
  end
 def update
    @painting = Painting.find(params[:id])
    if @painting.update_attributes(params[:painting].permit(:title, :image)) #safe_params
      redirect_to @painting
    else
      render :edit
    end
 end

Here's the form in my paintings view:
<%= form_for(@painting) do |f| %>
  <fieldset>
    <legend>painting</legend>

      <%= f.label :title %>
      <%= f.text_field :title %>

      <%= f.label :image %>
      <%= f.text_field :image %>

 <%= form_for([@painting,@painting.create_artist]) do |f| %>

      <%= f.label :Artist %>
      <%= f.text_field :name %>

  </fieldset>
  <%= f.submit %>
<% end %>
<% end %>

Artists Controller:
class ArtistsController < ApplicationController

  def index
    @artists = Artist.all
    @artists = params[:q] ? Artist.search_for(params[:q]) : Artist.all
  end

def show
    @artist = Artist.find params[:id]
  end

  def new
    @artist = Artist.new
  end

  def create
    @painting = Painting.find(params[:painting_id])
    @artist = @painting.create_artist(artist_params)
    redirect_to painting_path(@painting)
  end

  def destroy
    @artist = Artist.find(params[:id])
    @Artist.destroy
    redirect_to action: :index
  end

  def edit
    @artist = Artist.find(params[:id])
  end

 def update
    @painting = Painting.find(params[:painting_id])
    @artist = @artist.update_attributes(artist_params)
    redirect_to painting_path(@painting)
 end

end

private
    def artist_params
        params.require(:artist).permit(:name)
    end

Index view:

 Hello and Welcome to Museum App

<%= link_to "+ Add To Your Collection", new_painting_artist_path %>

<%= form_tag '/', method: :get do %>
  <%= search_field_tag :q, params[:q] %>
  <%= submit_tag "Search" %>
<% end %>

  <% @paintings.each do |painting| %>

<%= link_to painting.title, {action: :show, id:painting.id} %>    by   <%= painting.artist_name %>

<%= link_to (image_tag painting.image), painting.image %>

    <%= link_to "Edit", edit_painting_path(id: painting.id) %>
     ||
     <%= link_to 'Destroy', {action: :destroy, id: painting.id},method: :delete, data: {confirm: 'Are you sure?'} %>
  <% end %>

A: In your case you should use accepts_nested_attributes_for and fields_for to achieve this.
Artist

has_many :paintings, :dependent => :destroy
accepts_nested_attributes_for :paintings

Painting

belongs_to :artist

And also you should try creating artist with paintings like this
form_for(@artist) do |f| %>

<fieldset>
    <legend>Artist</legend>

      <%= f.label :Artist %>
      <%= f.text_field :name %>

      <%= fields_for :paintings, @artist.paintings do |artist_paintings| %>
      <%= artist_paintings.label :title %>
      <%= artist_paintings.text_field :title %>

      <%= artist_paintings.label :image %>
      <%= artsist_paintings.text_field :image %>

  </fieldset>
  <%= f.submit %>
<% end %>

Note:
You should be having your Artist Controller with at least new,create,edit and update methods defined in it to achieve this.
Edit
Try the reverse
Artist

   has_many :paintings, :dependent => :destroy

 Painting

    belongs_to :artist
    accepts_nested_attributes_for :paintings

    form_for(@painting) do |f| %>

       <fieldset>
          <legend>Painting</legend>

          <%= f.label :title %>
          <%= f.text_field :title %>

          <%= f.label :image %>
          <%= f.text_field :image %>

          <%= fields_for :artists, @painting.artists do |ff| %>
          <%= ff.label :Artist %>
          <%= ff.text_field :name %>

          </fieldset>
          <%= f.submit %>
        <% end %>

Put this form in paintings views.


text:
Q: open browser window (or other window) to very big width and height B"H
When I'm openning a web browser like chrome, I can resize the width of the window to some width, but not more then a certain maximum.
I want to open it to size like 3000x3000, more then my screen resolution.
Is it possible?
Thanks
Elchanan

A: You can use zoom for this purpose. For Chrome and Opera right click on the page, go to "Inspect", then press "Toogle Device Toolbar" (Ctrl+Shift+M). In the toolbar you can specify a big resolution like 3000x3000 and it will adjust zoom according to your screen resolution.


text:
Q: Solving Non-linear Overdetermined System of Equations I have a problem similar to The best fit for variables in a number of equations? but my system is nonlinear i.e.:
$$A_1 * X * Y = B_1$$
$$A_2 * X * Y = B_2$$
$$...$$
$$A_n * X * Y = B_n$$
Are there any methods to solve this system for $X$ and $Y$?

A: Reposting comment as answer, owing to clarification and so the post is properly marked as being answered.

No, since you just have that
$$XY=\frac{A_1}{B_1}= \cdots =\frac{A_n}{B_n} \equiv \text{constant}$$
If $XY=3$ for instance, you don't know whether $X=3$ and $Y=1$ or $X=Y=\sqrt 3$ or any other factorization.


text:
Q: Retrieving time from a time server from flash (as3) Please do forgive a newbie to all this fancy Action script and flash in general.
Prior to any comments, I have been trawling for the answers for a good while now - with no luck so I figured I would poise the question at a few of the boffins on here.
So here it is.  What I am trying to accomplish is two simple analogue world clocks (which I had already done using Jquery) but IE has turned out to be the biggest nightmare to get this working correctly in - so I am trying a different avenue.
I have written a small script to retrieve server times which is below:
var ldr:URLLoader = new URLLoader()
ldr.load(new URLRequest("http://chronos.csr.net"))
ldr.addEventListener(Event.COMPLETE, onLoaded)
function onLoaded(evt:Event){
    trace(ldr.data)
}

Could someone tell me how I could print out the output from the above syntax to ensure it is   in fact working?  And seeing I pulled bits of the code from my various searches - is it a requirement to have the url pointing to a specific file?
If the above is by the grace of the almighty Pixel in fact working, how would one go about inputing it into the code below:
var now:Date;
var ct:Timer = new Timer(1000);
ct.addEventListener(TimerEvent.TIMER, onTick);
ct.start();
function onTick(event:TimerEvent):void{
    now = new Date();
    var s:uint = now.getSeconds();
    var m:uint = now.getMinutes();
    var h:uint = now.getHours();
    second_hand_mc.rotation = 180 + (s * 6);
    minute_hand_mc.rotation = 180 + (m * 6);
    hour_hand_mc.rotation = 180 + (h * 30) + (m * 0.5);
}

And please do take into account DST as this was a slight pitfall I had even with JS (would have worked it out eventually but time is not on my side - excuse the pun).
Any and all help would be greatly appreciated!

A: There is an interesting thing you  might like to use, it's NTP (Network Time Protocol). It is a plain TCP stream which sends 4 bytes of data, which are the current time in the UTC format.
The problem in Flash is that you can't send plain TCP requests to an arbitrary server - Flash requires that the server sends a permissive policy response. So, you would have to proxy the responses obtained from NTP server (or, if you want to make it simpler, just print server's system date to the output stream) and call the script from Flash.
Here I found some example NTP synchronization script written in PHP http://www.xenocafe.com/tutorials/php/ntp_time_synchronization/index.php . You don't need the synchronization part, only the part where it tries to connect to couple of time servers and gets the response.
This won't be very precise, as connecting and sending data from Flash client to your server takes time, however, you can try to count the average time it takes for the data to travel to the client. Your course of action would be:

*

*Send current date from your server script to Flash.

*Once Flash receives the date, it sends it back.

*Repeat setps 1 and two few times to collect enough data to calculate the average time it takes to travel. Let server times of sending the response be called ST0, ST1, ... STN and server times of receiving the response: RT0, RT1, ... RTN. Then the average time it takes to travel roughly (RT0 - ST0 + RT1 - ST1 + ... RTN - STN) / (2 * N).

*You would then record the delta and add it to the time sent to Flash every time it tries to synchronize with the server.

Again, all depends on how precise you want it to be. You could simply print date to the request output stream and ignore the time to travel / never synchronize your server against NTP server etc.


text:
Q: Why this animate display none to block not working? Why this animate display none to block not working ?
First code look like this, and it's work good
$(".box_outer").stop().animate({top: '25px' , opacity: 1}, 100);

When i add display: none; to class box_outer and add , display: 'block'
My function animate not work , how can i do that ?
$(".box_outer").stop().animate({top: '25px' , display: 'block' , opacity: 1}, 100);

A: The animate() method works with only properties with numerical values, display is not 1 of them so try
$(".box_outer").stop().show().animate({top: '25px', opacity: 1}, 100);

or if you want to animate the display also, set the height to 0 then use height: 'show' as an animation property

A: You cannot animate display See this article for a workaround
http://www.impressivewebs.com/animate-display-block-none/
Live Demo: http://jsbin.com/iZUGaKI/1/

A: as far as i know you cant animate display property but you can use show() hide() or fadeIn() fadeOut() for the same purpose and they will work well with display:none
$(".box_outer").show(100);

OR
$(".box_outer").fadeIn(100);


text:
Q: Don't show password screen after using remote desktop I've just upgraded to Windows 10, I've disabled all the login screens by using the normal methods netplwiz and also disabling password after sleep. However whenever i remote desktop into my PC from an external source, After closing the remote desktop i have to then enter a password again to access my PC.
Is there a way to disable it so when i'm finished with the remote desktop it will just either auto login when i press enter or go back to windows screen.

A: You cannot disable the logon screen. This is a mechanic of Remote Desktop.
So the question becomes, is it possible to somehow unlock it after it was locked?
It might. I haven't tested it, as personally I don't need this. If I need to take over my PC remotely, I use teamviewer. That way the pc won't be locked.
But lets assume RDP is the only method here.
There's a program called logon.exe which allows you to unlock a computer using a username and password. For it to work, you need to set it to classic login as explained on that page.
Then, you can create a scheduled task that unlocks, where the trigger is an event called "Lock workstation".
So whenever the workstation is locked, task scheduler will unlock the workstation with your username and password. Of course, this does mean that you no longer will be able to lock your workstation.


text:
Q: POST request with file (image) and text with HttpURLConnection I have the following cURL that works in Bash:
$ curl -F "image=@/Users/my-name/Downloads/STARinside.jpg_256" -F "assetNumber=OS014005" -F "name=George" -F "make=Hamilton" -F "model=STAR" "http://exampleUrl.compute.amazonaws.com/Asmt3/updateInstrImage.php"

but I can't seem to quite get this working in Android Studio.  here's some code I've tried, but I can't seem to get to work.  I can get the POST of all the parameters themselves (including the image=@filename), but it appears the server (which is php that I wrote) is not receiving anything in $_FILES['image'] like it does from bash.  Or I can send the actual file via a bufferedOutputStream, but then it doesn't capture anything meaningful in the $_POST array.
this code is in an extension of AsyncTask, FTR:
HttpURLConnection conn = (HttpURLConnection) this.updateInstr.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
//conn.setRequestProperty("Content-Type", "image/jpeg");
conn.setDoInput(true);
params.append("assetNumber=");
params.append(this.asset);
params.append("&name=");
params.append(InstrList.get(this.asset));
params.append("&make=");
params.append(InstrMakes.get(this.asset));
params.append("&model=");
params.append(InstrModels.get(this.asset));
params.append("&image=@");
params.append(image.getAbsoluteFile());
/*
    conn.addRequestProperty("assetNumber", this.asset);
    conn.addRequestProperty("name", InstrList.get(asset));
    conn.addRequestProperty("make", InstrMakes.get(asset));
    conn.addRequestProperty("model", InstrModels.get(asset));
*/
conn.setChunkedStreamingMode(bt.length);
OutputStream out = new BufferedOutputStream(conn.getOutputStream());
byte[] b = params.toString().getBytes(StandardCharsets.US_ASCII);
out.write(b);
out.flush();
out.write(bt);
out.flush();
out.close();

//fully open connection with conn.getInputStream
InputStream in = new BufferedInputStream(conn.getInputStream());
in.read(bytes);
in.close();
response = new String(bytes, "utf-8");
Log.d("response: ", response);

Also, you can see, I've tried a different way to conn.addRequestProperty.  In that implementation, I tried writing b after bt (POST after FILE).
I definitely would appreciate help.  It certainly seems I should be able to replicate this cURL call in Android Studio, but I just can't quite get it.  I've added some echoing to the php on the server, so I know I'm assembling the params correctly (the $_POST array is correct based on a print_r($_POST) call), but the $_FILES array is empty from android studio (but is correct from bash-curl)
Quick note, I did find this other question which is very helpful and almost sufficient, but it appears that the ByteArrayBody class discussed for Java doesn't exist for Android Studio

A: This turned out to be pretty involved, and I needed several different sources scattered around SO and elsewhere to (finally) get it working.
So, I have posted a very detailed example on my free-for-now amazon EC2 instance.  if someone would like to take the source and post it elsewhere, I'd be happy for you to do so, provided you state the original author.  For now:
http://ec2-54-213-243-1.us-west-2.compute.amazonaws.com/How-to/index.html
The gist is that you need to extend AsyncTask, but you also need to build the Http request character by character to delineate what is files (stream of bytes) vs 'normal' data fields.
the most involved part is:

Which calls:


text:
Q: Operations with dates in cakephp How do operations with dates in cakephp?
I want to calculate the difference in days between two dates, for example: a date subtracting 10 days or a date and add 20 days.
How I do that?

A: You can use this:
CakeTime::format('r', '+20 days', true);

Take a look on this: http://book.cakephp.org/2.0/en/core-libraries/helpers/time.html
Maybe you wan't see this one too: http://www.php.net/manual/en/function.date.phpenter


text:
Q: Can datajs read non-odata services I have a wcf service hosted in sharepoint that retunrs a list of objects. Its a not a wcf data service, just a 'regular' wcf data service.
Can data js read dta from a 'regular' wcf data service?

A: In short - no. datajs can only consume OData formatted payloads.


text:
Q: Core Data Error - NSDate localizedCaseInsensitiveCompare: unrecognised selector sent to instance I have searched for the last several hours but have yet to find an answer. I implemented an AVFoundation camera, Im saving the image data to disk and storing only the path in core data. Everything works fine but after a random number of taken photos I get this error:
CoreData: error: Serious application error.  Exception was caught during Core Data change processing.  This is usually a bug within an observer of NSManagedObjectContextObjectsDidChangeNotification.  -[__NSDate localizedCaseInsensitiveCompare:]: unrecognized selector sent to instance
This is my fetch request code:
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Photo"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"notebook = %@", notebookItem];
[request setPredicate:predicate];
request.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"dateTaken"
                                                              ascending:NO
                                                               selector:@selector(compare:)]];

And here is how I save the data in a separate class:
//I create a photo Object to save to core data and set properties like dateTaken and tittle

//Here is where I create the path name
NSDate *dateString = [[NSDate alloc] init];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS"];
NSString *path = [formatter stringFromDate:dateString];

//Now I save to disk
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
// the path to write file
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:path];
NSLog(@"path: %@", path);
[[[self captureManager] ImageDataObject] writeToFile:filePath atomically:YES];

photo.imagePath = filePath;

[notebookItem addPhotosObject:photo];
[self.SharedDocumentHandlerInstance saveDocument];

I tracked down the point of crash and it occurs in the line of code where I save the document (the last one above) but maybe the fetch request is the one that causes it. I also set self.fetchedResultsController.delegate = nil in my table. And again, this error occurs after a random number of photos is taken. Thanks for any help in advance!

A: Your problem is that you cannot call localizedCaseInsensitiveCompare: on an NSDate. You need to change that to compare:. Check through the Apple documentation on NSDate.
The method localizedCaseInsensitiveCompare: requires an NSString (Apple documentation).
This SO Question may also be helpful.
Also Table 1 in this web page Creating and Using Sort Descriptors


text:
Q: Lodash _.chain with flatten to find matching value array I am trying to find matching object from my multidimensional array with help of lodash library. I am using combination of _.chain along with flatten to go one level deeper.
Don't know what approach I should use. Can anyone please review and help me out to get expected result?
JSFIDDLE Lin
var team = _.chain(data).flatten("divisionTeams").find({"id": 3222}).value();

A: You should first use map() to return divisionTeams and then flatten and find.

var data = [{"divisionName":"5th Grade - Green","divisionTeams":[{"id":3222,"name":"Columbia Ravens 5th","coach":"John Miller"},{"id":4299,"name":"D1 Spartans","coach":"Jacob Silverman"},{"id":3220,"name":"HC Elite OMalley 5th","coach":"Eddie OMalley"},{"id":3277,"name":"MD 3D 5th","coach":"Marty Libinski"},{"id":3275,"name":"Severn Elite Gold","coach":"Darryl Adams"},{"id":3224,"name":"Team Dedication 5th","coach":"Don Carpenter"}]},{"divisionName":"5th Grade - White","divisionTeams":[{"id":3225,"name":"CBSA Hoyas 5th Grade","coach":"Terrance Taylor"},{"id":3276,"name":"HC Elite 4th Tookes","coach":"Anthony Tookes"},{"id":3221,"name":"HC Elite Knisley 5th","coach":"Jordan Knisley"},{"id":3226,"name":"Randelstown Runnin Rebels 5th","coach":"Eric Levi"},{"id":3223,"name":"Up n Coming Clippers 5th","coach":"Brian Jackson"}]}]

var team = _.chain(data)
 .map(e => e.divisionTeams)
 .flatten()
 .find({ "id": 3222})
 .value();

console.log(JSON.stringify(team));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>


text:
Q: SQL Pull Replication not synchronizing I am trying to establish a pull transactional replication using SQL Server 2008 R2, I have a local DB and a Remote DB, I am using UNC file share for the snapshot.
All are running with no errors, however the publisher on the remote server is showing:

The initial snapshot for article  is not yet available.

I run the View Snapshot Agent Status and it shows:

[100%] A snapshot of 1 article(s) was generated.

What is going wrong?


text:
Q: Error in using canvas.toDataURL() in react- native with npm react-native-canvas latest     const image = new CanvasImage(canvas);
    canvas.width = 100;
    canvas.height = 100;
    const context = canvas.getContext('2d');
    image.src = 'http://i.imgur.com/c2wRzfD.jpg';
    image.addEventListener('load', async () => {
        context.drawImage(image, 0, 0, 100, 100);
        let dataURL = await canvas.toDataURL("image/png")
    });

This code gives me error like:

"Cannot read property 'constructor' of undefined"

This comes only when I drawImage() on canvas it works properly when I draw rectangle, round etc.
Android Studio is 3.0.1
node -v is stabble

A: The problem is with this cod inside the listener
let dataURL = await canvas.toDataURL("image/png")

It seems to break your constructor definition to the drawImage
This can be solved by using it as follows
 handleImageRect = async (canvas) => {
        const image = new CanvasImage(canvas);
        canvas.width = 100;
        canvas.height = 100;

        const context = canvas.getContext('2d');

        image.src = 'https://image.freepik.com/free-vector/unicorn-background-design_1324-79.jpg';
        image.addEventListener('load', () => {
            console.log('image is loaded');
            context.drawImage(image, 0, 0, 100, 100);

        });
        // Move it outside
        let dataURL =  await canvas.toDataURL("image/png")
        console.log(dataURL)
    }


text:
Q: Filling data in Ext.net FormPanel I am using Ext.net 2.0 and I am trying to load the first record of the store inside a form panel. I always get no records (getCount() = 0) in the store ? Am I missing something ?
 @(Html.X().Store()
              .ID("myStore")
              .AutoSync(true)
              .AutoDataBind(true)
              .Proxy(proxy =>
                     proxy.Add(
                         Html.X().AjaxProxy().API(api =>
                                   {
                                       api.Create = "/Property/Save/";
                                       api.Read   = "/Property/GetById/";
                                   })
                             .Reader(reader => reader.Add(Html.X().JsonReader().Root("data").IDProperty("P_ID")))
                             .Writer(writer => writer.Add(Html.X().JsonWriter().AllowSingle(true)))
                     ))
               .Listeners(c =>
                              {
                                  c.DataChanged.Handler ="var store = Ext.getStore('myStore');" +
                                                          "alert(store.getCount());";

                              })

              .AutoLoadParams(parameters =>
                                   {
                                       parameters.Add(Html.X().Parameter().Name("id").Value("document.location.href.split('/')[5]").Mode(ParameterMode.Raw));
                                   })

              .Model(model => model.Add(
                  Html.X().Model()
                      .Fields(fields =>
                                  {

                                      fields.Add(Html.X().ModelField().Name("ID").Type(ModelFieldType.Int));
                                      fields.Add(Html.X().ModelField().Name("DispalyName").Type(ModelFieldType.String));
                                      fields.Add(Html.X().ModelField().Name("Title").Type(ModelFieldType.String));
                                      fields.Add(Html.X().ModelField().Name("ShortDescription").Type(ModelFieldType.String));

                                  })
                          ))
                    )

For the form panel
@(
        Html.X().FormPanel()
        .ID("myPanel")
        .Layout(LayoutType.Form)
        .Width(350)
        .FieldDefaults(d => {
            d.LabelWidth = 150;
        })
        .BodyPadding(10)
        .Items(item =>
                    {
                        item.Add(Html.X().TextField().ID("Id").Name("ID").FieldLabel("Id").Hidden(true));
                        item.Add(Html.X().TextField().ID("DispalyName").Name("IdDispalyName").FieldLabel("Id Dispaly Name").MaxLength(400));
                        item.Add(Html.X().TextField().ID("Title").Name("Title").FieldLabel("Title").AllowBlank(false).MaxLength(200));
                        item.Add(Html.X().TextField().ID("ShortDescription").Name("ShortDescription").FieldLabel("Short Description").MaxLength(200));
                             }
            ) )

Thanks in advance.

A: More appropriate event is Load (it is fired when data is loaded to the store from a remote source)
See the following description
http://docs.sencha.com/ext-js/4-1/#!/api/Ext.data.Store-event-datachanged


text:
Q: Update fails without error I have below class where update on mycallsInc not happening. Can someone please help me?
public void Publish() {
    List<Incident_abv__c> selIncs = (List<Incident_abv__c>)contr.getSelected();
    for(Incident_abv__c inc:selIncs) {
        inc.status_abv__c = 'Open';
        inc.Report_Publish_Date_abv__c = Date.today();
        if(inc.Rep_abv__c !=null)
            inc.OwnerId = inc.Rep_abv__c;
    }
    update selIncs;

    List<SObject> myCalls = [SELECT Call_abv__c FROM Incident_Transaction_abv__c];
    //Set<Id> resultIds = (new Map<Id,SObject>(myCalls)).keySet();
    List <Call2_vod__c> myCallsInc = (List <Call2_vod__c>) myCalls;
    //List<Call2_vod__c> Call= new List<Call2_vod__c>();
    for(Call2_vod__c ita : myCallsInc )  {
        attribute = [SELECT count() FROM Incident_Transaction_Line_Item_abv__c WHERE (Call_Sample_abv__r.Call2_vod__c=:ita.id
             or Call_Sample_abv__r.Call2_vod__r.Parent_Call_vod__c=:ita.id) or (Call_detail_abv__r.Call2_vod__c=:ita.id
             or Call_detail_abv__r.Call2_vod__r.Parent_Call_vod__c=:ita.id)
             ];
        if(ita.Incidents_Count__c!=attribute)
            ita.Incidents_Count__c=attribute;
        System.debug('Saikat_N@@@@@@@@@@@@@@@@@@@');
    }
    System.debug('D_N@@@@@@@@@@@@@@@@@@@');
    update myCallsInc ;

    ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO, 'Successfully Published'));
}


text:
Q: Extract Last Part of URL using PHP How I can extract the last part of a URL using PHP.
Here is sample URL

http://www.example.com/123

I want following output

123

How can I do this in php?

A: There are many ways to solve this.

*

*Use parse_url and get the path

*Find the position of the / character and then extract the string based on that

*Use a regular expression (/\d+$/)

*Trim the numbers off the end (rtrim($url, '0123456789')), compare the lengths and, if not the same, calculate the difference and then extract the number.

*Using a simple loop you can iterate over the string backwards, checking if the characters are numbers. If they are then prepend them to a string, otherwise stop the loop.

I could probably find other ways to do it but I think this should do just fine. If you cannot figure it out then it is because of a lack of imagination.

A: this piece of code is work for me
 $id = substr($url, strrpos( $url, '/' )+1);

strrpos gets the position of the last occurrence of the slash; substr returns everything after that position.

A: try:
$url = "http://www.example.com/123";
echo str_replace('/','', parse_url($url, PHP_URL_PATH));

A: You can use this code to achieve what you want:
<?php
    $uri = explode( '?', $_SERVER['REQUEST_URI'] );
    $uri = $uri[0];
    $part_uri = explode( "/", $uri);
    print_r( $uri );
    print_r( $part_uri );
?>

$part_uri will become an array of the current website path.
For example will http://adomain.com/manual/test result in:
Array ( [0] => [1] => manual [2] => test )

So to get your "123" you would use $part_uri[1]

A: You can try:
end(explode('/', $url))

A: try substr()
echo substr('http://www.example.com/123', -3);

or parse_url()
$p =parse_url('http://www.example.com/123');
echo str_replace('/', '', $p['path']);


text:
Q: Meteor: How to get account password reset token only, no email I am looking to use a sendgrid template to send the account password reset email.
So basically instead of using the function Accounts.sendResetPasswordEmail I need the function Accounts.getResetPasswordURL
Which will give me a password reset URL which I can use to send over to sendgrid which will be used in a template.
So how can I do this? How can I use Meteor to just get the password reset URL but not actually send the email? I will send the email with the URL manually using a API call to sendgrid.

A: Note: I haven't used sendgrid, so I'm going by the API over here.
First off, you want to configure Meteor to use Sendgrid's SMTP servers. This way, you can send e-mails straight through Meteor:
Meteor.startup(function(){
    process.env.MAIL_URL = "smtp://" + sendgridUsername + ":" + sendgridPasswordOrAPIkey + "@smtp.sendgrid.net:465";
});

You can change the default template for the reset e-mail. This can be done by modifying Accounts.emailTemplates:
Accounts.emailTemplates.resetPassword.html = function(user, url){
    // url contains the reset url! :)
    var result;
    var sendgridTemplateId = ''; // Set this to the template id you're using in sendgrid
    try {
        // Get sendgrid template
        // API link: https://sendgrid.com/docs/API_Reference/Web_API_v3/Template_Engine/templates.html
        result = HTTP.get("https://api.sendgrid.com/v3/templates/" + sendgridTemplateId);
        result = result.data.templates[0].versions[0].html_content;
        // then insert URL to the template
    } catch (error) {
        console.error('Error while fetching sendgrid template!', error);
        return false;
    }
    return result;
};

Now when you use Accounts.sendResetPasswordEmail() the above template will be used, which actually just fetches the sendgrid template and returns that!

A: This is not really possible with the way the procedure is performed at the moment.
The accounts-password package generates a random token and sends the email in the sendResetPasswordEmail() method.
You can either fork the package, generate your own token the way it is done in the original method, or change the behavior of the email package to handle email on your own.