text:
Q: Verb (of perception) + objective + bare infinitive / gerund I have a question regarding the verb pattern :
[ Verb (of perception) + objective + bare infinitive / gerund ]
Why in some cases we use a bare infinitive :

*

*He heard the door open and bank shot in the other room.

*Do you like seeing people compete on reality shows? if so, which ones?

And sometimes we use gerund:

*

*When we reached the station we could hear the train arriving.

*On reality shows, you often see people behaving badly. Do you think shows like that are a bad influence on society?

A: First of all, a point of terminology. The forms ending in "-ing"in your question are not gerunds. They are present participles. A gerund is a word derived from a verb, that functions as a noun, or in some cases as an adjective.  A present participle is an actual verb form. The confusion is that in most verbs, they have the same spelling, and can only be distinguished by their usage.
Secondly, in most of the cases you list, either an -ing form or a present-tense form may be used, with only a slight change of meaning. Consider ther following pairs:

*

*(1A) He heard the door open.

*(1B) He heard the door opening.

*

*(2A) Do you like seeing people compete on reality shows?

*(2B) Do you like seeing people competing on reality shows?

*

*(3A) we could hear the train arrive.

*(3A) we could hear the train arriving.

*

*(4A) On reality shows, you often see people behave badly.

*(4B) On reality shows, you often see people behaving badly.

In each case, the B form emphasizes the event, while the A member emphasizes the action that takes place.  But in each pair, the two sentences are both grammatically valid and have very similar meanings.
The question implies that in each case only one form or the other is correct, or at least that one form is much more widely used than the other in each case, and asks why this is. Well both are correct. It may well be that one form is more commonly used. But usage frequencies follow changes in style and fashion, and are not generally subject to rules.

In addition somewhat similar pairs with no verb of perception involved. For example:

*

*(6A) The blacksmith had started to forge a sword when I entered the workshop.

*(6B) The blacksmith had started forging a sword when I entered the workshop.

Note that this is a somewhat different form from cases 1-5, and from the examples in the question. Depending on the verb and the construction, in some cases a participle form will be correct, and in some cases it will not. In some cases a non-participle  form will be correct. In some either will be correct. My point is that often a sentence using a participle form can be rephrased to use a non-participle  form with only minor change of meaning. But not in all cases.

A: You can use either. These are all valid (except I don't know what "bank shot" means):

He heard the door open and bank shot in the other room.
He heard the door opening and bank shot in the other room.

Do you like seeing people compete on reality shows? if so, which ones?
Do you like seeing people competing on reality shows? if so, which ones?

When we reached the station, we could hear the train arriving.
When we reached the station, we could hear the train arrive.

On reality shows, you often see people behaving badly. Do you think shows like that are a bad influence on society?
On reality shows, you often see people behave badly. Do you think shows like that are a bad influence on society?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Make custom cell's ( created with autolayout) height to zero I want to make height of a custom tableview cell to zero, which was created with autolayout. Basically I have container view added as subview to cell.contentview. Container view's top, bottom, left and right are pinned to content view's  top, bottom, left and right. Under certain condition I want to make height as 0.
I iterated through content views's constraints and found this constrain causing the problem.
NSLayoutConstraint:0x1369d8670 UITableViewCellContentView:0x1369b1a90.height == 48
This constraint is added by default by tableview.
Things I Tried : I removed all subviews of container view. But this does not make cell height to zero.
Things I don't want to do:

*

*I dont want to reload entire tableview coz I will be having many rows with many subviews.

*I don't want to delete row

How can I set height to zero?

A: You can reload particular row so it will call tableview's delegate method for height change heightForRorAtIndexpath. You can set the height 1 when you programmatically reload particular row. You can store temporary indexpath which you want to make zero.
Clip all the subiviews by clipsToBounds=YES
call [self.tableView layoutIfNeeded];


text:
Q: Remove editions of Windows 7 Iso I downloaded an ISO of Windows 7 64 bits, I have a problem: I saw 4 editions in .clg files (home basic, premium, professional and ultimate), I opened install.wim with 7zip and I saw folders called 1,2,3 and 4. I suppose numbers are the 4 editions I mentioned.
How to remove editions from ISO? My problem is those editions makes iso size be up to 5.5 GB. I just need ultimate, no more editions needed.

A: First run Dism /Get-WimInfo /WimFile:DVDDRIVELETTER:\sources\install.wim to see which index the Edition has you want to have alone:

Deployment Image Servicing and Management tool Version: 6.3.9600.17029
Details for image : E:\sources\install.wim
Index : 1 Name : Windows 7 HOMEBASIC Description : Windows 7 HOMEBASIC
  Size : 11.623.452.494 bytes
Index : 2 Name : Windows 7 HOMEPREMIUM Description : Windows 7
  HOMEPREMIUM Size : 12.136.659.100 bytes
Index : 3 Name : Windows 7 PROFESSIONAL Description : Windows 7
  PROFESSIONAL Size : 12.037.929.390 bytes
Index : 4 Name : Windows 7 ULTIMATE Description : Windows 7 ULTIMATE
  Size : 12.200.638.813 bytes
The operation completed successfully.

You want ultimate so run this command with the index 4 for Ultimate:
Dism /Export-Image /SourceImageFile:DVDDRIVELETTER:\sources\install.wim /SourceIndex:4 /DestinationImageFile:C:\Win7Ultimate\sources\install.wim /DestinationName:"Windows 7 Ultimate"

This new ISO should now only include the Ultimate Edition.


text:
Q: Export all subscription RBAC with focusing on Azure AD groups and resolving users assigned What would be best way to export all subscriptions with their RBAC but focusing on AAD groups and resolving user membership? I seems to be lost in if statement.
Get-AzSubscription |

foreach-object {

    Write-Verbose -Message "Changing to Subscription $($_.Name)" -Verbose

    Set-AzContext -TenantId $_.TenantId -SubscriptionId $_.Id -Force
    $Name     = $_.Name
    $TenantId = $_.TenantId
    $SubId    = $_.SubscriptionId

        Get-AzRoleAssignment -IncludeClassicAdministrators | Select-Object RoleDefinitionName,DisplayName,SignInName,ObjectType,Scope,
    @{name="TenantId";expression = {$TenantId}},@{name="SubscriptionName";expression = {$Name}},@{name="SubscriptionId";expression = {$SubId}
    }

        if(Get-AzRoleAssignment.ObjectType -eq "Group")
        {
        Get-AzADGroup -ObjectId.Id  | Select-Object DisplayName,SignInName,ObjectType,Scope | foreach-object { Get-AzADUser | Select-Object UserPrincipalName,ObjectType,Id
            }
        }
        else { continue }
    }

-OutVariable ra
$ra | Export-Csv -Path .\Export-SubAzRolesGroups-$Name.csv -NoTypeInformation
}

A: Easiest / quickest way would probably be to use powershell with the az module, write a little script to, get all subscriptions that account has access to (hopefully using some kind of tenant wide reading permission user), then get all role assignments for each subscription, and do whatever you need to do get the groups, and get members for each group. the write it all out to files.
the powershell commands you want to look into is:
get-azsubscription
get-azroleassignment
get-azadgroup
get-azaduser
other options include, you can use azure resource manager Rest API, or some other azurerm library to write an application that does the same.
hopefully that gets you started.
UPDATE
Get-AzSubscription |
foreach-object {
    Write-Verbose -Message "Changing to Subscription $($_.Name)" -Verbose

    Set-AzContext -TenantId $_.TenantId -SubscriptionId $_.Id -Force
    $Name     = $_.Name
    $TenantId = $_.TenantId
    $SubId    = $_.SubscriptionId

    Get-AzRoleAssignment -IncludeClassicAdministrators | Select-Object RoleDefinitionName,DisplayName,SignInName,ObjectId,ObjectType,Scope,
    @{name="TenantId";expression = {$TenantId}},@{name="SubscriptionName";expression = {$Name}},@{name="SubscriptionId";expression = {$SubId}} |
    foreach-object{ if($_.ObjectType -eq "Group")
        {
            $_ | ft
            $group = Get-AzADGroup -ObjectId $_.ObjectId
            $group | Select-Object DisplayName,SignInName,ObjectType,Scope | ft
            $group | Get-azadgroupmember | Select-Object UserPrincipalName,ObjectType,Id | ft
        }
        else { $_ | ft}
    }
} -OutVariable ra
$ra | out-file .\Export-SubAzRolesGroups-$Name.csv


text:
Q: Estimation with an orthonormalbasis in some finite dimensional subspace of $L_2(\Omega)$
I'm currently trying to understand a step of a proof of the following estimation:

$\displaystyle \sum_{j=2}^{N} \left(\left< \varphi_1-R_N\varphi_1, \varphi_{j,N} \right>_{L_2}\right)^2 \ \leq \ \displaystyle \sum_{j=1}^{N} \left(\left< \varphi_1-R_N\varphi_1, \varphi_{j,N} \right>_{L_2}\right)^2 \ \leq \ \| R_N \varphi_1 - \varphi_1 \|_{L_2}^2$
Where $\{ \varphi_k \}_{k=1}^{\infty}$ is a $L_2$-orthonormalbasis of $L_2(\Omega)$ and $\{ \varphi_{k,N} \}_{k=1}^{N}$ is a $L_2$-orthonormalbasis of some finite dimensional subspace $S_N \subset L_2(\Omega)$ with $\dim(S_N) = N$. Further information about the functions $R_N(\varphi_1) \in S_N$ are below if they're required to solve this problem.
I suppose that this has something to do with the orthonormality of the functions $\varphi_{j,N}$ since it kinda looks like the $ \mathbf{Parseval \ identity}$:
$\displaystyle \sum_{j=1}^{N} \left(\left< u_N, \varphi_{j,N} \right>_{L_2}\right)^2 \ = \ \| u_N \|_{L_2}^2$
Which holds for all $u_N \in S_N$, since $\{ \varphi_{k,N} \}_{k=1}^{N}$ is an $L_2$-orthonormalbasis of $S_N$.
But here we got $\varphi_1 \in L_2(\Omega)$, not necessarily be in $S_N$. I looked this proof up in three different sources and they all said nothing to this step, so i assume this is probably not very hard but i thought a whole day over this step and i couldn't figure out why this should be true, so i need some help.
I don't know if it's required, but here are also additional information what this $R_N$ and $\varphi_k$ is supposed to be:
$R_N:H^1_0(\Omega) \to S_N$ is some projector ("Ritz-Projector") on $H^1_0 \subset L_2(\Omega)$ defined as orthoprojector according to the $H^1_0(\Omega)$-scalar-product $a( \dot{} , \dot{} ) := \left< \nabla \dot{}, \nabla \dot{} \right>_{L_2}$, i.e. $R_N$ is defined by:
$a(R_N u, w_N) = \left<u,w_N\right>_{L_2} \ \ \forall w_h \in S_N$ and $u \in H^1_0(\Omega)$
The $\varphi_k$ and $\varphi_{k,N}$ are supposed to be $L_2$-normalized eigenfunctions of the weak formulation of the Laplace-Operator with zero-boundary-conditions, i.e.:
$-\Delta \varphi_k = \lambda_k \varphi_k$ on $H^1_0(\Omega)$ in the weak sense, and
$-\Delta \varphi_{k,N} = \lambda_{k,N} \varphi_{k,N}$ on $S_N$ in the weak sense
With sorted eigenvalues
$0 < \lambda_1 < \lambda_2 \leq \lambda_3 \leq \dots$, and  $0 < \lambda_{1,N} \leq \lambda_{2,N} \leq \dots$
I would be grateful for some help!
Thank You!

A: Perhaps one way to see this is to notice that if $f \in L^2$, then you can write $f = f_{//} + f_{\perp}$ where $f_{//} \in S_N$ and $f_{\perp} \in S_N^{\perp}$. In particular, $\|f\|_{L^2}^2 = \|f_{//}\|_{L^2}^2 + \|f_{\perp}\|^2_{L^2}$, which implies that $\|f\|_{L^2}^2 \geq \|f_{//}\|_{L^2}^2$. Notice that $\langle f, \varphi_{j,N}\rangle = \langle f_{//}, \varphi_{j,N} \rangle$ and so $$\sum_{j=1}^N \langle f, \varphi_{j,N}\rangle = \sum_{j=1}^N \langle f_{//}, \varphi_{j,N} \rangle = \|f_{//}\|_{L^2}^2 \leq \| f\|_{L^2}^2$$


text:
Q: redirect traffic to aws S3 / Cloudfront but keep dns and email at namesecure I have a domain registered at Namesecure but want to host the content on AWS S3 (also using Cloudfront).  I want to keep DNS and email handling at Namesecure. How should I go about this?  Thank you!
edit, added this:
I have read the material referenced below, thank you!  I have created a hosted zone in Route 53 and a Cloudfront distribution.  But I'm still not sure how to connect that with the DNS on Namesecure.
I don't want to change the DNS to AWS, because I want to maintain the email setup on Namesecure.
I was thinking of editing A records in the Zone File on Namesecure, but that would require an IP address on AWS to point the A records at, and I don't see that I have an IP address.
Currently, the A records in Namesecure look like this:
A Records:
  www.mydomain.com. IN A 205.178.189.131
  mydomain.com. IN A 205.178.189.131
  *.mydomain.com. IN A 205.178.189.131

When I created the Route 53 hosted zone, it automatically created an NS record with four Amazon DNS servers:
ns-78.awsdns-09.com
ns-649.awsdns-17.net
ns-1649.awsdns-14.co.uk
ns-1477.awsdns-56

Current nameservers at Namesecure are:
DNS1.NAMESECURE.COM207.204.40.155
DNS2.NAMESECURE.COM207.204.21.155

It seems to me I need to tell Namesecure to use the AWS name servers for web access but not for email.
Maybe I need to use the URL forwarding feature at Namesecure?  But if I forward it to the S3 URL (e.g. http://mydomain.com.s3-website-us-west-2.amazonaws.com) I'm bypassing Cloudfront.  Perhaps I forward to the Cloudfront domain name (e.g. kjhklsdhfksdfhkjsdh.cloudfront.net) with "URL gripper" on so that the user will still see mydomain.com in the address bar?
But, experimenting with that, it seems to be working for the main site, mydomain.com but not for instance for mydomain.com/myfolder/index.html
Also, no matter what folder (page) I go to (by clicking on menu choices on the main page), the URL remains mydomain.com, which is not ideal -- I'd rather have it reflect the folder I'm in.

A: *

*Find Amazon's documentation for how to setup your-own-domain-DNS to point to their infrastructure (AWS, Cloundfront, etc.). Here is some of their documentation on that

*Login to Namesecure, setup DNS there to point 80/HTTP & 443/HTTPS & anything else to AWS. Their Product Setup page details:

What it does:
  Using NameSecure's DNS will mean that all web forwarding, e-mail
  forwarding, MX records, CNAMEs and A Records will be handled by
  NameSecure. (You can change your nameservers at any time.)
How to use it

*

*Log in to My Account and click Modify/Update for the domain name.

*Click the WHOIS Info tab.

*Click Modify Domain Name Servers.

*Click Ok.


text:
Q: How to retrieve the current ID of sequence without using seq.currval i need last id that insert into persons for some manipulation in java.
I have two insert then if I use getGeneratedKeys I get "operation not allowed" error. I use a select query to retrieve current value of sequence but it cause "an into clause is expected" error. How could I manage to access to last person id.
The query:
    begin
        insert into Persons
           (Id,First_Name,Last_Name)
           values (person_seq.nextval  ,?  ,?  );
        insert into Relations (relation_id, person_id)
            values (relation_seq.nextval,person_seq.currval);
        SELECT person_seq.currval FROM DUAL;
    end;

the java code:
    stmt = connectionManager.getConnection().prepareStatement(query);//,new String[] {"ID"});
    stmt.setString(1, family.getFName());
    stmt.setString(2, family.getLName());
    ResultSet resultSet = stmt.executeQuery();
    ret = resultSet.getLong(1);

A: You can declare a variable to store the new id with RETURNING INTO clause:
declare
   new_id number; --or your id row type
begin
        insert into Persons
           (Id,First_Name,Last_Name)
           values (person_seq.nextval  ,?  ,?  )
           returning id into new_id;
        insert into Relations (relation_id, person_id)
            values (relation_seq.nextval,person_seq.currval);
end;


text:
Q: is using .catch with async await can cause problem? My question is, using .catch with async await can cause problem ?
for example:

function f1() {
  return new Promise((res, rej) => {
    rej(1)
  })
}

async function f2() {
  await f1().catch(ex => { }) // this is what I mean
}

f2()

A: I think what you're looking for is this
function f1(){
  return new Promise((res,rej)=>{
    rej(1)
  })
}

async function f2(){
  try {
    const response = await f1();
    // use the response from f1()
  } catch(err) {
    throw new Error(err);
  }
}

f2()

something along these lines as async/await is a wrapper for promises that allow you to write synchronous-looking code. Otherwise you'd be looking at
function f2(){
  let response;
  f1().then(res => {
    response = res
  })
  .catch(err => {
    throw Error(err)
  });
}

A: It depends on what you mean with "problem", but this code:
async function f2() {
  await f1().catch(ex => { /* ... code in catch ... */ }) // this is what I mean
}

is equivalent to:
async function f2() {
  try {
    await f1()
  } catch (ext) {
    /* ... code in catch ... */
  } // this is what I mean
}

And as you said it can be useful to use .catch instead of try-catch as is can - not in every case - make your code more readable. But you need to always think about if .catch is the right choice for readability. It works well if you use it for recoverable error handling.


text:
Q: Javascript Quiz - problems reaching the next sibling through next() method on jQuery I'm creating a quiz with JavaScript where I'm trying to use the jQuery to make 1 question appear at a time. I was able to get the html to show only one question on the page, by hiding the other elements, but for some reason I can't get the next sibling to show.
The jQuery API Documentation says the next() method reaches for the sibling element, but I'm not sure where the problem is.
My jQuery code is.
  function main()
  {
    $('.slide').hide();
    $('.active-slide').show();

    var currentSlide = $('.active-slide')
    var nextSlide = currentSlide.next();

    $('.btnNext').click(function() {
      currentSlide.removeClass('active-slide');
      nextSlide.addClass('active-slide');
    })

  }
  $(document).ready(main);

My HTML is.

Question 1: Answer is A!

          <input type="radio" name="q1" value="correct">A</input>

          <input type="radio" name="q1" value="incorrect">B</input>

          <input type="radio" name="q1" value="incorrect">C</input>

          <input type="radio" name="q1" value="incorrect">D</input>
          <input type="button" class="btnNext" value="Next">

Question 2: Answer is B!

          <input type="radio" name="q2" value="incorrect">A</input>

          <input type="radio" name="q2" value="correct">B</input>

          <input type="radio" name="q2" value="incorrect">C</input>

          <input type="radio" name="q2" value="incorrect">D</input>
          <input type="button" class="btnNext" value="Next">

The console on Chrome shows no errors which makes it harder to find.
Thanks for any help.

A: The first issue is the result of a jQuery selector is not live meaning if the selector properties of an element changes the cached object will not get updated. So you need to find the active slide inside the event handler.
The second issue could be related to css, since you are using hide() to hide the element, it will be using an inline display rule, but to show the element back you are only setting the active-slide class which might be having a lower order rule.

function main() {

  $('.btnNext').click(function() {
    var currentSlide = $('.active-slide').removeClass('active-slide');
    currentSlide.next().addClass('active-slide');
  })

}
$(document).ready(main);
.slide {
  display: none;
}
.slide.active-slide {
  display: block;
}

Question 1: Answer is A!

  <input type="radio" name="q1" value="correct">A

  <input type="radio" name="q1" value="incorrect">B

  <input type="radio" name="q1" value="incorrect">C

  <input type="radio" name="q1" value="incorrect">D
  <input type="button" class="btnNext" value="Next">

Question 2: Answer is B!

  <input type="radio" name="q2" value="incorrect">A

  <input type="radio" name="q2" value="correct">B

  <input type="radio" name="q2" value="incorrect">C

  <input type="radio" name="q2" value="incorrect">D
  <input type="button" class="btnNext" value="Next">

A: Your problem is that you only run the jQuery hide and show functions once; changing the classes of your divs isn't going to run that code again.  Your jQuery needs to do something like this JSFiddle.
This way, the shown div is updated each time the classes are changed.


text:
Q: Проверка орфографии слова из слов в базе Как написать программу для проверки "орфографии слова" из слов, которые записаны в базе, в VB.net 2008, не предлагать открытие Word-а в фоновом режиме.
A: Можно использовать любую библиотеку для .NET, например, NHunspell, которая поддерживает словари OpenOffice.
Алгоритм работы обычный: запрос к словарю, если слово неверное, - список возможных кандидатов.


text:
Q: tkinter:2 windows pop up at the same time As a beginner, I am not familiar with tkinter and I don't know how to improve the following codes which are supposed to function like this:
After running the renamer_v.py file, a window will pop up. It displays a short description at the top and beneath it there is an orange colored buttion 'Click Me'. Click the button and then pop up the second window to select a folder. All titles of files in the folder except the hidden ones and subfolders will be given a serialized prefix.
The problem is that the main window and the second widnow pop up at the same time. Howver, the latter is designed to appear after users clicked the button.
Here is my souce code.
renamer_V1.py:
import win32file
import win32con
import tkinter as tk
from tkinter import Button
from clicked import Clicked

root=tk.Tk()
root.geometry("550x200")
label=tk.Label(root,font=("Arial Bold",15),
              text='Please select a directory to rename files in the folder:')
label.pack()
c=Clicked()
btn=Button(root,font=("Arial",15),bg='orange',text="Click Me",command=c.clicked)
btn.pack()

c.clicked()
file_lists=os.listdir(c.file_path)
n=0

for file in file_lists.copy():
    oldname=c.file_path+os.sep+file
    file_flag=win32file.GetFileAttributesW(oldname)
    is_hiden=file_flag & win32con.FILE_ATTRIBUTE_HIDDEN

    if os.path.isdir(oldname) or is_hiden:
        continue
    else:
        oldname=c.file_path+os.sep+file
        newname=c.file_path+os.sep+'('+str(n+1)+')'+file
        os.rename(oldname,newname)
        n+=1
label=tk.Label(root,text=str(n)+' file(s) renamed.')
label.pack()
root.mainloop()

clicked.py:

from tkinter import filedialog

class Clicked:
    file_path=None

    def __init__(self):
        print()

    def clicked(self):
        self.file_path=filedialog.askdirectory(title='ReNamer')

A: The application is completed and now it is working perfectly under MacOS as desired. Here is the code:
import os
from tkinter import filedialog
import tkinter as tk
from tkinter import Button

root=tk.Tk()
class ReName():
    def __init__(self):
        self.n = 0
        self.label1=tk.Label(root)

    def rename(self):
        file_path = filedialog.askdirectory(title='ReNamer')
        self.file_lists = os.listdir(file_path)
        for self.file in self.file_lists.copy():
            self.oldname = file_path + os.sep + self.file
            if os.path.isdir(self.oldname) or self.file.startswith('.'):
                continue
            else:
                self.newname = file_path + os.sep + '(' + str(self.n + 1) + ')' + self.file
                os.rename(self.oldname, self.newname)
                self.n+=1
        self.label1.config(text='{} file(s) renamed'.format(self.n))
        self.label1.pack()
        btn.config(state='disabled')

ins=ReName()
root.geometry("550x200")
label=tk.Label(root,font=("Arial Bold",15),
               text='Please select a directory to rename files in the folder:')
label.pack()
btn=Button(root,font=("Arial",15),bg='orange',text="Click Me",command=ins.rename)
btn.pack()
root.mainloop()


text:
Q: how to autoincrement the default value in texbox Is there a way to autoincrement default value in text box assuming data type as text without having to create table? i needed this to happen when form loads.

A: This cannot be done when a form is opened, so you would need to call this Sub (located in a Module) to open the form:
Sub ChangeDefaultValue()
  DoCmd.Close acForm, "Form1"
  DoCmd.OpenForm "Form1", acDesign, , , , acHidden
  Dim f As Form
  Set f = Forms("Form1")
  Dim dv As Integer
  dv = f.Controls!Text0.DefaultValue
  f.Controls!Text0.DefaultValue = dv + 1
  DoCmd.Close acForm, "Form1", acSaveYes
  DoCmd.OpenForm ("Form1")
End Sub

You will need to change the form name "Form1" and TextBox name "Text0" to your names.


text:
Q: PHP can't open outlook to send email I am trying to send an email from php, I CAN'T USE SMTP or normal ways of sending email because smtp servers are blocked on my network. I have outlook 2016 installed on my server machine (windows 10 IIS) and found this code to use outlook to send email from php but it dosen't work.
Here is the code:
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
$subject="This is a test message";
$message="This is a Body Section now.....! :)";
$to="someaddress@somedomain.com";

// starting outlook
com_load_typelib("outlook.application");

if (!defined("olMailItem")) {define("olMailItem",0);}

$outlook_Obj = new COM("outlook.application") or die("Unable to start Outlook");

//just to check you are connected.
echo "Loaded MS Outlook, version {$outlook_Obj->Version}\n";
$oMsg = $outlook_Obj->CreateItem(olMailItem);
$oMsg->Recipients->Add($to);
$oMsg->Subject=$subject;
$oMsg->Body=$message;
$oMsg->Save();
$oMsg->Send();
?>

I am getting this error:
Fatal error: Uncaught exception 'com_exception' with message 'Failed to create COM object `outlook.application': Access is denied. ' in C:\Website2\test.php:13 Stack trace: #0 C:\Website2\test.php(13): com->com('outlook.applica...') #1 {main} thrown in C:\Website2\test.php on line 13


text:
Q: How can i referral user on my website using facebook register? I have social game website and my user want to get some benefit when they invite there friends. I only use login with facebook and register with facebook only with minimum detail  fullname and email
My idea is using referral but i have no idea how i can do that. website register is on click step.
if(!$user) {
    header("Location:$loginUrl");
} else {
    // check if user is register else login
    // if not register then register and take them to home page.
    $firstname = mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $user_info['first_name']);
    $lastname = mysqli_real_escape_string($GLOBALS["___mysqli_ston"], $user_info['last_name']);
    $email = $user_info['email'];
    // all register process goes here
}

So please any idea anyone can give me about referral if u need more detail about my register  i can give.
Thank you.


text:
Q: horizontal scrolling for Div using Protractor I am trying to scroll to the right, but nothing helps
I have tried
await browser.executeScript('arguments[0].scrollIntoView(true)',element.getWebElement())

but it's not working

A: Try this
let location = await $element.getLocation();

await browser.executeScript(
  `
    window.scroll(
      ${location.x},${location.y}
    );
  `
)

I haven't tested but the approach should work

A: I use mouseMove to scroll till the end of page and it works perfectly fine for me, I think same should work for horizontal scroll also.
browser.actions().mouseMove(element(by.css("provide element in the right most corner"))).perform();


text:
Q: What is Java EE reference implementation?
Unlike the Java EE standard, MicroProfile does not have a reference
  implementation but only TCKs (test compatibility kits) to pass.

(MicroProfile Technical White Paper, Lars Röwekamp)
I know GlassFish has served as a reference implementation of Java EE. I want to know what exactly is a reference implementation?


text:
Q: Room void methods on main thread When using the Room library for Android the documentation clearly states that we cannot make calls on the main thread unless we specifically allow them. What I'm curious about is methods that have a void return type. It seems silly that returning LiveData will automatically run them off the main thread, but void types will not (unless I'm missing something). Is there any easy way I can do this without having to run this in my own managed thread?
My Query:
@Dao
interface UserDao {
    @Query("DELETE FROM users")
    fun clear()
}

I've even tried using Kotlin reflection + extension functions, but this seemed to fail during runtime:
fun KFunction<Unit>.execOn(executor: Executor, vararg args: Any?) {
    executor.execute {
        this.call(args)
    }
}

Then make a call like:
myDb.userDao()::clear.execOn(diskExecutor)

Note what does work is:
diskExecutor.execute {
    myDb.userDao().clear()
}

A:
It seems silly that returning LiveData will automatically run them off the main thread, but void types will not (unless I'm missing something).

Without some sort of annotation, Room would have no idea that you want a void-returning DAO method to be run on a background thread. With a reactive return type (e.g., LiveData, Single), you are explicitly requesting background execution, so no additional metadata (e.g., an annotation) is required.
You might consider filing a feature request for such an annotation-based approach.

Is there any easy way I can do this without having to run this in my own managed thread?

If you are asking "does Room have a background-execution option for DAO methods other than those with reactive return types?", then the answer is no, at least at the present time.


text:
Q: Issues with kudan camera while merged with native android application I got a requirement where I need to merge the unity application with the native android app, I am using Kudan plugin in the unity 3d, I have exported the unity project to the android studio and created a new app in the android studio and merged the Unity app to native android app.Once I tested the build, everything is working fine except a camera(Kudan camera).Ar camera is not working as expected.I am using free ver of Kudan plugin.I have tested it without merging with the native app and it is working fine, in this case, If I merge unity app with native android app camera is not working fine.

A: I am facing same issue, it will stop working camera torch of system too when you extending class ARActivity you can't able to access setFlashMode() method
Test this case in your phone by opening application and then trying to on/off torch.
Torch will be disable from system.
After then try with extending Activity class
recently i have ask same question


text:
Q: Debug Tomcat deployed code with cargo plugin Can anyone please tell how to debug the code in eclipse with Cargo(Tomcat) plugin?
We are using Java 8, Tomcat 8, eclipse Juno in Windows 7 OS.
One other thing I want to mention is, we don't have control to modify Tomcat scripts as the tomcat is freshly getting installed from Nexus repository(or from local repo cache) for every execution of mvn -P dev clean package cargo:run.

A: For debug Cargo, you can configure you container like by this:
<container>
  <containerId>tomcat4x</containerId>
  <home>c:/apps/jakarta-tomcat-4.1.30</home>
  <log>target/cargo.log</log>
  <logLevel>debug</logLevel>
</container>

If you want to debug container, then set JVM with this:
-Xdebug
-Xrunjdwp:transport=dt_socket,server=y,suspend=<suspend>,address=<port>
-Xnoagent
-Djava.compiler=NONE

More information about Cargo debugging is here.
I wrote a blog post about maven cargo plugin for using integration test. Maybe it will help you. http://hrabosch.com/2016/06/12/how-to-run-integration-tests-with-cargo-maven-plugin-in-a-separate-container/
There is Jetty, but you can change it to tomcat.


text:
Q: Windows 10 (32-bit): MinGW-w64 doesnt work I've tried to compile my source files using minGW-w64, because of new C++14 standard but when i try to compile i got this error even all things and setup is allright i guess:
Execution of 'g++.exe   -c C:\Users\Denis\Desktop\isocpp.cpp -o C:\Users\Denis\Desktop\isocpp.o' in 'C:\Users\Denis\Desktop' failed.
MinGW-w64 Screenshot
My PC version is 32bit, from the official site i was notified that MinGW-w64 works for 64-32bit.

A: There are two distinctions to make here:

*

*Whether gcc.exe is a 32-bit binary or a 64-bit binary

*Whether that binary will generate programs that target 32-bit or 64-bit

mingw-w64 supports all four possible combinations here. But it sounds like you have downloaded a 64-bit binary.  32-bit Windows cannot run 64-bit binaries.
To fix this, use the official installer  (warning:Sourceforge, although it is not hosted anywhere else so far as I know), or look out when downloading prepackaged builds.


text:
Q: Android - second onActivityResult not being called I have 3 classes from FragmentActivity called A - B - C...
A extends Fragment and calls to B using:
Intent intent = new Intent(getActivity(), B.class);
startActivityForResult(intent, RESULT);

Bextends FragmentActivity and calls to C using
Intent intent = new Intent(B.this, C.class);
startActivityForResult(intent, RESULT);

The problem is, whe return from C, using:
Intent returnIntent = new Intent();
setResult(Activity.RESULT_OK, returnIntent);

Instead to return to onActivityResult of B, it returns to onActivityResult of A.
How can I return step by step, coming in order through each onActivityResult?
Thanks in advance.


text: Q: ITPSubscribe - how to make links? i have plugin and module ITP Subscribe on my website and I don't know how to make links. I need extension which allows users to subscribe content form the website. It doesn't work now. joomla 3. Help, please :)


text:
Q: Errors when running unit tests in Kitura I am new to the Kitura and Xcode and facing some issues when adding test files.
It seems to be related to the @testing directive.
I have setup the same as shown on Kitura website.
When I invoke in the console swift build then swift test I get following error:
Compile Swift Module 'testTests' (1 sources)
Linking ./.build/debug/testPackageTests.xctest/Contents/MacOS/testPackageTests
Undefined symbols for architecture x86_64:
  "__TFC4test3OkoCfT_S0_", referenced from:
      __TFC9testTests8OkoTests8test_addfT_T_ in OkoTests.swift.o
  "__TMaC4test3Oko", referenced from:
      __TFC9testTests8OkoTests8test_addfT_T_ in OkoTests.swift.o
ld: symbol(s) not found for architecture x86_64
<unknown>:0: error: link command failed with exit code 1 (use -v to see invocation)
<unknown>:0: error: build had 1 command failures
error: exit(1): /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift-build-tool -f /Users/*user*/Projects/Kitura/test/.build/debug.yaml test

However when I comment out line @testable import test and type swift build then swift test then I get following error:
Compile Swift Module 'testTests' (1 sources)
/Users/*user*/Projects/Kitura/test/Tests/testTests/OkoTests.swift:6:17: error: use of unresolved identifier 'Oko'
        let o = Oko()
                ^~~
<unknown>:0: warning: 'cacheParamsComputed' is deprecated
<unknown>:0: warning: 'cacheAlphaComputed' is deprecated
<unknown>:0: warning: 'keepCacheWindow' is deprecated
<unknown>:0: error: 'memoryless' is unavailable
Metal.MTLCommandBufferError:19:14: note: 'memoryless' has been explicitly marked unavailable here
        case memoryless
             ^
<unknown>:0: error: build had 1 command failures
error: exit(1): /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift-build-tool -f /Users/*user*/Projects/Kitura/test/.build/debug.yaml test

When I try to test it from Xcode generated project instead (swift package generate-xcodeproj) then I get compile error:

Without Testing files, everything works properly.
Below I present project structure:

A: I believe the issue is that Swift is not able to compile unit tests for modules that contain a main.swift file (i.e., modules that are meant to be compiled into executables as opposed to libraries for use in other projects). I cloned your repo and was able to compile and run unit tests after 1) removing main.swift and 2) uncommenting the testable import statement.


text:
Q: Using Bootstrap with Rails 4. Why do I get empty space between  with each_slice( )? I'm using Bootstrap with Rails 4. I'm creating two columns with each_slice(). However, with the following code, I get an empty big space on the left hand column.
<% @projects.each_slice(1) do |projects| %>

           <% projects.each do |project| %>

<%= project.name %>

           <% end %>

<% end %>

So to explain further, I get the following html:

This is displayed on the left

This is displayed on the right

This is displayed on the right

This is displayed on the left

This is displayed on the right

This is displayed on the left

This is displayed on the right

This is displayed on the left

The divs are of different length. How could I display them evenly, without getting a huge space sometimes between the divs? I have checked all the paddings and margins, and it's not because of them.

A: I think the problem is that there's no "left" div between the 2nd and third divs.  each_slice groups an array into subarrays, but i don't see what the point of splitting them into groups of one element each is, which is what you're doing when you call @projects.each_slice(1).  That could be simplified to
<% @projects.each do |project| %>

<%= project.name %>

<% end %>

But, i don't think that's your problem.  What html do you actually want to generate, if what you listed isn't what you want?


text:
Q: How to graph the data points of n dimensions? I'm very new to data science. I'm wondering how is it possible to graph data of n dimension. For example by Clustering high-dimensional data
https://en.wikipedia.org/wiki/Clustering_high-dimensional_data
How do we graph these data points? Do we use a specific data structure? Do we take only the three more relevant dimensions?

A: There are many techniques. They usually fall within the category of "manifold learning" and "dimensionality reduction" techniques. In both cases, it is assumed that the data lives in a much lower dimensional manifold as the original data.
For the purpose of visualization, you look for a mapping of your data to the plane, such that vicinity (topological distance) is preserved. That is, points mapped close to each other, are also close to each other in the original space.
One recent, very popular technique is tSNE, but there is a bunch of others.

A: Principal components analysis is always an option for reducing the number of variables you need to display. Alternatively, you can use things like point (on a graph) size, color, and shape to differentiate among different kinds of categorical and metric data. In R this can be done in ggplot.
As to clustering itself, I am unsure.


text:
Q: iOS send request directly to APNS without server On Android, to send a notification all you need to know is GCM id of a device you want to notify. Assuming my user knows the id of another user, he sends a message directly to GCM server, what decreases  the load on my server. I don't have experience building iOS apps, so I want to know if the same approach is possible for iOS devices. If my user knows id of another apple device, can he send a request directly to APNS?

A: Sending a push is just a matter of posting data to apple servers.
You can do it from your server or the device. It's up to you.

A: Try NWPusher. It contains an iOS demo application that shows how to send push notifications from iOS to iOS.


text:
Q: Python Pandas CParserError Error tokenizing data I am trying to use pandas to read a .csv file
df = pd.read_csv('ChildCareCenters06252017.csv')

and then I get this error
CParserError: Error tokenizing data. C error: Expected 31 fields in line 3, saw 42

I have read the pandas docs and I have gone through other stack posts similar to this but no solutions have worked.
I am going to this link
https://secure.dss.ca.gov/CareFacilitySearch/DownloadData
and then clicking child care centers and then saving that data and trying to read.
This is what the .csv looks like in TextEdit.
Header and the first couple school entries.

A: I downloaded the .csv, saved it as a .xlsx file, and then used read_excel() instead, which worked:
import pandas as pd

path = "C:\\Users\\nickb\\Desktop\\CCC.xlsx"  # update accordingly

df = pd.read_excel(path)

print df.head()

     Facility Type  Facility Number  \
0  DAY CARE CENTER        197416900
1  DAY CARE CENTER        191607790
2  DAY CARE CENTER        197416698
3  DAY CARE CENTER        304370894
4  DAY CARE CENTER        384001195
...


text:
Q: How do I get webkit styling to work with Vue.js? I have copied the styling from this Codepen demo: https://codepen.io/CSWApps/pen/MmpBjV into my own code like so:
<style>

body {
  background-color: #5c4084;
  text-align: center;
  padding: 50px;
}

.container {
  padding: 40px 80px;
  background-color: #fff;
  border-radius: 8px;
}
.heading {
  h1 {
    background: -webkit-linear-gradient(#fff, #999);
    -webkit-text-fill-color: transparent;
    -webkit-background-clip: text;
    text-align: center;
    margin: 0 0 5px 0;
    font-weight: 900;
    font-size: 4rem;
    color: #fff;
  }
  h4 {
    color: lighten(#5c3d86,30%);
    text-align: center;
    margin: 0 0 35px 0;
    font-weight: 400;
    font-size: 24px;
  }
}

</style>

However, beginning with H1 my IDE highlights the line background: -webkit-linear-gradient(#fff, #999); with the error message "semi-colon expected."  I can confirm that no linear gradient is being added.

A: If you click on settings then CSS, you can see that some older versions of Bootstrap are in use.
Note: I would recommend a newer version of Bootstrap, or better yet, Bootstrap-Vue


text:
Q: no tests found with test runner JUnit 5 even after adding Junit Library I wanted to test my classes in Java using JUnit 5, in Eclipse. all the files are in the same package. My test file is correct (syntax wise) and i get no errors from eclipse regarding the file itself. Only when i try to run the testfile, do i get the error: No tests found with test runner JUnit 5
I am really frustrated because i cannot seem to find the issue. i have included the JUnit-Library in my module path. I dont know if posting my code makes any sense, because i think it might be a different issue. Does anyone have any experience with this kind of error?
edit: here's a screenshot of my run configurations

A: Please check, if you added the Junit5 Library to your Java build path (Libraries).

If not, add the Library to your Java build path.

A: You can add Junit 5 libraries to your build path by right clicking on the project -> properties -> Java Build Path -> Add library -> Junit -> Junit 5 -> Finish to run the test in your IDE.


text:
Q: Error evaluating Javascript datastructure using JSON.parse I have the following stored as a javascript variable:
"{'Headings':
    [{'name': 'Behavior', 'majorTopic': 'N', 'vote': {'down': 1, 'up': 1}},
     {'name': 'Brain Mapping', 'majorTopic': 'N'},
     {'name': 'Evoked Potentials', 'majorTopic': 'N'}
 ]}"

such that the type of the variable is a string.
I am trying to evaluate the string to get a dictionary such that:
{"headings":[{"name":behavior,'majorTopic':"N", 'vote':{'down':1,'up':1}}]}

But when I attempt to use eval(variable) or JSON.parse(variable), I am getting the error:
Uncaught SyntaxError: Unexpected token :
    at eval For eval

and
VM529:1 Uncaught SyntaxError: Unexpected token ' in JSON at position 1
    at JSON.parse (<anonymous>)` For the JSON.parse function.

I believe the error pertains to the nesting of the vote dictionary with upvotes and downvotes,
but when I evaluate a nested statement like this independently, I am getting no issues.
How could I keep the nested vote tab while evaluating this statement?

A: You have to use double quotes in your JSON string. Other than that it is OK, should parse without issues.

A: Try creating a valid json:
{
"Headings": [{
    "name": "Behavior",
    "majorTopic": "N",
    "vote": {
        "down": 1,
        "up": 1
    }
}, {
    "name": "Brain Mapping",
    "majorTopic": "N"
}, {
    "name": "Evoked Potentials",
    "majorTopic": "N"
}]
}


text:
Q: Route 53 Setup for Elastic Beanstalk Blue/Green Deployment I've setup the infrastructure to do an environment variable swap for blue/green deployment, but the way we have our Route 53 setup it isn't working.
Currently, we have the root A record pointing at the EBS Load Balancer, is this correct? I think it should be pointing directly to the EBS, but I don't know enough to know for sure. I didn't set it up, and I'm not sure why this configuration was selected.
Is my assumption correct, or is there a better way to set this up?
Any articles or answers would be very appreciated!

A: You can do the following for a blue/green deployment. From Route 53:

*

*Click "Create record"

*Select "Simple routing"

*Click "Define simple record"

*Leave the subdomain blank for the root record

*Choose "A record - Routes traffic to an IP4 address and some AWS resources"

*Under Value/Route traffic to select "Alias to Elastic Beanstalk environment"

*Choose your region

*Select the environment you wish the record to point to.

*Click "Define simple record"

You can then create a new A record with a subdomain to point to the environment you would like to do the blue-green deploy with. Then in the Elastic Beanstalk console:

*

*Select one of the environments

*Click Actions

*Select "Swap environment URLs"

*Select the environment for you would like to switch URLs


text:
Q: iTunes Connect Reports "Invalid Binary" for Mac App I am trying to submit my first application to the Mac App Store.  I have setup the signing certificates on my computer, as well as setting up the application in iTunes connect.  Xcode allows me to produce an archive of my app, and even export a signed pkg file.  Both Application Loader and Xcode say that my binary passes "validation", but shortly after uploading my app to iTunes connect it is reported to have an "Invalid Binary." I read on Apple's iTunes Approval Process page some reasons why this might happen:

Appears when a binary is received through Application Loader, has been processed, but your binary is invalid. Examples of an invalid binary are: your binary icon does not meet our requirements, you have placed the payload directory at the wrong level in the .app wrapper, you attempted to use a non-increasing CFBundleVersion, etc.

Unfortunately I am not receiving an email when this error occurs, and nothing is telling me what the problem is.  I am kind of hoping that Xcode would tell me if I signed my binary wrong in the "Validate" stage, but I may be wrong.
My question here is: why might iTunes connect be reporting an "Invalid Binary" and how on earth can I fix it?
EDIT: I have taken some screenshots of my project's configuration settings, and of iTunes connect:

*

*iTunes connect app page

*Application in the Archive list

*Entitlements plist

*Code signing settings

*Info.plist

*Build settings (architectures, etc).

A: You most likely are trying to submit a build that has the same version number as an earlier build. All builds that you upload to iTunes connect must have different version numbers. For example: Joe submits his first build of his app to iTunes connect as version 1.0, next time he submits he must change the version to 1.1 or any other higher value.


text:
Q: Branching and Merging pcollection list in Apache Beam from common input I'm building a dataflow pipeline and I'm having some trouble branching and merging outputs. The pipeline I want to build is as follows:

*

*Read some input data input_data.

*A. Extract some metric, metric_1, on input_data.
B. Extract some other metric, metric_2, on input_data

*Since these metric extractions are computationally expensive, I want to branch off of the main input_data and merge the outputs afterwards for further calculation. Merge outputs output.

Here's some sample code that encapsulates my actual pipeline
class ReadData(beam.DoFn):
    def process(self, element):
        # read from source
        return [{'input': np.random.rand(100,10)}]

class GetFirstMetric(beam.DoFn):
    def process(self, element):
        # some processing
        return [{'first': np.random.rand(100,4)}]

class GetSecondMetric(beam.DoFn):
    def process(self, element):
        # some processing
        return [{'second': np.random.rand(100,3)}]

def run():
    with beam.Pipeline() as p:
        input_data = (p | 'read sample data' >> beam.ParDo(ReadData()))

        metric_1 = (input_data | 'some metric on input data' >> beam.ParDo(GetFirstMetric()))
        metric_2 = (input_data | 'some aggregate metric' >> beam.ParDo(GetSecondMetric()))

        output = ((metric_1, metric_2)
                  | beam.Flatten()
                  | beam.combiners.ToList()
                  | beam.Map(print)
        )

When I run this, I get a 'PBegin' object has no attribute 'windowing' error. I've seen some examples and sample code for doing something like this in Java. But I couldn't find the right resources for doing the same in Python. My question is as follows:

*

*What's the right way to branch and merge pcollections (especially if the branches came from a common input)?

*Is there a better pipeline design for accomplishing the same?
Thanks in advance!

A: In this code, your problem is that you are not 'starting' an initial PCollection. In ReadData.process - what is the value of the variable element?
Well, the runner can't come up with a value, because there's no input pcollection. You need to create your first PCollection. You'd do something like the following code...
As for making them into a list - perhaps a side input strategy may work. CAn you try the following:
def run():
    with beam.Pipeline() as p:
        starter_pcoll = p | beam.Create(['any'])
        input_data = (starter_pcoll | 'read sample data' >> beam.ParDo(ReadData()))

        metric_1 = (input_data | 'some metric on input data' >> beam.ParDo(GetFirstMetric()))
        metric_2 = (input_data | 'some aggregate metric' >> beam.ParDo(GetSecondMetric()))

        side_in = beam.pvalue.AsList((metric_1, metric_2)
                                     | beam.Flatten())

        p | beam.Create(['any']) | beam.Map(lambda x, si: print(si),
                                            side_in)

This should make your pipeline run. Happy to clarify about your specific questions further.


text:
Q: How to assign increment ID number from firebase I am new on Android Studio. I want to assign unique id (increment) from "1", but whenever I register account, I keep getting one only.
btn_register.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            final String email = et_email.getText().toString().trim();
            final String username = email.split("@")[0];
            final String pwd = et_password.getText().toString().trim();
            final long usr_id = 0; // not increment

            if (email.isEmpty() || pwd.isEmpty()) {
                et_email.setError("Entering Email Password Is required");
                et_email.requestFocus();
                return;
            }
            if (!Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
                et_email.setError("Entering Valid Email is required");
            }
            if (pwd.length() < 3) {
                et_password.setError("Password Length Should More Than 3");
                et_password.requestFocus();
            } else {
                m_auth.createUserWithEmailAndPassword(email, pwd).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                    DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("users");
                    DatabaseReference usr_uid = ref.child(m_auth.getCurrentUser().getUid());
                    if (task.isSuccessful()) {
                        Toast.makeText(MainActivity.this, "Registration Successed", Toast.LENGTH_SHORT).show();
                        //User usr = new User(email,username,usr_id+1);

                        usr_uid.child("email").setValue(email);
                        usr_uid.child("username").setValue(username);
                        usr_uid.child("password").setValue(pwd);
                        usr_uid.child("icon").setValue("default_icon");
                        usr_uid.child("id").setValue(String.valueOf(usr_id+1));

                        Intent refer_to_home = new Intent(MainActivity.this, Home_Activity.class);
                        startActivity(refer_to_home);
                        finish();
                    }
                    else
                        Log.e("user_reg_fail", "Field Empty!");
                    }
                });
            }
        }
    });

And this is my model:
public class User {

    private String email;
    private String username;
    private long usr_id=0;
    private String icon;

    public User(String email, String username, long id) {
        this.email = username;
        this.username = username;
        this.usr_id = id;
    }

    public void setIcon(String icon) {
        this.icon = icon;
    }

    public User() {
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public long getId() {
        return usr_id;
    }

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

The database I get
dldnPGvVsHeQmVqHkuJS4no4g1r1
|-email: "effeff@gmail.com"
|-icon: "default_icon"
|-id: "1"   //from one
|-password: "xxx"
|-username: "effeff"
gWEvZMOgi7hmuU5xOXhlG3vibgj1
|-email: "feefee@gmail.com"
|-icon: "default_icon"
|-id: "1" // id is still one
|-password: "xxx"
|-username: "feefee"

I have no idea why it does not increment the ID. How can I able to get increment "2" "3"? I can able to register my account successfully, but it keeps only assign ID "1"

A: So inside your onClick method you have those lines
final long usr_id = 0; // not increment
...
usr_uid.child("id").setValue(String.valueOf(usr_id+1));

every time that you click that button the usr_id will set its values to 0.
With firebase you have a unique document id (example in your question is dldnPGvVsHeQmVqHkuJS4no4g1r1,gWEvZMOgi7hmuU5xOXhlG3vibgj1) you don't need any extra id


text:
Q: Get request parameter in embedding controller In Symfony1 i can:
blog:
  url:   /blog/slug
  param: { module: blog, action: index }

and in action/controller i can get slug with: $request->getParameter('slug');
In Symfony2:
blog:
    path:      /blog/{slug}
    defaults:  { _controller: AcmeBlogBundle:Blog:show }

and i create "components" same as Symfony1 - http://symfony.com/doc/current/book/templating.html#templating-embedding-controller
How can i get slug in embedding controller? I tried:
$request->query->get('foo');
$request->request->get('bar');

but this still return null. In AcmeBlogBundle:Blog:show controller working ok.

A: The param converter will populate the argument with the string from the route.  So here is what your method looks like.
class BlogController extends Controller {
    public function showAction($slug) {
        // $slug will contain the value of the string from the route
    }
}

So if you wanted to embed this into a twig template it would look like this:
{{ render( controller('AcmeBlogBundle:Blog:show', {'slug': 'this-is-the-slug' })) }}

or from another controller
$this->render('AcmeBlogBundle:Blog:show.html.twig', array('slug' => 'this-is-the-slug'));


text:
Q: Why won't Android Support Libraries work in my project? Using Android Studio, I followed the steps at https://developer.android.com/tools/support-library/setup.html as acurately as I could, but it told me the following error:

Error:Could not find method compile() for arguments [com.android.support:appcompat-v7:18.0.+] on org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler_Decorated@18899229.
Please install the Android Support Repository from the Android SDK Manager.
  Open Android SDK Manager

But I have already installed the Support Repository and Library! Since I also got an error saying compile doesn't belong in the dependencies block, so I changed it to classpath, and got the following, similar error:

Error:Could not find any version that matches com.android.support:appcompat-v7:18.0.+.
  Required by:
      :ExpenseTracker:unspecified
Please install the Android Support Repository from the Android SDK Manager.
  Open Android SDK Manager

As you can see here, it still thinks the ASR isn't installed, but as the screenshot proves, it is. So what am I doing wrong here?

A: My problem was that after letting Android Studio upgrade the Gradle plugin to the latest version, it had messed up the dependency section of my module's build file. It had concatenated the dependency declaration lines together (except for the lines that were mere comments). Separating the lines (placing each dependency declaration in a single line) fixed the issue.

A: I think you're placing these lines in the wrong file.
They should go in the module's build.gradle file, not in the project's one (which this would seem to be, from the screenshot).
Also, the dependencies tag should not be a child of anything else. something like:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 20
    ...
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile "com.android.support:support-v4:18.0.+"
    ...
}

EDIT Did you see the comment? :)
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files


text:
Q: Unsure how to unmount scene in @react/three-fiber I'm building this scene, and I have a few issues.
One small issue is with directionalLight.  When I try using more up to date three.js attributes like shadow.camera.far on it, @react-three/fiber loses the ability to call the dispose function on the light's shadows.  So, I have to use the deprecated properties, which causes me to get these annoying warnings.  That's not the biggest problem though.  I can live with that, but I'd also be grateful if anyone had any idea how to get rid of those warnings.
The main problem is that when I try making the model in my scene clickable so that the user can go to a different page in the app, I get a @react-three/fiber error of Uncaught TypeError: Cannot read property 'disconnect' of undefined.  I think this is because I'm using the unmountComponentAtNode function in the scene's useEffect hook, and it's causing the component to unmount before @react-three/fiber can properly remove all the threejs objects.  However, when I remove that function, I get the common react error of: Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
Anyone have any idea what I can do?  I'd appreciate any help.
Here's my code:
import React, { Suspense, useRef, useEffect, useState } from 'react'
import {
  Canvas,
  extend,
  unmountComponentAtNode,
  useFrame,
  useLoader,
  useThree,
} from '@react-three/fiber'
import { CubeTextureLoader, DoubleSide, PerspectiveCamera, sRGBEncoding } from 'three'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import Model3D from '../../assets/models/model.glb'
import './Model.css'
import nx from '../../assets/environmentMap/nx.jpg'
import ny from '../../assets/environmentMap/ny.jpg'
import nz from '../../assets/environmentMap/nz.jpg'
import px from '../../assets/environmentMap/px.jpg'
import py from '../../assets/environmentMap/py.jpg'
import pz from '../../assets/environmentMap/pz.jpg'

extend({ OrbitControls })

const wallMap = {
  'side-panel': '/wall/1',
  'panel-material': '/wall/2',
  'panel-material-2': '/wall/3',
  'side-panel-2': '/wall/4',
  entrance: '/wall/5',
  'overhead-entrance': '/wall/5',
}

const CameraControls = () => {
  const {
    camera,
    gl: { domElement },
  } = useThree()

  const controls = useRef()
  useFrame(() => controls.current.update())

  return <orbitControls ref={controls} args={[camera, domElement]} enableDamping />
}

const SkyBox = () => {
  const { scene } = useThree()
  const loader = new CubeTextureLoader()
  const environmentMap = loader.load([px, nx, py, ny, pz, nz])

  environmentMap.encoding = sRGBEncoding
  scene.background = environmentMap
  scene.environment = environmentMap

  return null
}

const Model = ({ changePage }) => {
  const active = useRef(false)
  const moving = useRef(false)

  const material = useRef()
  const { scene } = useThree()
  const gltf = useLoader(GLTFLoader, Model3D)
  const camera = new PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 100)
  camera.position.set(-4.62, 1.3, 4)
  scene.add(camera)

  const handleClick = (e) => {
    if (moving.current) return

    const {
      material: { name },
    } = e.intersections[0].object

    changePage(wallMap[name])
  }

  const handlePointerDown = () => {
    active.current = true
  }

  const handlePointerUp = () => {
    if (active.current) {
      setTimeout(() => {
        moving.current = false
        active.current = false
      }, 30)
    }
  }

  const handlePointerMove = () => {
    if (active.current) {
      moving.current = true
    }
  }

  return (
    <primitive
      object={gltf.scene}
      position={[0, -1.25, 0]}
      scale={0.22}
      rotation={[0, -0.6, 0]}
      castShadow
      onClick={handleClick}
      onPointerDown={handlePointerDown}
      onPointerMove={handlePointerMove}
      onPointerUp={handlePointerUp}
    >
      <meshStandardMaterial attach='material' ref={material} />
    </primitive>
  )
}

const Plane = () => {
  return (
    <mesh receiveShadow rotation={[-Math.PI / 2, 0, 0]} position={[0, -0.8, 0]}>
      <planeGeometry args={[12.5, 12.5, 2, 2]} />
      <meshStandardMaterial color='#222' side={DoubleSide} />
    </mesh>
  )
}

const Scene = () => {
  const [redirectPath, setRedirectPath] = useState('')

  useEffect(() => {
    if (redirectPath) window.appHistory.push(redirectPath)

    return () => {
      unmountComponentAtNode(document.querySelector('canvas'))
    }
  }, [redirectPath])

  return (
    <div className='webgl'>
      <Canvas>
        <Suspense fallback={null}>
          <ambientLight color='#ffffff' intensity={0.3} />
          <directionalLight
            position={[-3, 5, 5]}
            color='#ffffff'
            intensity={3}
            castShadow
            // Last 4 are deprecated properties that cause warnings from three.js.
            // When I use something like shadow={ { bias: 0.05 } }, I lose the dispose
            // function from the shadow.  So, I'm still using them for now.
            shadowBias={0.05}
            shadowCameraFar={15}
            shadowMapHeight={1024}
            shadowMapWidth={1024}
          />
          <CameraControls />
          <Model changePage={(x) => setRedirectPath(x)} />
          <Plane />
          <SkyBox />
        </Suspense>
      </Canvas>
    </div>
  )
}

export default Scene


text:
Q: PHP Multi Dimensional Array Search returning Keys I am trying to search an array of arrays and if the needle is found I want to return or at least know the keys for the match.
For example given:
['foo'] =>
     ['bar'] => 'blah'

Searching for 'blah' I need to know there is a match and the keys are 'foo' and 'bar'
I have managed to implement a search which returns boolean for a match:
function search_array($needle, $haystack) {
        if(in_array($needle, $haystack)) {
            return true;
        }
        foreach($haystack as $element) {
            var_dump($element);
            if(is_array($element) && $this->search_array($needle, $element))
               return true;
        }
        return false;
}

But I am struggling with how to know the keys. Is this even possible?

A: Yes it is possible. One solution is to:

*

*In the base case utilize array_search() to get the key.

*In the recursive case, when iterating over each element in the haystack (before recursing) use  the $key => $value syntax of foreach. Then when the recursive call yields a value, check if the returned value is an array (by using is_array()) - if so, use array_unshift() to push the current key onto the returned array. Otherwise return an array with the key and the returned value.
function search_array($needle, $haystack) {
    if(in_array($needle, $haystack)) {
        return array_search($needle, $haystack);
    }
    foreach($haystack as $key => $element) {
        if(is_array($element) && search_array($needle, $element)) {
            $searchReturn = search_array($needle, $element);
            if (is_array($searchReturn)) {
                array_unshift($searchReturn, $key);
                return $searchReturn;
            }
            return [$key, $searchReturn];
        }
    }
    return false;
}

See it demonstrated in this playground example.

A: You can do it like this, since it's 2-dimensional array.
function search_array($needle, $haystack) {
    foreach($haystack as $key => $value) {
        if ($value == $needle) {
            return array($key);
        } else if (is_array($value)) {
            foreach ($value as $k => $v) {
                if ($v == $needle) {
                    return array($key, $k);
                }
            }
        }
    }
}

For an n-dimensional array you should use a recursive function...


text:
Q: Curious question about light and photons If a photon wavelength (e.g., yellow) is isolated from the other wavelengths that the sun emits (once it gets to earth), can that particular particle/photon be distorted slightly into a wavelength that is shorter (e.g., perceived as green)?
If yes; please explain.
If no; please explain.
Thank you!

A: I transform the wavelengths of light everyday in the laboratory; so do you if you have a green laser pointer. For how a green laser pointer works, see http://www.repairfaq.org/sam/laserpic/glpdpics.htm
This is called non-linear optics, and requires (a) higher than normal intensity of light, and (b) a properly cut crystal that meets specific structural requirements.
So if you want to convert yellow light to green light you will have to work harder, because the simplest processes change the wavelength by a factor of 2: double it, generating two new photons from each one destroyed, or divide it in half, which requires two photons to be destroyed while creating one replacement with double the energy (half the wavelength).
This was first demonstrated by Peter Franken, et al, at the University of Michigan, in 1961. The paper is discussed here, with references: http://www.laserfocusworld.com/articles/2011/09/sprc-symposium-2011.html

A: The concept of being able to change one frequency (it's a bit more correct in this context to use frequency rather than wavelength) into another is a question of linearity. Generally, the equations that govern light/optics (Maxwell's equations) are considered linear. This has the implication that any light you start with at one frequency will stay at the same frequency forever.
To change frequencies, it's necessary for light to interact non linearly. The short of it is that light will generally only act nonlinearly in materials, and only if your light has sufficient power. This is usually seen only in certain crystals, but can happen in any material if your light is sufficiently strong.

A: Interacting photons (Compton scattering)  with electrons at rest is a non linear process that decreases  light frequency (yellow to red).
Also , reflecting photons in a finite mass mirror decreases the frequency of photons as some momentum is transferred to mirror.
So it is no possible for a cold plasma or metal to increase the frequency of photons in order to promote them from yellow to green.


text:
Q: Http.Delete doesn't work Http.Delete doesn't working on angular 5.2.0
The Code is:
let headers = new HttpHeaders({ 'Content-Type': 'application/json' });
this.http.delete(this.url + encodeURIComponent(key.id), {headers : headers})
                           .toPromise();

The error message is:
Failed to load http://localhost/project/bfd19ece-f4a1-4935-ae3f-d5ea28969871: Response for preflight has invalid HTTP status code 403

Edit:
The delete is working using fiddler composer
Edit:
The problem is solved by open chrome by run this
chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security

From this link: Here
Thanks in advance.

A: This is not a problem with angular, it's that the OPTIONS request made by angular (to find out whether it can do a cross domain request) is failing with a 403.
Your origin is different to the requested URL so it needs to check that it's allowed to make the request.
This SO post may help


text:
Q: The $f(x)$ that minimizes $g(f(x))$ asymptotically Assume $f(x)\to \infty$ as $x\to\infty$ and $a,b>0$. Find the $f(x)$ that yields the lowest order for
$$g(x)=\ln f(x) + \frac{a x}{b+\ln(1+f(x))}$$
as $x\to\infty$.
By order I mean Big O and Little o notation.
I can only solve it roughly:
My solution: Since $f(x)\to\infty$, $\ln(1+f(x)) \approx\ln(f(x))$. Then, I have to minimize the order of $b+\ln f(x) + \frac{a x}{b+\ln f(x)}$. Since for any $c>0$, $y+c/y$ is miminized when $y =\sqrt{c}$, the following $f(x)$ should satisfy ${b+\ln f(x)}=\sqrt{ax}$. Therefore,
$$f(x)=e^{\sqrt{ax}-b}$$
and the lowest order for $g(x)$ is $2\sqrt{ax}$.
Can you help me obtain a rigorous answer?


text:
Q: Safety-Critical Diagnostic Signaling I need to (extremely) reliably detect the status of a normally-closed DPST momentary switch at the end of a short distance of cable (max. 3m, 22 AWG).
I propose to do this with two entirely independent circuits, driven with arbitrary pulse-trains generated by an MCU. Each circuit will have a dedicated LDO to supply a higher  signaling voltage (5V), which will be modulated by a MOSFET attached to the MCU. This should allow the MCU to detect mis-wiring, short to ground, short to any supply rail, short to a supply rail at a voltage higher/lower than the intended voltage, etc.
This is the high-level block diagram (apologies for the quality – too much coffee this morning):
EDIT: These should clearly be P-channel MOSFETs as high-side switches, not N-channel. Mis-drew them. Excellent catch by @brhans.

And this is the proposed input conditioning circuit (also drafted quickly for the purposes of feedback – please let me know if you spot any mistakes!):

My objective is that this input conditioning circuit will protect the MCU against ESD or more prolonged unintentional shorts to supply rails. The MCU will implement low-pass filtering, etc. and read these inputs with an ADC peripheral.
Overall, my questions are as follow:

*

*Is the overall concept (in particular, use of the separate LDOs) reasonable?

*Any feedback on the implementation of the input conditioning circuit?

Thank you for the advice and help! Really appreciate the StackExchange community.
EDIT I don't have a lot of details on the environment – it may be assumed to be a reasonably harsh electrical environment, in proximity to (smaller) brushless motors and other industrial equipment.

A: (You give no environmental or application details. Please can you edit these into your question.)
For your proposed circuit...
You have practically no load on the switch so it's passing a tiny current all that way. If it's to be 'extremely reliable' then a higher current makes it more resistant to radiated transients it might pick up. You give no environmental or application details at all but a guess/RoT value would be 10 mA.
For an alternative circuit...
You have a DPDT switch i.e. a double-pole changeover switch. So connect both poles of each switch to your cable.
That way, your MCU gets positive confirmation that the switch is in one position or another, rather than confirmation that switch is in one position but only assumption that it's in the other position. I have a used this schemes for similar applications, such as for relay contacts in a fault-intolerant dual-redundant design (warship firing system).
The below circuit shows the connections for one half of the switch. This delivers at least 2.8 V to the MCU with the 5 V down at 4.75 V. It puts approx. 8.6 mA through the switch when at 4.75 V.
Shorts of the switch drive output can be detected, along with the switch position. If your MCU has an ADC input, use that to detect the SW_DRV_SHORT_N voltage instead/as well as a GPIO input.

simulate this circuit – Schematic created using CircuitLab


text:
Q: Windows Certificate Authority request form submit failure I have a Windows 2012 R2 Standalone Root CA setup to issue authentication certificates when requested via the certrqma.asp page. This page has been modified to only show a small number of fields required but no configuration has been changed over the default and has worked fine in the past, however, recently (Not exactly sure when) the page simply won't submit the request.
I can see errors via the console in both IE and Chrome but the user feedback on form submission is to display the message:

This page has not finished loading yet. Please wait a few seconds and try again.

*

*IE Console: SCRIPT5009: 'GetCSPList' is undefined - certrqma.asp (1523,3)

*Chrome Console: Uncaught ReferenceError: loadXEnroll is not defined at postLoad (certrqm.asp:997) & at onload (certrqma.asp:9)

My ASP coding is non-existent and am feeling my way along but at least found the above so hoping it's useful detail. Any ideas?

A: So it turns out, this is a direct result of Microsoft disabling, by default, the execution of VBScript in IE11 onwards. This was changed in the August 2019 Windows Security Update and has been planned since early 2017: An update on disabling VBScript in Internet Explorer 11
VBScript can easily be re-enabled in IE using one of the methods in Option to disable VBScript execution in Internet Explorer for Internet Zone and Restricted Sites Zone but compromising security is not something we should have to ask clients to do in order to use this as intended.
I thought the Windows 2019 Server version of this form would be coded differently to address this seeing as disabling it has been in the pipeline for so long but is not the case as 2019 Server Certificate Services Web Enrollment still requires VBScript in order to use this form.


text:
Q: bash function parameters by index - difference between head and echo I'm confused as to the odd behaviour in the "head" command when accessing function parameters.
Here's the code:
function fun1 { echo $1; head $1; }

And here are the outputs of 2 different function calls
echo "asasa" | fun1
--- output start ---

asasa
--- end ---

and when passing a parameter:
echo "asasa" | fun1 "var1"
--- output start ---
var1
head: cannot open `var1' for reading: No such file or directory
--- end ---

What exactly is happening in the accessing parameter 1 ($1) and why are head and echo interpreting it very differently?

A: $1 always refers to the first argument passed on the command line, which is separate from any input via stdin.
head expects as its (non-option) arguments one or more filenames - in the absence of one, input is read from stdin. (Many utilities that process file content behave this way).
echo "asasa" | fun1 ... stdin input only, no arguments ($1 not set):

*

*echo $1 echoes an empty line (just \n), because $1 is not set.

*head $1 echoes (up to 10 lines from) stdin (asasa): because $1 is unset, it's as if no arguments were passed to head, so it reads from stdin.

echo "asasa" | fun1 "var1" ... both stdin input and 1 argument: $1 set to var1.

*

*echo $1 echoes var1, the value assigned to $1.

*head $1 reports an error, because var1 is interpreted as a filename, and no such file exists; stdin input is ignored in this case.

If you want echo to access the argument and head to access stdin input, simply drop the $1 argument from the head command:
function fun1 { echo $1; head; }

Conversely, if you really want to process the string passed via argument $1 with head, you must explicitly provide it via stdin inside the script (e.g., via <<<):
function fun1 { echo $1; head <<<"$1"; }

A: head reads input from stdin only if it's arguments are empty. Since you passed an argument to it, it tried to read it instead.
Usage: head [OPTION]... [FILE]...
Print the first 10 lines of each FILE to standard output.
With more than one FILE, precede each with a header giving the file name.
With no FILE, or when FILE is -, read standard input.


text:
Q: How to generate dynamic tiles I was studying the Trulia crime map and found that they were generating dynamic tiles with color block based on crime count. I am a newbie to mapping world and found how to generate static tiles, serve them, cache them etc. I am not able to understand how to generate dynamic tiles based on crime count.
On the data side, i have the latitude and longitude about where the crime happened. Is it possible to generate dynamic polygon tiles with this data ?


text:
Q: Convergence of series and limit involving partial sum Suppose that $\sum b_n$ converges absolutely.
Is it true that
$$\lim_{N\to \infty} \frac{1}{N^2}\sum_{n=1}^N n^2 b_n = 0?$$
I suspect that this is false but I am finding it difficult to come up with a counterexample.

A: This is true. One way is to use DCT. We have to show that $\sum_n I_{n\leq N} {(\frac n N)^{2} {|b_n|}} \to 0$. Each of the the terms tends to $0$ and the terms are dominated by the terms of $\sum|b_n|$.


text:
Q: FFMPEG Input area failure I'm trying to convert an input clip to a fixed, padded output and applying an overlay on it.
This command works fine for resizing:
ffmpeg -y -i clip.mp4 -vf scale="min(iw*375/ih\,500):min(375\,ih*500/iw),pad=500:375:(500-iw)/2:(375-  ih)/2" output.mp4

I created the following one to make sure the overlay would be created:
ffmpeg -y -i clip.mp4 -i clip_overlay.png -strict -2 -filter_complex "[0]scale=min(iw*375/ih\,500):min(375\,ih*500/iw),pad=500:375:(500-iw)/2:(375-ih)/2[v];[v][1]overlay=x=W-w-5:y=H-h-5" output.mp4

I cannot find the error, but ffmpeg returns:
[Parsed_pad_1 @ 0x2eae8e0] Input area 144:0:355:375 not within the padded area 0:0:500:374 or zero-sized
[Parsed_pad_1 @ 0x2eae8e0] Failed to configure input pad on Parsed_pad_1
Error reinitializing filters!
Failed to inject frame into filter network: Invalid argument
Error while processing the decoded data for stream #1:0
[aac @ 0x2eb3020] Qavg: 102.113
[aac @ 0x2eb3020] 2 frames left in the queue on closing

Why does that upper command work, and combined with the second one, it doesn't?

A: The most common pixel format in a typical MP4 video stream is yuv420p and the default encoder (x264) requires that the dimensions be even.
So, set pad to use even dimensions,
ffmpeg -y -i clip.mp4 -i clip_overlay.png -strict -2 -filter_complex "[0]scale=min(iw*375/ih\,500):min(375\,ih*500/iw),pad=500:376:(500-iw)/2:(376-ih)/2[v];[v][1]overlay=x=W-w-5:y=H-h-5" output.mp4


text:
Q: Is there a better way to construct variables to pass to a template? Given a series of objects, I am trying to split them up into a nice, sorted, easy-to-display table view, which will serve as a generic (i.e. no dates) calendar.
def view_working_hours(request, user_id):
"""
Shows the working hours for a certain user.
This generates seven sorted lists which are then passed to the generic template

"""
wh0 = list(WorkingHours.objects.filter(user__id=user_id, DOW=0))
wh1 = list(WorkingHours.objects.filter(user__id=user_id, DOW=1))
wh2 = list(WorkingHours.objects.filter(user__id=user_id, DOW=2))
wh3 = list(WorkingHours.objects.filter(user__id=user_id, DOW=3))
wh4 = list(WorkingHours.objects.filter(user__id=user_id, DOW=4))
wh5 = list(WorkingHours.objects.filter(user__id=user_id, DOW=5))
wh6 = list(WorkingHours.objects.filter(user__id=user_id, DOW=6))
wh0.sort(key = lambda x: x.startHours)
wh1.sort(key = lambda x: x.startHours)
wh2.sort(key = lambda x: x.startHours)
wh3.sort(key = lambda x: x.startHours)
wh4.sort(key = lambda x: x.startHours)
wh5.sort(key = lambda x: x.startHours)
wh6.sort(key = lambda x: x.startHours)
return render_to_response('homesite/show_schedule.html',
                          {'wh0': wh0, 'wh1': wh1, 'wh2': wh2, 'wh3': wh3, 'wh4': wh4, 'wh5': wh5, 'wh6': wh6,},
                          context_instance=RequestContext(request))

The variables are then iterated over with foreach in the table columns in the template.
This seems really inelegant. Are my instincts correct?

A: I don't think you want seven lists at all. You should simply get all the objects for a user in one go, sorting by DOW and start hour:
WorkingHours.objects.filter(user_id=user_id).order_by('DOW', 'startHours')

and pass this to the template. There you can simply iterate through, perhaps using the ifchanged or regroup filters to output them in days.

A: You can consider using the following approach:
def view_working_hours(request, user_id):
    """
    Shows the working hours for a certain user.
    This generates seven sorted lists which are then passed to the generic template

    """

    result = {}
    for i in xrange(7):
        result["wh"+str(i)] = sorted(
            list(WorkingHours.objects.filter(user__id=user_id, DOW=i)),
            key=lambda x:x.startHours)

    return render_to_response('homesite/show_schedule.html', result,
                              context_instance=RequestContext(request))


text:
Q: The Default Freezer (iOS) Levin had a chapter in his book Mac OS X and iOS internals: To the Apple's Core. related to The Default Freezer which can be used in Virtual Memory Management.  It is stated that it is implemented in osfmk/vm/default_freezer.c
At the time of writing this was still incomplete. Does anyone know if this is implemented in newer versions of iOS?  I did not find a lot of documentation for this.

A: It is, in iOS 8, in conjunction with memorystatus/jetsam. It'll be covered in more detail in the 2nd Edition of his book, too.


text:
Q: Code::blocks cmake makefile nothing to be done when building I've downloaded PhysFS and attempted to build it with Cmake. The option I
generated with is Code::Blocks makefiles, which generated a project file.
I supposed it was as easy as opening that project file and trying to build but
that didn't happen.
Upon building the project I get
-------------- Build: all in PhysicsFS ---------------

Using makefile: Makefile
Execution of 'make.exe -s -f Makefile all' in
'C:\Documents and Settings\Stefan.MONA-H6H4KPUJNF\Desktop\build' failed.
Nothing to be done.

I've tried checking out a similar question, but the options in the answer
were already good, and it didn't work.
I'm on windows XP SP3


text:
Q: Expandable search bar in Angular 6 I am using Angular 6 and I  want to do expandable search bar for that I have written below code.
My Code
Now my problem is I want to stop transition after entering value in searchbox on focusout. If searchbar is empty then transition will happen. Please help.

A: you must work with ngClass, I add the class "filled" when click and remove if blur and have no value

  <form id="search">
    <input #search type="search" placeholder="Search" [ngClass]="{'filled':filled}"
         (click)="filled=true" (blur)="filled=search.value?true:false">
  </form>

//remove in your css
//#search input[type=search]
//And add (is the same adding .filled)
#search input[type=search].filled
{
  width: 400px;
  padding-left: 32px;
  color: #4a83c0;
  background-color: #fff;
  cursor: auto;

}

Update a button to close can be like

  <form id="search">
    <input #search type="search" [placeholder]="filled?'Search':''" [ngClass]="{'filled':filled}"
         (click)="filled=!filled" (blur)="filled=search.value?true:false">
         <button class="close" *ngIf="filled" (click)="search.value='';filled=false">X</button>
  </form>

.close
{
  z-index:10;
  margin-left:-3rem;
  margin-right:1rem;
}

A: You could put conditional class on your search input that is only there when it has a non-empty value and then target your CSS specifically. Something like:
<input type="search" [class.has-value]="searchValue" placeholder="Search">
input[type=search]:focus, input.has-value {
   ...
}


text:
Q: DC motor in vacuum, heat generation I am designing a motor system that has to run in a vacuum chamber (sub mbar). I am a little bit worried about the heat that would not dissipate at all in the vacuum. Therefore, I want the least amount of energy wasted to heat(high efficiency). Some people advised me to get a big motor that is much more capable so that it can withstand the heat generated under low load.
The rpm I need ranges from 30 rpm to 600 rpm. So I need PWM on top of gearbox+motor. PWM and speed input will be controlled using Arduino. Also I realised that there are brushless and brushed motors. I figured that brushless motors are a bit more efficient which means less wasted as heat.
So in conclusion, I want a setup that is, big brushless motor + gearbox + PWM. Am I thinking correct? I have never gotten a chance to do any electrical engineering so I might be missing obvious flaws. Please let me know if there are any better ways to achieve this.
Additional info) I chose dc motor because the important part is to run continuously and smoothly at a set constant speed without bumps or jittering.
One session of running time would be ~10 minutes. Torque is not so much of a problem, probably maximum of 1000gcm needed I guess.

A: Interesting question!
Your worst case is that you have a perfect vacuum and no heat path out of your chamber.  600 rpm at 1000 gcm is about 6 watts of mechanical power.  I wouldn't choose a big motor because it would be less efficient; rather, choose a "right-sized" brushless motor and gearbox for your speed and load.  You should be able to achieve at least 50% efficiency, meaning that 6 watts will be going into your load and 6 watts will be lost as heat.  If you run for 10 minutes (or 600 seconds), 6 watts will produce 3600 joules or 860 calories.  You only need to attach a heat sink capable of absorbing 860 calories.  Aluminum has a specific heat of 0.215 calories/gram-Kelvin.  Do the math, and 200 grams of aluminum heat sink will have a temperature rise of 20 degrees K.  So attach a heat sink and you can play around with the time, losses, and thermal mass until you get what you need.  Of course, you must cool it after each run by allowing air in for convection or some other heat path out of your chamber.  Otherwise the temperature will continue to rise with each run.
Good luck!

A: I recommend putting the motor outside of the vacuum and use a magnet-coupled drive through the container wall.
Another option is using an AC induction motor and putting the coil outside of the vaccum for better heat transfer. This is done for high-power X-ray tubes to rotate the anode. Again, the reason is better heat transfer.

https://en.wikipedia.org/wiki/File:Rotating_anode_x-ray_tube_(labeled).jpg


text:
Q: I can not get text value in a div by using val() or innerHTML or I tried val(), innerHTML, innerText, value but it return undefined or blank. why?

var a = $('#test').val();
alert(a);

hello

A: To get the innerText of a node you should use .text();
Source: https://api.jquery.com/text/

var a = $('#test').text();
alert(a);

hello


text:
Q: Remove elements from a hash array if a value matches a line in a text file I have a JSON file with a hash in that looks like this
{
  "1": {
    "organisation": "Example1",
    "name": "Name1",
    "items": [
      {
        "name": "Name1",
        "html_url": "URL1",
        "results": [
          "items go here"
        ]
      },
      {
        "name": "Name2",
        "html_url": "URL2",
        "results": [
          "Items go here"
        ]
      },

I want to delete elements whose html_url matches a list stored in a text file, I have been toying with a delete-if like this.
@org.each do |key,value|
    File.open('views/investigated.txt').each do |line|
        value['items'].delete_if { |h| h['html_url'] == line }
    end
end

but it doesn't seem to alter the array, I'm completely lost, any help would be much appreciated

A: @Stefan is right, it's better practice to create a separate array with the lines you'd like to delete from the array:
urls_to_delete = []
File.open('views/investigated.txt').each do |line|
    urls_to_delete.push(line)
end

Then use that array to remove the lines from the hash:
@org.each do |key,value|
    value['items'].delete_if { |h| urls_to_delete.include?(h['html_url']) }
end

Tested it with your example and does exactly what you're trying to achieve.

A: Maybe you can delete records in one iteration by using each_key on ˙@org˙ and you dont need new array.
Like this:
@org.each_key do |key|
  File.open('views/investigated.txt').each do |line|
    line.chomp!
    @org[key]['items'].delete_if { |h| h['html_url'] == line }
  end
end


text:
Q: modulo operation with negative numbers in python I found this definition for modulo

mod(a, n) = a - n * floor(a / n)

Doing an integer division and then multiplying it again means finding the biggest number smaller than a that is dividable by n without a remainder. Subtracting this from a yields the remainder of the division and by that the modulo."
source:https://torstencurdt.com/tech/posts/modulo-of-negative-numbers/

It seemed to help me understand intuitively, and it worked for cases where both a and n where positive and also cases where a was negative while b was positive. For example:
-10 mod 3
-12 is the largest number smaller than -10 divisible by 3. So the remainder is -10-(-12)=2 which is correct.
But when I tried doing 10 mod -3 my answer was incorrect. Because while 9 is the largest number smaller than 10 divisible by -3 it will give the wrong answer as it would evaluate to 10-9=1.
Instead it is supposed to be 10 -((-4)*(-3))=10-12=-2.
But 12 isn't the biggest number smaller than a.
I understand how to solve for the answer using the formula a= (a//n)(n)+(a%n) in python. But is there an intuitive definition to help me understand?

A: The Python 3 documentation gives the identity x == (x//y)*y + (x%y), from which it can be deduced that x%y == x - (x//y)*y. // denotes "floor division"; x//y is the greatest integer not greater than x/y.
For x=10 and y==−3, x/y is −3⅓. floor(−3⅓) is −4. Therefore x//y is −4. Then x - (x//y)*y is 10 − (−4)*−3 = 10−12 = −2.
Here is a graph of x%3:

Here is a graph of x%-3:

A: I found an anser here https://en.wikipedia.org/wiki/Remainder
it seems there are two types of remainders and a programming languages picks which one to use


text:
Q: Open new mail interaction window in Genesys Interaction Workspace I got the task to show the "new outbound mail" dialog in Genesys IWS upon an external event from a webservice. I put my IWS extension in place and it loads and can provide a webservice interface.
My main problem now is that I don't understand how I can open the interactions window from my code. I tried to get an instance of it by using:
IInteractionsWindow interactionsView = Container.Resolve<IInteractionsWindow>();
interactionsView.Create();
interactionsView.ShowView();

This actually works only halfway, as I get a new window, but it's completely empty. Do I need to load every single region on its own? Is there a simpler way to achieve my goals in a fully integrated way?
UPDATE: I have now tried to achieve things using the Platform SDK although I have no idea if this really helps me in showing the "new mail" window to the agent. I tried with the following code:
interactionServerProtocol = new InteractionServerProtocol(new Endpoint(new Uri("tcp://ixnServer:7319")));
interactionServerProtocol.ClientName = "CRMIntegrationModule";
interactionServerProtocol.ClientType = InteractionClient.AgentApplication;

contactServerProtocol = new UniversalContactServerProtocol(new Endpoint(new Uri("tcp://ucsServer:5130")));
contactServerProtocol.ClientName = "CRMIntegrationModule";

interactionServerProtocol.Open();
contactServerProtocol.Open();

RequestSubmit request = RequestSubmit.Create();
request.InteractionType = "Outbound";
request.InteractionSubtype = "OutboundNew";
request.MediaType = "email";
request.Queue = "default";

EventAck response = interactionServerProtocol.Request(request) as EventAck;
if (response != null)
{
    string id = Convert.ToString(response.Extension["InteractionId"]);

    RequestInsertInteraction insertRequest = RequestInsertInteraction.Create();
    insertRequest.InteractionAttributes = new InteractionAttributes
    {
        Id = id,
        MediaTypeId = "email",
        TypeId = "Outbound",
        SubtypeId = "OutboundNew",
        TenantId = 101,
        Status = new NullableStatuses(Statuses.Pending),
        Subject = "Testmail",
        EntityTypeId = new NullableEntityTypes(EntityTypes.EmailOut)
    };
    insertRequest.EntityAttributes = new EmailOutEntityAttributes()
    {
        FromAddress = "dummy@gmx.net",
        ToAddresses = "dummy@gmx.net",
    };
    insertRequest.InteractionContent = new InteractionContent()
    {
        Text = "This is the e-mail body."
    };
    contactServerProtocol.Send(insertRequest);

    RequestPlaceInQueue queueRequest = RequestPlaceInQueue.Create();
    queueRequest.InteractionId = id;
    queueRequest.Queue = "default";
    interactionServerProtocol.Send(queueRequest);
}

interactionServerProtocol.Close();
contactServerProtocol.Close();

The bad thing is the response from the interaction server which is:
attr_ref_id [int] = 2
attr_error_code [int] = 34
attr_error_desc [str] = "Client is not logged in"

I think this could be related to not being logged in correctly somehow but I have not a single clue how to achieve this. Any help?
UPDATE 2 I could send an e-mail using the Platform SDK, but this is not what I really want. The initial question is still valid, as I just want to invoke the interactions window and that's it. The other stuff is up to the user. Is it possible?

A: You need to use PlatformSDK. add Genesyslab.platform.webmedia.protocols.dll
After that you can use *webmedia.tserver.request, under that tab there is requestWeb or sth.
channelService.RegisterEvents(tServerChannel, new Action<Genesyslab.Enterprise.Model.Channel.IClientChannel>

In your main module(have Initialize method), need to registerevent like that. You can put a button or sth, then you can trigger event or you can use commandchain after logon, is up to you.
Good luck.

A: I made use of the given command chains:
    public IObjectContainer Container { get; set; }

    public void NewItem(string contactId, string emailAddress)
    {
        IAgent agent = Container.Resolve<IAgent>();
        IRoutingBasedManager routingManager = Container.Resolve<IRoutingBasedManager>();

        IDictionary<string, object> parameters = new Dictionary<string, object>();
        parameters.Add("CommandParameter", agent.FirstMediaEmail);
        parameters.Add("TargetId", contactId);
        parameters.Add("OwnerId", agent.ConfPerson.EmailAddress);
        parameters.Add("Destination", emailAddress);
        parameters.Add("RecentIndex", contactId);
        bool todo = routingManager.RequestToDo("CreateNewOutboundEmail", RoutingBasedTarget.Contact, parameters);
        if (todo && parameters.ContainsKey("RoutingBaseCommand"))
        {
            IChainOfCommand chainOfCommand = parameters["RoutingBaseCommand"] as IChainOfCommand;
            if (chainOfCommand != null)
            {
                chainOfCommand.Execute(parameters["RoutingBaseCommandParameters"]);
            }
        }
    }


text:
Q: Passing different list of methods to be called on listener event I'm currently using an 3rd-party library  to load images,data asynchronously.
I pass a listener to that method and when the loading\download completed an event is passed to my listener and I start to use him. for example:
 getMainDownloader.getImagesLoader().loadImages(new IListener() {

                        @Override
                        public void loadingCompleted() {

                       //calling methods that uses this asset
                         method1();
                         method2();

                        }
                    }, ImagesList.get(0), ImagesList.get(3),ImagesList.get(5));

the listener Interface:
public static interface IListener {
    public void loadingCompleted();

}

In my code I have a lot of places where I should download those assets above, and call to different methods - method5(),method12()... on loadingCompleted(), so I copy the code above and each time change the methods what create a duplicated code.
Is there a technic to set one method for loading those assets and some how to pass the methods (method1()...) I want to be called in  loadingCompleted() ?

A: Instead of using an anonymous class you could use a "real" or nested class:
private static class MultiImagesListener implements IListener() {
    private final String imageId;
    public MultiImagesListener (String imageId) {
        this.imageId = imageId;
    }

    @Override
    public void loadingCompleted() {
        // use this.imageId to decide which methods to call...
        if (IMG_ID1.equals(imageId)) {
            method1();
            method13();
            method27();
        // ...
    }
}

Every time you pass an instance of your listener to the loadImages-method, you should pass a different argument to the constructor in order to distinguish the listener-instances:
getMainDownloader.getImagesLoader().loadImages(new MultiImagesListener(IMG_ID1);
getMainDownloader.getImagesLoader().loadImages(new MultiImagesListener(IMG_ID2);