text:
Q: Script returns No user is logged in on site in Pywikibot 7.2.0 Recently I decided to update Pywikibot to version 7 since the legacy API had been deprecated in Fandom wiki. Far from solving the issue, I ended up bashing my head with "No user is logged in" error instead. I had user-config.py and the credentials configured correctly according to the latest Pywikibot documentation.
Do you want to accept these changes? ([y]es, [N]o): y
WARNING: No user is logged in on site fkg:en
Traceback (most recent call last):
  File "C:\Python38\lib\site-packages\pywikibot\page\_decorators.py", line 32, in handle
    func(self, *args, **kwargs)
  File "C:\Python38\lib\site-packages\pywikibot\page\_pages.py", line 1260, in _save
    done = self.site.editpage(self, summary=summary, minor=minor,
  File "C:\Python38\lib\site-packages\pywikibot\site\_decorators.py", line 89, in callee
    raise UserRightsError('User "{}" does not have required '
pywikibot.exceptions.UserRightsError: User "None" does not have required user right "edit"

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:\FKGProcessing-master\src\update_lists.py", line 36, in save
    page.save(summary=comment or self.comment,
  File "C:\Python38\lib\site-packages\pywikibot\page\_pages.py", line 1248, in save
    self._save(summary=summary, watch=watch, minor=minor, botflag=botflag,
  File "C:\Python38\lib\site-packages\pywikibot\page\_decorators.py", line 53, in wrapper
    handle(func, self, *args, **kwargs)
  File "C:\Python38\lib\site-packages\pywikibot\page\_decorators.py", line 45, in handle
    raise OtherPageSaveError(self, err)
pywikibot.exceptions.OtherPageSaveError: Edit to page [[Module:Equipment/Names]] failed:
User "None" does not have required user right "edit"

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:\FKGProcessing-master\src\update_lists.py", line 139, in <module>
    run(sys.argv)
  File "D:\FKGProcessing-master\src\update_lists.py", line 136, in run
    bot.update()
  File "D:\FKGProcessing-master\src\update_lists.py", line 108, in update
    my.update_equipment_names()
  File "D:\FKGProcessing-master\src\update_lists.py", line 76, in update_equipment_names
    my.save(text, page)
  File "D:\FKGProcessing-master\src\update_lists.py", line 38, in save
    except pywikibot.LockedPage:
AttributeError: module 'pywikibot' has no attribute 'LockedPage'

Here's the script I intended to run:
https://github.com/HydroKirby/FKGProcessing/blob/master/src/update_lists.py

A: The update_lists.py script looks wrong. Line 38 contains
except pywikibot.LockedPage:

but it should be
except pywikibot.exceptions.LockedPageError:

since Pywikibot 7. You have to login first. There is a login.py script which can be used: https://doc.wikimedia.org/pywikibot/stable/utilities/scripts_ref.html#module-pywikibot.scripts.login. If you are using Pywikibot as a site-package you have to update your bot to release 7.4 and call this script:
pwb.exe login

For previous Pywikibot releases 7.0 you can use:
pwb.exe shell
>>> site = pywikibot.Site()
>>> site.login()

The latter also works with IDLE or as a script but you have to
import pywikibot

first.
Refer the documentation for parameters which are available for Siteconstructor function and loginmethod:

*

*https://doc.wikimedia.org/pywikibot/stable/api_ref/pywikibot.htm#pywikibot.Site

*https://doc.wikimedia.org/pywikibot/stable/api_ref/pywikibot.site.html#pywikibot.site._apisite.APISite.login


text:
Q: Why do I get ErrorException from AuthManager? I am trying to authenticate users in Laravel with Ajax form.  After the user is authenticated, he is redirected to front page.  On this front page, I am trying to set and use the model method and display name of user - like  Auth::model_name()->method, but it is showing this error:

ErrorException in AuthManager php call_user_func_array() expects parameter 1 to be a valid callback, class 'Illuminate\Auth\SessionGuard'

Front end code:
if (!Auth::check()){
Login2

{{ Auth::Hublancers_users()->username }}
}
else{
Login

}

Why do I get this error, and how can I fix it?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why doesn't the cursor stay at the same place? I have a very strange problem which I can't resolve after trying the whole morning.
This is my function and mapping:
nnoremap ,zz :call SwapAW("2-2","5")<CR>
nnoremap ,zc :call SwapAW("2-2","5")<CR>

function! SwapAW(keyw,number)
  let li = line('.')
  let co = col('.')

 exe "call cursor(li,co)"
 let linew= line('.')
 let conew= col('.')
 echo linew conew
endfunction

,zc --> moves the cursor to the right
,zz --> the cursor stays where it is
I changed everything but can't find out why the cursor doesn't stay where it is in both cases.
I changed p.e. the mapping, from ,zc to ,zd and ,zz to ,zw  (tried others as well) and changed the leaderkey from , to \, and tried to swap both mapping lines.
Nothing changes.
What's happening?
What did I wrong?
Thanks in advance.

A: You have a trailing <Space> character in your ,zc mapping (after the <CR>). That moves the cursor after the function invocation.
With mappings, one must be careful with hidden characters. Therefore, it's advisable (and sometimes, e.g. at the beginning of a mapping, necessary) to literally write the special form <Space> when you actually need to include one.

My ShowTrailingWhitespace plugin will highlight those trailing spaces and tabs, as many code guidelines frown on them. The plugin page also contains links to alternatives.


text:
Q: Symfony 4 Twig Set background image without attachement I'm trying to set a background image in my template email, but without attachement.
I've tried to upload the image in the server, it works fine but to view the email it needs to click for downloading it.
I've tried this :

and this :

Thanks.

A: I think the problem is that you need an absolute URL (starting with http://your.domain.com/etc) for the image to work inside the email:


text:
Q: WebException Could not establish trust relationship for the SSL/TLS secure channel My company has developed a .NET web service and a client dll that uses that web service. The webservice is hosted on our server over ssl and the cert is provided and signed by GoDaddy.  We have some clients in a hosted environment that are getting the following error message from the client dll when it tries to access our web service.
System.Net.WebException The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
Our fix has been to have them open IE on the server, which is a challenge in and of itself for a lot of the hosted services, and go to the WSDL url. IE then prompts them with a security alert dialog. It says the cert date is valid and a valid name matching the name of the page, but was issued by a company you have not chosen to trust. When they click Yes to proceed, the client dll can then succesfully connect to the web service and operate as normal.
Does anyone have any idea why GoDaddy would not have been in there valid publishers list? All of the servers we have running has GoDaddy as a valid authority. I'm guessing, for security reasons, they've uninstalled the authority for GoDaddy, but not totally convinced that there's not some other underlying issue.
Unfortunately, I haven't had much luck trying to recreate this locally. If I go into Internet Options and remove the GoDaddy authorities and hit our service, ssl works just fine. I go back into the list of publishers and GoDaddy gets put right back in. So my second question is, How the heck do you get rid of GoDaddy so I can get an invalid cert warning?
Okay, last question. Is there a way in code I can tell the web service to ignore invalid certs. I've seen some posts on doing this programatically with WCF but not old web services.

A: You may need to install on your servers the intermediate certificates used to sign your SSL certs.
Browsers will attempt to validate the SSL certificate by checking the validation of the chain of certs that signed the SSL cert.  If the server doesn't supply the certificate chain with the SSL certificate, the browser may reject the SSL cert.  (More of an issue for Firefox than IE).  The root certificate must still be installed on the client machine for any of this to work.

A: I fixed this error by adding this line before calling the web method:
System.Net.ServicePointManager.ServerCertificateValidationCallback = (senderX, certificate, chain, sslPolicyErrors) => { return true; };

A: VB.NET equivalent is
   System.Net.ServicePointManager.ServerCertificateValidationCallback = Function(senderX, certificate, chain, sslPolicyErrors)
                                                                             Return True
                                                                         End Function

A: This is really more of a serverfault question, but I'll add what I can here.
The root cert authority list that windows machines normally trust is updated fairly regularly.  This comes down as a windows update to IE.  You can see MSDN for more information.
If your clients do not have windows update turned on or are actively ignoring windows updates, which is unfortunately very common for a lot of IT departments, then there's not much you can do other than switch SSL providers.
Basically, they need to get the certificate updates or you need to switch to a cert provider that has a high probability of already being trusted by the machines in question.  Typically this means Verisign or Thawte.  The third alternative is the route you've been going down: have them manually trust the root CA.
At the end of the day I hate the idea of changing an app in this way simply because the IT departments in question are morons but the real question boils down to how your company wants to handle this.

A: When you look at the Go Daddy Certification Path of that certificate on the web server, do you see Go Daddy Class xxx or Starfield Class xxx ?
And from your non-legacy client i.e Windows Vista upwards, what does the Go Daddy Certification Path display? Go Daddy Class xxx or Starfield Class xxx ?
And these clients that get the warning, are they legacy clients? i.e WinXP and older?
Root Certificate updates works differently as of Windows Vista.
http://support.microsoft.com/kb/931125
Root certificates on Windows Vista and later are distributed via the automatic root update mechanism – that is, per root certificate. When a user visits a secure Web site (by using HTTPS SSL), reads a secure email (S/MIME), or downloads an ActiveX control that is signed (code signing) and encounters a new root certificate, the Windows certificate chain verification software checks Microsoft Update for the root certificate. If it finds it, it downloads the current Certificate Trust List (CTL) containing the list of all trusted root certificates in the Program, and verifies that the root certificate is listed there; it then downloads the specified root certificate to the system and installs it in the Windows Trusted Root Certification Authorities Store.
You'll probably find that your Go Daddy Certification Path on the web server thinks it's Starfield Class 2 instead of Go Daddy Class 2 so you installed the wrong root certificate. It caught me out as when you view in on the web server it doesn't display a root certificate warning, download and install the Do Daddy class 2 root cert and remove the Starfield one and your problem should dissapear.


text:
Q: Let U and V be subspaces of a vector space W. Is U\V a subspace? I'm not sure on how to answer such a question, or how exactly to prove that this is true or not. Should I consider whether $\,U \cap V $ exists and check the case if they are exclusive, or something else. I'm having trouble answering these questions and some methodology would help.

A: This will never be the case.
Since $V$ is a subspace, you have $0\in V$, so $0\notin U\setminus V$.
So $U\setminus V$ cannot be a subspace of the vector space.
Edit.
To answer your comment, it can't be closed under multiplication since
$$0\cdot x=0\notin U\setminus V,$$
and it can't be closed under addition since
$$x-y=0\notin U\setminus V.$$


text:
Q: what a bug of apk may cause android reboot my app is drawing some images on surfaceview ,and have a certain probability cause android system reboot.I have pull the file "/proc/last_kmsg" out, may this be a bug of android system? The device is Samsung T805c.
Here is the last_kmsg log:
[ 5968.925578] I[B0: com.example.test:  7576] ---------[ cut here ]------------
[ 5968.925738] I[B0: com.example.test:  7576] kernel BUG at drivers/media/video/exynos/fimg2d/fimg2d_drv.c:208!
[ 5968.925997] I[B0: com.example.test:  7576] Internal error: Oops - BUG: 0 [#1] PREEMPT SMP ARM
[ 5968.926240] I[B0: com.example.test:  7576] CPU: 0    Not tainted  (3.4.39-6095882 #1)
[ 5968.926460] I[B0: com.example.test:  7576] PC is at fimg2d_sysmmu_fault_handler+0x78/0x10c
[ 5968.926631] I[B0: com.example.test:  7576] LR is at console_unlock+0x204/0x250
[ 5968.926830] I[B0: com.example.test:  7576] pc : [<c048c658>]    lr :
[<c003baec>]    psr: 600f0193
[ 5968.926901] I[B0: com.example.test:  7576] sp : db3cbc08  ip : db3cba80  fp : db3cbc2c
[ 5968.927168] I[B0: com.example.test:  7576] r10: 8ff9b000  r9 : c09072f8  r8 : 00000000
[ 5968.927362] I[B0: com.example.test:  7576] r7 : deaf8790  r6 : d76d0000  r5 : c0b8cf38  r4 : c0c434dc
[ 5968.927572] I[B0: com.example.test:  7576] r3 : 00000000  r2 : c0b5c554  r1 : 800f0193  r0 : 00000068
[ 5968.927774] I[B0: com.example.test:  7576] Flags: nZCv  IRQs off  FIQs on  Mode SVC_32  ISA ARM  Segment user
[ 5968.927989] I[B0: com.example.test:  7576] Control: 10c5387d  Table: 376d006a  DAC: 00000015
[ 5968.928129] I[B0: com.example.test:  7576] CPU 0 / CLUSTER 0
[ 5968.928308] I[B0: com.example.test:  7576] DFSR: 00000021, ADFSR: 00000000, IFSR: 00000007, AIFSR: 00000000
[ 5968.928520] I[B0: com.example.test:  7576] CPUMERRSR: 00000000_00000000, L2MERRSR: 00000000_00000000
[ 5968.928730] I[B0: com.example.test:  7576] CPUFREQ: 900000 KHz

A: Is difficult to find the cause. Maybe the problem is something linked to your graphical adapter.
Try that in your manifest (put it inside

android:hardwareAccelerated="false"


text:
Q: When I developing an Android application ,how can I cancel a running AsyncTask?
Possible Duplicate:
Ideal way to cancel an executing AsyncTask

When I developed an Android application, I used an AsyncTask to download something, I used a progressDialog to show the progress of this AsyncTask, now When I press the back button, I want to cancel this AsycTask, I invoked the AsycTask.cancel(), but it doesn't work. How can I cancel a running AsyncTask ?

A:  class ImplementAsynctask extends AsyncTask implements OnDismissListener{
       ProgressDialog dialog = new ProgressDialog(ActivityName.this);

       protected onPreExecute() {
           //do something and show progress dialog
       }
       protected onPostExecute() {
          //cancel dialog after completion
       }

       @Override
        public void onDismiss(DialogInterface dialog) {
            //cancel AsycTask in between.
            this.cancel(true);
        }
};

A: The most correct way to do it would be to check periodically inside doInBackground if the task was cancelled (i.e. by calling isCancelled). From http://developer.android.com/reference/android/os/AsyncTask.html:
Cancelling a task :
A task can be cancelled at any time by invoking
 cancel(boolean). Invoking this method will cause subsequent calls to
 isCancelled() to return true. After invoking this method,
 onCancelled(Object), instead of onPostExecute(Object) will be invoked
 after doInBackground(Object[]) returns. To ensure that a task is
 cancelled as quickly as possible, you should always check the return
 value of isCancelled() periodically from doInBackground(Object[]), if
 possible (inside a loop for instance.)
Check also this blog post if you need more information: http://vikaskanani.wordpress.com/2011/08/03/android-proper-way-to-cancel-asynctask/

A: do the following on click of back button:
declare your Aynctask as global variable like this:
//AysncTask class
private contactListAsync async;

    if(async != null){

    async.cancel(true);

    async= null;

    }


text:
Q: Hibernate : delete child entity with two different kinds of parent entities I have a data base schema like in the picture DB schema where 1 child entity has 2 different kinds of ManyToOne relations to different parents: father and mother. When I let this be created by Hibernate, I can delete a child by removing it from the mother, but I can not delete it by removing it from the father.
The father entity looks like this, and the mother is identical.
@Entity
@Table(name = "father_entity")
public class FatherEntity extends BaseEntity {
@OneToMany(mappedBy = "fatherEntity", cascade=CascadeType.ALL, orphanRemoval=true)
private Collection<ChildEntity> childEntities = new ArrayList<>();

public void addChildEntity(ChildEntity childEntity) {
    this.childEntities.add(childEntity);
    childEntity.setFatherEntity(this);
}

public void removeChildEntity(ChildEntity childEntityToRemove) {
    Iterator<ChildEntity> iterator = this.childEntities.iterator();
    while (iterator.hasNext()) {
        ChildEntity childEntity = iterator.next();

        if (childEntity.equals(childEntityToRemove)) {
            iterator.remove();
            childEntityToRemove.setFatherEntity(null);
        }
    }
}

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "grand_parent_entity_id", referencedColumnName = "id", nullable = false)
private GrandParentEntity grandParentEntity;

@Column(name = "name", nullable = false)
private String name;

The child class is:
@Entity
@Table(name = "child_entity")
public class ChildEntity extends BaseEntity {

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "father_entity_id", referencedColumnName = "id", nullable = false)
private FatherEntity fatherEntity;

@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "mother_entity_id", referencedColumnName = "id", nullable = false)
private MotherEntity motherEntity;

@Column(name = "name", nullable = false)
private String name;

So basically with this in place, this test succeeds, as expected:
@Test
void testCascadeRemove2() {
    assertThat(fatherEntityRepository.count()).isEqualTo(1l);
    assertThat(motherEntityRepository.count()).isEqualTo(1l);
    assertThat(childEntityRepository.count()).isEqualTo(1l);
    assertThat(fatherEntity.getChildEntities().contains(childEntity));

    motherEntity.removeChildEntity(childEntity);

    assertThat(fatherEntityRepository.count()).isEqualTo(1l);
    assertThat(motherEntityRepository.count()).isEqualTo(1l);
    assertThat(childEntityRepository.count()).isEqualTo(0l);
    assertThat(fatherEntity.getChildEntities().isEmpty());
}

But this symmetrical one gives an error, from which I deduct that the child was not removed, but only its foreign key to the father was set to null:
@Test
void testCascadeRemove1() {
    assertThat(fatherEntityRepository.count()).isEqualTo(1l);
    assertThat(motherEntityRepository.count()).isEqualTo(1l);
    assertThat(childEntityRepository.count()).isEqualTo(1l);
    assertThat(motherEntity.getChildEntities().contains(childEntity));

    fatherEntity.removeChildEntity(childEntity);

    assertThat(fatherEntityRepository.count()).isEqualTo(1l);
    assertThat(motherEntityRepository.count()).isEqualTo(1l);
    assertThat(childEntityRepository.count()).isEqualTo(0l);
    assertThat(motherEntity.getChildEntities().isEmpty());
}

The error:
Hibernate: insert into father_entity (grand_parent_entity_id, name) values (?, ?)
Hibernate: insert into mother_entity (grand_parent_entity_id, name) values (?, ?)
Hibernate: insert into child_entity (father_entity_id, mother_entity_id, name) values (?, ?, ?)
Hibernate: select count(*) as col_0_0_ from father_entity fatherenti0_
Hibernate: select count(*) as col_0_0_ from mother_entity motherenti0_
Hibernate: select count(*) as col_0_0_ from child_entity childentit0_
Hibernate: select count(*) as col_0_0_ from father_entity fatherenti0_
Hibernate: select count(*) as col_0_0_ from mother_entity motherenti0_
Hibernate: update child_entity set father_entity_id=?, mother_entity_id=?, name=? where id=?
2020-07-30 16:53:46.049  WARN 10068 --- [           main] o.h.engine.jdbc.spi.SqlExceptionHelper
SQL Error: 0, SQLState: 23502
2020-07-30 16:53:46.050 ERROR 10068 --- [           main] o.h.engine.jdbc.spi.SqlExceptionHelper
ERROR: null value in column "father_entity_id" violates not-null constraint
Detail: Failing row contains (52, child, null, 52).

Does anyone know why the one parent can delete the child by removing it from its list, and the other cannot?
Thanks


text:
Q: Struggling with gravitational potential definition The textbook for my A-Level physics course defines the gravitational potential at a point as:
The work done per unit mass to move a small object from infinity to that point.
But if Work = Force * distance,
This definition makes no sense, because to move something from A to B you can apply as small a force as you want, let go, and it will keep on going until it gets there. If you're not in a rush, you can do it with as little work as you like, so F is effectively 0.
Also, if you're moving from infinity to a finite displacement, distance d is effectively infinite.
Any help would be appreciated.

A:
This definition makes no sense, because to move something from A to B you can apply as small a force as you want, let go, and it will keep on going until it gets there.

That would be correct if there was no gravitational force, but it is not true in the case you are talking about. If you throw some object up it won't keep going forever, it will come back, exactly because of the gravitational force, so you can't move an object away from a source of gravitational force (like the earth) with an arbitrarily small force, as you can see for yourself when lifting something from the surface of the earth.

Also, if you're moving from infinity to a finite displacement, distance d is effectively infinite.

The distance is infinite, but there is no force infinitely far away, so the work is still finite. For gravitational force you have:
$$F \propto \frac {1}{r^2} \implies \lim_{r \to \infty}F=0$$
But if you want to be more precise, it is important to notice that $F \to 0$ as $x \to \infty$ is not enough for the work to be finite, since the work in this case is:
$$W= \int_{\infty}^d F(r) \cdot dr$$
You can see that for $F(r) \propto \frac {1}{r}$ the work would be infinite, even though $\lim_{r \to \infty}F=0$. So the fact that the potential is $0$ at $\infty$ needs not only the force to go $0$ at $\infty$, but it also needs the force to go to $0$ "fast enough".


text:
Q: PostGIS - Snapping a point to a line doesn't work I'm trying to snap one polygon to another, and I found that not all points are being snapped as expected. I tried to simplify the issue to make it all clear, and created this dummy example:
SELECT ST_AsText(ST_Snap(point,polygon, 0.00001)) AS point_snapped
FROM (SELECT
   ST_GeomFromText('POINT(-0.00000001 1)') As point,
   ST_GeomFromText('POLYGON((0 0,0 2,2 2,0 0))') As polygon
 ) As foo;
  point_snapped
-----------------
 POINT(-1e-08 1)

Why isn't the point "fixed" to be (0 1)?
And why does it work when I modify the polygon to have that point (which doesn't change the geometry at all)?
SELECT ST_AsText(ST_Snap(point,polygon, 0.00001)) AS point_snapped
FROM (SELECT
   ST_GeomFromText('POINT(-0.00000001 1)') As point,
   ST_GeomFromText('POLYGON((0 0,0 1,0 2,2 2,0 0))') As polygon
 ) As foo;
 point_snapped
---------------
 POINT(0 1)

Of course one thing I can do to solve that, for each point not snapped correctly, is to add the closest point to it from the other geometry to that geometry, and then snap. But it's quite difficult, and if there is a nicer way to do it, with built-in PostGIS function, that would be better.

A: This is the expected behavior: snapping occurs on existing vertices only.

Snaps the vertices and segments of a geometry [to] another Geometry's
  vertices.

The solution would be to add the missing vertices, or to just consider the closest point. Note that you might want some extra validations should the closest point be within the tolerance distance of an existing vertex.
SELECT ST_AsText(ST_Snap(point,ST_ClosestPoint(polygon,point), 0.00001)) AS point_snapped
FROM (SELECT
   ST_GeomFromText('POINT(-0.00000001 1)') As point,
   ST_GeomFromText('POLYGON((0 0,0 2,2 2,0 0))') As polygon
 ) As foo;
 point_snapped
---------------
 POINT(0 1)

A: I had the same problems with snap and this topic helped me to include the ST_3DClosestPoint function in my view.
line_table - one polyline (id=1)
points_table - multiple points
SELECT ST_AsText(
    (SELECT ST_AsEWKT(ST_AddPoint(
    (SELECT (ST_Snap(
    (SELECT geom1 AS points_line
    FROM(SELECT ST_Union(a.geom2) AS geom1
    FROM (select geom AS geom2
    FROM line_table where id = 1) AS a) AS foo),
    (SELECT geom1 AS points_line
    FROM(SELECT ST_Multi(ST_Union(a.geom2)) AS geom1
    FROM (select ST_Multi(ST_Union(geom_inter)) AS geom2
    FROM points_table) AS a) AS foo), 0.1)))
    ,
    (SELECT
    ST_3DClosestPoint(
    (SELECT geom1 AS points_line
    FROM(SELECT ST_Union(a.geom2) AS geom1
    FROM (select geom AS geom2
    FROM line_table where id = 1) AS a) AS foo),
    (SELECT geom1 AS points_line
    FROM(SELECT ST_Multi(ST_Union(a.geom2)) AS geom1
    FROM (select ST_Multi(ST_Union(geom_inter)) AS geom2
    FROM points_table) AS a) AS foo)) as foo)))))


text:
Q: Appyphony lightning JS not showing slds icons correctly I am using Appyphony Lightning JS to create lookup relationship field for me. Everything else was working pretty well. But the slds icons are not displaying well. I am constantly getting the below error in chrome's developer tool:

Unsafe attempt to load URL
  https://ap2.salesforce.com/assets/icons/standard-sprite/svg/symbols.svg#account
  from frame with URL
  https://v6.ap2.visual.force.com/apex/Auto_Subscription_Edit?retURL=%2Fa08%2Fo&save_new=1&sfdc.override=1.
  Domains, protocols and ports must match.

And the lookup relationship field now looks like this:

I have added the initialization code as below:
        var assetsLocation = "{!URLFOR($Resource.Slds213, 'assets')}";
        $.aljsInit({
            assetsLocation: '',
            scoped: true
        });

Is there anything else I am missing here?

A: In appyphony, the assetsLocation is meant to specify the location of the resource, not the actual assets directory itself.
So change the line into:
var assetsLocation = "{!URLFOR($Resource.Slds213)}";

And hopefully it will work.

A: "Appyphony Lightning JS" was working for old SLDS bundles because Icons were exist in the 'Assets' folder but now icons are exist directly in 'icons' folder.
There is a mistake in Appyphony js files.  Please follow these steps:

*

*Open 'jquery.aljs-all-with-moment.min.js' file and search for 'svg#account' or any icon you want to show in your plugin.

*Replace this URL '/assets/icons/standard-sprite/svg/symbols.svg#account' with '/icons/standard-sprite/svg/symbols.svg#account'.

*Save file 'jquery.aljs-all-with-moment.min.js'.

*Now initialize assetlocation just like below if you are using "apex:slds" in your VF Page:
$.aljsInit({
    assetsLocation: '/_slds',
    scoped: true
});


text:
Q: linux-image-generic error My ubuntu 16.04 will give me the result that
Errors were encountered while processing:
 linux-image-4.4.0-70-generic
 linux-image-extra-4.4.0-70-generic
 linux-image-generic
 linux-generic
 linux-signed-image-4.4.0-70-generic
 linux-signed-image-generic
 linux-signed-generic
E: Sub-process /usr/bin/dpkg returned an error code (1)

whenever and whatever I install, what should I do?

A: https://help.ubuntu.com/community/RemoveOldKernels
it can solve the problem ,which maybe due to lack of storage.


text:
Q: how to fetch List of data from Postgres Database using Spring Batch I am using spring batch to fetch, process and write some data. I am using Postgres. I want to fetch list of data instead of fetching data one by one and want to pass the same list to processor. Is this possible in Spring Batch?

A: The chunk-oriented processing is designed to read one item at a time. Now how to define an "item" is up to you. If you think a "list of items" is one item then you can still use that model, but you would need a custom item reader that returns a list.
All item readers provided by Spring Batch are designed to return a single piece of data, like a line in a flat file, a record in database table, a document from a NoSQL collection, a message from a queue, a file in a folder, etc. Anything that deviates from that requires a custom item reader.


text:
Q: Python Skipping a Parameter in a Function Beginner Here and I just want to know how to skip a parameter in python for example
def function(a, b):
    pass

function(5)

I want to only assign 5 to b. How can I do it?

A: You can do this:
def function(a=None, b=None):
    pass

function(b=5)

This makes the values that don't get assigned None (in this case a is gonna be None).
If you don't add =None to the two parameters, it will throw an error because I didn't assign anything to a.
If in the last line you don't say b=5 and instead say just 5, it will think that is for the a parameter since the a parameter is before the b parameter in the parenthesis.

A: Simply, You can set a default value to a in that case.
def function(b,a=None):
pass

function(5)

Please note that the default parameters are supposed to follow the non-defualt ones.


text:
Q: maxscale proxy does not route read requests from flask-sqlachamy to the slaves I have a maxscale mariadb cluster with one master and two slaves. I am using flask-sqlachemy ORM for querying and writing.
I have written read queries in style
db.session(User).join()....
Now all my read queries are going to max scale master node
Below are maxcalse logs
2021-09-14 17:38:26   info   : (1239) (Read-Write-Service) > Autocommit: [disabled], trx is [open], cmd: (0x03) COM_QUERY, plen: 287, type: QUERY_TYPE_READ, stmt: SELECT some_col FROM user
2021-09-14 17:38:26   info   : (1239) [readwritesplit] (Read-Write-Service) Route query to master: Primary <

I have tried other ways too
conn = mysql_connector.connect(...)
conn.autocommit(True)
cursor = conn.cursor()
cursor.execute(query)

This works fine and routes query to one of slave.
But my most of code is written in ORM style. Is there any way to achieve this while using flask-sqlalchemy

A: If autocommit is disabled, you always have an open transaction: use START TRANSACTION READ ONLY to start an explicit read-only transaction. This allows MaxScale to route the transaction to a slave.


text:
Q: How can I set the color of words as they are added to a TMPro UI element? I've got a script that is added words according to an order when you pick them up, but when you get the order wrong, it is filling in the words that should have gone in that order.  Most of the script is listed below, but I'm struggling to find a solution to having the words that are correct (In the OnMouseDown else if statment) being added with the color white, and the other two SetText calls adding the words with the color red.
`
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;

public class WordOrderOnDestroy : MonoBehaviour
{
        private TextMeshProUGUI pickedUpWords;

    void Start()
    {
                pickedUpWords = GameObject.Find("Picked Up Words").GetComponent<TextMeshProUGUI>();
    }

    void OnMouseDown()
    {
        if (gameObject.name != memorySlotOne[currentIndexOne])
        {
            GetComponent<MeshRenderer>().material = redForWrong;
            StartCoroutine(DestroyObjects());
        }
        else if (gameObject.name == memorySlotOne[currentIndexOne])
        {
            Debug.Log("Correct!");
            pickedUpWords.SetText(pickedUpWords.text + memorySlotOne[currentIndexOne] + " ");
            Destroy(gameObject);
        }
    }

    IEnumerator DestroyObjects()
    {
        for (int i = currentIndexOne; i < memorySlotOne.Count; i++)
        {
            if (memorySlotOne[i] == gameObject.name)
            {
                Debug.Log("And then, " + (memorySlotOne[i]));
                Destroy(gameObject);
                memoryListManager.currentIndexOne++;
                pickedUpWords.SetText(pickedUpWords.text + memorySlotOne[i] + " ");
                break;
            }
            // Append the current word to the text mesh pro UI element
             pickedUpWords.SetText(pickedUpWords.text + memorySlotOne[i] + " ");

            yield return new WaitForSeconds(rateOfDestroy);
            Destroy(GameObject.Find(memorySlotOne[i]));
            Debug.Log("Next correct word was: " + (memorySlotOne[i]));
        }

    }
}

`

A: TextMeshPro supports Rich Text so you can simply wrap your words in e.g.
"<color=red>" + memorySlotOne[currentIndexOne] + "</color>"

Might need to enable TEMP_Text.richText (should be default though afaik)


text:
Q: jeditable dynamic maxlength following up to this question: jquery select and use part of class name
i thought to use this way to dynamically assign a maxlength to the jeditable script (i assign a special class to each element startig with edit_*, where the star is the maxlength):
$("[class^='edit_']").editable('url', {
    id          : $(this).attr('id'),
    maxlength   : $("[class^='edit_']").on('click',function() {
            return $(this).attr('class').split(' ')[0].split('_')[1];
    }),
});

problem is that while the function itself works if used separately, it doesn't work inside the above script. I even tried to return a number manually (ex. return 2) and it works...what's the trick?

A: ok, for those who will be landing here...i solved this way:
$("[class^='edit_']").each( function() {
    var ml = $(this).attr('class').split(' ')[0].split('_')[1];
    $(this).editable('[url]', {
        [...]
        maxlength   : ml,
    });
});


text:
Q: webpack не билдит компоненты index.tsx (React Redux Toolkit TypeScript) При команде npm run build webpack собирает проект как нода.
При запуске index.html применяются только стили, и не загружает компоненты, не выдавая ошибок ни при сборке, ни при запуске.
мой webpack.common.ts
import path from "path";
import HtmlWebpackPlugin from "html-webpack-plugin";
import TsconfigPathsPlugin from "tsconfig-paths-webpack-plugin";

module.exports = {
    entry: './src/index.tsx',
    devtool: 'inline-source-map', // only in dev mode
    output: {
        path: path.join(__dirname, '/dist'),
        publicPath: '/',
        filename: 'bundle.js'
    },
    module: {
        rules: [
             // TypeScript
            {
                test: /\.ts|\.tsx$/,
                use: 'ts-loader',
                exclude: /node_modules/
            },
             // Style
            {
                test: /\.s?css$/,
                use: ["style-loader", "css-loader", "sass-loader"],
            },
             // Images
             {
                test: /\.(?:ico|gif|png|jpg|jpeg)$/i,
                type: 'asset/resource',
             },
             // Fonts and SVGs
             {
                test: /\.(woff(2)?|eot|ttf|otf|svg|)$/,
                type: 'asset/inline',
             },
        ]
    },
    resolve: {
        extensions:  [ '.tsx', '.ts', '.js' ],
        plugins: [new TsconfigPathsPlugin({ configFile: "./tsconfig.json" })]
    },
    plugins: [
        new HtmlWebpackPlugin({
            favicon: "./public/img/favicon.ico",
            template: './public/index.html'
        })
    ]
}

package.json
{
  "name": "svodki",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@electron/remote": "^1.2.2",
    "@reduxjs/toolkit": "1.9.1",
    "@testing-library/jest-dom": "5.16.5",
    "@testing-library/react": "13.4.0",
    "@testing-library/user-event": "14.4.3",
    "@types/jest": "27.5.2",
    "@types/node": "17.0.45",
    "@types/react": "18.0.26",
    "@types/react-dom": "18.0.9",
    "bootstrap": "5.2.3",
    "cors": "2.8.5",
    "electron-is-dev": "^1.2.0",
    "font-awesome": "4.7.0",
    "lodash.debounce": "^4.0.8",
    "react": "18.2.0",
    "react-debounce-input": "^3.3.0",
    "react-dom": "18.2.0",
    "react-redux": "8.0.5",
    "react-router-dom": "^6.4.5",
    "react-scripts": "5.0.1",
    "typescript": "4.9.4",
    "use-debounce": "^9.0.2",
    "web-vitals": "2.1.4"
  },
  "main": "src/app.tsx",
  "homepage": ".",
  "scripts": {
    "start": "webpack serve --open --config webpack.dev.ts",
    "build": "webpack --progress --color --stats-error-details --config webpack.prod.ts",
    "test": "jest --coverage",
  },

    "directories": {
      "buildResources": "assets"
    }
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@types/lodash.debounce": "^4.0.7",
    "concurrently": "^5.3.0",
    "cross-env": "^7.0.3",
    "css-loader": "6.7.1",
    "dotenv-webpack": "8.0.1",
    "electron": "^11.2.1",
    "electron-builder": "^22.9.1",
    "eslint-plugin-react-hooks": "^4.6.0",
    "html-webpack-plugin": "5.5.0",
    "node-sass": "7.0.3",
    "prettier": "^2.2.1",
    "sass": "1.55.0",
    "sass-loader": "13.0.2",
    "source-map-loader": "^4.0.0",
    "style-loader": "3.3.1",
    "stylelint": "14.13.0",
    "ts-loader": "9.4.1",
    "ts-node": "10.9.1",
    "tsconfig-paths-webpack-plugin": "4.0.0",
    "typescript": "4.8.4",
    "wait-on": "^5.2.1",
    "webpack": "5.74.0",
    "webpack-cli": "4.10.0",
    "webpack-dev-server": "4.11.1"
  }
}

tsconfig.json
{
  "compilerOptions": {
    "outDir": "./dist/",
    "target": "ES6",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "commonjs",
    "sourceMap": true,
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": false,
    "jsx": "react-jsx",
    "baseUrl": "./src/",
  },
  "exclude": ["node_modules"],
  "include": [
    "./src/**/*", "tests"
  ],
}


text:
Q: unknown column mysql where clause - but I can access and set it within my app. what is causing this? models:
   class Change < ActiveRecord::Base
      attr_accessor :selected_end_index, :selected_start_index, :revision_number

error:
 ActiveRecord::StatementInvalid: Mysql::Error: Unknown column 'revision_number' in 'where clause': SELECT * FROM `changes` WHERE (kind = 2 && status = -1 && content_id = 2 && revision_number = 0)  ORDER BY id DESC

method:
  def new_change_requests_for_latest_version
    changes = Change.find(:all,
                :conditions => ["kind = ? && status = ? && content_id = ? && revision_number = ?",
                                Change::CHANGE, Change::NEW, self[:id], self.current_version],
                :order => "id DESC")

    return changes
  end

A: It means there is no column named "revision_number".  The reason you can access it in your app is because  attr_accessor sets up the field in the in-memory object.  But any value assigned to it will not be persisted in the database, nor can you query on it.


text:
Q: My discord.js bot wont start when I run "npm run start" When I try and run npm run start in my console for my discord.js bot I have no idea why it won't work.
(here is my package.json)
{
  "name": "spinier-bot",
  "version": "1.0.0",
  "description": "Moderation & utility bot with a little bit of fun sprinkled in.",
  "main": "src/bot.js",
  "scripts": {
    "test": "node ."
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@discordjs/rest": "^1.2.0",
    "chalk": "^4.1.2",
    "discord-api-types": "^0.37.12",
    "discord.js": "^14.5.0",
    "dotenv": "^16.0.3"
  }
}

I was looking for a solution for this and I could not find anything, I just want to know how I can fix it so I can get my bot online for testing. (I don't know much about discord.js or JavaScript at all so I have no idea what is going on).

A: It should be:
{
  "name": "spinier-bot",
  "version": "1.0.0",
  "description": "Moderation & utility bot with a little bit of fun sprinkled in.",
  "main": "src/bot.js",
  "scripts": {
    "start": "node ."
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@discordjs/rest": "^1.2.0",
    "chalk": "^4.1.2",
    "discord-api-types": "^0.37.12",
    "discord.js": "^14.5.0",
    "dotenv": "^16.0.3"
  }
}

Here, I changed the test script to start.


text:
Q: gradle not coordinated with the project I am using android studio version 4.1.3 and gradle version 6.8.3 . My target sdk version for the project is API 26.
After clicking on sync the project, the result seems have no problem but after clicking on run app, I have some errors. One of them says,
gradle-6.8.3\caches\transforms-3\71de35e86c45a332199eb23f9129d32f\transformed\material-1.4.0\res\values\values.xml:1316:-1327:11:  AAPT: error: style attribute 'android:attr/dialogCornerRadius' not found

I have seen the Error:(9, 5) error: resource android:attr/dialogCornerRadius not found
But again the problem is not solved
I don't know what should I do?


text:
Q: Why does this come up as non-object? I am trying to create a really simple database connection class in PHP, but I ran into a bit of problem.
First off, here's the code I wrote:
class db {

    protected $db;

    public function __construct() {

        $this->db = new PDO('mysql:host=127.0.0.1;dbname=main', 'root', '');
    }
}

Whenever I try to call $db from another class that extends my database class, I get an error like this one:

Fatal error: Call to a member function prepare() on a non-object in class.php

I call the database link in the other class like the following example:
class example extends db {

    public function challenge_exists($challenge) {

        $query = $this->db->prepare('SELECT * FROM challenges WHERE challenge = :challenge');
        $query->bindParam(':challenge', $challenge, PDO::PARAM_STR);
        $query->execute();

        if($query->rowCount() > 0) {
            return true;
        }
    }
}

I have no idea what I have done wrong and would appreciate any suggestions on how to make this work.

A: To the question, if there is a __construct() method in the child class then you need to call the __construct() of the parent class explicitly, or else it is not executed and $db is never instantiated.  Though you don't show the child constructor in your example code it is safe to assume that there is one based on the behavior, so:
class example extends db {

    public function __construct() {
        parent::__construct();
        //more stuff
    }
}

If you don't need a constructor in the child class then remove it and the parent constructor will be called when you instantiate an object of the child class.
As for the design, this is bad and you should consider one database object and inject that into objects that need it or similar approach:
class example {

    public function __construct($db) {
        $this->db = $db;
    }
}

$db = new db();              // do this once
$example = new example($db); // inject when needed

A: You should never extend an applications class from a database class in the first place.
User is not a database. It's a user. They have nothing in common. Database have to be used as a service by a user, not being a parent.
Not to mention that creating a hundred connections from the same script is a very bad idea.
Regarding the "accepted" answer, it's just wrong. As long as there is no constructor in the child class defined (like in the OP), then parent counstructor is used. Welcome to Stack Overfraud.


text: Q: Linking Heroku review apps for separated frontend and backend So, i plan to implement review apps into our deploy flow. Our application is separated in two codebases and two Heroku instances (frontend and backend). When I open pull request review app is created for that PR, how would I or can I somehow link two review apps for features that bring changes to both frontend and backend and are part of same feature, can I link two review apps from two PR's?


text:
Q: Use typeof with a variable frmMainPage is a Form in my project.
This is correct
var myType = typeof(frmMainPage);

This is incorrect
Form frm = (Form)Activator.CreateInstance(Type.GetType("frmMainPage"), _userName);

var myType = typeof(frm);

How can I use typeof with a variable?

A: typeof takes a type name you specify at compile time.
GetType gets the runtime type of an instance.


text:
Q: how can i resolve this kind of error in VB.net? MySql.Data.MySqlClient.MySqlException: 'You have an error in your Sql syntax; check the manual...' Private connection As New MySqlConnection("datasource=localhost;port=3306;username=root;password=;database=hotelmanagementdb")

    ReadOnly Property getConnection() As MySqlConnection
        Get
            Return connection
        End Get
    End Property

    Sub openConnection()
        If connection.State = ConnectionState.Closed Then
            connection.Open()
        End If
    End Sub

    Sub closeConnection()
        If connection.State = ConnectionState.Open Then
            connection.Close()
        End If
    End Sub

the error at the adapter.Fill(table)
throwing an error to check the manual that corresponds to your MariaDB server version for the right syntax to use near 'password=''' at line 1
Ive been constantly updating my MySql ports in Xampp due to errors, i guess this is the reason why some errors occurs

A: on mysql password please do not null in password.
if your mysql don't have password please set,  Password='';


text:
Q: Is keeping track of dependencies in a randomly initialized neural network for a NEAT algorithm necessary? I'm attempting to code a NEAT algorithm from scratch using C#. I'm very early in the process and I'm now going about writing a method for randomly initializing a network. I want to use the mutations detailed in this video and apply a certain amount of these mutations until a good starting neural network is created.
As I thought about it, I realized that if I just do this randomly there's the possibility of circular dependency. Is there a better way of initializing and mutating these neural networks or will I have to implement a dependency graph as well to ensure no circular dependencies occur? That seems like it could end up being pretty computationally slow, which I'd like to avoid as much as possible.
Any material explaining in detail how these neural networks are initialized and mutated properly would be much appreciated.


text:
Q: functions are undefined inside react object I am trying to call imagesLoaded function (which is imported properly in the scripts area), but when calling it from inside a component prop, I get an error that it is indefined.
my code:
    var MasonryContainer = React.createClass({

    imagesLoadedFunc: function() { //omitting the imageloaded call here fix everything
                  this.imagesloaded();
                  this.refs[reference].getDOMNode().imagesLoaded(function() {
                   this.masonry.layout()
                     });

    },
    componentDidMount: function() {
                if (!isBrowser) return;
                this.initializeMasonry();
                this.performLayout();
                this.imagesLoadedFunc();
            },

    componentDidUpdate: function() {
                if (!isBrowser) return;

                this.performLayout();
                this.imagesLoadedFunc(this);
            },

            domChildren: [],

    initializeMasonry: function(force) {
        if (!this.masonry || force) {
            this.masonry = new Masonry(this.refs[reference].getDOMNode(), options);
            this.domChildren = this.getNewDomChildren();
        }
    },

    getNewDomChildren: function () {
        var node = this.refs[reference].getDOMNode();
        var children = options.itemSelector ? node.querySelectorAll(options.itemSelector) : node.children;

        return Array.prototype.slice.call(children);
    },

    diffDomChildren: function() {
        var oldChildren = this.domChildren;
        var newChildren = this.getNewDomChildren();
        var removed = oldChildren.filter(function(oldChild) {
            return !~newChildren.indexOf(oldChild);
        });

        var added = newChildren.filter(function(newChild) {
            return !~oldChildren.indexOf(newChild);
        });

        var moved = [];

        if (removed.length === 0) {
            moved = oldChildren.filter(function(child, index) {
                return index !== newChildren.indexOf(child);
            });
        }
        this.domChildren = newChildren;
        return {
            old: oldChildren,
            'new': newChildren, // fix for ie8
            removed: removed,
            added: added,
            moved: moved
        };
    },

    performLayout: function() {
        var diff = this.diffDomChildren();

        if (diff.removed.length > 0) {
            this.masonry.remove(diff.removed);
            this.masonry.reloadItems();
        }

        if (diff.added.length > 0) {
            this.masonry.appended(diff.added);
        }

        if (diff.moved.length > 0) {
            this.masonry.reloadItems();
        }

        this.masonry.layout();
    },

    componentWillReceiveProps: function() {
        setTimeout(function() {
            this.masonry.reloadItems();
            this.forceUpdate();
        }.bind(this), 0);
    },

    render: function () {
        return (

        );
    }
});
    React.render(
    <MasonryContainer/>, document.getElementById('reactbody')
    )
</script>

if I call the imageloaded constructor outside of the react component, it is working.
What am I missing?

A: Your calling imagesloaded using this,
this.imagesloaded();

However, imagesloaded is not part of your component, nor a standard in React. Thus, this.imagesloaded is undefined, since it never has been declared. Try removing the "this" part of the statement.
 imagesLoadedFunc: function() {
     imagesloaded();
     //the rest of the method
 },


text:
Q: Summarize and Rank Data Frame Using R, I need to build a report of the top 2 employees per departments with the most expenses and add an "Others" for the other employees of the department. For instances, I would need a report similar to this.
Dept.      EmployeeId     Expense
Marketing       12345         100
Marketing       12346          90
Marketing      Others         200
Sales           12347          50 <-- There's just one employee with expenses
Research        12348        2000
Research        12349         900
Research       Others       10000

In other words, I need to summarize the data with a focus on the top 2 employees with the most expenses. The sum of the expense column should be the total amount of the expenses of the company.
employeIds <- sample(1000:9999, 20)
depts <- sample(c('Sales', 'Marketing', 'Research'), 20, replace = TRUE)
expenses <- sample(1:1000, 20, replace = TRUE)

df <- data.frame(employeIds, depts, expenses)

# Based on that data, how do I build a table with the top 2 employees with the most expenses in each department, including an "Other" employee per department.

I am new to R and I am not sure on how to approach this. In SQL I would have been able to use the RANK() function and JOIN but it isn't an option here.

A: Here's a data.table solution:
Creating data: I've also made cases where "Others" won't happen (the number of entries for that dept is: 1 <= entries <= 2)
set.seed(45)
employeIds <- sample(1000:9999, 20)
depts <- sample(c('Sales', 'Marketing', 'Research'), 20, replace = TRUE)
expenses <- sample(1:1000, 20, replace = TRUE)

df <- data.frame(employeIds, depts, expenses)
df <- df[-c(6,10,12,18,19), ]

A data.table solution:
require(data.table)
dt <- data.table(df, key=c("depts", "expenses"))
k <- 2
dt[, if(.N > k) {
        idx <- (seq_len(.N)-1) %/% max(k, (.N - k)) == 1
        list(EmployeeIds = c(employeIds[idx], "Others"),
           Expenses = c(expenses[idx], sum(expenses[!idx])))
     } else {
        list(EmployeeIds = as.character(employeIds), Expenses = expenses)
     }, by = depts]

#        depts EmployeeIds Expenses
# 1: Marketing        4870      567
# 2: Marketing        3167      591
# 3: Marketing      Others     2285
# 4:  Research        5989      878
# 5:  Research        9667      930
# 6:  Research      Others     1301
# 7:     Sales        6700      129
# 8:     Sales        3857      714

Idea: The first step of creating dt with key = depts, expenses ensures that expenses is sorted in increasing order. Then, depending on the number of entries per dept, we either create an "Others" entry or not.

A: May not be the most elegant, but it's a solution:
func <- function(data) {
 data1 <- aggregate(data$expenses, list(employeIds=data$employeIds), sum)
 # rank without ties.method = "first" will screw things up with identical values
 data1$employeIds[!(rank(data1$x, ties.method="first") %in% 1:2)] <- 'Others'
 data1 <- aggregate(data.frame(expenses=data1$x), list(employeIds=data1$employeIds), sum)
}

do.call(rbind, by(df, df$depts, func))

A: Another data.table approach (which might be closer to the SQL style you know) :
dt <- data.table(employeIds, depts, expenses)
dt[, rank:=rank(-expenses), by=depts][,
    list("Expenses"=sum(expenses)),
    keyby=list(depts, "Employee"=ifelse(rank<=2,employeIds,"Other"))
]
       depts Employee Expenses
1: Marketing     6988      986
2: Marketing     7011      940
3: Marketing    Other     2614
4:  Research     2434      763
5:  Research     9852      731
6:  Research    Other     3397
7:     Sales     3120      581
8:     Sales     6069      868

A: df <- split(df, df$depts)
df <- lapply(df, FUN=function(x){
  x <- x[order(x$expenses, decreasing=TRUE), ]
  x$total.expenses <- sum(x$expenses)
  x$group <- 1:nrow(x)
  x$group <- ifelse(x$group <= 2, x$group, "Other")
  x
})
df <- do.call(rbind, df)


text:
Q: How to start a fragment from an activity I am trying to run a class extending a fragment from a class extending AppCompactActivity, I have tried everything I have saw in Stackover flow and I cant get any to fix my problem. LineDetails is extending the Fragment
    Progress1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Fragment fr = new LineDetails();
            android.app.FragmentManager fm = getFragmentManager();
            android.app.FragmentTransaction fragmentTransaction = fm.beginTransaction();
            fragmentTransaction.replace(R.id.fragment_place, fr);
            fragmentTransaction.commit();
        }
    });

XML
<fragment android:name="com.almac.tracker.LineDetails"
        android:id="@+id/fragment_place"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
PART OF XML FOR ACTIVITY CLASS
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:overScrollMode="never"
   android:scrollbars="none"
   tools:context=".Dashboard">
   <FrameLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/fragment_place">
  </FrameLayout>
</RelativeLayout >

A: If your activity extends AppCompatActivity, then you cannot use getFragmentManager().
In fact you should get rid of classes in the package android.app such as android.app.FragmentManager. You should use the support classes from the package android.support.v4.app such as android.support.v4.app.FragmentManager
Use getSupportFragmentManager() instead of getFragmentManager()
The stack trace reports that you don't have any Layout with id R.id.fragment_place inside your activity. Check the xml of your activity and correct the id of fragment holder.

A: You're replacing instead of adding without a refresh, just do an add. I also simplified one of your useless variables and just went straight to ft instead of having an intermediate fm.
Progress1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {

        Fragment fr = new LineDetails();
        android.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.add(R.id.fragment_place, fr);
        ft.commit();
    }
});

A: Double check your layout xml, It should have a FrameLayout with attribute @+id/fragment_place act as a placeholder for your LineDetails fragment.
If you already place <fragment /> in your layout, you don't need to replace() it programmatically.

A: getSupportFragmentManager() should be used if activity extends AppcompatActivity
EDIT :
As per the Errors ! There is no View named fragment_place in the activity's layout that is @+id/fragment_place must exist in activity_main (If this is the layout attached to activity)


text:
Q: Python: writes only one row into SQLite DB despite loading the full file data into pandas framework I am trying to read the data from "data.txt" and write it to SQLITE database, what I actually get is only first row of the record. I figured out by printing the pandas frame object, it does get all the data from "txt" but failed to iterate throughout, to me the iteration loop looks fine can anybody figure out what  I am doing wrong here which making it fail to replicate all the rows of file.
File data looks like this:
862     1
4828    1
6429    1
10013   1
7729    1
380    1
3808 1
7246    1
1663 1

Secondly, you will notice that spaces between the columns are inconsistent, at some places there are spaces and at some places these are tab separated. I have few thousands of inconsistent rows , this is just a subset of those for reference. Is there any way to handle this?
I tweaked delimiter parameter and also split function but it doesn't workout here. Any suggestion?
Actual results:
Only one row into DB
862     1

Expected results:
862     1
4828    1
6429    1
10013   1
7729    1
380     1
3808    1
7246    1
1663    1

Here is the piece of code I tried:
data = pd.read_csv ("data.txt")
rows = pd.DataFrame(data)

#print (rows)

for row in rows:
    r = row.split()
    object_id = r[0]
    object_type = r[1]
    cur.execute(''' INSERT INTO objects (object_id, object_type)
     VALUES (?, ?) ''', (object_id, object_type))
    conn.commit()

Any valuable input is appreciated! Thanks in advance.

A: This should work as expected:
data = pd.read_csv ("data.txt", delimiter=' ', header=None, names=['object_id', 'object_type'], skipinitialspace=True)

for row in data.itertuples(index=False):
    cur.execute(''' INSERT INTO objects (object_id, object_type)
     VALUES (?, ?) ''', (row.object_id, row.object_type))

conn.commit()

header=None ensures the first row in the file is not considered as a header row.
names lists out the column names
skipinitialspace=True resolves the whitespace issue.
In your code you were iterating through the column names and not the rows.
Since the first row(862, 1) was parsed as header, only that row got inserted into the db.
Also, you don't have to commit at every iteration. A single commit at the end of iteration is suffice.

A: Nevermind this answer, Shiva's is better.
Few things wrong:

*

*If you want to iterate over rows in DataFrame, you have to use:

for row in df.iterrows():
    print(row)

*If the file has inconsistent spaces, then I don't think you can use pandas here. I would do something like this to output a dictionary:

with open('test.txt','r') as f:
    lines = f.readlines()

out = []
for line in lines:
    for item in line.strip('\n').split(' '):
        if item:
            out.append(item)

d = {}
i = 0
while i < len(out)-1:
    key = out[i]
    value = out[i+1]
    d[key] = value
    i+=2

then iterate over dictionary d to upload to sql


text:
Q: ZipArchive not properly compressing files I have a php code which is creating a zip file and download the same. The below code is zipping the files on the php server however when I am trying to unzip the downloaded file at my local system, it is not unzipping the files and shoing the below error :

Cannot open the file as [zip] Archive Is not archive.

Below is my code :
<?php
$data = json_decode(stripslashes($_POST['data']));

$prefix = $filelist = '';
foreach($data as $d)
{
    $filelist .= $prefix . '"' . $d . '"';
    $prefix = ', ';
}

$files = $filelist;
$zipname = 'file45.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($files as $file) {
    $zip->addFile($file);
}
$zip->close();

header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);

?>

Any inputs would be highly useful


text:
Q: Azure Portal's App Registration shows "Network error" when updating an app I'm not able to update my Application Registration in Azure Portal. I consistently get "Network error: There is an issue establishing a connection to the service" :
Error screenshot
I am able to view my App Registrations, and create new App registrations. Only when I save them, the update fails.
The application registration experience:
https://portal.azure.com/#blade/Microsoft_AAD_RegisteredApps/ApplicationsListBlade
I am the owner of these apps or the tenant administrator.
I noticed that all network requests to graph.windows.net with http verb PATCH fails. POST, GET, etc work. The same requests work when I'm not on my corporate network. What action can I take to determine the root cause and fix this?

A: Most likely the case is your web filter does not support the HTTP PATCH verb.  On some versions of Cisco WSA the verb is not supported at all.  On version 11+, the verb must be enabled explicitly with the httppatchconfig config
You can also set implicit TLS inspection mode for graph.windows.net - this will allow the HTTPS request to pass through the WSA unmodified


text:
Q: Why doesn't activity_main.xml show my components in Android Studio, and why does 28 API not work? I've recently downloaded Android Studio on a new Surface Laptop and have had a couple problems. I've had a few problems that I do not know how to fix. Right off the bat after beginning an Empty Activity, it does not display the "hello world" TextView that automatically comes with the activity. The only thing that displays is a white screen. This is the error that is displayed:
The following classes could not be instantiated:
   - android.support.v7.widget.ActionBarContainer (Open Class, Show Exception, Clear Cache)
   - android.support.v7.widget.ActionBarContextView (Open Class, Show Exception, Clear Cache)
   - android.support.v7.app.WindowDecorActionBar (Open Class, Show Exception, Clear Cache)

( I have tried to manually build the project and refresh, as the hint suggests )
Also, when I try running the project on a Pixel 2, API 28 virtual device, it gets stuck at turning on the device (where you can only see the colorful "G" and the white screen behind it).
In the event log, the following is displayed:
Emulator:
ERROR: Missing initial data partition file: C:\Users\aboli\.android\avd\Pixel_2_API_28.avd/userdata.img

I've tried looking at similar problems, but haven't found anything that works. I was hoping someone may have any suggestions or any similar experiences. Thanks in advance

A:
"Why doesn't activity_main.xml show my components in Android Studio"

In [project]>app>src>main>res>values>styles.xml add Base. like this:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

gets
<style name="AppTheme" parent="Base.Theme.AppCompat.Light.DarkActionBar">

and your components should show.
I have to do this for every new project so I have looked for a general solution, a template somewhere?, but until now to no avail. My Android Studio is 3.1.3


text:
Q: @Value "Could not resolve placeholder" in Spring Boot Test I want to take a Junit test for Spring-boot as below:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {ApplicationTest.class})
public class TestOnSpring {
    @Value("${app.name}")
    private String appName;

    @Test
    public void testValue(){
        System.out.println(appName);
    }
}

and ApplicationTest.java like this
@ComponentScan("org.nerve.jiepu")
@EnableAutoConfiguration()
public class ApplicationTest {

    public static void main(String[] args) {
        SpringApplication.run(ApplicationTest.class, args);
    }
}

and my POM like this:
<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.0.BUILD-SNAPSHOT</version>
    </parent>

When I run the test, I got below error information
Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'app.name' in string value "${app.name}"
    at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:174)
    at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:126)
    at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:204)
    at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:178)
    at org.springframework.context.support.PropertySourcesPlaceholderConfigurer$2.resolveStringValue(PropertySourcesPlaceholderConfigurer.java:172)
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveEmbeddedValue(AbstractBeanFactory.java:807)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1027)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:543)
    ... 31 more

But When I run this application as normal Java Application
@SpringBootApplication
public class Application {

    public static void main(String[] args){
        SpringApplication.run(Application.class, args);
    }
}

It work well!
What's wrong with it ? How should I take the junit test with Spring-boot?
Thanks a lot!

A: You need to add

@PropertySource("classpath:application.properties")

to your class, so it will pick your normal configurations.
If you need different configurations for test you can add

@TestPropertySource(locations="classpath:test.properties")

If not just copy paste your config file to test/resources folder, then boot will pick from there.
See this.

A: You have annotated your test class with @ContextConfiguration(classes = {ApplicationTest.class}). Wherein ApplicationTest.class does the component scan on a mentioned package. When you run your test it tries to find the configuration from the resources folder in 'main' instead of 'test'. If you annotate your class with @SpringBootTest(classes = {ClassToBeTested.class}) or just @SpringBootTest in this particular case, I think (not 100% sure) it will create a limited context and pick up the properties from test/resources.
If your properties are test specific, you can name your properties/yml file as application-test.properties or application-test.yml. And use @ActiveProfiles("test") in your test class so that it will always read test specific properties file.
I usually use this solution which works for me.

A: You can use the @SpringBootTest that will do create the PropertySourcesPlaceholderConfigurer automatically.
This is described in the Testing chapter of the Spring Boot documentation.
http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html#boot-features-configfileapplicationcontextinitializer-test-utility

A: For me the issue was related to the profile set for the application properties.
application.yml:
spring:
  config:
    activate:
      on-profile: local
mongodb:
  uri: mongodb+srv:/

Class with reference to value:
@Value("${mongodb.uri}")
private String uri;

Resolution in test class method:
@SpringBootTest
@ActiveProfiles("local")
class myTestClass {


text:
Q: Can I change a user role from command-line in Windows? I want to change a user from normal user to administrator in command-line. Is this possible? What command should I use?

A: Net group is the command your seeking.
add user to local administrator group:
net group administrators /add adminguy


text:
Q: Flash and ActionScript 3: change frame based on cursor's x-axis position If you navigate to the gallery page on this flash site you can see Tintin does as I describe. I have googled a few times but haven't been able to turn up anything. Any help is greatly appreciated, thanks!
EDIT: Although, just changing a symbol's position instead of the current frame would work too. Either way, I just want to know how to do what the link shows.

A: Use a linear function to calculate all points given the beginning and the end proportions.
In this example, the movieclip myMc will change its x position based on the cursor given this two pairs: On mouseX = 0 it will be at 100px, and on mouseY = stage.stageWidth it will be at 300px. Remember this is a linear function, so the proportion continues beyond the given limits!
function onEnterFrame(e:Event){
    myMc.x = solveLinearFunction(0, 100, this.stage.stageWidth, 300, this.stage.mouseX);
}
function solveLinearFunction(x1:Number, y1:Number, x2:Number, y2:Number, xx:Number):Number{
    //linear f(x) = mx + b;
    var mypos:Number = (y1 - y2) / (x1 - x2);
    var bypos:Number = y1 - (mypos * x1);
    return mypos * xx + bypos;
}
this.addEventListener(Event.ENTER_FRAME, onEnterFrame);

Here is some more info on Linear functions, they are quite handy to make scrollbars and paralax scrolling effects: http://earthmath.kennesaw.edu/main_site/review_topics/linear_functions.htm


text:
Q: Store update, insert, or delete statement affected an unexpected number of rows (0)" Error in delete function Each task has a reference to the goal it is assigned to.  When I try and delete the tasks, and then the goal I get the error
"Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries." on the line _goalRepository.Delete(goalId);
What am I doing wrong?
 [HttpPost]
    public void DeleteGoal(int goalId, bool deleteTasks)
    {
        try
        {
            if (deleteTasks)
            {
                Goal goalWithTasks = _goalRepository.GetWithTasks(goalId);

                foreach (var task in goalWithTasks.Tasks)
                {
                    _taskRepository.Delete(task.Id);
                }
                goalWithTasks.Tasks = null;
                _goalRepository.Update(goalWithTasks);

            }

            _goalRepository.Delete(goalId);

        }
        catch (Exception ex)
        {
            Exception deleteException = ex;
        }
    }

A: Most likely the problem is because you're attempting to hold onto and reuse a context across page views.  You should create a new context, do your work, and dispose of the context atomically.  It's called the Unit Of Work pattern.
The main reason for this is that the context maintains some state information about the database rows it has seen, if that state information becomes stale or out of date then you get exceptions like this.
There are a lot of other reasons to use the Unit of Work pattern, I would suggest you do a web search and do a little reading as an educational exercise.

A: This may have nothing to do with data access though. You are removing items from a list as you are iterating it, which would cause problems if you were using a normal List. Without knowing much about the internals of EF, my guess is that your delete calls to the repository are changing the same list that you are iterating.
Try iterating the list in one pass and record the Task ids you want to delete in separate list. Then when you have finished iterating, call delete on the Task list. For example:
var tasksToDelete = new List<int>();
foreach (var task in goalWithTasks.Tasks)
{
    tasksToDelete.Add(task.Id);
}

foreach (var id in tasksToDelete)
{
    _taskRepository.Delete(id);
}

This may not be the cause of your problem but it is good practice to never change the collection you are iterating.

A: I ran across this issue at work (I am an Intern), I was getting this error when trying to delete a piece of Equipment that was referenced in other data-tables.
I was deleting all references before attempting to delete the Equipment BUT the reference deletion was happening in another Model which had its own database context, the reference deletion would be saved within the Model's context.
But the Equipment Model's context would not know about the changes that just happened in another Model's context which is why when I was trying to delete the Equipment and then save the changes (eg: db.SaveChanges()) the error would happen (the Equipment context still thought there was references to that equipment in other tables).
My solution for this was to re-allocate the context before attempting to delete the Equipment:
db = new DatabaseContext();
Now the newly allocated context has the latest snapshot of the database and is aware of all changes made. Deletion happens without issues.
Hope my experience helps.


text:
Q: my input is a string consisting of numbers seperated by space like 10 20 200 120 50 i need to print largest number in the array Can any one help me please. I need to perform any operation on such type of input format:
The input is a string consisting of numbers separated by space like
  10 20 200 120 50
 I need to print largest number in the array.
I am unable perform operations since in strings s[3] means it takes fourth value
that is 2 but how to separate 10 and 20 and then compare or perform some arithmetic operation.

A: Here, What you can do is , you can separate the string using ' ' (Space),
Store it somewhere, convert it to integer using the atoi() function and then compare.


text:
Q: is Boost.Geometry mature enough? I've been recently hired by a GIS company to rewrite their old geomatics libraries. So I'm currently looking for a good computational geometry library. I've seen CGAL, which is amazing, but my boss wants something free.
So I'm now checking Boost.Geometry. This library seems great, but it also seems that it is changing pretty fast. A lot of things are not implemented yet, and a lot of issues are discussed on the mailing list.
Hence my question : is Boost.Geometry mature enough so I can build something on it ? Or is the design still going to evolve ?
Thanks

A: Depending on your needs, you could look at GEOS, which is used by PostGIS for its geometry operations, among others, and is more mature than boost::geometry. However, it is hard to extend, which you will have to do yourself if you want support for more than Simple Features.
Where boost::geometry shines, in my opinion, is its ability to adapt to existing (legacy) libraries, which means that you should be able to keep some of your employer's data structures (or any other existing geometric library), and build upon them with boost::geometry.
Boost::geometry is gaining maturity and extended features pretty fast, but I don't think the design has changed much since last year (when it was accepted into boost). I would ask on the mailing list -- the authors are very active and helpful.

A: It depends on your needs.
Boost is one of the most efficient, performant and mature c++ libraries, but when it comes to geometries geos is the best, i tried both of them in a 3D data optimization project.
Boost-Geometry Pros :
-Performant
-Well designed API
Geos Pros :
-Accurate
-Mature


text:
Q: Chaining Constructors I am trying to better understand chaining of constructors in C# and I have run into the following issue.
class Item
{
    private string _name;
    private string _category;
    private int _sku;
    private double _price;

    // default values
    public Item()
    {
        _name = "";
        _category = "Sale Item";
        _sku = 123;
        _price = 1.99;
    }

    public Item(string name, double price) : this()
    {
        this._name = name;
        this._price = price;
    }

    public Item(string name, string category, int sku, double price)
    {
        this._name = name;
        this._category = category;
        this._sku = sku;
        this._price = price;
    }

    public string Name
    {
        get { return this._name; }
    }

    public string Category
    {
        get { return this._category; }
    }

    public int SKU
    {
        get { return this._sku; }

    public double Price
    {
        get { return this._price; }
    }
}

My idea was to use the parameterless constructor to set default values and use the parametrized constructors to only change those values which need to be updated.
Unfortunately this does not work. The code does not compile. The error message is 1729: there is no constructor that takes 2 arguments. I realize that this is not how constructors are normally chained but I do not understand why this fails to compile as the parameterless constructor Item() is called first before the second constructor Item(string name, double price) is called.
Any insight and sugegstions would be greatly appreciated.

A: Nothing wrong with the chaining constructors per se, the error you get is related to other code instantiating it with 2 specific paramaters which their is no specific constructor provided.
You need to add another 2 parameter constructor which matches that signature to fix that error.


text:
Q: Error with rendering nested directive using ng-repeat This question was asked by myself here:
Nesting angularjs directives recursively
and the inital problem was resolved, however, there appears to be a strange bug.
The code is here:
https://plnkr.co/edit/PhDvLZyWvyFThg57qZDV?p=preview
The double ng-repeat seems to be broken when calling a directive inside it. All of the data is being rendered on one element. I am guessing I have either made a mistake, or this is to do with the order angular pushes items into the digest cycle. The structure should be:
1
    1.1
        1.1.1
        1.1.2
        1.1.3
    1.2
        1.2.1
        1.2.2
        1.2.3
    1.3
        1.3.1
        1.3.2
        1.3.3
2
    2.1
        2.1.1
        2.1.2
        2.1.3
    2.2
        2.2.1
        2.2.2
        2.2.3
    2.3
        2.3.1
        2.3.2
        2.3.3

but is coming out as:
1
2
    2.1
    2.2
    2.3
        2.3.1
        2.3.2
        2.3.3
        2.2.1
        2.2.2
        2.2.3
        2.1.1
        2.1.2
        2.1.3
        1.3.1
        1.3.2
        1.3.3
        1.2.1
        1.2.2
        1.2.3
        1.1.1
        1.1.2
        1.1.3
    1.1
    1.2
    1.3

index.html
<!DOCTYPE html>

    <link rel="stylesheet" href="style.css" />

        <button class="btn btn-default dropdown-toggle" type="button">

        </button>

menu-entry.html

    <button ng-if="menu.SubMenus.length>0" type="button" ng-bind="menu.Text">

    </button>

0" class="dropdown-menu" role="menu">

script.js
var app = angular.module('app', []);

app.controller('MainCtrl', function($scope) {
  $scope.menus = [
    { Text: '1', SubMenus: [
      { Text: '1.1', SubMenus: [{Text:'1.1.1',SubMenus:[]},{Text:'1.1.2',SubMenus:[]},{Text:'1.1.3',SubMenus:[]}]},
      { Text: '1.2', SubMenus: [{Text:'1.2.1',SubMenus:[]},{Text:'1.2.2',SubMenus:[]},{Text:'1.2.3',SubMenus:[]}]},
      { Text: '1.3', SubMenus: [{Text:'1.3.1',SubMenus:[]},{Text:'1.3.2',SubMenus:[]},{Text:'1.3.3',SubMenus:[]}]}
      ]},
    { Text: '2', SubMenus: [
    { Text: '2.1', SubMenus: [{Text:'2.1.1',SubMenus:[]},{Text:'2.1.2',SubMenus:[]},{Text:'2.1.3',SubMenus:[]}]},
    { Text: '2.2', SubMenus: [{Text:'2.2.1',SubMenus:[]},{Text:'2.2.2',SubMenus:[]},{Text:'2.2.3',SubMenus:[]}]},
    { Text: '2.3', SubMenus: [{Text:'2.3.1',SubMenus:[]},{Text:'2.3.2',SubMenus:[]},{Text:'2.3.3',SubMenus:[]}]}
    ]},
    ];
});

app.directive('menuEntry', function() {
        var cFn = ['$scope', function ($scope) {

        }];

        var lFn = function (scope, element, attr, ctrl, transclude) {
        };

        return {
            restrict: 'A',
            replace: true,
            templateUrl: 'menu-entry.html',
            controller: cFn,
            link: lFn,
            scope: {
                menus: '='
            }
        };
});

A: Move the ul that is just outside of the menu-entry directive and put it inside of the directive template.  Template should look like this:

    <button ng-if="menu.SubMenus.length>0" type="button" ng-bind="menu.Text">

    </button>

0" class="dropdown-menu" role="menu">


text:
Q: What does this required empty parameter mean, when defining something? \newenvironment{nameOfEnvironment}[1][]%

Can someone explain the empty bracket?

A: You should consider reading Is there a comprehensive and complete LaTeX reference? where you'll find information on all sorts of LaTeX2e sources.
Technically, \newenvironment{<cmd>}[<num>][<default>]{<beg-def>}{<end-def>} uses \newcommand as base, so understanding the latter will help you understand the former.
Specific to your case, LaTeX2e for authors user guide mentions the following about \newcommand:

...the command:
\newcommand{<cmd>}[<num>][<default>]{<definition>}

defines <cmd> to be a command with <num> arguments, the first of which is
  optional and has default value <default>.
Note that there can only be one optional argument but, as before, there can be
  up to nine arguments in total.

So,
\newenvironment{nameOfEnvironment}[1][]%
  {<beg-def>}
  {<end-def>}

defines an environment nameOfEnvironment that takes a single argument (as a result of [1]). This single argument is an optional argument (as a result of the second []) that, if not specified, has an empty default value.
You would be able to use it as
\begin{nameOfEnvironment}
  <stuff>
\end{nameOfEnvironment}

or
\begin{nameOfEnvironment}[something]
  <stuff>
\end{nameOfEnvironment}

In the former case, the optional argument #1 is empty, while the second has an optional argument value of something.

The following explanation is taken from LaTeX: Structured documents for TeX (unofficial LaTeX reference manual):

13.5 \newenvironment & \renewenvironment
Synopses:
\newenvironment[*]{env}[nargs][default]{begdef}{enddef}
\renewenvironment[*]{env}[nargs]{begdef}{enddef}

These commands define or redefine an environment env, that is, \begin{env} ... \end{env}.

*

**
  The *-form of these commands requires that the arguments (not the contents
  of the environment) not contain multiple paragraphs of text.

*env
  The name of the environment. For \newenvironment, env must not be
  an existing environment, and the command \env must be undefined. For
  \renewenvironment, env must be the name of an existing environment.

*nargs
  An integer from 1 to 9 denoting the number of arguments of the newly-defined
  environment. The default is no arguments.

*default
  If this is specified, the first argument is optional, and default gives the default value for that argument.

*begdef
  The text expanded at every occurrence of \begin{env}; a construct of the form #n in begdef is replaced by the text of the nth argument.

*enddef
  The text expanded at every occurrence of \end{env}. It may not contain any
  argument parameters.


text:
Q: my program is 'crashing' when it encounters "%.2f" after the text "Gross Pay : " in BlueJ This program is for calculating an employees net pay after deductions, but i am running into issues in displaying gross pay in the summary of the employees salary.
I have changed around the types of dialog boxes etc. , is there also a solution to allow me to use a non input dialog box in the summary of the payslip?
import javax.swing.JOptionPane; // Dialog boxes are created to allow user inputs
public class Payslipgenerator
{

  public static void main(String[] args)
  {
      String employeeName,grossPay,payslipFinal; //Declaring String variables
      double PRSI=.025, PAYE=.2, USC=.04, Pension=.05, healthInsurance= 75; //Declaring consants used in the Application
      double prsiCalc, payeCalc, uscCalc,pensionCalc, netValue; //Double variables that will store calculations

      employeeName = JOptionPane.showInputDialog(null, "Enter Employee name : ", "User Info"); //Asks Employee to input their name, which is then stored
      grossPay = JOptionPane.showInputDialog(null, "Enter Gross Pay (€) : ", "User Info"); //Prompts employee to enter Gross Pay for deduction calculation
      double employeeGrossPay = Double.parseDouble(grossPay); //Stores input in double Variable

      prsiCalc      = employeeGrossPay * PRSI;
      payeCalc      = employeeGrossPay * PAYE;
      uscCalc       = employeeGrossPay * USC ;
      pensionCalc   = employeeGrossPay * Pension ;
      netValue      = employeeGrossPay - (prsiCalc + payeCalc + uscCalc + pensionCalc + healthInsurance);
      payslipFinal  = String.format("Gross Pay :€%.2f \nPRSI : €%.2f \nUSC : €%.2f \nPension Plan : €%.2f \nHealth Insurance : €75.00 \nNet Earnings: €%.2f"
      + employeeGrossPay, prsiCalc, uscCalc, pensionCalc, netValue);

      JOptionPane.showInputDialog(null, "Employee Name : " + employeeName + "\n\n" + payslipFinal, "Payslip Breakdown");

  }
}

A: Change
payslipFinal  = String.format("Gross Pay :€%.2f \nPRSI : €%.2f \nUSC : €%.2f \nPension Plan : €%.2f \nHealth Insurance : €75.00 \nNet Earnings: €%.2f"
      + employeeGrossPay, prsiCalc, uscCalc, pensionCalc, netValue);

to
payslipFinal  = String.format("Gross Pay :€%.2f \nPRSI : €%.2f \nUSC : €%.2f \nPension Plan : €%.2f \nHealth Insurance : €75.00 \nNet Earnings: €%.2f"
      , employeeGrossPay, prsiCalc, uscCalc, pensionCalc, netValue);

Test:
public static void main(String[] args) {
    String payslipFinal  = String.format("Gross Pay :€%.2f \nPRSI : €%.2f \nUSC : €%.2f \nPension Plan : €%.2f \nHealth Insurance : €75.00 \nNet Earnings: €%.2f"
            , 1f, 2f, 3f, 4f, 5f);
    System.out.println(payslipFinal);
}

Output:
Gross Pay :€1,00
PRSI : €2,00
USC : €3,00
Pension Plan : €4,00
Health Insurance : €75.00
Net Earnings: €5,00


text:
Q: Print index from array I am working on a text-based game, and I want to print the results in the end.
However, at the moment it only prints the latest input data and not the 5 loops in the array.
This is my array
int[] turnarr = new int[5];

turnarr[x] = turn;

for (int i = 0; i < turnarr.Length; i++)
     Console.WriteLine(turnarr[i] + "\t" );

A: It's hard to be certain, as I only see part of the code, but I suspect that you are recreating the turnarr array in each turn, which would make every entry except the last one zero.

A: If the value of x never changes then you're only writing to a single item in the array, and thus overwriting it every time with the latest value of turn.

A: If turn is your last turn value, and x is 4, you will see four zeroes on their own lines and then the value of turn because you are only assigning to the xth index of turnarr

A: I took a look at your pastebin and tracked the issue down I believe:
The following line:
Console.WriteLine(turnarr[i] + "\t" + windarr[i] + " ms \t" + apmeterarr[x] + "m\t\t" + lenghtarr[x] + " meter\t\t");
you are using i for 2 spots, and x for the other 2 for your index variable...
Change
apmeterarr[x] and
lenghtarr[x]
To
apmeterarr[i] and
lenghtarr[i]


text:
Q: is it possible to embed a fractal inside another fractal I have been looking at one-dimensional (1D) cellular automata (CAs) which generate two-dimensional (2D) fractal patterns. Among the 256 1D elementary CAs, I tried to list down the fractal generating ones by looking at pictures here https://www.wolframscience.com/nks/p54--more-cellular-automata/
I was wondering if it is possible to list down both elementary and non-elementary CAs which generate fractals? The elementary CAs that generate fractals can be listed down by checking the 256 patterns. But it also seems there is a formal result i.e. the elementary CAs which can be represented by a linear recursive relation for the CA states are the ones that generate fractals. I wonder if this is generalized to non-elementary CAs.
My main question is related to this and is simple to state: is there a fractal which can be embedded inside another fractal? Note that these two fractals do not have to be generated by elementary CAs. Any reference that goes into this will be helpful. By embedding, I mean that all the 1 automata states of one fractal coincide with a subset of the 1 automata states of the other fractal.


text:
Q: Why my max health is capped at 50% of the bar in Dark Souls 2? I have just started this game and noticed that my character looks like a ghoul and the HP bar is capped at 50%. How can I prevent this and remedy to it ?

A: When you first start a new game, you start out "hollowed" with your health capped at 50%. To regain your human form and 100% health cap, simply walk past the first intro area and you will regain your humanity after the character creation.
After that, every time you die (or get cursed), you will gradually lose some of your maximum health down to a minimum of 50%. You can regain it by using1 a Human Effigy, a consumable item found in limited supply around the world, or by using a White Sign Soapstone and helping another player successfully defeat a boss.
There is another way to regain your humanity which does not depend on limited items or online play, but it doesn't become available until near the end of the game.

 After the Demon of Song boss fight in the Shrine of Amana, there is a door which only opens when you are in hollow form. Inside this door, past a handful of enemies, there is a fire. If you pray at this fire with no Human Effigies in your inventory, your humanity will be restored.

 There is also a convenient bonfire just before this door so that you can easily travel here when you're out of effigies and need to regain your humanity.

There is also an item which reduces the health penalties from dying.

 There is a ring called the Ring of Binding which can be found just outside the Cathedral of Blue near Heide's Tower of Flame, which reduces the health penalty and increases the minimum health cap from 50% to about 75%.

1 You need to use the Human Effigy from the inventory screen or by equipping it in your item belt. Do not burn it. If you burn it, it instead reduces the likelihood of invasions and blocks you from summoning phantoms.

A: According to this article dying removes health from you permanently. That means if you die too often you only have Half HP, losing 10% for each consecutive death. You can return your health to its normal value by using a Human Effigy from your inventory. Also, Curse can inflict the same status, to the same degree with each infliction, and is cured in the same way.


text:
Q: A woman with a unique trait, a special spark In Russian, when one wants to describe a woman that has some special trait in her that makes her stand out, some tiny spark in her character, a pinch of salt making her flavor special, so to speak, he sometimes tends to use the phrase "A woman with a raisin (in her)." That is, Женщина с изюминкой. Like a bun that is made unique by the addition of a single raisin.
I wonder what counterpart idioms in English exist. "A woman with a special charm"? "A charm of her own"? A woman with a certain piquancy? Maybe there's more.
P.S. It's a question asked at one forum by a translator.

A: On the page titled "List of French words and phrases used by English speakers", Wikipedia has:

je ne sais quoi
lit. "I-don't-know-what": an indescribable or indefinable 'something' that distinguishes the object in question from others that are superficially similar. (Source)

This term is often applied to people who have qualities that set them apart, especially when these qualities are intangible and difficult to describe.
It is widely used in English, but you could also say someone has "a certain something" if you are particularly interested in using words that have been more thoroughly incorporated into the language.
As evidence of its prevalence, it is the subject of a joke made by Mike Myers in the second Austin Powers movie:

Dr. Evil: Mojo; the libido; the life force; the essence; the right stuff. What the French call a certain... I don't know what.

There is also the related concept of an "it" girl, about which Rudyard Kipling says:

It isn't beauty, so to speak, nor good talk necessarily. It's just "It".

I have only ever heard it applied to women who attract men, but Elinor Glyn says:

With "It" you win all men if you are a woman and all women if you are a man. "It" can be a quality of the mind as well as a physical attraction.

So you'd be reasonably justified in simply saying (or singing) "she's got It."

A: She's quite striking
Perhaps she doesn't conform to today's standard of beauty, but there's something about her that makes you stop and admire her.
She has something special which makes her stand out from the crowd.


text:
Q: jar download with dependencies from maven I need a command to download jar with all dependencies from maven., I saw this tool online
https://jar-download.com/online-maven-download-tool.php
but I need to do it from cli. Any methods?

A: You can use the Maven dependency plugin, especially the goals
https://maven.apache.org/plugins/maven-dependency-plugin/copy-dependencies-mojo.html
and
https://maven.apache.org/plugins/maven-dependency-plugin/get-mojo.html
which download the dependencies and the jar, respectively.


text:
Q: Ctrl-P on a page with alternating  colors I'm currently generating a form to print out using PHP, and I have my table row colors alternating back and forth between grey and white.
I need to print this page, but when I hit CTRL-P, the table row colors don't appear on the printed page. Is there any way to make it so it does?

A: Long story short, the default is to never print background images or colors (so the user doesn't end up wasting their ink by unnecessarily printing a full color background image on a site).
You can add CSS properties to try to override the default settings such as -webkit-print-color-adjust:exact; or background: #fefefe !important in certain browsers, but the default will always be to not print backgrounds.

A: I actually ended  up figuring it out. Adding !important in the CSS worked for me.
.table-striped > tbody > tr:nth-child(odd) > th {
    background-color: #eee !important;
}