text:
Q: What's causing a Concurrency Violation when using a MySQL linked Dataset via TableAdapters? The more I read on this, the more confused I get, so hope someone can help. I have a complex database setup, which sometimes produces the error on update:
"Concurrency violation: the UpdateCommand affected 0 of the expected 1 records"
I say sometimes, because I cannot recreate conditions to trigger it consistently. I have a remote mySQL database connected to my app through the DataSource Wizard, which produces the dataset, tables and linked DataTableAdapters.
My reading suggests that this error is meant to occur when there is more than one open connection to the database trying to update the same record? This shouldn't happen in my instance, as the only updates are sequential from my app.
I am wondering whether it has something to do with running the update from a background worker? I have my table updates in one, for example, thusly:
    Gi_gamethemeTableAdapter.Update(dbDS.gi_gametheme)
    Gi_gameplaystyleTableAdapter.Update(dbDS.gi_gameplaystyle)
    Gi_gameTableAdapter.Update(dbDS.gi_game)

These run serially in the backgroundworker, however, so unsure about this. The main thread also waits for it to finish, and there are no other db operations going on before or after this is started.
I did read about going into the dataset designer view, choosing "configure" in the datatableadapter > advanced options and setting "Use optimistic concurrency" to false. This might have worked (hard to say because of the seemingly random nature of the error), however, there are drawbacks to this that I want to avoid:

*

*I have around 60 tables. I don't want to do this for each one.

*I sometimes have to re-import the mysql schema into the dataset designer, or delete a table and re-add it. This would obviously lose this setting and I would have to remember to do it on all of them again, potentially. I also can't find a way to do this automatically in code.

I'm afraid I'm not at code level in terms of the database updates etc, relying on the Visual Studio wizards. It's a bit late to change the stack as well (e.g. can't change to Entity Framework etc).
SO my question is:

*

*what is/how can I find what's causing the error?

*What can I do about it?

thanks

A: When you have tableadapters that download data into datatables, they can be configured for optimistic concurrency
This means that for a table like:
Person
ID  Name
1   John

They might generate an UPDATE query like:
UPDATE Person SET Name = @newName WHERE ID = @oldID AND Name = @oldName

(In reality they are more complex than this but this will suffice)
Datatables track original values and current values; you download 1/"John", and then change the name to "Jane", you(or the tableadapter) can ask the DT what the original value was and it will say "John"
The datatable can also feed this value into the UPDATE query and that's how we detect "if something else changed the row in the time we had it" i.e. a concurrency violation
Row was "John" when we downloaded it, we edited to "Jane", and went to save.. But someone else had been in and changed it to "Joe". Our update will fail because Name is no longer "John" that it was (and we still think it is) when we downloaded it. By dint of the tableadapter having an update query that said AND Name = @oldName, and setting @oldName parameter to the original value somedatarow["Name", DataRowVersion.Original].Value (i.e. "John") we cause the update to fail. This is a useful thing; mostly they will succeed so we can opportunistically hope our users can update our db without needing to get into locking rows while they have them open in some UI
Resolving the cases where it doesn't work is usually a case of coding up some strategy:

*

*My changes win - don't use an optimistic query that features old values, just UPDATE and erase their changes

*Their changes win - cancel your attempts

*Re-download the latest DB state and choose what to do - auto merge it somehow (maybe the other person changed fields you didn't), or show the user so they can pick and choose what to keep etc (if both people edited the same fields)

Now you're probably sat there saying "but noone else changes my DB" - we can still get this though, if the database has changed some values upon one save and you don't have the latest ones in your dataset..
There's another option in the tableadapter wizardd - "refresh the dataset" - it's supposed to run a select after a modification to import any latest database calculated values (like auto inc primary keys or triggers/defaults/etc). Some query like INSERT INTO Person(Name) VALUES(@name) is supposed to silently have a SELECT * FROM PERSON WHERE ID = last_inserted_id() tagged on the end of it to retrieve the latest values
Except "refresh the dataset" doesn't work :/

So, while I can't tell you exactly why youre getting your CV exception, I hope that explaining why they occur and pointing out that there are sometimes bugs that cause them (insert new record, calculated ID is not retreieved, edit this recent record, update fails because data wasn't fresh) will hopefully arm you with what you need to find the problem: when you get one, keep the app stopped on the breakpoint and inspect the datarow: take a look at the query being run and what original/current values are being put as parameters - inspect the original and current values held by the row using the overload of the Item indexer that allows you to state the version you want and look in the DB
Somewhere in all of that there will be the mismatch that explains why 0 records were updated - the db has "Joe" as the name or 174354325 as the ID, your datarow has "John" as the original name or -1 as the ID (it never refreshed), and the WHERE clause is finding 0 records as a result

A: Some of your tables will contain a field that is marked as [ConcurrencyCheck] or [TimeStamp] concurrency token.
When you update a record, the SQL generated will include a WHERE [ConcurrencyField]='Whatever the value was when the record was retrieved'.
If that record was updated by another thread or process or something other than the current thread, then your UPDATE will return 0 records updated, rather than the 1 (or more) that was expected.
What can you do about it?  Firstly, put a try/catch(DbConcurrencyException) around your code.  Then you can re-read the offending record and try and update it again.


text:
Q: Lost permissions on database on replication slave I set up master slave replication and everything was fine. I had a user x that was able to access all my tables. The user x also existed on the slave and had access to all tables.
I created a new database in the master as root and grant permissions to user x on the master.
Once I did this, user x lost access to many of the databases on the slave.
I'm not able to grant user x permissions too. It looks like it gets overridden or permissions or not being granted.
Any ideas on why?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I install rpy2 when clang doesn't support OpenMP (Mac OSX)? I am trying to use pip to install rpy2 on OSX 10.12.5.  I get this error:
clang: error: unsupported option '-fopenmp'
clang: error: unsupported option '-fopenmp'
error: command '/usr/bin/clang' failed with exit status 1

From what I understand, this is because my version of clang does not support OpenMP.  Using homebrew, I installed LLVM 8.1.0 (clang 802.0.42), but now I need to update clang to support OpenMP.  Can anyone give me detailed instructions of how to go about this?  I am not understanding the other sources I am reading online.

A: I just got rpy2-2.9.0 to install via pip on Mac OSX 10.13, after getting the same error you reported, by downgrading to R 3.3.3, downloaded from https://cran.r-project.org/bin/macosx/. I just re-installed R 3.3.3 then re-ran 'pip install rpy2' and it installed fine.


text:
Q: Get manager of current user in workflow how can I get the current user's manager's phone information.
I select the current user id like this:
public Guid workflowId = default(System.Guid);
public SPWorkflowActivationProperties workflowProperties = new SPWorkflowActivationProperties();

    private void onWorkflowActivated1_Invoked(object sender, ExternalDataEventArgs e)
    {

        SPWeb web = workflowProperties.Web;

        SPUser spuser = this.workflowProperties.OriginatorUser;

        string strusername = spuser.Name;
        string strid = spuser.LoginName;

        SPListItem lisitem= workflowProperties.Item;

        if (lisitem["Full Name"] == null)
        {
            listitem["Full Name"] = strid;
            listitem.Update();
        }

but i couldnt find a way to reach manager 's phone information.


text:
Q: Experience with Hybrid Apps I want to learn from other's experience regarding Hybrid Apps. I want to make hybrid and I know Ionic, React and Onsen UI are some of the platforms on which I could create that.
Currently, I am working as an Android Developer and I want to go in hybrid ship too. However there are some of my questions, if someone could help me on these, then please do.

*

*Is there any performance issue with hybrid apps.

*How much time it take to create a Hybrid app comparative to native

*What are the features of the native apps which can not be used in Hybrid apps.

A: Ok I'll try to answer your question the the best of my knowledge:

*

*Yes there are of course performance differences, native languages like Java (Android) or ObjC/Swift (iOS) are compiled languages, Javascript on the other side needs to be parsed and then interpreted by the js-engine of a webview (the browser embedded in a native project). But modern bundling tools like webpack do a pretty decent job optimizing/minifing/splitting your javascript code into small chunks so in most cases performance should not be an issue. Angular for example also comes with its own "compiler" ngc wich precompiles your html templates. React uses virtual-dom, which is also really performant. If you want to do some really heavy things (e.g. optical character recognition) you can always do this on the native side of you hybrid app.

*Coming to the time effort: As you mentioned you have no experience in writing any code on the web platform but still the learning curve for javascript (or as you are coming from the java world you will love typescript) is usually described as steep. Also most of the currently popular hybrid frameworks come with a big palette of prebuilt components which are ready to use - so spinning up a first app should not be too hard. What you should do definitely is reading about the basic concepts of javascript (like how asynchronity is handled in javascript, callbacks, closures, variable scoping, ...), otherwise you will have a hard time solving problems in your code. There are of course things that will take more time: For example if you have a use-case where you need native functionality and there is no existing plugin or library to do so - more on that in the next point.

*If you need native functionality cou can always create a plugin for that (speaking of cordova because thats the platform I know best). Up to now I personally was always able to solve everything that was not possible in javascript by creating a native-plugin for it. This can be quite time-consuming sometimes but there is a huge amount of already existing plugins which will solve most of your problems.

I hope some of my opinions will be of help for you.


text:
Q: ubuntu 20.04.1 LTS stop showing wifi adapter? So one day I opened my laptop and it stopped showing wifi and the error message was wifi adapter not found. I try to fix that using pre existing solutions like mentions in this form didn't work for me. I tried to reinstall the wifi driver from the additional driver menu. It showing me this specific error:
Error while applying changes

pk-client-error-quark: Error while installing package: installed bonwl-kerneksource package post-installation script subprocess returned error exit status 10 (03)

Since I had a pretty specific issue, I created a new question.
screenshot

A: This worked for me.
https://ubuntuforums.org/showthread.php?t=2442975&p=13959089#post13959089
apt purge bcmwl-kernel-source
apt-get install broadcom-sta-source
apt-get install broadcom-sta-dkms
apt-get install broadcom-sta-common

after this steps restart your machine.


text:
Q: VMware Host only networks: Hosts not receiving NULL/FIN/XMAS packets using PFsense router Setup:
2 host-only ints each connected to a separate host on a separate network
PFsense VM routing between 2 networks (implicit accept on both networks, no other rules)
Can receive normal, syn,syn/ack,rst/ack, ACK, etc, essentially all the normal traffic you'd expect to see, but when I do a NULL/FIN or XMAS scan on nmap (nmap -sX ), I get an ICMP request, reply, timestamp, and a syn & rst/ack packets, but not the NULL, FIN or PSH/URG/FIN.
Wondering if anyone has come across this before. Maybe it's blocked by an underlaying rule in PFsense/ my Linux kernel version but I cant find the right literature to confirm.
Kernel version: 5.19.0-32-generic
Wireshark Capture Image


text:
Q: How do you find the size of a particle in Three.js? How do you find the size of a particle in Three.js?
With geometrys you can use the bounding box/sphere to calculate its size in three.js units. But a particle has no bounding box and I can't see of anyway to calulate its size.
Does anyone have any suggestions?

A: It depends what meaning of 'particle' you are dealing with. With a WebGLRenderer you would be referring to a vertex in a ParticleSystem, but with a CanvasRenderer you mean Particle (which is Canvas only). In terms of the ParticleSystem the material used to construct it has a size, like in the usual examples:
    geometry = new THREE.Geometry();
for ( i = 0; i < 10000; i ++ ) {
  var vertex = new THREE.Vector3(); // and set its location
  geometry.vertices.push( vertex );
}

material = new THREE.ParticleBasicMaterial( {
  size: 35,  // This might be the size you are thinking of?
  sizeAttenuation: false,
  map: // Some THREE.Texture
});

particles = new THREE.ParticleSystem( geometry, material );

Then you can access the size, and modify it simply with
particles.material.size = newSize;

If you are creating a Particle for canvas, then it is very similar:
// Construct the particle with a material
var material = new THREE.ParticleBasicMaterial( {
  map: new THREE.Texture(  canvas ),
  blending: THREE.AdditiveBlending
});
particle = new THREE.Particle( textMaterial );
// Just need to access the material to get the 'size'
var size = particle.material.size


text:
Q: How to sort result set on basis of a value? I am writing some queries for search engine having 5 parameters.
Its a basic search but the problem is I want to sort the order of the results on the basis of a selection like we do in the search engines with the relevance functionality.
I am using codeigniter as the framework and Active Records Library for the Database operations.
Thanks
J

A: First you have to define a relevance function, then you need to compute the relevance of each result, then you need to sort by the result of that computation. It's theoretically simple, the hard part is coming up with a good relevance function. We can't do that for you based on a vague description of some search engine.


text:
Q: Host file is open in another process I am trying to edit my host file under
C:\Windows\System32\drivers\etc

But I keep getting the message
The process cannot access the file because it is being used by another process.

My PC has been restarted a few times, even tried full shut down and searched through possible programs that might be using it.
I found a way to edit the file with the command prompt, but still gave the same message?
Hope someone can help!

A: As stated in a comment in the question by AFH -

You may be able to edit in safe mode

I was able to log into windows 10 safe mode by following
these steps.
I could edit and save the file without the popup stopping me

A: Easiest way to do this is, Copy hosts file to desktop edit it and then copy it back to the original location and replace the original file.

A: Turning off webroot secure fixed the problem for me.  If you're not using webroot secure try turning off any antivirus/malware/spyware apps you are running temporarily.
An easy way to see what process is using it, try moving the host file to the desktop and it will tell you.


text:
Q: Possible triangle center associated with Apollonius circle of excircles When I was playing around with Geogebra, I personally found a possible triangle center, but I'm not 100 % sure if my personal conjecture is true.
Consider the following configuration:

Let $E_A$, $E_B$, $E_C$ be the excircles of a given triangle $ABC$. Let $S$ be the Apollonius circle internally tangent to the three excircles. Denote the point of tangency of $E_A$ with $S$ by $T_A$. Define $T_B$ and $T_C$ similarly. Draw the circle $S_A$ that is tangent to $AB$ and $CA$ and internally tangent to $S$, other than the three excircles. Denote the point of tangency of $S_A$ with $S$ by $U_A$. Define $S_B$, $S_C$, $U_B$, and $U_C$ cyclically.

It seems that the three lines $T_A U_A$, $T_B U_B$, $T_C U_C$ are concurrent.

Question: Are these lines actually concurrent or not? If it's true and is an already known result, does this theorem or point have a name?

Edit
A demonstration of this proposition on Geogebra applet is available here.
Let $I_A$, $I_B$, $I_C$, $O_A$, $O_B$, and $O_C$ be the centers of $E_A$, $E_B$, $E_C$, $S_A$, $S_B$, and $S_C,$ respectively. Let $I$ be the incircle of $\triangle{ABC}$. Denote by $B_A$ and $A_B$ the intersections of the ray $\overrightarrow{AB}$ with $S$ and the ray $\overrightarrow{BA}$ with $S$, respectively. $A_B$, $A$, $B$, $B_A$ lie on a line in this order. Define $C_B$, $B_C$, $A_C$, $C_A$ cyclically.

What I know about this configuration is as follows:

*

*$T_A U_A$, $T_B U_B$, $T_C U_C$ are concurrent $$\iff \frac{\vert \overline{U_C T_B} \vert}{\vert \overline{T_B U_A} \vert} \cdot \frac{\vert \overline{U_A T_C} \vert}{\vert \overline{T_C U_B} \vert} \cdot \frac{ \vert \overline{U_B T_A} \vert}{\vert \overline{T_A U_C} \vert}=1$$ (Ceva's theorem for chords)

*$BC$ and $B_A C_A$ are parallel (parallel tangent theorem). $S$ is a Tucker circle centered at $X_{13323}$ of the triangle bounded by $B_A C_A$, $C_B A_B$, and $A_C B_C$. See also Darij Grinberg and Paul Yiu, "The Apollonius Circle as a Tucker Circle".

*$T_B$, $T_C$, and the exsimilicenter of $E_B$ and $E_C$ are collinear. This is a special case of Monge's theorem.

*$A T_A$, $B T_B$, and $C T_C$ meet at the exsimilicenter of $S$ and $I$, known as Apollonius point $X_{181}$. Similarly, $A U_A$, $B U_B$, $C U_C$ meet at the insimilicenter of $S$ and $I$, which is $X_{1682}$. These are consequences of Monge's theorem as well.

*$A_B A_C$, $B_A C_A$, and $T_B T_C$ are concurrent.

*$I_B$, $I_C$, the incenter of $\triangle{A_B B_C C_B}$ and the incenter of $\triangle{A_C B_C C_B}$ are collinear. Similarly, $I_B$, $O_C$, the incenter of $\triangle{C_B A_C C_A}$ are collinear (Sawayama-Thébault's theorem).

*$A_C$, $U_A$, the point of contact of $S_A$ with $A A_C$, the incenter of $\triangle{A A_B A_C}$, and the incenter of $\triangle{A_C B_A A_B}$ are concyclic (attributed to Yūzaburō Sawayama).

*If $E_A$ is not tangent to $BC$, then the proposition does not hold generally. Even if we assume that $BC \parallel B_A C_A$, $CA \parallel C_B A_B$, and $AB \parallel A_C B_C$, the proposition is generally not true.

I found another way to construct this point: Let $V_1=T_A A_B \cap T_C C_B$, $V_2=T_C C_B \cap T_B B_C$, $V_3=T_B B_C \cap T_A A_C$, $V_4=T_A A_C \cap T_C C_A$, $V_5=T_C C_A \cap T_B B_A$, and $V_6=T_B B_A \cap T_A A_B$. The three lines $V_1 V_4$, $V_2 V_5$, $V_3 V_6$ meet at this point.
I could not find this center in Kimberling's Encyclopedia of Triangle Centers, at least in the list from $X_1$ to $X_{47627}$.

A: This claim was algebraically confirmed. César Lozada found the following barycentric coordinates for this point.
Let $a$, $b$, $c$ be the lengths of the sides $\overline{BC}$, $\overline{CA}$, $\overline{AB}$, respectively. Then,
$$X=(f(a,b,c):f(b,c,a):f(c,a,b)),$$
where
$$f(a,b,c)=a^2(b^2+c^2+a(b+c))(a^4(b+c)^2-bc(b+c)^2(b^2+c^2)+a^3(b+c)(b^2+bc+c^2)-a(b^2-c^2)(b^3-c^3)-a^2(b^4+c^4-bc(b^2+6bc+c^2)))$$
This triangle center was not listed in the Encyclopedia of Triangle Centers. Now it is $X_{50032}$.
This theorem may be generalized to circular triangles.


text:
Q: how to use image tag Can someone help me out in inserting an image in the below function. I've used a json object that returns values for campaignid and campaignname.

output should be this

I'm getting the checkbox as well as the campaign name. I want the image in between these two.

A: As simple as this..
searchcmp += '<input type="checkbox" id=' + data[0][j].campaignId + ' name=' + data[0][j].campaignName + '/>' +
             ''+
             'data[0][j].campaignName + '
';

A: I suggest you a code like this one:
<input type="checkbox">Test</input>

Also, based on your code, it can be updated like this:
searchcmp += '<input type="checkbox" id=' + data[0][j].campaignId + ' name=' + data[0][j].campaignName + '>' + data[0][j].campaignName + '</input>
';

Where YOUR_URL_LOCATION, can be in the JSON or somewhere else.
It's going to display something like this:


text:
Q: Spree overriding default variables.scss I am attempting to change sprees admin styling. I went looking through the spree_backend engine and saw that they provided a file called _variables_override.scss its in app/assets/stylesheets/admin/globals/ and within the engine. I saw this inside
/*---------------------------------------------------------
Empty file to override variables in user applications.

To set your own colors, sizes or fonts just override this
file in you're application and set variables according to
globals/_variables.scss file.
--------------------------------------------------------- */

So I created my own app/assets/stylesheets/admin/globals/_variables_override.css and copied in the data from the engines globals/_variables.scss thinking that spree would override the styles but it won't I tried precompiling my assets but that won't work either, this all seemed too easy. But I always thought that what you had in your app would override whatever is in an engine if it had the same the same file name in the same directory path, am I wrong to assume that?

A: Your styleshhet name needs to match exactly.  Your description lists the name as:

app/assets/stylesheets/admin/globals/_variables_override.css

it needs to be

app/assets/stylesheets/admin/globals/_variables_override.scss


text:
Q: OWIN password hash manual comparison from JavaScript I need to use an existing ASP.NET OWIN database with Auth0. A problem that I've encountered is that I need to write a function in JavaScript (for the Auth0 Action Scripts) that takes a plaintext password, hashes it and compares that hash to an existing hash from the OWIN database. The hashes are created using ASP.NET Identity UserManager class.
How can I replicate the algorithm that UserManager uses in JavaScript?
Thanks in advance,
Arthur.

A: Found the answer. You can use this C# code snippet that from node using edge to has the password like UserManager does it in ASP.NET Identity.
var edge = require('edge');

  var verifyHash = edge.func(function() {/*
    using System;
    using System.Runtime.CompilerServices;
    using System.Security.Cryptography;
    using System.Threading.Tasks;
    using System.Runtime.InteropServices;
    using System.Security.Principal;

    internal static class Crypto
    {
        private const int PBKDF2IterCount = 1000; // default for Rfc2898DeriveBytes
        private const int PBKDF2SubkeyLength = 256/8; // 256 bits
        private const int SaltSize = 128/8; // 128 bits

        public static string HashPassword(string password)
        {
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }

            // Produce a version 0 (see comment above) text hash.
            byte[] salt;
            byte[] subkey;
            using (var deriveBytes = new Rfc2898DeriveBytes(password, SaltSize, PBKDF2IterCount))
            {
                salt = deriveBytes.Salt;
                subkey = deriveBytes.GetBytes(PBKDF2SubkeyLength);
            }

            var outputBytes = new byte[1 + SaltSize + PBKDF2SubkeyLength];
            Buffer.BlockCopy(salt, 0, outputBytes, 1, SaltSize);
            Buffer.BlockCopy(subkey, 0, outputBytes, 1 + SaltSize, PBKDF2SubkeyLength);
            return Convert.ToBase64String(outputBytes);
        }

        // hashedPassword must be of the format of HashWithPassword (salt + Hash(salt+input)
        public static bool VerifyHashedPassword(string hashedPassword, string password)
        {
            if (hashedPassword == null)
            {
                return false;
            }
            if (password == null)
            {
                throw new ArgumentNullException("password");
            }

            var hashedPasswordBytes = Convert.FromBase64String(hashedPassword);

            // Verify a version 0 (see comment above) text hash.

            if (hashedPasswordBytes.Length != (1 + SaltSize + PBKDF2SubkeyLength) || hashedPasswordBytes[0] != 0x00)
            {
                // Wrong length or version header.
                return false;
            }

            var salt = new byte[SaltSize];
            Buffer.BlockCopy(hashedPasswordBytes, 1, salt, 0, SaltSize);
            var storedSubkey = new byte[PBKDF2SubkeyLength];
            Buffer.BlockCopy(hashedPasswordBytes, 1 + SaltSize, storedSubkey, 0, PBKDF2SubkeyLength);

            byte[] generatedSubkey;
            using (var deriveBytes = new Rfc2898DeriveBytes(password, salt, PBKDF2IterCount))
            {
                generatedSubkey = deriveBytes.GetBytes(PBKDF2SubkeyLength);
            }
            return ByteArraysEqual(storedSubkey, generatedSubkey);
        }

        // Compares two byte arrays for equality. The method is specifically written so that the loop is not optimized.
        [MethodImpl(MethodImplOptions.NoOptimization)]
        private static bool ByteArraysEqual(byte[] a, byte[] b)
        {
            if (ReferenceEquals(a, b))
            {
                return true;
            }

            if (a == null || b == null || a.Length != b.Length)
            {
                return false;
            }

            var areSame = true;
            for (var i = 0; i < a.Length; i++)
            {
                areSame &= (a[i] == b[i]);
            }
            return areSame;
        }
    }

    class Startup
    {
        public async Task<object> Invoke(dynamic input)
        {
            return await Task<object>.Run(() => {
                return Task.FromResult<object>(Crypto.VerifyHashedPassword (input.hashedPassword, input.providedPassword));
            });
        }
    }
*/});

  verifyHash({ hashedPassword: 'AONmKUXiPKhN1J+t8DwCp2uTq3TBcJNabcc4HuQkx+uwO+5+yRJZreJ9jZyxyGzhzg==', providedPassword: 'abc' }, function (error, result) {
    if (error) {
      console.log(error);
    }
    else {
      if (result) {
        // Password matches!
      }
    }
  });


text:
Q: How to setup QGIS Server with PostGIS? I need setup QGIS Server + PostGIS (+ Lizmap) in Docker for our GIS users. I spent a lot of time reading documentation and searching for information on that matter but it's unclear for me as for sysadmin.
I feel like QGIS server documentation limited on this topic.
Could you direct me on right way?
EDIT:
I've used Docker based Lizmap project, with my additions in docker-compose file, I've added Postgis and Pgadmin services (containers)
version: '3'
services:
  postgis:
    # image: "mdillon/postgis"
    image: "mdillon/postgis:10"
    container_name: postgis
    restart: always
    privileged: true  # add for centos7 firewall.
    volumes:
      - ./postgis:/var/lib/postgresql/data # default volumn path is /data/postgis.
    ports:
      - "9823:5432" # port 5432 of host machine will be listened.
    environment:
      - POSTGRES_PASSWORD=************** # default password is "1".
      - POSTGRES_USER=postgres # default username is "postgres".
      - PGDATA=/var/lib/postgresql/data # folder in container to store data.
      - POSTGRES_DB=postgres # default database is "postgres".

  pgadmin:
    container_name: pgadmin_container
    image: dpage/pgadmin4
    environment:
      PGADMIN_DEFAULT_EMAIL: ${PGADMIN_DEFAULT_EMAIL:-support@example.org}
      PGADMIN_DEFAULT_PASSWORD: ${PGADMIN_DEFAULT_PASSWORD:-************}
    volumes:
       - ./pgadmin:/root/.pgadmin
    ports:
      - "${PGADMIN_PORT:-5050}:80"
    restart: unless-stopped

  lizmap:
    image: 3liz/lizmap-web-client:3.2
    environment:
      LIZMAP_CACHEREDISDB: '1'
      LIZMAP_CACHEREDISHOST: redis
      LIZMAP_CACHESTORAGETYPE: redis
      LIZMAP_HOME: /srv/lizmap
      LIZMAP_USER: ${LIZMAP_USER_ID}
      LIZMAP_WMSSERVERURL: http://map:8080/ows/
    volumes:
      - ${LIZMAP_DIR}/instances:/srv/projects
      - ${LIZMAP_DIR}/var/lizmap-theme-config:/www/lizmap/var/lizmap-theme-config
      - ${LIZMAP_DIR}/var/lizmap-config:/www/lizmap/var/config
      - ${LIZMAP_DIR}/var/lizmap-db:/www/lizmap/var/db
      - ${LIZMAP_DIR}/www:/www/lizmap/www
      - ${LIZMAP_DIR}/www/var/log:/www/lizmap/var/log
    command:
      - php-fpm
    restart: unless-stopped
  map:
    image: 3liz/qgis-map-server:3.4
    environment:
      PGSERVICEFILE: /srv/etc/pg_service.conf
      QGSRV_CACHE_ROOTDIR: /srv/projects
      QGSRV_CACHE_SIZE: '20'
      QGSRV_LOGGING_LEVEL: DEBUG
      QGSRV_USER: ${LIZMAP_USER_ID}:${LIZMAP_USER_GID}
      ROUTER_HOST: map
    volumes:
      - ${LIZMAP_DIR}/instances:/srv/projects
      - ${LIZMAP_DIR}/etc:/srv/etc:ro
      - ${LIZMAP_DIR}/wps-data:/srv/data
    restart: unless-stopped
  redis:
    image: redis:5
  web:
    image: nginx:1
    volumes:
      - ${LIZMAP_DIR}/etc/nginx.conf:/etc/nginx/nginx.conf
      - ${LIZMAP_DIR}/var/log/nginx:/var/log/nginx
      - ${LIZMAP_DIR}:/srv/lizmap
    ports:
      - 8888:80
    depends_on:
      - lizmap

I'm able now login into lizmap in web browser, but tests projects in *.qgs files don't appears, so my lizmap web page is blank, even I try to change in UI lizmap setting regard to repository and projects.
Also I'm able now to connect from Qgis Desktop on my local machine to Postgis database and use Pgadmin webclient to connect to the same Postgis database. Although I'm aware that my Postgis DB doesn't integrate with Qgis server, Lizmap and Nginx webserver.
At the moment I think that I need, break down on sub tasks:

*

*Put test project (map) to my current Postgis DB

*Setup connection Qgis Server with Postgis DB through writing FCGI web config file for web server (in my case Nginx) . So some DB query should be writed in thi config file.

*Setup connection Lizmap web client with Postgis DB

*Probably setup/config XVFB in conjuction with QGIS server (container)

A: You have to create a QGIS project (.qgs not .qgz) and a Lizmap configuration file with help of the Lizmap plugin. Put those files in a new directory created in lizmap/instances/.

Note that there are yet two directories test_france_parts and
test_france_parts2 if you just want to test everything is ok
before creating your own project.

Then, in the administration page, declare a Lizmap repository pointing on one of your directories (it should be visible in 'Local folder path' dropdown) : http://localhost:8090/admin.php/admin/maps/editSection
Then you should see your repository and project in the main Lizmap page.


text:
Q: Find out which commit removed a particular word/line in GIT With both GIT tools and command line, what is the easiest way to find out which commit removed a particular word from a file?

A: You could use the methods described in this post:

If you know the contents of the line, this is an ideal use case for:

git log -S<string> path/to/file
git log -G<regex> path/to/file

Or you could try:
git blame --reverse

A: git blame will show you the most recent commit that changed each line of a file. You can use that on your file, and then go to the line where your word is.

A: Type gitk in command line it would show the graphical tool for comparisons of the file.
(OR)
   $ git log -p

One of the more helpful options is -p, which shows the diff introduced
  in each commit.


text:
Q: Is there a way to control the legends of cartographic representations with Python? I have a ArcGIS feature class with 3 cartographic representations.  Two of them represent the features with line offsets.  These representations are determined based on multiple fields.  One field determines the color of the line, the other field determines the offset.  In the legend this means that each color is repeated once for each offset.  This can be controlled using Layer Properties>Symbology>Legend Options to make it so that each line color is only shown once in the legend.  Is there a way to control this setting with Python?

A: Unfortunately, you won't be able to access this using arcpy. Currently, your only option is to search for custom tools that other users might have built or develop your own using ArcObjects.


text:
Q: Let $X=[0,\infty)$. Construct a sequence of functions $f_n:X\rightarrow \mathbb{R}$ that converges uniformly, but that does not converge in $L^2(X)$. Does someone mind checking my proof here? I'm primarily concerned with everything from my definition of the set K and onward. I would appreciate any other feedback as well.
NOTE: I am not educated in measure theory or Lebesgue integration. I have a decent understanding of Riemann integration and that is it. My original proof just shows that $f_n$ is not Cauchy in $L^2(X)$ but I wanted to try a proof by contradiction with an arbitrary $f$.
Define the sequence
$$f_n(x)=\frac{1}{\sqrt{n(x+1)}}.$$
First, we show that $f_n\to 0$ uniformly.
$$\sup_{x\in[0,\infty)}\frac{1}{\sqrt{n(x+1)}}=\frac{1}{n}\to 0.$$
Now, let $f$ be a Lebegue integrable function on $[0,\infty)$. Then,
\begin{align*}
\int_0^{\infty}\bigg(\frac{1}{\sqrt{n(x+1)}}-f(x)\bigg)^2&=\int_0^{\infty}\bigg(\frac{1}{n(x+1)}-\frac{2f(x)}{\sqrt{n(x+1)}}+f^2(x)\bigg)dx\\
&\geq \int_0^{\infty}\bigg(f^2(x)-\frac{2|f(x)|}{\sqrt n}\bigg)dx.
\end{align*}
If we can show that $\int_0^{\infty}\bigg(f^2(x)-\frac{2|f(x)|}{\sqrt n}\bigg)dx>0$, then we will succeed in showing that $f_n$ does not converge in $L^2(X)$. So, we assume that
$$\int_0^{\infty}\bigg(f^2(x)-\frac{2|f(x)|}{\sqrt n}\bigg)dx\leq0.$$
There must then be a set $K=\{x\in [0,\infty)|f^2(x)-\frac{2|f(x)|}{\sqrt n}\leq 0\}$ with positive measure. But then, for all $x\in K$, $f(x)=0$ or $|f(x)|\leq \frac{2}{\sqrt n}$. Since $n$ is arbitrary, however, this inequality forces $f$ to be zero on all of $K$. Thus, $f$ is either zero almost everywhere on $[0,\infty)$, in which case
\begin{align*}
\int_0^{\infty}\bigg(f_n(x)-f(x)\bigg)^2dx&=\int_0^{\infty}\frac{1}{n(x+1)}(x)dx\\
&=\lim_{R\to\infty}\frac{\log (R+1)}{n}\\
&=\infty.
\end{align*}
Or, $\int_0^{\infty}\bigg(f^2(x)-\frac{2|f(x)|}{\sqrt n}\bigg)dx>0$, in which case our norm is bounded below by a positive value.


text:
Q: return to filemanger/gallery after sharing a image to my app i am using intent-filter to share images to my application.
the uploading Activity is (B) and the main Activity in my app is (A).
so the images sent from filemanger/gallery to Activity (B) then the user click upload and i kill the (B) Activity with
    finish();

and i am using
    onActivityResult()

method to check if the user came from the uploading Activity and end the main Activity (A) with the finish() function.
now i killed my app but the system take the user to the home or the apps list.
i want the system take the user back to the filemanger or the gallery to share more photos.

A: i had to add a attribute to the Activity in the manifest file
you have to change the way of lunching the Activity
add this code in the Activity tag
        android:launchMode="singleTask"

more info : http://developer.android.com/guide/topics/manifest/activity-element.html#lmode


text:
Q: Reputation for "correctly" triaging Triaging is a mostly thankless job, and I feel like a little bit of a reputation boost for "correctly" triaging (where correctly triaging is triaging in accordance with the final decision) would be nice. This should probably eventually apply to the other queues as well, but for triage it is clear what reputation should be given for.

A: First, the entire point of the review queue is that there is no good measure of good and bad. Hence, we need humans, multiple of them, to review a case. That would make rewarding 'good' reviews almost impossible. Note that the end result of a review is not always the end result it should be, thanks to robo-reviewers.
Awarding reputation for reviewing is a bad idea. Not only for the above reason, also because it encourages robo-reviewing, something we definitely not want to have.


text:
Q: Need help to understand accelerometer code I have read through a lot of code but I do not understand how you can make an image move using the accelerometer sensor, I understand how to register it but I do not understand how to actually make an image or a shape draw move in sync with the accelerometer axis, I am using android java to do this. Please can someone help me as I am really struggling. Thank you for your time and help.

A: So, here's the code to register a listener (I know you said you've done this already, but it can never hurt):
private void enableAccelerometerListening() {
sensorManager = (SensorManager) getSystemService(COntext.SENSOR_SERVICE);
sensorManager.registerListener(sensorEventListener), sensorManager.getDefaultSensor(
Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
}

private void disableAccelerometerListening() {
if (sensorManager != null) {
sesnsorManager.unregisterListener(sensorEVentListener, sensorManager.getDefaultSensor(SensorManager.SENSOR_ACCELEROMETER));
sensorManager = null;
}}

You will need a couple fields just below your class declaration:
private SesnsorManager sensorManager;
private float acceleration;
private float currentAcceleration;
private float lastAcceleration;
private static final int ACCELERATION_THRESHOLD = 15000;

Here is the event handler, which gets very close to what you need help with:
    private SensorEventListener sensorEventListener = new SensorEventListener() {
    public void onSesnsorChanged(SensorEvent event) {

    float x = event.values[0];
    float y = event.values[1];
    float z = event.values[2];

lastAcceleration = currentAcceleration; //save previous accel value

currentAcceleration = x*x + y*y + z*z;

acceleration = currentAcceleration * (currentAcceleration - lastAcceleration); // calc the change in acceleration

//if the accel is above a certain threshold:
if (acceleration > ACCELERATION_THRESHOLD) {
//MAKE YOUR CODE HERE THAT RESPONDS TO ACCELERATION EVENTS
//Note, your accel threshold should be determined by trial and error on a number of devices
}
}

public void onAccuracyChanged(Sensor sensor, int accuracy {}

};

A: Also, I'll try to address some of your animation needs, though I am much more spotty in this area. I imagine that what you need to do is make your image move as the accelerometer detects moves. The image will have to be moved via an animation, rather than the accelerometer directly. So say 'spot' is your image, okay? (the code below both adds a spot and sets up its animations(which are not directly tied to the accelerometer, but I hope this will be helpful nonetheless):
public void addSpot() {

int x = random.nextInt(viewWidth - SPOT_DIAMETER);
int y = random.nextInt(viewHeight = SPOT_DIAMETER);
int x2 = random.nextInt(viewWidth - SPOT_DIAMETER);
int y2 = random.nextInt(viewWidth - SPOT_DIAMETER);

final ImageView spot = (ImageView) layoutFinlater.inflate(R.layout.untouched, null);
spot.setLayoutParams(new RelativeLayout.LayoutParams(SPOT_DIAMETER, SPOT_DIAMETER));
spot.setX(x);
spot.setY(y);

Well right here is where I think you could start doing something with the accelerometer events...
As you saw in my other response above,
if (acceleration > ACCELERATION_THRESHOLD) {
spot.animate().x(x2).y(y2).setDuration(animationTime);

animationTime will just be something in milliseconds that you feel is appropriate, and don't forget to take care of importing the necessary packages.


text:
Q: How to get the edges of a 3D Delaunay tessellation with CGAL? The question is clear from the title. I tried a ton of variants of
  const DT3::Finite_edges itedges = mesh.finite_edges();
  for(DT3::Finite_edges_iterator eit = itedges.begin(); eit != itedges.end(); eit++) {
      const CGAL::Triple<DT3::Cell_handle, int, int> edge = *eit;
      edge.first->vertex((edge.second+1) % 3)->info();
      edge.first->vertex((edge.third+1) % 3)->info();
  }

but none has worked (I tried % 2, % 4, +2, etc).
I'm able to get the tetrahedra and the triangles. Of course I could extract the edges from them but that would require to remove some duplicates.

A: No need to use addition or modular arithmetic. The solution is simpler:
  const DT3::Finite_edges itedges = mesh.finite_edges();
  for(DT3::Finite_edges_iterator eit = itedges.begin(); eit != itedges.end(); eit++) {
      const DT3::Edge edge = *eit;
      const DT3::Vertex::Info v1_info = edge.first->vertex(edge.second)->info();
      const DT3::Vertex::Info v2_info = edge.first->vertex(edge.third)->info();
  }

The documentation of the nested type Edge is here as well as in the section "Representation" of the user manual of 3D Triangulation Data Structure.

Edit: note that I have chosen to respect your coding style, ignoring modern C++ features. Using C++11 features, I prefer to write it this way, using auto and range-based for loop:
  for(const auto edge: mesh.finite_edges()) {
      const auto v1_info = edge.first->vertex(edge.second)->info();
      const auto v2_info = edge.first->vertex(edge.third)->info();
  }


text:
Q: Unable to print documents in WCF service using amyuni converter We have an application service hosted in IIS which is using Amyuni PDF Converter 6.0 to print the report in PDF file. The application was working fine with Amyuni PDF Converter 5.5.
This issue is seen in Windows Server Operating System & When the service is hosted on IIS. Whereas in Windows 10 OS the application seems to be working fine.
When trying to print using a console application either on Windows Server or Windows 10 OS, we are able to print the document.
We ensured that both console applications and services were run under the same user/Identity.
Any advice on this issue?


text:
Q: Question of call function in cmd batch file I have a question about the call function of cmd batch file.
According to the source code below:
If you I want to call a REDO/NORMAL function, when the function end, the question is it possible return to ECHO Copying File... to run and until to EXIT(0) to the end?
Thanks.
Source Code
@ECHO OFF

ECHO Checking Network Connection...
ECHO.
TIMEOUT /T 1 /NOBREAK > NUL

PING -n 2 192.168.1.1 | FIND "TTL" > NUL

IF errorlevel 1 (

    Powershell -noP -c "Write-Host 'ERROR: Failure! Please Check Network Connection! Script Exit!' -BackgroundColor BLACK -ForegroundColor RED"
    TIMEOUT /T 1 /NOBREAK > NUL
    TIMEOUT /T 5
    EXIT(0)

) ELSE (

    Powershell -noP -c "Write-Host 'INFO: Success! Network Connected!' -ForegroundColor GREEN"
    TIMEOUT /T 2 /NOBREAK > NUL

)

FOR /F %%a IN ('Powershell -Nop -c "Get-Date -Format 'HH:mm'"') DO SET time=%%a

IF %time% GTR 12:00 (

GOTO REDO

) ELSE (

GOTO NORMAL

)

ECHO Copying File...
ECHO.

TIMEOUT /T 1 /NOBREAK > NUL

COPY "C:\temp\A.csv" "D:\temp\"

ECHO.
ECHO Copy Completed!
TIMEOUT /T 1 /NOBREAK > NUL

EXIT(0)

:REDO
ECHO THIS IS REDO FUNCTION

:NORMAL
ECHO THIS IS NORMAL FUNCTION

A: Try this:
    @ECHO OFF

ECHO Checking Network Connection...
ECHO.
TIMEOUT /T 1 /NOBREAK > NUL

PING -n 2 192.168.1.1 | FIND "TTL" > NUL

IF errorlevel 1 (

    Powershell -noP -c "Write-Host 'ERROR: Failure! Please Check Network Connection! Script Exit!' -BackgroundColor BLACK -ForegroundColor RED"
    TIMEOUT /T 1 /NOBREAK > NUL
    TIMEOUT /T 5
    EXIT(0)

) ELSE (

    Powershell -noP -c "Write-Host 'INFO: Success! Network Connected!' -ForegroundColor GREEN"
    TIMEOUT /T 2 /NOBREAK > NUL

)

FOR /F %%a IN ('Powershell -Nop -c "Get-Date -Format 'HH:mm'"') DO SET time=%%a

IF %time% GTR 12:00 (

GOTO REDO
:BACK
) ELSE (

GOTO NORMAL
:BACK
)

ECHO Copying File...
ECHO.

TIMEOUT /T 1 /NOBREAK > NUL

COPY "C:\temp\A.csv" "D:\temp\"

ECHO.
ECHO Copy Completed!
TIMEOUT /T 1 /NOBREAK > NUL

EXIT(0)

:REDO
ECHO THIS IS REDO FUNCTION
GOTO BACK

:NORMAL
ECHO THIS IS NORMAL FUNCTION
GOTO BACK


text:
Q: How do I install libmono.so on Ubuntu 18? I am trying to build some code that uses CMake to find and link to Mono. It is trying to link to libmono.so and libmono-2.0.so.
I have installed mono-complete (which installs mono-devel) without errors and the files still do not exist. Using dpkg on mono-devel shows that these libraries are not part of the installation. So where do I get them?
Using locate shows some Steam games have the library so they clearly exist...somewhere.
How do I install these development libraries on my machine?

A: *

*Check in which package this file exists:
apt-file search libmono-2.0.so
libmono-2.0-1: /usr/lib/libmono-2.0.so.1
libmono-2.0-1: /usr/lib/libmono-2.0.so.1.0.0
libmono-2.0-dev: /usr/lib/libmono-2.0.so

*Check if you have installed this package:
apt policy libmono-2.0
libmono-2.0-1:
  Installed: (none)
  Candidate: 5.18.0.240+dfsg-2ubuntu2
  Version table:
     5.18.0.240+dfsg-2ubuntu2 500
        500 http://ubuntu.task.gda.pl/ubuntu disco/universe amd64 Packages
libmono-2.0-dev:
  Installed: 5.18.0.240+dfsg-2ubuntu2
  Candidate: 5.18.0.240+dfsg-2ubuntu2
  Version table:
 *** 5.18.0.240+dfsg-2ubuntu2 500
        500 http://ubuntu.task.gda.pl/ubuntu disco/universe amd64 Packages
        100 /var/lib/dpkg/status

*If you haven't installed, install it
sudo apt install libmono-2.0
My output is from Ubuntu 19.04 but on Ubuntu 18 you will be have the same package names.


text:
Q: Is this group simple? I have this group presentation $G = \langle a,b | ba = a^{-1}b\rangle$. I'm wondering if this group is solvable or not. I tried to show that this group is simple, because if it is, then it can not be solvable as it is an infinite group. I'm not sure if it even is simple, as I do not have much experience with group presentations and proving that (infinite) groups are simple.
Is there anyone who can tell me if this group is solvable and if so, if this strategy is will work.
Thank you in advance.

A: Consider the infinite cyclic group $G=\langle a\rangle$, this admits an automorphism that sends $a\to a^{-1}$ and this is in fact the only nontivial automorphism it admits. Let $H= \langle b\rangle$ be another copy. There is a group morphism $\eta:H\to {\rm Aut}\,G$ that sends $b$ to the automorphism $a\mapsto a^{-1}$. This is just the projection map $\Bbb Z\to\Bbb Z_2={\rm Aut}\,\Bbb Z$. Then your group is the semidirect product $K=G\rtimes H$ under this action, and in particular $G$ is normal, and $K/G\simeq H$, so there is a solvable series $1\lhd  G\lhd  K$, for $G$ and $K/G$ are both infinite cyclic, in particular abelian. In general if $A,B$ are abelian groups then any semidirect product of $A$ with $B$ is solvable by the same reasoning.


text:
Q: Spring Security. Login error i'm new in spring mvc and security autorization. All good with basic auth, but i want to add custom auth. Added boot-secrity to gradle, login.html page to templates with 2 inputs, websecuritycinfig file with auth rules and "login" mapping to login.html
I have problem with Spring Security custom authorization. If i enter right or wrong credentials, both return me login?error. Here is my code. Please help.
stackoverflow asks me add more description.
Here is my code: WebSecurityConfig.java
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configurers.GlobalAuthenticationConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
        .anyRequest().authenticated();
    http
        .formLogin()
        .loginPage("/login")
        .permitAll();
  }

  @Configuration
  protected static class AuthenticationConfiguration extends
      GlobalAuthenticationConfigurerAdapter {

    @Override
    public void init(AuthenticationManagerBuilder auth) throws Exception {
      auth
          .inMemoryAuthentication()
          .withUser("qwerty").password("123").roles("ROLE");
    }

  }

}

login.html
<form th:action="@{/login}" method="post">

            Invalid username and password.

                Логин

                    <input type="text" class="form-control" id="login" placeholder="Логин"/>

                Пароль

                    <input type="password" class="form-control" id="password" placeholder="Пароль"/>

                    <button type="submit" class="btn btn-primary">Войти</button>

</form>

eSchoolController.java
import com.testgreetgo.eSchool.config.FlashMessage;
import com.testgreetgo.eSchool.dao.StudentDaoImpl;
import com.testgreetgo.eSchool.model.Student;
import com.testgreetgo.eSchool.service.StudentService;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;
import javax.validation.Valid;

@Controller
public class eSchollController {
  @Autowired
  private StudentService studentService;

@RequestMapping(value="/login")
  public String loginForm() {
  return "login";
  }

  @SuppressWarnings("unchecked")
  @RequestMapping(value = "/")
  public String listStudents(ModelMap modelMap) {
    List<Student> students = studentService.findAll();
    modelMap.put("students", students);
    return "home";
  }
  @RequestMapping(value = "/student/{id}")
  public String studentDetails(@PathVariable Long id, ModelMap modelMap) {
    Student student = studentService.findById(id);
    modelMap.put("student", student);
    return "student-detail";
  }

  //Add a student
  @RequestMapping(value = "/students", method = RequestMethod.POST)
  public String addStudent(@Valid Student student, BindingResult result, RedirectAttributes redirectAttributes) {
    //Check if there errors on validation
    if (result.hasErrors()) {
      //Include valiation errors upon redirect
      redirectAttributes.addFlashAttribute("org.springframework.validation.BindingResult.student", result);

      //Add student if invalid was received
      redirectAttributes.addFlashAttribute("student", student);
      return "redirect:/students/add";
    }
    studentService.save(student);
    redirectAttributes.addFlashAttribute("flash", new FlashMessage("Новый студент добавлен!", FlashMessage.Status.SUCCESS ));

    return "redirect:/";
  }

  @RequestMapping(value="students/add")
  public String formNewStudent(Model model) {
    if (!model.containsAttribute("student")) {
      model.addAttribute("student", new Student());
    }
    model.addAttribute("action", "/students");
    model.addAttribute("submit", "Добавить");
    return "form";
  }

  @RequestMapping(value="/students/{id}/edit")
  public String formEditStudent(@PathVariable Long id, Model model) {
    if (!model.containsAttribute("student")) {
      model.addAttribute("student", studentService.findById(id));
    }
    model.addAttribute("action", String.format("/students/%s", id));
    model.addAttribute("submit", "Сохранить");
    return "form";
  }

  //Update an existing student
  @RequestMapping(value="students/{id}")
  public String updateStudent(@Valid Student student, BindingResult result, RedirectAttributes redirectAttributes) {
    if (result.hasErrors()) {
      //Include valiation errors upon redirect
      redirectAttributes.addFlashAttribute("org.springframework.validation.BindingResult.student", result);

      //Add student if invalid was received
      redirectAttributes.addFlashAttribute("student", student);
      return String.format("redirect:/students/%s/add", student.getId());
    }
    studentService.save(student);
    redirectAttributes.addFlashAttribute("flash", new FlashMessage("Студент обновлен!", FlashMessage.Status.SUCCESS ));

    return "redirect:/";
  }

  //Delete an existing student
  @RequestMapping(value="/students/{id}/delete", method = RequestMethod.POST)
  public String deleteStudent(@PathVariable Long id, RedirectAttributes redirectAttributes) {
    Student student = studentService.findById(id);
    studentService.delete(student);
    redirectAttributes.addFlashAttribute("flash", new FlashMessage("Студент успешно удален!", FlashMessage.Status.SUCCESS));
    return "redirect:/";
  }

}

A: Problem solved. If someone need: You need to tell Spring Security to exclude them from restricted resources.
@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/javax.faces.resource/**");
}

If problem is still there, try to exclude other files, like
web.ignoring().antMatchers("/javax.faces.resource/**", "/custom.css", "/img/**");


text:
Q: How can I prohibit other Linux Kernel modules to get access to some regular files? The problem is to prohibit access to some files (files from my "blacklist"). It implies that nobody besides me (my own kernel module) can either read or modify these files.
I've already asked this question here, on StackOverflow, but I haven't gotten an answer. There was only one solution offered to change file's permissions and file's owner. However, it isn't enough for my goals, since file's permissions as well as file's owner can be easily modified by someone else.
But I haven't given up, I've carried on studying this problem.
I replaced some fields of the system calls table by the pointers to my own functions. Thus I managed to prohibit any USER module to get an access to the files from my blacklist; in addition, this approach doesn't depend on file's permissions or file's owner. However, the key word is "user modules". I mean that any kernel module still can easily get an access to the files from my blacklist via calling, for instance, the filp_open() function. I looked through the Linux code sources and it turned out that all these system calls that I hooked (open, openat, ...) are simple wrappers and no more.
Could you help me? Is there a way to do something with filp_open that is similar to what I've done with system calls? Any other solutions (without hooking) are welcome.

A: What you are asking for is impossible. Theoretically, this could be achieved by running the kernel under a custom-made hypervisor or running on custom-made hardware, but it would be extremely complicated (if not impossible) to achieve in reality.
You cannot protect the kernel from itself. In any normal scenario (i.e. no dedicated hardware or hypervisor), the Linux kernel runs at the highest privilege level on the machine, and can therefore revert any changes you make if it wants. If your module needs to deny access to some file to the whole kernel, then there's really something conceptually wrong about what you are doing. Moreover, you seem to be assuming that other kernel modules would be somehow "interested" in messing with your module: why would that be the case?
Furthermore, even changing permissions or overriding syscalls does not solve any problem: unless you correctly configure kernel lockdown (kernel >= v5.4) and/or some other security measure like module signing (and ideally also secure boot), the root user is always able to insert modules and subvert your "security" measures.
If you need to deprive root of access to these files, then as I said there's really something logically wrong. The root user can already do whatever it wants with whichever configuration file it wants, of course destroying important configuration files is going to break the system, but that's not really something that you can avoid. Assuming that root is evil doesn't make much sense as a threat model in any normal scenario.


text:
Q: How to make a template with an overloaded function based on the type? I came across a numeric_limits static method.
For example, numeric_limits::infinity(); gives the infinity when we do
numeric_limits::infinity(), we get a different result.
My understanding is that infinity() is a static method of the class numeric_limits.
If I want to implement similar kind of mechanism how can I do so. How to make a template class that will return a different answer based on
the type passed.

A: You can provide a specialization for each type you want to supports, and give each specialization member functions with the same name that return different values, and even different types.
#include <iostream>

template <typename T>
struct my_limits;

template <>
struct my_limits<int> {
    static constexpr int max() {
        return 2000;
    }
};

template <>
struct my_limits<char> {
    static constexpr char max() {
        return 127;
    }
};

int main() {
    std::cout << my_limits<int>::max() << ' ' << static_cast<int>(my_limits<char>::max());
}


text:
Q: How can I get the two product_ID of the current image in the two carrousel and the pass the two productID in the controller(Codeigniter)

    <?php var_dump($products['upper']); ?>

STEP 1: Choose your TOP

                            <?php foreach ($products['upper'] as $index => $product): ?>
                              <div class="item <?php echo ($index == 0) ? 'active' : ''; ?>">
                            <img name="data" value="<?php echo $product['productID'] ?>" class="img-responsive center-block" src="<?php echo base_url();?>image/productimages/<?php echo $product['image'] ?>" style="margin: auto; height: 300px">

                                <?php echo $product['productname']; ?>

                        <?php endforeach ?>

    <?php var_dump($products['lower']); ?>

STEP 2: Choose your BOTTOM

                     <?php foreach ($products['lower'] as $index => $product): ?>
                              <div class="item <?php echo ($index == 0) ? 'active' : ''; ?>">
                            <img name="<?php echo $product['productID'] ?>" class="img-responsive center-block" src="<?php echo base_url();?>image/productimages/<?php echo $product['image'] ?>" style="margin: auto; height: 300px">

                                <?php echo $product['productname']; ?>

                        <?php endforeach ?>

STEP 3: Submit

            <button type="submit" form="hidden_form" class="btn btn-lg btn-block btn-primary">Go!</button>

</form>

A: The simplest way to get the product_ID data is as below
<img class="img-responsive center-block" src="<?php echo base_url();?>image/productimages/<?php echo $product['image'] ?>" style="margin: auto; height: 300px">
<input type="hidden" value="<?php echo $product['productID'] ?>" name="data" />

Use an <input type="hidden" tag to get the value exactly.


text:
Q: Прочитать цифру в элементе span никак не пойму, никак не найду, как прочитать цифру в строке такого типа?

6 600 ₽/шт

Элемент выделил Element Prs=doc.getElementById("price");
А вот как из него число вытащить?

A: Если нужно получить 6 600 ₽/шт:
String price = Prs.text();

Если нужно получить только число 6600 (в общем случае оно может быть и не целое):
float price = Float.parseFloat(Prs.text().substring(0, Prs.text().lastIndexOf(" ")).replaceAll(" ", ""));

UPD.
Только стоимость (6600.0):
Document doc = Jsoup.connect("https://www.layta.ru/rvi-ipc31ms-ir.html").get();
Element priceElement = doc.select("span.price").get(0);
float price = Float.parseFloat(priceElement.text().substring(0, priceElement.text().lastIndexOf(" ")).replaceAll(" ", ""));

Стоимость, валюта и единицы (6 600 ₽/шт):
Document doc = Jsoup.connect("https://www.layta.ru/rvi-ipc31ms-ir.html").get();
Element priceElement = doc.select("span.price").get(0);
String price = priceElement.text();

A: Попробуйте так:
Element Prs = doc.getElementById("price");
String prs = Prs.text();


text:
Q: STL vector taking up too much memory Im using a STL vector in my SDL program. and it looks like this: vector< Bullet * > vec; this makes a vector that can contain pointers to Bullet objects. when i run my program i only add one item at a time using: vec.push_back( new_bullet ); (new_bullet is a pointer to a "new" Bullet object. then in a following function i erase an object using: vec.erase(...); vec.size() shows that the items are being pushed and popped properly. I'm running Ubuntu 9.10 and System Monitor shows my programs memory usage slowly increasing. Is it my program or something I'm missing about STL vector?

A: erase() only removes an element from a vector, it does not delete the memory pointed to if that element is a pointer.  This makes sense... imagine you had a vector<const char *> of string literals and did v.erase(i); you can't delete a const char *!
However, erase() will call the destructor for the element removed.  So if you used a sort of "pointer object" rather than a pointer, it could release the memory when destroyed.  If you're interested, you should check out boost::shared_ptr which implements reference counted garbage collection.

A: Sounds like you're not deleteing the "bullet" objects as you remove them from the vector.

A: If you're only adding to the end of the array and you're worried about memory fragmentation, you might want to use std::list instead. The only problem is, list accesses are O(n) time if they're not at the beginning.
Are you calling free()/delete on your bullets when you're done with them after pulling them out of the vector?

A: While I'm guessing the original poster is not freeing his "popped" pointers (pop doesn't do that for you), std::vector has another "feature" that may cloud it issue.  std::vector overallocate space such that every push_back doesn't entail a reallocation and copy of the existing contents.  In other words, the space used for vector is generally more than what's returned by .size().
Take a look at the shrink-to-fit idiom if you wish to make a std::vector take up no more space than it needs to hold its elements.    Not useful if you are constantly manipulating the vector, but once you have everything loaded, it can save some space.


text:
Q: Why does construction with a function not cause a memory leak? I have a matrix class and a transpose function (which is not part of the class) which looks like this:
matrix transpose(const matrix& rhs) {
    matrix Rmat(rhs.nc(),rhs.nr());
    for(unsigned ir = 0; ir < rhs.nr(); ir++) {
        for(unsigned ic = 0; ic < rhs.nc(); ic++ ) {
            Rmat(ic,ir) = rhs(ir,ic);
        }
    }
    return Rmat;
}

Now, when I declared matrix At(M,M) and then assign At = transpose(A), I get a memory leak. However, when I create At as matrix At(transpose(A)), I do not get a memory leak. Why is this leak happening? As I cannot pinpoint where it is occurring, I may not have included enough information. If constructors/destructors are required, please ask and I will post them.

A: If you wrote your matrix class, it is quite possible that your copy assignment operator or copy constructor has a memory leak. Per the rule of three, if you're going to define a destructor, then you need to also define copy assignment and copy constructor. Otherwise, you will get default copy assignment and copy constructor implementations that will not properly free any resources you allocated (e.g. with new).
To avoid these issues, you can use standard containers (e.g. vector, list, etc.) to store data, and/or smart pointers (e.g. auto_ptr, smart_ptr) to manage memory (semi-)automatically. These may save you from having to write a destructor (since the STL classes will clean up automatically), and thus save you from needing to also supply copy assignment and copy construction operations.


text:
Q: Why is the DNS Resolver necessary in a crawler architecture? In every paper I have read about crawler proposals, I see that one important component is the DNS Resolver.
My question is:
Why is it necessary? Can't we just make a request to http://www.some-domain.com/?

A:
DNS resolution is a well-known bottleneck in web crawling. Due to the
  distributed nature of the Domain Name Service, DNS resolution may
  entail multiple requests and round-trips across the internet,
  requiring seconds and sometimes even longer. Right away, this puts in
  jeopardy our goal of fetching several hundred documents a second.
There is another important difficulty in DNS resolution; the lookup
  implementations in standard libraries (likely to be used by anyone
  developing a crawler) are generally synchronous. This means that once
  a request is made to the Domain Name Service, other crawler threads at
  that node are blocked until the first request is completed. To
  circumvent this, most web crawlers implement their own DNS resolver as
  a component of the crawler.

http://nlp.stanford.edu/IR-book/html/htmledition/dns-resolution-1.html


text:
Q: multiple parameters with no annotation error on Javax WS and retrofit when I use "suspend" , how to handle? I am creating a very basic controller using Kotlin with javax.ws and retrofit libraries.
I created a controller like this...
@POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    suspend fun sayHello(request: StudentRequest): StudentResponse {

that basically calls another service.
But when I run the app I get this error:
[FATAL] Method public final java.lang.Object MyResource.sayHello(StudentRequest,kotlin.coroutines.Continuation) on resource class MyResource contains multiple parameters with no annotation. Unable to resolve the injection source.;

handlerConstructors=[org.glassfish.jersey.server.model.HandlerConstructor@a0bf272]},
 definitionMethod=public final java.lang.Object my.org.package.MyResource(sayHello,k**otlin.coroutines.Continuation**),

the weird part is that are couple of similar posts Jersey @PathParam : contains multiple parameters with no annotation
How can I pass multiple parameter to restful webservice using http post
https://github.com/dropwizard/dropwizard/issues/1115
but are not the same because my problem is with my ONLY parameter
There is no missing tag to my body request and I basically dont know what to look for at this point, any idea what could be wrong with this?
After debugging I noticed that there are two parameters, mine and one injected by Kotlin, when removing the "suspend" everything works fine, but then I am not able to make my async call.

A: To use coroutines from blocking code you need to use coroutine builder (e.g. launch {} or runBlocking {}).
Unfortunately in this case you can't just mark your glassfish controller as a suspendable function because framework don't know how to deal with continuations.


text:
Q: display row values depending on column values in python I am still a beginner in Python. I am reading a tab delimited text file generated from a software to filter out a set of values. But the values generated are all in a format similar to IEEE floating point format. (for example : 1.5656565656E+02).
My tab delimited file is something like this(actually it is 250 columns. roughly it is like this)
Time [s]       Offset_Angle              observability_Analysis
0.00E+00      0.89040261167028E+00        0.00000000000000E+00
4.32E+02      0.21319658757004E+00        0.00000000000000E+00
8.64E+02      0.26803683992125E+00        0.00000000000000E+00
1.30E+03      2.67379011780784E+02        1.00000000000000E+00
1.73E+03      2.89704767087971E+02        1.00000000000000E+00
2.16E+03      2.93302157473406E+02        1.00000000000000E+00

Th aim is  to filter those Offset_Angle values that have their observability_Analysis as 1.0000000000000E+00 But as of now I am trying to print the row number which has observability_Analysis as 1.0000000000000E+00.
The code i tried is like this
with open('E:\\trialpy\\textfile.txt') as f:
    reader = csv.reader(f, delimiter="\t")
    d = list(reader)

for ind in range(len(d)):
    if d[ind][2] == "1.00000000000000E+00":
        print ind

The first set of code works correctly. The print ind is just empty. It doesnt give any values. Please help me with this. And sorry if the question is very silly. Stuck at this place for sometime now. Is there a way to solve this or I have to switch to Pandas
Thanks.

A: The problem seems to be that csv reader cannot properly  process this data, so each line is saved as a single string into a list (row)...
with open('data.csv', 'r') as f1:
    r = csv.reader(f1, delimiter='\t')
    next(r, None) # skip first line
    for row in r:
        thirdc = row[0].split()[2]
        if float(thirdc) > 0.0:
            print(thirdc)

    1.00000000000000E+00
    1.00000000000000E+00
    1.00000000000000E+00


text:
Q: Sort sentences in list in order of text I have extracted some sentences from a text in Python. The text is stored in a string and the sentences in a list. Here's some sample input:
text = "This is a text. This is sentence 1. Here is sentence 2. And this is sentence 3."
extracted = ['Here is sentence 2.', 'This is a text']

Now I would like to order the elements from the list extracted according to their chronology in the text. This is my desired output:
ordered_result = ['This is a text', 'Here is sentence 2.']

Does anybody has an idea how to do so?
Thanks in advance.

A: Straightforwardly sort them by the position in the original string:
ordered_result = sorted(extracted, key=lambda x: text.index(x))

A: One way is to use a dictionary to construct an index mapping with O(n) complexity.
Then use sorted with a custom key, utilizing this dictionary.
This method relies on having a list of sentences to begin with. I've constructed one below in case you don't have this available.
text = "This is a text. This is sentence 1. Here is sentence 2. And this is sentence 3."

extracted = ['Here is sentence 2.', 'This is a text.']

# create list of sentences
full_list = [i.strip()+'.' for i in filter(None, text.split('.'))]

# map sentences to integer location
d_map = {v: k for k, v in enumerate(full_list)}

# sort by calculated location mapping
extracted_sorted = sorted(extracted, key=d_map.get)

['This is a text.', 'Here is sentence 2.']

A: The preferred (but slightly more complex) way to do this is to use a regex search:
import re

expression = re.compile(r'([A-Z][^\.!?]*[\.!?])')
text = "This is a text. This is sentence 1. Here is sentence 2. And this is sentence 3."

# Find all occurences of `expression` in `text`
match = re.findall(expression, text)

print match
# ['This is a text.', 'This is sentence 1.', 'Here is sentence 2.', 'And this is sentence 3.']

The trivial (but simpler) way to do this is to split it on ". " and then you have your list of sentences, in chronological order. The only downside to this is you lose the punctuation.
text = "This is a text. This is sentence 1. Here is sentence 2. And this is sentence 3."
splitt = text.split(". ")

print splitt
# splitt = ['This is a text', 'This is sentence 1', 'Here is sentence 2', 'And this is sentence 3.']


text:
Q: how can i join with an id number vs list string id I have table 1: with id is a number int,
Table 2 contain references id 1 like this: '1,2,3...', you can see more detail bellow:
WITH TB1 AS(
     SELECT 1 ID FROM DUAL UNION ALL
     SELECT 2 ID FROM DUAL UNION ALL
     SELECT 3 ID FROM DUAL
), TB2 AS
(
   SELECT 'A' NAMES, '1,2' IDREF FROM DUAL
)
SELECT t1.*, t2.Names FROM TB1 t1 join tb2 t2 on t1.id in t2.idref

How can i join tb1 vs tb2 by id in?

A: You can join using the LIKE operator, with a small trick baked into the cake:
SELECT t1.*
FROM TB1 t1
INNER JOIN TB2 t2
    ON ',' || t2.IDREF || ',' LIKE '%,' || t1.ID || ',%'

Taking ID=1 for example, the idea here is to look for ,1, the following CSV string:
,1,2,

We can prepend and postpend a comma to the IDREF column, to ensure that every isolated ID value is delimited by a comma on both sides.  Then, simply search for a given ,ID,, with commas on both sides.
Demo

A: Try:
WITH TB1 AS(
     SELECT 1 ID FROM DUAL UNION ALL
     SELECT 2 ID FROM DUAL UNION ALL
     SELECT 3 ID FROM DUAL
), TB2 AS
(
   SELECT 'A' NAMES, '1,2' IDREF FROM DUAL
)
select T1.*, T2.*
from TB1 T1
    join TB2 T2 on T1.id in (select regexp_substr(T2.IDREF,'[^,]+', 1, level) as list from dual
                                            connect by regexp_substr(T2.IDREF, '[^,]+', 1, level) is not null)

A: Do not store the values as a string list.
Either use a collection and the MEMBER OF operator:
SQL Fiddle
Oracle 11g R2 Schema Setup:
CREATE TYPE IntList IS TABLE OF INTEGER

Query 1:
WITH TB1 ( ID ) AS (
     SELECT 1 FROM DUAL UNION ALL
     SELECT 2 FROM DUAL UNION ALL
     SELECT 3 FROM DUAL
),
TB2 ( names, idref ) AS (
   SELECT 'A', IntList( 1,2 ) FROM DUAL
)
SELECT t1.*,
       t2.Names
FROM   TB1 t1
       join tb2 t2
       on t1.id MEMBER OF t2.idref

Results:
| ID | NAMES |
|----|-------|
|  1 |     A |
|  2 |     A |

Or separate your list into its own table so that you can properly reference the foreign keys of TB1:
Query 2:
WITH TB1 ( ID ) AS (
     SELECT 1 FROM DUAL UNION ALL
     SELECT 2 FROM DUAL UNION ALL
     SELECT 3 FROM DUAL
),
TB2 ( names ) AS (
   SELECT 'A' FROM DUAL
),
TB3 ( names, idref ) AS (
   SELECT 'A', 1 FROM DUAL UNION ALL
   SELECT 'A', 2 FROM DUAL
)
SELECT t1.*,
       t2.Names
FROM   TB1 t1
       join tb3 t3
       on t1.id = t3.idref
       join tb2 t2
       on t2.names = t3.names

Results:
| ID | NAMES |
|----|-------|
|  1 |     A |
|  2 |     A |


text:
Q: Dimensionar altura do header dinamicamente Então, eu tenho a seguinte estrutura HTML

    Esse é o cabeçalho

Esse é o artigo que vem sobre do cabeçalho

Tenho umas 10 div's dessa uma abaixo da outra.
O problema: Tem header que tem um texto muto grande tipo umas 10 palavras e outros menores. Então, quando vou reduzir a tela para mobile o header que antes ocupava 1 linha agora passa a ocupar 2 linhas.
E isso, atrapalha o uso do line-height de apenas 1 linha.
Existe algum recurso onde eu consigo calcular em tempo de execução e aplicar para cada header o line-header correspondente?
Atualmente estou fazendo algo como:
div > header {
   height: 50px;
   line-height: 50px;
}

Mas isso só funciona para uma linha.
Algum recurso?

A: Ao avaliar esse estrutura percebe-se claramente que vc tentou centralizar verticalmente o texto dentro da div usando um line-height: 50px; com o mesmo valor do height: 50px;. Não é que isso seja totalmente errado, mas é gambiarra, não se deve usar line-height para fazer alinhamento de texto... line-height  é para controlar o distanciamento entre uma linha é outra, não para centralizar nada, 90% das vezes que vejo essa propriedade sendo usada é de maneira equivocada, a utilidade dela é apenas para formatação tipográfica do texto.

The line-height CSS property sets the height of a line box. It's commonly used to set the distance between lines of text.

Recomendo que entre nesse link para ver a propriedade funcionando em um exemplo prático e ver a documentação e aplicação https://developer.mozilla.org/en-US/docs/Web/CSS/line-height
Uma alternativa simples é colocar display: flex na div > header  e alinhar o texto com align-itens: center. Assim mesmo que o texto quebre linha ele se manterá no centro do header

header,
article {
  border: 1px solid #000;
}
div > header {
   height: 50px;
   display: flex;
   align-items: center;
}

  Esse é o cabeçalho

Esse é o artigo que vem sobre do cabeçalho

  Esse é o cabeçalho Lorem ipsum dolor sit amet Lorem ipsum dolor sit amet consectetur adipisicing elit. autem!

Esse é o artigo que vem sobre do cabeçalho


text:
Q: .Net Core Automapper with many to many relationship problem I am new with Automapper and I have a problem with mapping my classes which have many-to-many relationships.
I think I need something like nested mapping but the documentation does not seem for me clearly. I know that I am doing something wrong with AutoMapper configuration but I can't figure out what's wrong.
When I am adding a new book to the database I would like to receive information about the book and the authors who are written the book. (expected JSON result is below)
I have the following classes:
    public class Book
    {
        public int BookId { get; set; }
        public string Title { get; set; }
        public string ISBN { get; set; }
        public string Category { get; set; }
        public int PublisherId { get; set; }
        public Publisher Publisher { get; set; }
        public ICollection<BookAuthor> BooksAuthors { get; set; }
}

    public class Author
    {
        public int AuthorId { get; set; }
        public string AuthorName { get; set; }
        public string AuthorLastName { get; set; }
        public ICollection<BookAuthor> BooksAuthors { get; set; }
    }

    public class BookAuthor
    {
        public int BookId { get; set; }
        public Book Book { get; set; }

        public int AuthorId { get; set; }
        public Author Author { get; set; }
    }

DTOs
    public class BookForNewDto
    {
        public string Title { get; set; }
        public string ISBN { get; set; }
        public string Category { get; set; }
        public int PublisherId { get; set; }
        public ICollection<AuthorForNewBookDto> Authors { get; set; }
    }

    public class AuthorForNewBookDto
    {
        public int AuthorId { get; set; }
    }

BookController (AddBook)
        public async Task<IActionResult> AddBook([FromBody] BookForNewDto bookForNewDto)
        {
            var bookToCreate = _mapper.Map<Book>(bookForNewDto);

            var bookToReturn = _mapper.Map<BookForNewDto>(bookToCreate);

            var bookToAdd = await _context.Books.AddAsync(bookToCreate);

            await _context.SaveChangesAsync();

            var bookIdToAdd = bookToCreate.BookId;
            var authorIdToAdd = bookForNewDto.Authors.Select(aa => aa.AuthorId).ToList();

            foreach (var item in authorIdToAdd)
            {
                var bookAuthorToAdd = new BookAuthor()
                {
                    BookId = bookIdToAdd,
                    AuthorId = item
                };
                var newBookAuthor = await _context.BooksAuthors.AddAsync(bookAuthorToAdd);
                await _context.SaveChangesAsync();
            }

            return Ok(bookToReturn);
        }

AutoMapper Profiler // I attached only the section which concerns Adding a new book.
public class AutoMapping : Profile
    {
        public AutoMapping()
        {

            CreateMap<BookForNewDto, Book>();
            CreateMap<Book, BookForNewDto>()
                .ForMember(dto => dto.PublisherId, opt => opt.MapFrom(x => x.PublisherId))
                .ForMember(dto => dto.Authors, c => c.MapFrom(c => c.BooksAuthors));

            CreateMap<BookForNewDto, AuthorForNewBookDto>()
                .ForMember(dto => dto.AuthorId, opt => opt.MapFrom(x => x.Authors.Select(aaa => aaa.AuthorId)));
        }

My question is how do I configure my AutoMapper Profiler to get the JSON result below? I have a problem with the authors. I'm still getting an empty list.
{
    "title": "sample title",
    "isbn": "123-41-5-12311",
    "category": "test",
    "publisherId": 1,
    "authors": [
            {
                "authorId": 43
            },
            {
                "authorId": 45
            },
            {
                "authorId": 134
            },
}

A: You have to remember that automapper relies on property names to identify which "automap" can be done. They need to be identical if you want Automapper to automap them.
In your case with this line of code:
var bookToCreate = _mapper.Map<Book>(bookForNewDto);

you are trying to map a BookForNewDto entity to a Book one. What you are missing is the fact that BookForNewDto has a property called Authors and Book has a property called BooksAuthors. Automapper will never know that Authors and BooksAuthors is what it should map.
So you need to specify this configuration with 1 line of code in your Automapper configuration:
CreateMap<BookForNewDto, Book>() (this line is already present)
                    .ForMember(dto=>dto.BooksAuthors, opt => opt.MapFrom(x => x.Authors));

Now if you debug your code you'll see that the ICollection BooksAuthors has been mapped from your BookForNewDto.
Next mapping you need to add is also the AuthorForNewBookDto and BookAuthor since they are present in your 2 entities: remember that if you don't specify it, automapper will set null to your values.
Here the final automapper configuration:
CreateMap<BookForNewDto, Book>()
                .ForMember(dto=>dto.BooksAuthors, opt => opt.MapFrom(x => x.Authors));
CreateMap<Book, BookForNewDto>()
                .ForMember(dto => dto.PublisherId, opt => opt.MapFrom(x => x.PublisherId))
                .ForMember(dto => dto.Authors, c => c.MapFrom(c => c.BooksAuthors));

CreateMap<BookForNewDto, AuthorForNewBookDto>()
               .ForMember(dto => dto.AuthorId, opt => opt.MapFrom(x => x.Authors.Select(aaa => aaa.AuthorId)));
CreateMap<AuthorForNewBookDto, BookAuthor>();
CreateMap<BookAuthor, AuthorForNewBookDto>();


text:
Q: Ninject getting Null when use StandardKernel.Get() I have two branches under my master interface,
and try to use Ninject IOC here to dynamically load proper class based on some condiction. here is my description of my class structure and problem I have
  Interface I
  {
      Void method1 ();
      Void method2 ();
      Void method3 ();
  }

Abstract class A : I
{
      Abstract void method1 ();
      Abstract void method2 ();
      Void Method3() {  //Some implementation can be shared by all classes    }
}

Branch 1
Abstract Class B : A
{
      void method1 () {   //Some implementation can be shared by B1, B2   }
}

B1 and B2 are lowest level classes in branch1, which will be used in the code
Class B1 : B
{
      Void Method2() {  //Some implementation    }
}

Class B2 : B
{
      Void Method2() {  //Some implementation    }
}

But there is another branch start from inhabitant from  Abstract class A, as following
Branch 2
Abstract Class C : A
{
      void method1 ()
      {
         //Some implementation which is different from in B.Method1
         //and can be shared by C1
      }
}

C1 are lowest level classes in branch2, which will be used in the code
Class C1 : C
{
       Void Method2() {  //Some implementation    }
}

I use Ninject to bind and get to load classes dynamically, like below:
Bind<I>().To<B1>();
Bind<I>().To<B2>();
Bind<I>().To<C1>();

And  retrieve them like using kernel.Get<I>();
Now the issue is that B1 and B2 are retuned ok, but when I retrieve C1, it always throw an null error. Am I missing something here? Any help is appreciated

A: The detail is too long for the comment, so I had to put it in another section
When I use watch I see this: Value cannot be null.Parameter name: source
stackTrace is:
 at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source, Func`2 predicate)
   at ThePoint.Ingestion.Abstract.FeedsProcessor..ctor() in c:\Users\houyang\Documents\GitHub\The-Point-Redesign\ThePoint.Ingestion\Abstract\FeedsProcessor.cs:line 34
   at ThePoint.Ingestion.Abstract.WebServiceFeedsProcessor..ctor()
   at ThePoint.Ingestion.Concrete.GannettLocalProcessorTest..ctor()
   at DynamicInjector08125ba6b65f454d9309fa177f39cd2d(Object[] )
   at Ninject.Activation.Providers.StandardProvider.Create(IContext context) in c:\Projects\Ninject\ninject\src\Ninject\Activation\Providers\StandardProvider.cs:line 97
   at Ninject.Activation.Context.Resolve() in c:\Projects\Ninject\ninject\src\Ninject\Activation\Context.cs:line 157
   at Ninject.KernelBase.<>c__DisplayClass10.<Resolve>b__c(IBinding binding) in c:\Projects\Ninject\ninject\src\Ninject\KernelBase.cs:line 386
   at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
   at System.Linq.Enumerable.<CastIterator>d__b1`1.MoveNext()
   at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source)
   at Ninject.ResolutionExtensions.Get[T](IResolutionRoot root, IParameter[] parameters) in c:\Projects\Ninject\ninject\src\Ninject\Syntax\ResolutionExtensions.cs:line 37


text:
Q: Implementing \luaescapestring in plain e-TeX I'm trying to implement \luaescapestring in plain e-TeX. My solution needs to be fully expandable, so that \immediate\write\luascript{ local file = "\luaescapestring{\something}" } works. The following code is almost there, but it consumes space characters:
\def\luaescapestring#1{%
  \expandafter\expandafter\expandafter\expandafter\expandafter\expandafter
  \expandafter\next\expandafter\expandafter\expandafter\gobbleone
  \expandafter\detokenize\expandafter{\csname#1\endcsname}\relax}%
\def\gobbleone#1{}%
\begingroup
  \catcode`\"=12%
  \catcode`\|=0%
  \catcode`\\=12%
  |gdef|next#1{%
    |if#1|relax|else
      |if#1"%
        \"|expandafter|expandafter|expandafter
          |next
      |else
        |if#1\%
          \\|expandafter|expandafter|expandafter|expandafter
            |expandafter|expandafter|expandafter|next
        |else
          #1|expandafter|expandafter|expandafter|expandafter
            |expandafter|expandafter|expandafter|next
        |fi
      |fi
    |fi}%
|endgroup

A code similar to the one used in the letterspacing.tex package takes into account the spaces, but \futurelet spoils the party.

A: I used OPmac trick 0153, so I needed to define the \eapply macro only:
\def\tmp#1{}\edef\nb{\expandafter\tmp\string\\}  % \nb is normal backslash

\def\luaescapestring#1{\etoksA #1{\end}}
\def\etoksA#1#{\etokssB#1 {\end} }
\def\etokssB#1 #2 {\etoksC#1\end
    \ifx\end#2\empty\expandafter\etoksD\else\space\fihere{\etokssB#2 }\fi}
\def\etoksC#1{\ifx\end#1\else\eapply{#1}\expandafter\etoksC\fi}
\def\etoksD#1{\ifx\end#1\empty\else\fihere{{\luaescapestring{#1}}\etoksA}\fi}
\def\fihere#1\fi{\fi#1}

\def\eapply#1{\ifx"#1\nb"\else\bbstring#1\fi}
\def\bbstring#1{\expandafter\bbstringA\string#1}
\def\bbstringA#1{\expandafter\ifx\nb#1\nb\fi#1}

%test:
\message{...\luaescapestring{"a"\ hah ah \a}}

\end

The \message command expands its parameter and prints ...\"a\"\\ hah ah \\a in our example.
Note that you need not any special eTeX primitive. All is done by classical TeX.


text:
Q: FPDF Error: Error while decompressing stream I've built a web application incorporating the fpdf library which allows clients to upload pdf files which my system then combines into a monthly report (adding a cover, contents page etc.).
Last month I got this error:
FPDF Error: Error while decompressing stream
I've googled it and the only people who have encountered it before seem to be German!
The error handler is at line 241 of fpdi_pdf_parser.php and refers to "case '/FlateDecode':" and other things I don't understand.
I traced the problem to a single pdf file which appeared normal but consistently caused the problem. I created a new version of the pdf by screen grabbing from the old one and when I uploaded that everything worked.
As I say I got round the problem but don't really understand how and don't want to run into the same thing again.
Any ideas what was going on?
Thanks in advance.

A: PDF files can be compressed in different ways with different algorithms, if your application is open to receive any file it is possible that you got a corrupt one that FPDF was not able to decompress. Even in such scenarios (I mean corrupt files) other PDF parsers/readers may be able to recover the file and show the content (or some part of it), but it does not mean the file is valid.
It is also possible that this file contains some specific feature from the PDF specification that is not supported by FPDF. If it is an option for you to post the offending file it might be possible to narrow down the issue a bit more.

A: usual in such cases helps install or update zlib module by PHP. The problem also arises due to the pictures are inserted into the pdf-document (see requirements by image on http://www.fpdf.org/en/doc/image.htm).


text:
Q: Unique combinations I'm looking to examine unique combinations of 7 binary variables (cannabis modes of delivery [yes/no]) and was under the impression this should be a fairly simple task in SAS. However, all of the coding examples I've come across online seem a bit overcomplicated for such a basic process. If anyone has insight regarding this concept I would appreciate it!

A: So if you want the counts probably it easiest to use PROC SUMMARY.
proc summary data=have nway missing ;
  class var1-var7 ;
  output out=want(rename=(_freq_=count));
run;

A: proc sort data=yourdataset(Keep=Variables to examine seperated by blanks) out=choose_a_name noduprec;
  by Variables to examine seperated by blanks;
run;

Resulting dataset choose_a_name will contain all unique combinations of examined variables.


text:
Q: How to properly handle errors while consuming messages? I'm consuming messages with spring-integration-kafka, using a message-driven-channel-adapter:
<int-kafka:message-driven-channel-adapter
    id="kafkaListener"
    listener-container="container1"
    channel="outputFromKafka"
    error-channel="errorChannel"/>

The container uses a JsonDeserializer to deserialize the incoming JSON to an object:
<beans:bean id="container1" class="org.springframework.kafka.listener.KafkaMessageListenerContainer">
    <beans:constructor-arg>
        <beans:bean class="org.springframework.kafka.core.DefaultKafkaConsumerFactory">
            <beans:constructor-arg>
                <beans:map>
                    <beans:entry key="bootstrap.servers" value="localhost:9092" />
                    <beans:entry key="key.deserializer" value="org.apache.kafka.common.serialization.StringDeserializer" />
                    <beans:entry key="group.id" value="mygroup" />
                </beans:map>
            </beans:constructor-arg>
           <beans:property name="valueDeserializer">
                <beans:bean class="org.springframework.kafka.support.serializer.JsonDeserializer">
                    <beans:constructor-arg value="com.foo.MyType"/>
                </beans:bean>
            </beans:property>
        </beans:bean>
    </beans:constructor-arg>
    <beans:constructor-arg>
        <beans:bean class="org.springframework.kafka.listener.config.ContainerProperties">
            <beans:constructor-arg name="topics" value="foo" />
        </beans:bean>
    </beans:constructor-arg>
</beans:bean>

If the message can't be parsed successfully (e.g. because the consumer accidentally uses the wrong type), an exception is thrown:
ERROR org.apache.kafka.clients.NetworkClient - Uncaught error in request completion: org.apache.kafka.common.errors.SerializationException: Can't deserialize data ...

After this, the adapter is receiving the same message again (probably because the last one wasn't committed?), and fails in exactly the same way, resulting in an endless stream of exceptions.
It looks like the configured error-channel is not used.
What are the options to handle errors like this, and how is it configured in XML?

A:
It looks like the configured error-channel is not used.

What makes you believe that?
I just ran a test with the error channel set to errorChannel (the default, with a logging adapter)...
12:06:08.366 [container-kafka-consumer-1] ERROR o.s.i.handler.LoggingHandler - ...

Can you provide a debug log snippet for org.springframework.integration showing a failure?
EDIT
Oh, sorry...
ERROR org.apache.kafka.clients.NetworkClient - Uncaught error in request completion: org.apache.kafka.common.errors.SerializationException: Can't deserialize data ...

That's much lower down in the stack before Spring Integration gets the message.


text:
Q: Workflow Copy List Items Disappearing Scenario: I created a workflow in SharePoint Designer that takes the name of a person that's in a single line item column (Column A) and copies it to another column (Column B) (in the same list) that is a people and group.  When I add an item to Column A and the workflow starts the person's name no longer appears instead "No Title" and then there is nothing in Column B.
Can you help me figure out I am doing wrong? I do not want the information in Column A to disappear I want to copy it in Column B.  Here is my workflow.
Update item Current Item

Set this field: Column A

to

To this value: Column B

A: You need to set Column B to the value of Column A.
Ensure the user name in Column A is formatted as "domain\user".
In the following case, it sets managers (people and group field) to the value of UserName (single line of text field):


text:
Q: Pandas performance: Multiple dtypes in one column or split into different dtypes? I have huge pandas DataFrames I work with. 20mm rows, 30 columns. The rows have a lot of data, and each row has a "type" that uses certain columns. Because of this, I've currently designed the DataFrame to have some columns that are mixed dtypes for whichever 'type' the row is.
My question is, performance wise, should I split out mixed dtype columns into two separate columns or keep them as one? I'm running into problems getting some of these DataFrames to even save(to_pickle) and trying to be as efficient as possible.
The columns could be mixes of float/str, float/int, float/int/str as currently constructed.

A: Seems to me that it may depend on what your subsequent use case is. But IMHO I would make each column unique type otherwise functions such as group by with totals and other common Pandas functions simply won't work.


text:
Q: VUE with vue-rx / rxjs : How to create a subscription with $watchAsObservable using filter and interval I need the help in the following vue-rx / RxJs question.
I have to make a subscription in vue-rx that watches a props value, and when it is true then it calls a http request in every 500 ms, and stops it when it is false, or when the returned value is 'COMPLETED'.
I tried something like this:
export default {
  props: ['started'],
  subscriptions() {
   return {
    currentHttpState: this.$watchAsObservable('started')
                      .pipe(pluck('newValue'),filter(value => value === false))
                      .switchMap(() => interval(500).pipe(switchMap(() => this.callHttpRequest()),distinctUntilChanged())),

Thank you for the help!

A: I'm not too familiar with vue (or vue-rx), so this may just be half the answer (the RxJS bit).
I'm assuming this.$watchAsObservable('started') with pluck('newValue') is a stream of true and false? (reflecting the value of the started prop)
If so, I would use switchMap to switch between an interval/timer and nothing.
currentHttpState: this.$watchAsObservable('started').pipe(
  pluck('newValue'),
  map(val => val? timer(0,500) : EMPTY),
  switchMap(timer$ => timer$.pipe(
    switchMap(_ => this.callHttpRequest()),
    takeWhile(result => result.status !== 'COMPLETED')
  )
)

that second switchMap will have the effect that if a call takes over 500ms to complete, it will be dropped and you'll never see the results. This also unsubscribed if the takeWhile() condition isn't met - so you'll have to change that to meet your specific requirements.