text:
Q: how to use firebase auth in Polymer 3? Im very confused cause before I did an authentication with firebase in Polymer 2 but now I cant :( I just have this simple component to test:

import { LitElement, html } from 'lit-element';
import firebase from '@firebase/app';
import '@firebase/auth';
import '@firebase/firestore';
//import firebase from 'firebase/app';
import '@polymer/paper-button/paper-button.js';

class DataAuth extends LitElement {
  autenticar(){

  firebase.initializeApp(
    {
      apiKey: "",
      authDomain: "",
      databaseURL: "",
      projectId: "",
      storageBucket: "",
      messagingSenderId: ""
  }
  )

  const autentica = firebase.auth();
  var provider = new firebase.auth.GoogleAuthProvider();
  autentica.signInWithPopup(provider).then(function(result) {
    // This gives you a Google Access Token. You can use it to access the Google API.
    var token = result.credential.accessToken;
    // The signed-in user info.
    var user = result.user;
    console.log(user);
    // ...
  }).catch(function(error) {
    // Handle Errors here.
    var errorCode = error.code;
    var errorMessage = error.message;
    // The email of the user's account used.
    var email = error.email;
    // The firebase.auth.AuthCredential type that was used.
    var credential = error.credential;
    // ...
  });
  }

  render() {
    return html`
    <paper-button raised @click="${this.autenticar}">Autenticar</paper-button>
    `;
  }
}
customElements.define('data-auth', DataAuth);

And I import it in view1 in the polymer proyect but I got this error:

And I realy dont know why, Im new in Polymer :(, please I realy apreciate any help

A: Try to install firebase dependencies outside polymer. Like Index file
index.html
 <script src="https://www.gstatic.com/firebasejs/5.8.4/firebase-app.js"></script>
 <script src="https://www.gstatic.com/firebasejs/5.8.4/firebase-auth.js"></script>
 <script src="https://www.gstatic.com/firebasejs/5.8.4/firebase-database.js"></script>
 <script src="https://www.gstatic.com/firebasejs/5.8.4/firebase-messaging.js"></script>

 <script>
   // Initialize Firebase
   var config = {
     apiKey: "Api - key - String",
     authDomain: "<api-name>.firebaseapp.com",
     databaseURL: "https://<api-name>.firebaseio.com",
     projectId: "<api-name>",
     messagingSenderId: "1013602754277"
   };
   firebase.initializeApp(config);
 </script>

I use Firebase without problem with the above
And check user status inside like: (you may fire this func. after lazy-loading.)
checkUserStatus(){
    firebase.auth().onAuthStateChanged((user)=> {
      if (user) {
         // User is signed In.
         console.log("signed IN..");
      } else {
        // User is signed out.
         console.log("signed out..");
      }

    });
}

A: @HakanC thanks a lot, but when I use the command: npm run build (wich acording with the package.json is: "build": "polymer build --auto-base-path && gulp prpl-server", )
I don't know why have this errors :(:

0 info it worked if it ends with ok
1 verbose cli [ 'C:\\Program Files\\nodejs\\node.exe',
1 verbose cli   'C:\\Users\\Marcos\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-cli.js',
1 verbose cli   'run',
1 verbose cli   'build' ]
2 info using npm@6.0.1
3 info using node@v8.11.1
4 verbose run-script [ 'prebuild', 'build', 'postbuild' ]
5 info lifecycle pwa-starter-kit@0.9.0~prebuild: pwa-starter-kit@0.9.0
6 info lifecycle pwa-starter-kit@0.9.0~build: pwa-starter-kit@0.9.0
7 verbose lifecycle pwa-starter-kit@0.9.0~build: unsafe-perm in lifecycle true
8 verbose lifecycle pwa-starter-kit@0.9.0~build: PATH: C:\Users\Marcos\AppData\Roaming\npm\node_modules\npm\node_modules\npm-lifecycle\node-gyp-bin;C:\Users\Marcos\Dropbox\proyectos web\polymer3\my-app\node_modules\.bin;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\ProgramData\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\;C:\Program Files\Microsoft SQL Server\110\Tools\Binn\;C:\Program Files (x86)\Windows Live\Shared;C:\Program Files\Microsoft\Web Platform Installer\;C:\Program Files\Calibre2\;;C:\Program Files (x86)\Windows Kits\8.1\Windows Performance Toolkit\;C:\Program Files\Microsoft SQL Server\120\Tools\Binn\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\WINDOWS\system32\config\systemprofile\.dnx\bin;C:\Program Files\Microsoft DNX\Dnvm\;C:\Program Files\Git\cmd;C:\ProgramData\ComposerSetup\bin;C:\PHP7;C:\curl-7.58.0\src;C:\Program Files\nodejs\;C:\Program Files (x86)\Panda Security\WaAgent\Common;C:\Program Files (x86)\Pinnacle\Shared Files\;C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\130\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\130\Tools\Binn\;C:\Program Files\Microsoft SQL Server\130\Tools\Binn\;C:\Program Files\Microsoft SQL Server\130\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL Server\Client SDK\ODBC\130\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\140\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL Server\140\DTS\Binn\;C:\Program Files (x86)\Microsoft SQL Server\140\Tools\Binn\ManagementStudio\;;C:\Program Files (x86)\Compac\SDK\Librerias Interfaz;C:\Program Files\Microsoft VS Code\bin;C:\Program Files (x86)\Yarn\bin\;C:\RailsInstaller\Git\cmd;C:\RailsInstaller\Ruby2.1.0\bin;C:\Program Files (x86)\Microsoft VS Code\bin;C:\Users\Marcos\AppData\Local\Microsoft\WindowsApps;C:\Users\Marcos\AppData\Local\Programs\Fiddler;C:\Users\Marcos\AppData\Roaming\Composer\vendor\bin;C:\Users\Marcos\AppData\Local\GitHubDesktop\bin;C:\Users\Marcos\AppData\Local\Microsoft\WindowsApps;C:\Users\Marcos\AppData\Roaming\npm;C:\Users\Marcos\AppData\Local\Yarn\bin
9 verbose lifecycle pwa-starter-kit@0.9.0~build: CWD: C:\Users\Marcos\Dropbox\proyectos web\polymer3\my-app
10 silly lifecycle pwa-starter-kit@0.9.0~build: Args: [ '/d /s /c',
10 silly lifecycle   'polymer build --auto-base-path && gulp prpl-server' ]
11 silly lifecycle pwa-starter-kit@0.9.0~build: Returned: code: 3  signal: null
12 info lifecycle pwa-starter-kit@0.9.0~build: Failed to exec build script
13 verbose stack Error: pwa-starter-kit@0.9.0 build: `polymer build --auto-base-path && gulp prpl-server`
13 verbose stack Exit status 3
13 verbose stack     at EventEmitter.<anonymous> (C:\Users\Marcos\AppData\Roaming\npm\node_modules\npm\node_modules\npm-lifecycle\index.js:283:16)
13 verbose stack     at emitTwo (events.js:126:13)
13 verbose stack     at EventEmitter.emit (events.js:214:7)
13 verbose stack     at ChildProcess.<anonymous> (C:\Users\Marcos\AppData\Roaming\npm\node_modules\npm\node_modules\npm-lifecycle\lib\spawn.js:55:14)
13 verbose stack     at emitTwo (events.js:126:13)
13 verbose stack     at ChildProcess.emit (events.js:214:7)
13 verbose stack     at maybeClose (internal/child_process.js:925:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:209:5)
14 verbose pkgid pwa-starter-kit@0.9.0
15 verbose cwd C:\Users\Marcos\Dropbox\proyectos web\polymer3\my-app
16 verbose Windows_NT 10.0.16299
17 verbose argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Users\\Marcos\\AppData\\Roaming\\npm\\node_modules\\npm\\bin\\npm-cli.js" "run" "build"
18 verbose node v8.11.1
19 verbose npm  v6.0.1
20 error code ELIFECYCLE
21 error errno 3
22 error pwa-starter-kit@0.9.0 build: `polymer build --auto-base-path && gulp prpl-server`
22 error Exit status 3
23 error Failed at the pwa-starter-kit@0.9.0 build script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 3, true ]


text:
Q: In VS 2005 How do I generate the connection strings for web.config? I thought that VS 2005 automatically generated the connection strings in the web.config, however I can't for the life of me remember how.

A: Ah figured it out on my own. In the design view drag in the sql data source object and configure from there.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Setting up a second Angular application on same server using NGINX I currently have a AngularJS application running on my virtual private server. To run this I'm using NGINX, Node and 'http-server' and pm2 to keep everything running.
So I start my backend using for example 'node server.js' (port 3000) and I setup a second process of 'http-server' (which I think runs on port 8080) in the public folder.
This is the configuration of my NGINX:
server {
listen 80;
server_name mywebsite.be;

location /{
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_set_header X-NginX-Proxy true;
    proxy_pass    http://127.0.0.1:3000/;
}
}

Now I would like to setup a second application which is made with Angular (2). I'm trying to also run my backend with node on port 3001 and then starting http-server on port 8081.
How should I configure my NGINX?

A: Just add a second location with the correct proxy_pass directive (based on your configuration):
location /otherlocation {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_set_header X-NginX-Proxy true;
    proxy_pass    http://127.0.0.1:3001/;
}

You can match on location or if you wish, on a second diffrent domain.

A: Federico's answer helped me further but I also wanted to post my final solution.
I setup two locations right now, one for the backend (api) and one for the gui.
location /backend/ {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_set_header X-NginX-Proxy true;
    proxy_pass    http://127.0.0.1:3001/;
}
location /gui/ {
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_set_header X-NginX-Proxy true;
    proxy_pass    http://127.0.0.1:4200/;
}

This works for me for now! :)


text:
Q: Python Mechanize/BeautifulSoup Scraping (Iterating over Dictionaries) I am currently scraping a site using BS and Mechanize, and I was able to get my scraper working for an instance, but I want to iterate over a dictionary, inserting a value each type it loops. Because I am a total noob to python (my apologies), I am having trouble understanding how to do just that.
See code below for one value:
import mechanize
import cookielib
import csv
from bs4 import BeautifulSoup as BS

ids = csv.DictReader(open("csv_to_scrape.csv"))
persons = [person for person in ids]

br = mechanize.Browser()
br2 = mechanize.Browser()
cj = cookielib.LWPCookieJar()

br.set_cookiejar(cj)
br2.set_cookiejar(cj)

br.open('https://www.example.com')

br.select_form(nr=0)
br.form['licenseNumber'] = '012345' #This is the value that comes from my dict.
br.submit()

for link in br.links(url_regex="/details"):
    req = br.click_link(url=link.url)
    html = br2.open(req).read()

soup = BS(html)
text1 = soup.find('div', {'class':'infobox append-bottom span-11'}).text
text2 = soup.find('div', {'class':'infobox append-bottom'}).text

f = open('output.csv', 'w')
x = '012345'
write_to_file = x + "," + '"""' + text2 + '"""' + "," + '"""' + text1 + '"""' + "\n"
write_to_unicode = write_to_file.encode('utf-8')
print x
f.write(write_to_unicode)
f.close()

I have a basic dict that looks like this:
[{'': '3008', 'name': 'Doe, John', 'date': '05-09-89', 'location': 'New York, NY', 'action': 'Dance', 'id': '012345'}, {'': '3080', 'name': 'Smith, John', 'date': '12-04-92', 'location': 'San Francisco, CA', 'action': 'Singing', 'id': '543210'}, etc.....

I am trying to iterate with 'id', putting it into the form below where 'licenseNumber' is and then append it to another dict or write it to a csv.
I know this is probably very easy (and basic), but I've been stuck for two days (putting in 10 hours a day). Any help would be greatly appreciated.

A: Getting an item from your dictionary is incredibly easy in python.  Just call the get method on the dictionary and pass it the key you want.  For example: dictionary.get(key).  In your case, your key would be your 'id.'
Because you show a list of dictionaries and you mention iteration, here's a quick line of code to extract all of the ids from your list of dictionaries.
list_of_ids = [_dict.get("id") for _dict in list_of_dicts]

That's it.  Now you can iterate over the list and input the id into your form -- which may mean that you need to nest your current for loop but it's not clear from your code, so I won't say.
I hope that helps, and I apologize if I'm totally misinterpreting your question.


text:
Q: Overall Unique count from two tables in MySQL I have two tables, both having column a device_id column that I want to count. For the purposes of demonstration, the schema looks like:
Table 1: 'id', 'save_val', 'device_id_major'
Table 2: 'id', 'save_val', 'location', 'device_id_team'

Table 1 could have many of the same 'device_id_major'.
I basically want to get the unique device_id's from both tables, then from that result set, get the count of unique device_id's (the same device_id can appear in both tables).
Is this possible in one query?

A: select distinct aa.device_id, count(*)
from(select distinct device_id from table1
union all
select distinct device_id from table2) as aa
group by device_id
order by device_id

Or something like... As I don't have the schema to hand, I can't fully validate it.

A: SELECT count(DISTINCT aa.id)
FROM (SELECT DISTINCT major_id AS id FROM `major`
UNION ALL
SELECT DISTINCT team_id AS id FROM `team`)
AS aa

This seems to do the trick.

A: You could use a query that takes the UNION of both tables, then SELECT the unique values.


text:
Q: Which is the best way define Lie derivative? I read 2 main definitions of the Lie derivative. One is done using the concept of flow and the pullback-pushfoward while the other one uses the algebraic with axioms. Both of these can be found on wikipedia. I know that these ways are equivalent but I sort of need to find a principal one. Since I am studying this alone and I don't have a unique definition given by a professor I started wondering which one is the best/most correct way to define the Lie derivative for vector and tensor fields so here I am in trouble also in understanding it. So, in which way should I define this in differential geometry ?

A: My opinion is that the definition using flows is the clearest, because it shows in what sense this is a derivative. Indeed, for $\theta$ the flow of $X\in \mathfrak{X}(M)$, and $W$ another vector field we get
$$
(\mathcal{L}_XW)_p=\lim_{t\to 0}\frac{d(\theta_{-t})_{\theta_t(p)}W_{\theta_t(p)}-W_p}{t}
$$
which shows that the Lie derivative is measuring how $W$ changes as we flow along $X$. Ideally, you would then prove the algebraic characterization.

A: I can write my opinion. Consider that I am just a student. The ideal variant is to define something axiomatically, then to give an example of such object, a realization of it. You ask why? I give an explonation. I think you know that real numbers can be defined with at least three ways. The first is a set of classes of equivalence of fundamental sequences of rational numbers. The second is a set of Dedecind's sections of rational numbers. The third is a set of sequences of numbers from zero to nine. All these constructions can be used as a definition. But from set theory point of view these sets are not the same, they are different as sets. "Geometrically" they are about one thing, but formally they are different. So where are "real" real numbers? To avoid this problem it is better as I think to define real numbers with a list of axioms. I hope you heard about these axioms. Then you prove two things. The first is the existence, for it you may give one of constructions I mentioned. Then you prove uniqness up to an "isomorphism". I hope you get my idea. This way is ideal for me and as I think it is good to try to correspond with defining something.


text:
Q: From io.Reader to string in Go I have an io.ReadCloser object (from an http.Response object).
What's the most efficient way to convert the entire stream to a string object?

A: func copyToString(r io.Reader) (res string, err error) {
    var sb strings.Builder
    if _, err = io.Copy(&sb, r); err == nil {
        res = sb.String()
    }
    return
}

A: The most efficient way would be to always use []byte instead of string.
In case you need to print data received from the io.ReadCloser, the fmt package can handle []byte, but it isn't efficient because the fmt implementation will internally convert []byte to string. In order to avoid this conversion, you can implement the fmt.Formatter interface for a type like type ByteSlice []byte.

A: EDIT:
Since 1.10, strings.Builder exists. Example:
buf := new(strings.Builder)
n, err := io.Copy(buf, r)
// check errors
fmt.Println(buf.String())

OUTDATED INFORMATION BELOW
The short answer is that it it will not be efficient because converting to a string requires doing a complete copy of the byte array. Here is the proper (non-efficient) way to do what you want:
buf := new(bytes.Buffer)
buf.ReadFrom(yourReader)
s := buf.String() // Does a complete copy of the bytes in the buffer.

This copy is done as a protection mechanism. Strings are immutable. If you could convert a []byte to a string, you could change the contents of the string. However, go allows you to disable the type safety mechanisms using the unsafe package. Use the unsafe package at your own risk. Hopefully the name alone is a good enough warning. Here is how I would do it using unsafe:
buf := new(bytes.Buffer)
buf.ReadFrom(yourReader)
b := buf.Bytes()
s := *(*string)(unsafe.Pointer(&b))

There we go, you have now efficiently converted your byte array to a string. Really, all this does is trick the type system into calling it a string. There are a couple caveats to this method:

*

*There are no guarantees this will work in all go compilers. While this works with the plan-9 gc compiler, it relies on "implementation details" not mentioned in the official spec. You can not even guarantee that this will work on all architectures or not be changed in gc. In other words, this is a bad idea.

*That string is mutable! If you make any calls on that buffer it will change the string. Be very careful.

My advice is to stick to the official method. Doing a copy is not that expensive and it is not worth the evils of unsafe. If the string is too large to do a copy, you should not be making it into a string.

A: var b bytes.Buffer
b.ReadFrom(r)

// b.String()

A: Answers so far haven't addressed the "entire stream" part of the question.  I think the good way to do this is ioutil.ReadAll.  With your io.ReaderCloser named rc, I would write,
Go >= v1.16
if b, err := io.ReadAll(rc); err == nil {
    return string(b)
} ...

Go <= v1.15
if b, err := ioutil.ReadAll(rc); err == nil {
    return string(b)
} ...

A: data, _ := ioutil.ReadAll(response.Body)
fmt.Println(string(data))

A: I like the bytes.Buffer struct.  I see it has ReadFrom and String methods.  I've used it with a []byte but not an io.Reader.


text:
Q: Spring boot @Transactional not rolling back the database inserts Need some help here, I'm not able to understand why my transactions are not getting rolled back in an event of exception.
I will try to put my code as close to as It is on the project (cannot share on the internet)
This is my Service
@Service
@SL4j
@Transactional(propagation = propagation.SUPPORTS, readOnly=true)
public class PublicationServiceImpl implements PublicationService{
    @Autowired
    private PartnerRepo partnerRepo;

    @Autowired
    private FlowRepo flowRepo;

    @Autowired
    private PubRepo pubRepo;

    @Override
    @Transactional(propagation = propagation.REQUIRED, rollbackFor=Exception.class)
    public int save(Request request) {
    try{
                   int  pk_id_partner = partnerRepo.save(request);
                   int  pk_id_flow = flowRepo.save(request);

                   String publicationCode = generatePubCode(request);
                   int publicationCode= pubRepo.save(pk_id_partner, pk_id_flow, request);
        }
        catch(Exception e){
        log.error("Exception in saving");
    }
    return 0;
    }
}

This is my Repository (example of 1 , all 3 repos follow same coding standards)
@Repository
@Slf4j
public class PartnerRepo implemets PartnerRepo{
    @Autowired
    private NamedParamaterJDBCTemplate namedParamaterJDBCTemplate;
    //String Declarations .....

    private MapSqlParameterSource sqlParameterSource;

    @Override
    public int save(Request request){
        sqlParamatersSource = new MapSqlParameterSource();
        //sqlParamatersSource.addValue(.....)
        //sqlParamatersSource.addValue(.....)
        //sqlParamatersSource.addValue(.....)

        return executeQuery();
    }

    private int executeQuery(){
        try{
            keyHolder = new GenerateKeyHolder();
            namedParamaterJDBCTemplate.update(getInsertQuery(), sqlParamaterSource , kekHolder, new String[]{"pk_id"})
            return keyHolder.getKey().intValue();
        }catch(Exception e){
            log.error("Exception while saving");
            return 0;
        }
    }
}

So the problem is , Consider there is an exception in the method generatePubCode(request); , ideally since I have used @Transactional at class level and method level , The previous 2 repo transactions () should be rolled back right? However it isn't happening, Even After the code is finished execution I can see the records in DB (Postgres DB v10).
Please help figure out this issue , Am I doing something fundamentally wrong ?
Please do let me know in case you need further information that might help here!
P.S: I have tried all permutations of @Transactional , nothing works : ONLY having this in the catch block works!  TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
I wonder If its the right approach for a springBoot project
Thanks in advance for the help!
Edit: as per suggestion made the PublicationServiceSaverImpl.save() public
Best reagards,
Bhargav.

A: Annotations in general never work on methods called from the same class because of how proxies are created in Spring.
It has nothing to do with @Transaction in particular but with the fact that your methods is private and called from the within same object.
Please make the method public and move the @Transactional method in a separate class annoted with @Service and called it from outside of the instance of the class
  @Service
  public class PublicationServiceSaverImpl {

     @Transactional
     **public** int save(Request request) {
      ...
     }
  }

You must call the save method  from outside of the class PublicationServiceSaverImpl, maybe from PublicationServiceImpl.

A: There are several things that break proper transactions in Spring

*

*Your service method is private

*You are catching and swallowing exceptions

private method
The fact that your PublicationServiceImpl save method is private basically makes the @Transactional on that method useless. As a private method cannot be proxied, no transactions will apply. Even if it would be public it wouldn't work as you are calling the method from within the same object, hence the transactionality of that method applies.
To fix, make your method public and call the save method from an other class (or make the actual method that is calling save have the proper @Transactional.
The fact that is doesn't work is due to the type op AOP being used, by default Spring will use proxies and this is a drawback of using proxy based AOP.
Another solution to make it work with private methods is to switch to full-blown AspectJ with either compile-time or load-time weaving of the classes. Both require additional setup and that can be tedious.
Catch and swallow exceptions
You have in both your repository as well as your service a try/catch block. Each of those catches and swallows the exceptions (they are logged but not re-thrown).
For transactions to work properly it needs to see the exceptions. The fact that you are catching and swallowing them, makes the transaction aspect not see them and instead of doing a rollback, do a commit. For the transaction aspect everything is ok because there was no exception.
To fix, remove either the try/catch or rethrow the exceptions.

A: The method PublicationServiceImpl.save must be public if you want to use @Transactional.
As per Spring Documentation:

When you use transactional proxies with Spring's standard configuration, you should apply the @Transactional annotation only to methods with public visibility. If you do annotate protected, private, or package-visible methods with the @Transactional annotation, no error is raised, but the annotated method does not exhibit the configured transactional settings.

A: First of all: make your method public.
Second: you have to throw the exception. If you catch and not rethrow it, how do you expect the transactional processing to know that an error occured and then rollback?
You have two options: throw the Exception instead of catching it, or catch, do some further processing and then rethrow it.
So in your repository, just add a throws keyword and then rethrow the exception after the log statement:
public int executeQuery() throws Exception {
  try {
    keyHolder = new GenerateKeyHolder();
    namedParamaterJDBCTemplate.update(getInsertQuery(), sqlParamaterSource, kekHolder, new String[] {
      "pk_id"
    })
    return keyHolder.getKey().intValue();
  } catch(Exception e) {
    log.error("Exception while saving");
    throw e;
  }
}

Now, for your service:
Example 1 - use the throws keyword to propagate the checked exception:
@Override
@Transactional(propagation = propagation.REQUIRED, rollbackFor = Exception.class)
public int save(Request request) throws Exception {
  int pk_id_partner = partnerRepo.save(request);
  int pk_id_flow = flowRepo.save(request);

  String publicationCode = generatePubCode(request);
  int publicationCode = pubRepo.save(pk_id_partner, pk_id_flow, request);
  return 0;
}

Example 2 - catch and rethrow it as an RuntimeException, which is unchecked.
@Override
@Transactional(propagation = propagation.REQUIRED)
public int save(Request request) {
  try {
    int pk_id_partner = partnerRepo.save(request);
    int pk_id_flow = flowRepo.save(request);

    String publicationCode = generatePubCode(request);
    int publicationCode = pubRepo.save(pk_id_partner, pk_id_flow, request);
  } catch(Exception ex) {
    throw new RuntimeException(ex);
  }
  return 0;
}

Note that the second example doesn't need the rollbackFor argument to the @Transactional. By default, a transaction is rolled back if a unchecked exception occurs, so there's no need to explicitly use rollbackFor in cases of RuntimeExceptions.

A: Another verification that would have to be done if the solution does not work. It is to verify that the database tables allow the rollback. For this, the engine has to be in InnoDB and not in MyISAM and others.

A: In my case adding @EnableTransactionManagement annotation on Application class resolved the issue

A: In stead of @Transactional(propagation = propagation.REQUIRED provide @Transactional(propagation = propagation.REQUIRED_NEW
If you use the latter, it will use the parent transaction boundary, which is at class level.
And you don't need explicitly state rollbackFor=Exception.class. By default spring will roll back on exception
And do change private to public
Try this out


text:
Q: IExpress command line without using .SED file Can I create installation (msi) package using IExpress in post build event but without using .SED file?
And if SED file is required then how to change TargetName and SourceFile path from command line?
I have created package but due to paths in SED file, it is not working for Automation build.

A: IExpress doesn't generate MSI files, it generates executables and CAB files only.
SED files are required. There's no easy way to "override" the TargetName or SourceFiles. You'd have to write some kind of program to edit the SED file on-the-fly.


text:
Q: sending voip push notification from one signal I want to use one signal to send VoIP push notifications to the iPhone. so I created a VoIP push notification and uploaded the p12 certificate to one signal dashboard in postman or curl. When I send a notification, it returns 200 (status success) but no notification is sent to my device. do you have any idea why?
request :

curl --include \
       --request POST \
       --header "Content-Type: application/json" \
       --data-binary "{\"app_id\" : \"xxxxxxxx-xxxx-4a41-ac20-363497c923e5\",
  \"identifier\":\"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\",
  \"language\":\"en\", \"device_type\":0,
  \"tags\":{\"FirstName\":\"amir\",\"LastName\":\"tutunchi\",\"Speciality\":\"Yoga\",\"MeetingID\":\"456354646\",\"AppointmentDate\":\"2019-05-29T22:45:47+04:30\",\"AppointmentTitle\":\"check\"}}"\
      https://onesignal.com/api/v1/players

response :

{
      "success": true,
      "id": "xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx" }


text:
Q: Installing psycopg2 in virtual env on RHEL fails I have been on this for days now. Everytime I attempt to install psycopg2 into a virtual environment on my RHEL VPS it fails with the following error. Anyone with a clue should please help out. Thanks.
(pyenv)[root@10 pyenv]# pip install psycopg2==2.5.4
 Collecting psycopg2==2.5.4
  Using cached psycopg2-2.5.4.tar.gz
  /tmp/pip-build-Vn6ET9/psycopg2/setup.py:12: DeprecationWarning: Parameters                                                                                to load are deprecated.  Call .resolve and .require separately.
  # FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
Installing collected packages: psycopg2
Running setup.py install for psycopg2
building 'psycopg2._psycopg' extension
gcc -pthread -fno-strict-aliasing -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=                                                                                2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic                                                                                -D_GNU_SOURCE -fPIC -fwrapv -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2                                                                                -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -                                                                                D_GNU_SOURCE -fPIC -fwrapv -fPIC -DPSYCOPG_DEFAULT_PYDATETIME=1 -DPSYCOPG_VERSI                                                                                ON="2.5.4 (dt dec pq3 ext)" -DPSYCOPG_EXTENSIONS=1 -DPSYCOPG_NEW_BOOLEAN=1 -DHA                                                                                VE_PQFREEMEM=1 -DPG_VERSION_HEX=0x080414 -DPSYCOPG_EXTENSIONS=1 -DPSYCOPG_NEW_B                                                                                OOLEAN=1 -DHAVE_PQFREEMEM=1 -I/usr/include/python2.6 -I. -I/usr/include -I/usr/                                                                                include/pgsql/server -c psycopg/psycopgmodule.c -o build/temp.linux-x86_64-2.6/                                                                                psycopg/psycopgmodule.o -Wdeclaration-after-statement
unable to execute gcc: No such file or directory
error: command 'gcc' failed with exit status 1
Complete output from command /root/pyenv/bin/python -c "import setuptools,                                                                                tokenize;__file__='/tmp/pip-build-Vn6ET9/psycopg2/setup.py';exec(compile(getatt                                                                                r(tokenize, 'open', open)(__file__).read().replace('\r\n', '\n'), __file__, 'ex                                                                                ec'))" install --record /tmp/pip-9d8Iwo-record/install-record.txt --single-vers                                                                                ion-externally-managed --compile --install-headers /root/pyenv/include/site/pyt                                                                                hon2.6:
running install

running build

running build_py

creating build

creating build/lib.linux-x86_64-2.6

creating build/lib.linux-x86_64-2.6/psycopg2

copying lib/psycopg1.py -> build/lib.linux-x86_64-2.6/psycopg2

copying lib/extras.py -> build/lib.linux-x86_64-2.6/psycopg2

copying lib/__init__.py -> build/lib.linux-x86_64-2.6/psycopg2

copying lib/_json.py -> build/lib.linux-x86_64-2.6/psycopg2

copying lib/pool.py -> build/lib.linux-x86_64-2.6/psycopg2

copying lib/errorcodes.py -> build/lib.linux-x86_64-2.6/psycopg2

copying lib/extensions.py -> build/lib.linux-x86_64-2.6/psycopg2

copying lib/_range.py -> build/lib.linux-x86_64-2.6/psycopg2

copying lib/tz.py -> build/lib.linux-x86_64-2.6/psycopg2

creating build/lib.linux-x86_64-2.6/psycopg2/tests

copying tests/dbapi20_tpc.py -> build/lib.linux-x86_64-2.6/psycopg2/tests

copying tests/test_copy.py -> build/lib.linux-x86_64-2.6/psycopg2/tests

copying tests/test_notify.py -> build/lib.linux-x86_64-2.6/psycopg2/tests

copying tests/test_quote.py -> build/lib.linux-x86_64-2.6/psycopg2/tests

copying tests/dbapi20.py -> build/lib.linux-x86_64-2.6/psycopg2/tests

copying tests/test_lobject.py -> build/lib.linux-x86_64-2.6/psycopg2/tests

copying tests/test_bug_gc.py -> build/lib.linux-x86_64-2.6/psycopg2/tests

copying tests/test_psycopg2_dbapi20.py -> build/lib.linux-x86_64-2.6/psycop                                                                                g2/tests

copying tests/testutils.py -> build/lib.linux-x86_64-2.6/psycopg2/tests

copying tests/test_cursor.py -> build/lib.linux-x86_64-2.6/psycopg2/tests

copying tests/__init__.py -> build/lib.linux-x86_64-2.6/psycopg2/tests

copying tests/test_bugX000.py -> build/lib.linux-x86_64-2.6/psycopg2/tests

copying tests/test_types_basic.py -> build/lib.linux-x86_64-2.6/psycopg2/te                                                                                sts

copying tests/test_connection.py -> build/lib.linux-x86_64-2.6/psycopg2/tes                                                                                ts

copying tests/test_extras_dictcursor.py -> build/lib.linux-x86_64-2.6/psyco                                                                                pg2/tests

copying tests/test_transaction.py -> build/lib.linux-x86_64-2.6/psycopg2/te                                                                                sts

copying tests/test_module.py -> build/lib.linux-x86_64-2.6/psycopg2/tests

copying tests/test_dates.py -> build/lib.linux-x86_64-2.6/psycopg2/tests

copying tests/testconfig.py -> build/lib.linux-x86_64-2.6/psycopg2/tests

copying tests/test_cancel.py -> build/lib.linux-x86_64-2.6/psycopg2/tests

copying tests/test_async.py -> build/lib.linux-x86_64-2.6/psycopg2/tests

copying tests/test_with.py -> build/lib.linux-x86_64-2.6/psycopg2/tests

copying tests/test_green.py -> build/lib.linux-x86_64-2.6/psycopg2/tests

copying tests/test_types_extras.py -> build/lib.linux-x86_64-2.6/psycopg2/t                                                                                ests

running build_ext

building 'psycopg2._psycopg' extension

creating build/temp.linux-x86_64-2.6

creating build/temp.linux-x86_64-2.6/psycopg

gcc -pthread -fno-strict-aliasing -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=                                                                                2 -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic                                                                                -D_GNU_SOURCE -fPIC -fwrapv -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2                                                                                -fexceptions -fstack-protector --param=ssp-buffer-size=4 -m64 -mtune=generic -                                                                                D_GNU_SOURCE -fPIC -fwrapv -fPIC -DPSYCOPG_DEFAULT_PYDATETIME=1 -DPSYCOPG_VERSI                                                                                ON="2.5.4 (dt dec pq3 ext)" -DPSYCOPG_EXTENSIONS=1 -DPSYCOPG_NEW_BOOLEAN=1 -DHA                                                                                VE_PQFREEMEM=1 -DPG_VERSION_HEX=0x080414 -DPSYCOPG_EXTENSIONS=1 -DPSYCOPG_NEW_B                                                                                OOLEAN=1 -DHAVE_PQFREEMEM=1 -I/usr/include/python2.6 -I. -I/usr/include -I/usr/                                                                                include/pgsql/server -c psycopg/psycopgmodule.c -o build/temp.linux-x86_64-2.6/                                                                                psycopg/psycopgmodule.o -Wdeclaration-after-statement

unable to execute gcc: No such file or directory

error: command 'gcc' failed with exit status 1

----------------------------------------
Command "/root/pyenv/bin/python -c "import setuptools, tokenize;__file__='/                                                                                tmp/pip-build-Vn6ET9/psycopg2/setup.py';exec(compile(getattr(tokenize, 'open',                                                                                open)(__file__).read().replace('\r\n', '\n'), __file__, 'exec'))" install --rec                                                                                ord /tmp/pip-9d8Iwo-record/install-record.txt --single-version-externally-manag                                                                                ed --compile --install-headers /root/pyenv/include/site/python2.6" failed with                                                                                error code 1 in /tmp/pip-build-Vn6ET9/psycopg2

A: I found my way around it. I noticed it installs successfully globally. So I installed psycopg2 globally and created a new virtual environment with --system-site-packages option. Then I installed my other packages using the -I option.
Hope this helps someone else.
OK. I later found out that I had no gcc installed. So I had to install it first. And after that, I could pip install psycopg2. Thank you cel for the direction.

A: For me, I'm using Redhat 8 enterprise and my issue wasn't solved by installing gcc and gcc-c++.
I was able to solve the issue by installing python3-devel and development tools.
to install them on Redhat using yum manager, please follow this link


text:
Q: Dual monitors won't "wake up" after sleep My laptop is set to go to sleep when not in use, but when I have it set to use Dual screens, after I "wake it up", all I can see is the mouse on the second screen, flickering. If I unplug the VGA cable, the laptop screen wakes up, and I can see the log-in screen. Once I plug the VGA cable back in, the second screen "wakes up" too.
This problem does not occur on startup, and I have set the second screen to be my main display - but I do often disconnect the laptop to take it with me. I have also changed the settings to make the laptop screen my main display, and the issue still occurs, just on the laptop screen instead.
This has only just started happening, around the time of the last update (2017-06 Cumulative Update for Windows 10 Version 1607 for x64-based Systems (KB4022715)).
Running Windows 10 Home, Acer Aspire E 15. Let mem know if additional information is required.

A: I had a similar issue with one of my dual monitors not showing up after resuming from sleep. I used the keyboard shortcut Ctrl+Shift+Win+B to restart the graphics driver and my main screen flickered off and then both screens turned on.
There's some more information in this question.

A: I found a simple solution I make sure that no monitor is using VGA. It seems that Windows 10 will "wake up" the Digital Monitor (HDMI/DVI/DP) but not VGA. I have had to remove the VGA connection on countless users computers to get around the problem.
I have tried to use the DP to VGA, HDMI to VGA and DVI to VGA converters but that
does not seem to solve the problem. The monitor works correctly with DVI to HDMI, mini DP to DVI and DP to DVI.

A: Perhaps it'll be useful to anyone:
My unit is old Fujitsu P710, fairly standard business aimed, core i3 based pc. BIOS: Aptio Setup Utility | Code ver. 4.6.5.3
I fixed the issue with secondary monitor not waking up after exiting sleep mode by changing bios settings:
Go to Power tab: change "Hibernate like Soft OFF" value to disabled.
Save & exit.
That's it. Problem went away in my case.

A: disabling the display driver that is not working and enabling again in the device manger worked for me .
it caused my screen to flicker for 1 time   but it worked .
hope it helps
have been searching all over in the net for answers.

A: Here are some troubleshooting steps that may help in solving that issue.

*

*Open Power Option and click on Change plan settings then Change advanced power settings.

*Expand Hard disk then Turn off hard disk after and set it to Never.

*Expand Allow hybrid sleep and set it to Never, set Hibernate after to Never as well.

*On Power Option main menu, on the left pane click on Change what the power buttons do.

*Once open under Shutdown settings remove the check on Turn on fast startup then click Save changes.

*Also do disable the screen saver mode of your PC when it idles.

*Next is to do a clean install of your graphics card driver as well.

*Please do follow the guide in this article on how to do a clean install of your GPU driver. http://www.tomshardware.com/faq/id-2767677/clean-graphics-driver-install-windows.html

A: I have yet to locate the solution to this issue, but an easier work-around than rebooting is to switch your display to mirror mode. This wakes the second monitor immediately, and then simply click revert in the "are you sure" popup to get back to your desired setting. Its still annoying, but this is a faster way to get thru it in the meantime.

A: I just wanted to add my solution, in case it can help anyone. I searched high and low on the internet why my 2nd monitor would not wake up after computer goes to sleep etc, but my solution ended up being very simple - cable issue. once i replaced the cable connecting my second monitor to my laptop, I have not had any issues!

A: On your keyboard, press the Windows key + X and select Control Panel.
Click Hardware and Sound, then click Power Options.
Click Change plan settings for the plan you want to change.
Click Change advanced power settings.
Click the plus sign (+) next to "USB settings" and "USB selective suspend setting" to expand the options and change the setting to Disabled.
Click OK to apply the setting.
This worked for me on my Lenovo P52

A: I have a PC with dual monitors and use the latest version of win10. I have increasingly had issues with the graphics side since upgrading to win 10, most I have lived with or overcome to a certain extent. My latest issue has been related to sleep mode start up, without going into too much detail this was overcome by changing from sleep to hibernation. Now the PC is in hibernation mode the 2nd monitor will not wake up until I restart the PC. I don't like to be beaten and have spent a lot of time going around in circles, the PC was a high end spec when built in 2011 but the root of the problems are due to the graphics chipset on the mobo do not support win 10. It's not obvious until I contacted asrock who confirmed this. The PC still works well when running but I am going to change the mobo for one that supports win10. In summary if something in your PC/laptop is not compatible with the latest win10 update you can spend a lot of time chasing your tail until you hit a brick wall. Hope this helps.
Update - have changed motherboard to one with a Win10 compatible chipset and the problem has disappeared.

A: ati radeon HD 3850 does work with 2 screens but screen 2 doesn't start after sleep. Workaround. Screen settings, copy screen change into extend screen. (Screen will wake up) revert the setting to either extend or copy  This works in a AMD 64 win 10 with fall update problem. screens are Acer AL1916w and Neovo 17e My setup worked flawless with w10 64 amd processor and hd3850 but after fall update recently...neovo e-17 screen keeps in standby (yellow light) only wakes up when change settings from extend to copy or visa versa. Problem is Windows update. But here is my workaround.

A: I had the same issue recently and thought it was windows. Turns out, I did a driver update for my GPU (Nvidia 1080) and chose a clean install while updating and it fixed the issue.


text:
Q: cannot place view programatically using ConstraintLayout I have a constraint layout that has an image view which is like an archery target. On touch event I'm trying to place another image (a bullet) where user pressed on the target. However, I can only adjust the top alignment of the image which is correct, but I cannot adjust the view horizonaly at all. It always ends up adjusted to the left. What am doing wrong ? The coordinates are working 100% ok, I even tried hardcoding the values but no luck.
 target.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            Matrix inverse = new Matrix();
            imageView.getImageMatrix().invert(inverse);
            float[] touchPoint = new float[]{event.getX(), event.getY()};
            inverse.mapPoints(touchPoint);
            int x = (int) touchPoint[0];
            int y = (int) touchPoint[1];

            ConstraintSet set = new ConstraintSet();
            ImageView view = new ImageView(this);
            ConstraintLayout.LayoutParams vp =
                new ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT);
            Bitmap bm = BitmapFactory.decodeResource(getResources(),
                R.drawable.bullet);
            view.setImageBitmap(bm);
            layout.addView(view, 7, vp);
            set.clone(layout);
            set.connect(view.getId(), ConstraintSet.TOP,
            target.getId(), ConstraintSet.TOP, (int) y - 60);
            set.connect(view.getId(), ConstraintSet.LEFT, target.getId(), ConstraintSet.LEFT, (int) x);
            set.applyTo(layout);

        }
    });

A: You may be running into this issue:  62154545
ConstraintSet connect ignores right and left margins.

When adding a TextView using ConstraintSet#connect to an empty ConstraintLayout defined in XML, left and right margins are ignored (are zero) while top and bottom margins are honored. The TextView height and width are both set to "MATCH_CONSTRAINT". See the following code and screen shot. This works fine when everything is set in XML.

Just took another look at this. Use ConstraintSet.START and ConstraintSet.END instead of ConstraintSet.LEFT and ConstraintSet.RIGHT. I just tried it and it works OK. I can't say why left and right don't work.


text:
Q: Could anyone tell me a way to make this text not get out of the div background?

   body {
          margin:0;
        }
        #header {
          display:flex;
          max-height:50px;
        }

        #nav-bar {
          width:50vw;
          justify-content:space-around;
          align-items:center;
        }
        .image {
          width:55vw;
        }
        #header-img{
          height: 100%;
          width: 50%;
        }

         ul {
          padding: 0;
          list-style-type:none;
          display:flex;
          justify-content:space-around;
        }

#videodiv {
  width:100%;
  margin-top:50px;
  display:flex;
  justify-content:center;
}
h3{
  text-align:center;
}

#form {
  margin-top:25px;
  display:flex;
  justify-content:center;
}

a {
  color:chocolate;
  text-decoration:none;
  font-size:20px;
}

#container {
   min-height:200px;
  text-align:center;
  width:60%;
  margin: 0 auto;
  margin-top:5em;
  background-color:gray;
  display:grid;
  grid-template-columns:1fr 1fr ;
  grid-template-rows:1fr 1fr;
  grid-template-areas:
    "price price"
    "pay nopay";
}
#price {
  grid-area:price;
  font-weight:bold;
}
#nopay {
  grid-area:nopay;
  background-color:red;

}
#pay {
  grid-area:pay;
  background-color:green;

}

span {
  color:yellow;
  text-decoration:underline;
}

#containertwo {
  margin-top:5em;
  display:flex;
  width:100%;
  background-color:green;
  flex-wrap:wrap;
  height:1000px;
}
#containertwo > div {
  width:60%;
  height:15%;
}
#containertwo > div  > span {
  float:left;
}

.works1 {
  background-color:#60bcc1;
}
.works2 {
  background-color:#74993e;
}
.works3 {
  background-color:#a07580;
}

#containertwo> div > p {
  text-align:center;
  float:left;
  font-size:24px;
}

#containertwo> div > span {
  font-size:100px;
  float:left;

}

Price

Process

Location

Subscribe to our news letter

    <form id="form" action="https://www.freecodecamp.com/email-submit">
      <input type="email" name="email" required placeholder="Enter your email">

<input id="submit" type="submit" value="Subscribe">
    </form>

The whole price of the product depends on the damage the vehicle has received and you will be informed as soon as possible about the full cost.

For vehicle auto parts changing you will need to pay less than 100$

To fix broken things inside of your car we will take more than 100$

            1
You will arrive at the auto service.

            2
You will need to fill out some documents in order to begin the car check.

            3
After we've fixed your vehicle , you are going to receive a call to pick the vehicle from the service.

Could anyone explain me why the text on the .works3 goes out of the div?
I know I could change #container>div width to 70% and it would fix it, But I would like to know if there'a a better option without increasing/decreasing the width ? Here's a code pen if in some case the snippet doesn't show it correctly. :
https://codepen.io/edga9966/pen/XBqarB

A: Just remove float:left from #containertwo > div > p. And if you want the text to be on the left, use text-align: left instead of text-align: center.

body {
  margin: 0;
}

#header {
  display: flex;
  max-height: 50px;
}

#nav-bar {
  width: 50vw;
  justify-content: space-around;
  align-items: center;
}

.image {
  width: 55vw;
}

#header-img {
  height: 100%;
  width: 50%;
}

ul {
  padding: 0;
  list-style-type: none;
  display: flex;
  justify-content: space-around;
}

#videodiv {
  width: 100%;
  margin-top: 50px;
  display: flex;
  justify-content: center;
}

h3 {
  text-align: center;
}

#form {
  margin-top: 25px;
  display: flex;
  justify-content: center;
}

a {
  color: chocolate;
  text-decoration: none;
  font-size: 20px;
}

#container {
  min-height: 200px;
  text-align: center;
  width: 60%;
  margin: 0 auto;
  margin-top: 5em;
  background-color: gray;
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-template-rows: 1fr 1fr;
  grid-template-areas: "price price" "pay nopay";
}

#price {
  grid-area: price;
  font-weight: bold;
}

#nopay {
  grid-area: nopay;
  background-color: red;
}

#pay {
  grid-area: pay;
  background-color: green;
}

span {
  color: yellow;
  text-decoration: underline;
}

#containertwo {
  margin-top: 5em;
  display: flex;
  width: 100%;
  background-color: green;
  flex-wrap: wrap;
  height: 1000px;
}

#containertwo>div {
  width: 60%;
  height: 15%;
}

#containertwo>div>span {
  float: left;
}

.works1 {
  background-color: #60bcc1;
}

.works2 {
  background-color: #74993e;
}

.works3 {
  background-color: #a07580;
}

#containertwo>div>p {
  text-align: left;
  font-size: 24px;
}

#containertwo>div>span {
  font-size: 100px;
  float: left;
}

Price

Process

Location

Subscribe to our news letter

  <form id="form" action="https://www.freecodecamp.com/email-submit">
    <input type="email" name="email" required placeholder="Enter your email">

<input id="submit" type="submit" value="Subscribe">
  </form>

The whole price of the product depends on the damage the vehicle has received and you will be informed as soon as possible about the full cost.

For vehicle auto parts changing you will need to pay less than 100$

To fix broken things inside of your car we will take more than 100$

      1

You will arrive at the auto service.

      2

You will need to fill out some documents in order to begin the car check.

      3

After we've fixed your vehicle , you are going to receive a call to pick the vehicle from the service.


text:
Q: Monit dont work because cant find "if" program Im trying to configure monit on my ubuntu server for tomcat, but when I execute:
monit reload

It throws an error:
/etc/monit/monitrc:292: Program does not exist: 'if'

I dont know why it happends.
I added my configuration at the end of the file :
/etc/monit/monitrc

And this is my configuration code:
check process tomcat7 with pidfile "/usr/local/tomcat/tomcat.pid"
  start program = "/etc/init.d/tomcat start"
  stop program = " "/etc/init.d/tomcat stop"
  if failed port 8080 for 5 cycles then restart

   include /etc/monit/conf.d/*
   include /etc/monit/conf-enabled/*

What am I doing wrong? Why throws this error?
Thanks!

A: you simply have one double quote too much at stop program.
It should be:
check process tomcat7 with pidfile "/usr/local/tomcat/tomcat.pid"
  start program = "/etc/init.d/tomcat start"
  stop program = "/etc/init.d/tomcat stop"
  if failed port 8080 for 5 cycles then restart

  include /etc/monit/conf.d/*
  include /etc/monit/conf-enabled/*


text:
Q: Why does a deterministic algorithm in Java run at different times? I have a Java program that calculates an n-body problem. At every iteration it checks the forces each body exerts on every other body, and then moves them according to the forces.
The bodies always start in the same spot (I have them arranged in a circle, from body 0 to body n), they are always inspected and moved in the same order (from body 0 to n). However, when I run the program 30 times, I get drastically different running times. One running time would be 2,947,188 milliseconds (49 minutes), while another would be 920,967 milliseconds (15 minutes). I'm not surprised by the order of magnitude of these times because I'm using brute force method (O(n^2)) on A LOT of bodies. But I'm wondering why is there such a variance for a deterministic algorithm? if it's the same algorithm time after time, shouldn't the running time be the same (or at least close)?
Before you ask, yes, I'm measuring the time of the thread that does the calculation, not wall-clock time.
Edit - I'm measuring time like this:
ThreadMXBean bean = ManagementFactory.getThreadMXBean();
long startUserTimeNano = bean.getCurrentThreadCpuTime();

// ... Code to do the stuff...

double taskUserTimeNano = (bean.getCurrentThreadCpuTime() - startUserTimeNano);
CPUmillisecondsElapsed += taskUserTimeNano/1000000.0;

Does this measure anything other than the calculation step?
Second Edit - Now I changed it to measure time like this:
ThreadMXBean bean = ManagementFactory.getThreadMXBean();
long startUserTimeNano = bean.getCurrentThreadUserTime();

// ... Code to do the stuff...

double taskUserTimeNano = (bean.getCurrentThreadUserTime() - startUserTimeNano);
CPUmillisecondsElapsed += taskUserTimeNano/1000000.0;

However, the results are still not repeatable. I also tried to run my program with the flag -Xint, and the results were STILL not repeatable.
Is it safe to assume the issue is within the algorithm and multithreading? or can it still be an issue relating to Java?

A: Are you sure that you are measuring the time correctly?  There could be many threads that are running inside the jvm that are invisible to you as a user.  If you get the system time then you are ignoring the existence of those threads.  Also, if you are running any other threads you might be ignoring the time that they add in.

A: Benchmarking multi-threaded programs can be challenging due to dynamic compilation, garbage collection, and adaptive optimization. I suggest reading chapter 12 of Brian Goetz's "Java Concurrency in Practice".

A: Assuming the thread you are timing is just one of many threads, simply getting a diff of the start and end times of the computation in the thread is really not measuring the actual CPU time taken by the thread. It competes with other threads and would have to suspend/wait as other threads run, but you would be counting the time it is waiting as well.
Since the way threads are scheduled may vary, and we have to consider garbage collection as well, the total time taken from start to finish for the thread can vary a lot. But the actual amount of CPU time needed will not vary.
Edit:
I think what you need to measure is the amount of time the thread spent in user mode. This should get rid of time spent waiting for the OS/JVM and only measure the time spent running the in the thread. So, try using getCurrentThreadUserTime.
I found an earlier SO thread about it: Difference between thread user time and thread cpu time in Java


text:
Q: VBA Macro to Remove Only Numbers from All the Tables in File. I would to like to get help in VBA (In MS WORD) , If some body tells me how to create a macro that just removes numbers from all the cells of Tables, but leaves those numbers that are with Text (like gh4).
Thanks for help in advance.

A: Just record the macro in Word. Use wildcard search and replace. Search for <[0-9]@> and replace with nothing.


text:
Q: How do Bayesian GLMs with noninformative priors on the coefficients compare to estimation using MLE's? I'm curious as to how putting noninformative priors on the regression coefficients in a GLM compares to maximum likelihood estimation, in frequentist terms. A dispersion parameter $\phi$ is of course a source of trickiness, so perhaps we assume that these are estimated using empirical Bayes.
In the simplest situation, the response $Y_i, i = 1, ..., n$ might be Gaussian distributed with mean
$$
E(Y_i | \beta) = x_i ^T \beta
$$
have common variance $\sigma^2$, and be independent (given $\beta$). Then the Bayes estimator of $\beta$ is the same as the MLE, and for $\sigma^2$ estimation via empirical Bayes results in $\hat \sigma^2 = \frac{\sum(Y_i - \hat Y_i)^2}{n - p}$ where $p$ is the number of $\beta$'s, which makes an appropriate correction to the denominator that the MLE does not make.
My general sense is that it is a bit easier to get away with flat priors on mean parameters, and that integrating out the mean parameters is generally what you want to be doing to estimate the dispersion parameter $\phi$ (short of putting an informative or "weakly informative" (in Gelman's sense) prior on it). That is to say, we would rather integrate out $\beta$ than max-marginalize (aka profile) it out.
It isn't obvious to me immediately that flat priors on regression coefficients lead to proper posteriors in GLMs; part of me feels that they usually ought to, but part of me also feels that maybe they run into the same sort of issues as MLE's; for example, maybe flat priors break down if the data are perfectly seperated in a logistic regression.
So, general insight or guidance on this is appreciated, as well as references.

A: One big difference (philosophical basis aside) - in a Bayesian analysis, if you're interested in inference on the parameters, you're normally looking at the posterior distribution, often the posterior mean; ML is looking at the mode of the likelihood. In large samples with uniformative priors, they'll usually be very similar, but in small samples they can be quite different. For example, likelihood can be distinctly asymmetric.


text:
Q: Comparing ordinal age group data from two samples with different scales I have two samples of data from one population:
Sample 1= 4,491 participants
Sample 2 = 262 participants
I want to compare age of participants in each sample but both samples have a different scale on which participants logged their ages.
Sample 1 scale = under 21, 22-24 years, 25-34 years, 35-44 years, 45-54 years, 55-64 years, 65 or over.
Sample scale 2 = 17 years or under, 18-24, 25-30, 31-40, 41-50, 51-60, 61 or over.
What can I do?

A: I think you may be able to do something here using methods developed for incomplete contingency tables. Suppose for example you just have three categories for each sample. For A under 18, 19 to 24, 25 and over and for B under 16, 17 to 30, 31 and over. You can now view this as coming from a table with five categories: under 15, 17 to 18, 19 to 24, 25 to 30, 31 and over but where for quite a few categories in each sample you only know the number in two adjacent cells fused together. So in sample A the number under 18 corresponds to cells under 16 and 17 to 18 fused but in sample B you know under 16 for sure.
For some references look at the manual for this R package where there are some examples if you use R but also reference to some papers outlining the method.
This is not going to give you a simple answer but it may help to find a method which suits your scientific question.


text:
Q: Find non-unique values in a db with criteria present I am using a SQLite Server and I don't understand how to achieve my goal.
I have a database called billing that looks like:
+------------+---------+-------+---------+--------+
|         ID | Account | Date  | Product | Charge |
+------------+---------+-------+---------+--------+
|          1 |       1 | 04-01 | Water   |  20    |
|          1 |       1 | 04-02 | Water   |  20    |
|          2 |       2 | 06-01 | Phone   |  30    |
|          2 |       3 | 08-04 | Water   |  40    |
+------------+---------+-------+---------+--------+

I am trying to find the sum of all the most recent charges for all the products combined. Meaning, I would have to sum together $20 for ID-1 (the one dated 04-01 is ignored because its not most recent) for their water bill, and $30 and $40 for ID-2's Water and Phone bills.
Right now, I'm using Python's sqlite3 module and am using:
for i in range (2):
    c.execute("SELECT Charge FROM billing WHERE ID = " + str(i+1) + " ORDER BY Date DESC")
    rows = c.fetchone()
    sum.x += rows[0]
print("Todays Sum = $" + str(sum.x))

But using this method makes only one value from ID-2 to be counted. The least recent one is not counted because the database is being descended.
How can I apply the criteria that the ID has to be unique, while also looking for non-unique Products?

A: Try this query:
SELECT SUM(b1.Charge)
FROM billing b1
INNER JOIN
(
    SELECT Account, Product, MAX(Date) AS max_date
    FROM billing
    GROUP BY Account, Product
) b2
    ON b1.Account = b2.Account AND
       b1.Product = b2.Product AND
       b1.Date = b2.max_date;

A critical assumption here is that your dates are stored in YY-MM format.  If you stored them as MM-YY, then they won't sort properly and you have an even bigger problem with your table.

A: Plese change the query to below and try again:
SELECT sum(Charge) FROM billing WHERE ID = " + str(i+1) + " group by id ORDER BY Date DESC


text:
Q: Why is there a small gap between an absolutely positioned child and parent with borders? All margins, padding, and positions are set to 0 I recreated a stripped down version of the phenomenon I'm facing. So the parent has position: relative and the ::after child has position: absolute with all directional values set to zero. This would normally stretch out the child directly over the parent perfectly in my experience. Also * { margin: 0; padding: 0 } is set to be safe and make sure this isn't a margin or padding issue.
I know I can just set the child element -1px left and up... but I'm kind of curious to why this is happening if the child is stretched out directly over it's parent? Is there a way to make it work with top, right, bottom, and left set to 0?

* {
  margin: 0;
  padding: 0;
}
body {
  padding: 5rem; /* to push div closer to center of snippet window */
}
div {
  transform: scale( 5 ); /* added so displacement can be easily seen */
}
div, div::after {
  display: block;
  position: relative;
  width: 1rem;
  height: 1rem;
  background-color: #eee;
  border-style: solid;
  border-width: 0.1rem;
  border-color: #666;
  border-radius: 0.25rem;
  content: '';
}
div::after {
  position: absolute;
  top: 0; right: 0; bottom: 0; left: 0;
}

Notice from the snippet ( In Chrome atleast ) The div's are offset from each other by about 1 px.
Picture of what I'm seeing in Chrome on desktop:

Why aren't these div's placed directly on top of each other?

A: The reference is the padding-box and not the border-box

If the element has 'position: absolute', the containing block is established by the nearest ancestor with a 'position' of 'absolute', 'relative' or 'fixed', in the following way:
... the containing block is formed by the padding edge of the ancestor. ref

Then the values are over-constrained since you are defining left/right/width and the width is equal to the parent (containing block) width so the right will be ignored (use any value for it and nothing will happen)

If the values are over-constrained, ignore the value for 'left' (in case the 'direction' property of the containing block is 'rtl') or 'right' (in case 'direction' is 'ltr') and solve for that value. ref

Same logic with top/bottom/height where the bottom is ignored.
If you replace your border with a box-shadow for example you will have a perfect overlap:

* {
  margin: 0;
  padding: 0;
}
body {
  padding: 5rem; /* to push div closer to center of snippet window */
}
div {
  transform: scale( 5 ); /* added so displacement can be easily seen */
}
div, div::after {
  display: block;
  position: relative;
  width: 1rem;
  height: 1rem;
  background-color: #eee;
  box-shadow:0 0 0 0.1rem #666;
  border-radius: 0.25rem;
  content: '';
}
div::after {
  position: absolute;
  top: 0; right: 0; bottom: 0; left: 0;
}


text:
Q: file_get_contents not working from my server I am crawling a website using following code
require 'simple_html_dom.php';

$opts = array('http'=>array('header' => "User-Agent:MyAgent/1.0\r\n"));
$context = stream_context_create($opts);
$header = file_get_contents('http://www.cinnetwork.org',false,$context);
print_r($header);

This code works correctly in phpfiddle. But when i use it from my server it says

Warning: file_get_contents(http://www.cinnetwork.org): failed to open
  stream: Connection timed out

I also tried using curl. It also shows the similar error.

A: $url= 'https://example.com';

$arrContextOptions=array(
  "ssl"=>array(
        "verify_peer"=>false,
        "verify_peer_name"=>false,
    ),
);

$response = file_get_contents($url, false, stream_context_create($arrContextOptions));

A: A suggestion, you can use CURL instead ..


text:
Q: JQWidgets: JqxNumberInput setting editor value to null I am using jqxNumberInput as an numeric editor for my web application in a web user control. I would like to set the default value of the editor to be null. Currently it shows up with a zero in it. jqxNumberInput doesn't support a null value itself. Is there a way to remove that zero using javascript, jquery, or in the codefile of my vb.net web application?
I am using the current version of JQWidgets, Visual 2012, .Net Framework 4.
Here is my script
 $(document).ready(function () {
   $("#test").jqxNumberInput({ width: "<%=m_sWidth%>", height: "<%=m_sHeight%>", inputMode: "<%=m_sInputMode%>", decimalDigits: "<%=m_iDecimalDigits%>" });
    $("#test").setDecimal('');

});

A: As I have understood, you want to initialize your jqxNumberInput with nothing in.
Here is a solution :
        $(document).ready(function () {
            $("#test").jqxNumberInput({
                width: "<%=m_sWidth%>",
                height: "<%=m_sHeight%>",
                inputMode: "<%=m_sInputMode%>",
                decimalDigits: "<%=m_iDecimalDigits%>"
            });
            $("#test input").val('');
        });

The instruction $("#test input").val(''); is going to get the input used by jqxNumberInput directly in the DOM and clear it


text:
Q: TestNg DataBinding : setting the location of properties on test start up I was looking at https://sourceforge.net/projects/testngdatabind/ and searched for the possibility to set the properties location on start up of the tests. The usecase is that I have more environments (e.g. different databases) where I want to run the same tests.
There are two different properties files in the TestNG databinding. The first (called data properties file) defines the type of data source ('properties in my case) and the URL of actual key/value pairs used by the test (called Properties Data Source). But none of them accepts variable passed to the test through e.g. system environment variable.
Even if TestNG databinding framework is not developed for ~6 years it works quite well. Is there any alternative how to make TestNG tests generic so that they can be run on environments differing just by data used?

A: As alternative, you can make use of TestNG extension QAF which provides different in-built data-providers and also has resource and environment management. With QAF if your test case is data driven and have different data for different environment it may look like below:
    @QAFDataProvider(dataFile = "resources/${env}/data/tc_01.json")
    @Test
    public void tc_01(Map<String, Object>){
    }

Value of ${env} in data file path can be provided at the time of execution in different ways.This is just as an example. There can be other alternative ways by using different features of qaf depending on need.


text:
Q: Why can't in format the new HDD on my sony vaio laptop? I am working on a Sony Vaio Laptop, Model VPPCCA2FXX. Upon boot-up the error message, "Your HDD is in danger of immanent failure. Replace your HDD" appears. Press F2 to continue...the machine then continues to boot into Windows 7 although painfully slow. I backed up all of the data...tried to make a recovery disk as none were provided with the unit purchased 2 years ago. The Sony VAIO Care program installed does not seem to work...many error messages appear.
I installed a new HDD which is compatible with this laptop. When booting from the Optical drive, the installation would not take effect. Next, I rebooted to the windows media and at the first installer screen, I entered into the Command prompt screens. I then typed the following:
DISKPART,
LIST DISK,
SELECT DISK 0,
CLEAN,
CREATE PARTITION PRIMARY,
FORMAT FS=NTFS LABEL="WINDOWS 7". At this point I received a message saying "no disk volume" something to that effect.
It appears to me that I may need a driver in order to make the new HDD compatible for this Sony Mother board. I went to the Sony site and have had little luck with finding drivers etc.
Any assistance is greatly appreciated. Thank you in advance.

A: You don't need a drive for the new harddisk.
But you probably need a driver for the SATA controller on the motherboard.
You can load this during the setup of Win7 from a USB key.
Windows 7 will recognize most older SATA controllers on its own (although not always with the best drivers, but at least well enough to get Windows installed).
But for hardware younger than 3-4 years you will usually need a SATA AHCI driver for the SATA controller.
You can set the SATA controller in IDE (or sometimes called "legacy") mode in the BIOS and usually Win7 can use that without needing extra drivers, but this has slightly less performance AND is the wrong thing to do for an SSD (Trim can't work in IDE mode!).
Please note: Some BIOS allow changing the controller between 3 modes: IDE, AHCI and AHCI-RAID. With a single disk AHCI makes most sense. AHCI-RAID is only for the experimenters out there who want to mess with fake-RAID.
Note that in most cases AHCI and AHCI-RAID mode require different drivers.


text:
Q: No such table error : sqlite (moor) tables created only after clearing app data in Flutter I am creating a database using Moor for my flutter app. It has 5 tables and corresponding DAOs (Data Access Objects).
@UseMoor(
    tables: [Cart, CartTotal, Books, Subjects, Images],
    daos: [CartDao, CartTotalDao, BooksDao, SubjectsDao, SearchDao, ImagesDao])
class AppDatabase extends _$AppDatabase {
  AppDatabase()
      : super(FlutterQueryExecutor.inDatabaseFolder(
            path: 'db.sqlite', logStatements: true));

  @override
  int get schemaVersion => 1;
}

When I run the app on an emulator, everything works fine. All tables are created properly. The error occurs when I run the app on an actual device. 3 tables are created fine and populated with data from the cloud as expected. The other 2 tables for cart and total are not created and throw a no such table error when accessing the cart page.
I/flutter ( 5321): Moor: Sent SELECT * FROM cart WHERE name != ? with args [Total]
E/SQLiteLog( 5321): (1) no such table: cart

Also no logging from my database update service that runs at app start is shown.
Once I clear the app data from the app info section on my device and start the app again, everything works fine again.
I/flutter ( 5717): Moor: Sent CREATE TABLE IF NOT EXISTS books (amazon_link VARCHAR NULL, author VARCHAR NOT NULL, cost INTEGER NOT NULL, cover_url VARCHAR NULL, description VARCHAR NULL, discounted_cost INTEGER NULL, flipkart_link VARCHAR NULL, isbn INTEGER NOT NULL, language VARCHAR NULL, name VARCHAR NOT NULL, pages INTEGER NULL, publication_number INTEGER NOT NULL, publication_status VARCHAR NOT NULL, youtube_link VARCHAR NULL, PRIMARY KEY (publication_number)); with args []
I/flutter ( 5717): Moor: Sent CREATE TABLE IF NOT EXISTS subjects (publication_number INTEGER NOT NULL, sub_name VARCHAR NOT NULL, PRIMARY KEY (publication_number, sub_name)); with args []
I/flutter ( 5717): Moor: Sent CREATE TABLE IF NOT EXISTS images (url VARCHAR NOT NULL, publication_number INTEGER NOT NULL); with args []
I/flutter ( 5717): Moor: Sent CREATE TABLE IF NOT EXISTS cart (name VARCHAR NOT NULL, quantity INTEGER NOT NULL, cost INTEGER NOT NULL, discounted_cost INTEGER NOT NULL, PRIMARY KEY (name)); with args []
I/flutter ( 5717): Moor: Sent CREATE TABLE IF NOT EXISTS cart_total (name VARCHAR NOT NULL, quantity INTEGER NOT NULL, cost INTEGER NOT NULL, discounted_cost INTEGER NOT NULL, PRIMARY KEY (name)); with args []

Opening the cart page works as expected.
I/flutter ( 5717): Moor: Sent SELECT * FROM cart WHERE name != ? with args [Total]
I/flutter ( 5717): Moor: Sent SELECT * FROM cart_total WHERE name = ?; with args [Total]

Am I missing something here? I also searched if there are any limits to creating tables but could not find any. Since moor works by generating code using build_runner, I also tried clearing the old build and rebuilding again.
Since the app runs fine on an emulator and on device after clearing data, I am assuming that my code is correct. What could be the problem?

A: So the issue was not with moor or my code. As the app is in not released yet and I am still making changes to the database, I did not want make changes to schema version and provide a migration strategy.
My understanding was that the database will get deleted on app uninstall and whatever changes made to the database will be the new schema for the app next time I install it. That is not the case. Atleast not always.
Turns out Google Drive backs up your app's database file on some devices and restores it on app reinstall. That is what was causing weird behaviour in my app.
Here's a link to the github issue for detailed explanation.


text:
Q: Convert array of sound data to wav file and play it in react I have an array of data that Bluetooth records.
I want to convert this array to sound and play it online.
I searched a lot and I came up with this solution:
  const prepareWavFile = () => {
    const wav = new Blob([sound], { type: 'audio/wav' })
    var url = URL.createObjectURL(wav)
    var audio = new Audio(url);
    audio.play().catch(console.log);
  };

I don't know why it doesn't work. It says:
DOMException: Failed to load because no supported source was found.
Why does it say this?
Is there any other solution to this problem?


text:
Q: How to increase the number of observations in xts object by taking previous value? What I have:
dta <- xts(
  c(1,2,3,4),
  order.by = timeDate(c(
     "2000-01-01 00:01:01",
     "2000-01-01 00:01:05",
     "2000-01-01 00:01:06",
     "2000-01-01 00:01:07"
     )
  )
)

                    [,1]
2000-01-01 00:01:00    1
2000-01-01 00:05:00    2
2000-01-01 00:06:00    3
2000-01-01 00:07:00    4

What I need:
                    [,1]
2000-01-01 00:01:00    1
2000-01-01 00:02:00    1
2000-01-01 00:03:00    1
2000-01-01 00:04:00    1
2000-01-01 00:05:00    2
2000-01-01 00:06:00    3
2000-01-01 00:07:00    4

Similar questions on stackoverflow only deal with decreasing the periodicity of an xts object and did not help me with this problem.
I am cleaning minute price data, where prices where only recorded if there actually where trades. Obviously, if there where no trades this means that the price stays the same as in the previous minute.

A: Merge it with a zero width sequence (grid) having the required times:
rng <- range(time(dta))
g <- xts(, seq(rng[1], rng[2], by = 1))
na.locf(merge(dta, g))


text:
Q: Multiple storyboards on one property I have multiple storyboards that access the same property (not at the same time). After one storyboard changed the property, the other one seems to have no access to it and does not change anything.. What can I do against this?
Sample:
<ListBox>
    <ListBox.ItemContainerStyle>
        <Style TargetType="ListBoxItem">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type ListBoxItem}">
                        <Border Name="Border" BorderBrush="DarkGray" BorderThickness="1" Margin="3">
                            <ContentPresenter />
                            <Border.Background>
                                <SolidColorBrush />
                            </Border.Background>
                        </Border>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsSelected" Value="True">
                                <Trigger.EnterActions>
                                    <BeginStoryboard>
                                        <Storyboard>
                                            <ColorAnimation Storyboard.TargetName="Border" Storyboard.TargetProperty="Background.Color" To="#3e8bff" Duration="0:0:0.1" />
                                        </Storyboard>
                                    </BeginStoryboard>
                                </Trigger.EnterActions>
                                <Trigger.ExitActions>
                                    <BeginStoryboard>
                                        <Storyboard>
                                            <ColorAnimation Storyboard.TargetName="Border" Storyboard.TargetProperty="Background.Color" To="White" Duration="0:0:0.1" />
                                        </Storyboard>
                                    </BeginStoryboard>
                                </Trigger.ExitActions>
                            </Trigger>
                            <MultiTrigger>
                                <MultiTrigger.Conditions>
                                    <Condition Property="IsMouseOver" Value="True" />
                                    <Condition Property="IsSelected" Value="False" />
                                </MultiTrigger.Conditions>
                                <MultiTrigger.EnterActions>
                                    <BeginStoryboard>
                                        <Storyboard>
                                            <ColorAnimation Storyboard.TargetName="Border" Storyboard.TargetProperty="Background.Color" To="Orange" Duration="0:0:0.1" />
                                        </Storyboard>
                                    </BeginStoryboard>
                                </MultiTrigger.EnterActions>
                                <MultiTrigger.ExitActions>
                                    <BeginStoryboard>
                                        <Storyboard>
                                            <ColorAnimation Storyboard.TargetName="Border" Storyboard.TargetProperty="Background.Color" To="White" Duration="0:0:0.1" />
                                        </Storyboard>
                                    </BeginStoryboard>
                                </MultiTrigger.ExitActions>
                            </MultiTrigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ListBox.ItemContainerStyle>
    <ListBox.Items>
        <sys:String>hey</sys:String>
        <sys:String>du</sys:String>
        <sys:String>dux</sys:String>
        <sys:String>duy</sys:String>
        <sys:String>dua</sys:String>
    </ListBox.Items>
</ListBox>

This is the smallest sample code I could make. After you've hovered an item, it won't turn blue when it's selected (try to click on one item and then use the arrow keys to select items without hovering them).

A: I have a solution!!! Triggers and actions order does matter... the answer is not to play more then one storyboard at the same time, just stop other.
<ControlTemplate.Triggers>
    <MultiTrigger>
        <MultiTrigger.Conditions>
            <Condition Property="IsMouseOver" Value="True"/>
            <Condition Property="Selector.IsSelected" Value="False" />
        </MultiTrigger.Conditions>
        <MultiTrigger.EnterActions>
            <StopStoryboard BeginStoryboardName="SelectedBegin" />
            <StopStoryboard BeginStoryboardName="UnselectBegin" />
            <BeginStoryboard x:Name="EnterBegin" Storyboard="{StaticResource MouseEnterSb}"/>
        </MultiTrigger.EnterActions>
        <MultiTrigger.ExitActions>
            <BeginStoryboard x:Name="LeaveBegin" Storyboard="{StaticResource MouseLeaveSb}"/>
        </MultiTrigger.ExitActions>
    </MultiTrigger>
    <Trigger Property="Selector.IsSelected" Value="True">
        <Trigger.EnterActions>
            <StopStoryboard BeginStoryboardName="LeaveBegin" />
            <StopStoryboard BeginStoryboardName="EnterBegin" />
            <BeginStoryboard x:Name="SelectedBegin" Storyboard="{StaticResource SelectedSb}"/>
        </Trigger.EnterActions>
        <Trigger.ExitActions>
            <BeginStoryboard x:Name="UnselectBegin" Storyboard="{StaticResource UnselectSb}"/>
        </Trigger.ExitActions>
    </Trigger>
</ControlTemplate.Triggers>

A: I've been able to reproduce your erroneous results using the following code (I'm stumped too):
<ListBox>
<ListBox.ItemContainerStyle>
    <Style TargetType="ListBoxItem">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ListBoxItem}">
                    <ControlTemplate.Resources>
                        <Storyboard x:Key="BorderAnimationToRed">
                            <ColorAnimation Storyboard.TargetName="Border" Storyboard.TargetProperty="Background.Color" To="Red" Duration="0:0:0.1" />
                        </Storyboard>
                        <Storyboard x:Key="BorderAnimationToBlue">
                            <ColorAnimation Storyboard.TargetName="Border" Storyboard.TargetProperty="Background.Color" To="Blue" Duration="0:0:0.1" />
                        </Storyboard>
                        <Storyboard x:Key="BorderAnimationToOrange">
                            <ColorAnimation Storyboard.TargetName="Border" Storyboard.TargetProperty="Background.Color" To="Orange" Duration="0:0:0.1" />
                        </Storyboard>
                        <Storyboard x:Key="BorderAnimationToWhite">
                            <ColorAnimation Storyboard.TargetName="Border" Storyboard.TargetProperty="Background.Color" To="White" Duration="0:0:0.1" />
                        </Storyboard>
                    </ControlTemplate.Resources>
                    <Border Name="Border" BorderBrush="DarkGray" BorderThickness="1" Margin="3">
                        <ContentPresenter />
                        <Border.Background>
                            <SolidColorBrush />
                        </Border.Background>
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Trigger.EnterActions>
                                <BeginStoryboard Storyboard="{StaticResource BorderAnimationToOrange}"/>
                            </Trigger.EnterActions>
                            <Trigger.ExitActions>
                                <BeginStoryboard Storyboard="{StaticResource BorderAnimationToWhite}"/>
                            </Trigger.ExitActions>
                        </Trigger>
                        <Trigger Property="IsSelected" Value="True">
                            <Trigger.EnterActions>
                                <BeginStoryboard Storyboard="{StaticResource BorderAnimationToBlue}"/>
                            </Trigger.EnterActions>
                            <Trigger.ExitActions>
                                <BeginStoryboard Storyboard="{StaticResource BorderAnimationToWhite}"/>
                            </Trigger.ExitActions>
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ListBox.ItemContainerStyle>
<ListBox.Items>
    <sys:String>hey</sys:String>
    <sys:String>du</sys:String>
    <sys:String>dux</sys:String>
    <sys:String>duy</sys:String>
    <sys:String>dua</sys:String>
</ListBox.Items>

This code is a little easier to read, as the visuals, resources, and triggers are declared separately. Maybe you could try to use EventTriggers to accomplish your goal (using the "ListBoxItem.MouseEnter" and "ListBoxItem.MouseLeave" routed events). Good luck!


text:
Q: mysql limit x, y equivalent for SQL Server l? I need to write the code for pager on the web-page and usually with mysql it is simple solutions to SELECT with LIMIT 60, 20 which means select from 60 position 20 rows.
Now I'm working with SQL Server, but should to solve this problem - I know that the TOP syntax is unsuitable, I've also heard about ROW_NUMBER() function in SQL Server, but the examples that I'd found wasn't clear enough - please help on the test table like "cars" to simply
select * from cars limit 20, 10

A: ROW_NUMBER() can't be in your where clause, so you have to use a separate select:
select *
from (select row_number() over (ORDER BY cars.CarId) as Row, *
    from cars
    ) temp
where Row between 20 and 29

A: SQL Server 2005 introduced new ROW_NUMBER() function that makes paging task easier. To achieve paging like in previous examples, get third page from Customers table where Country column is 'Spain' with 10 records per page and ordered by CompanyName stored procedure will look like this:
CREATE PROCEDURE Paging_Customers
(
  @SelectedPage int,
  @PageSize int
)
AS
BEGIN
  WITH CTE_Customers(PageNumber, ContactTitle, ContactName, CompanyName, Phone, Country)
  AS
  (
  SELECT CEILING((ROW_NUMBER() OVER
  (ORDER BY CompanyName ASC
  AS PageNumber, ContactTitle, ContactName, CompanyName, Phone, Country
  FROM Customers
  )

SELECT *
FROM CTE_Customers WHERE PageNumber = @SelectedPage
END

Then, we call this procedure (for third page and ten rows per page) with this simple line:
EXEC Paging_Customers 3, 10

A: -- Sample data
;with cars(Name) as
(
  select 'SAAB' union all
  select 'Volvo' union all
  select 'Opel' union all
  select 'Ford'
)

-- Query using row_number
select *
from
  (
   select *,
          row_number() over(order by Name) as rn
   from cars
  ) as C
where C.rn between 2 and 3

Result:
Name  rn
----  --
Opel  2
SAAB  3

A: Try this:
SELECT * FROM
    (SELECT *, ROW_NUMBER() OVER (ORDER BY col1) AS row FROM sys.databases) table1
WHERE row > 20 and row <= 30

More answers provided here on SO.


text:
Q: Wow animation: what if JS fails? I'm using Wow.JS to animate website elements. To prevent elements from first showing, then disappearing and then appearing again (animation) when using wow, I added the CSS line:
.wow { visibility:none;}

However, this causes elements to stay hidden when JS fails or disabled in browser. For that, I created this little  / script function:
<!-- wow backup -->
<noscript><style>.wow {visibility: initial;}</style></noscript>
<script>window.onload=function(){elem = document.querySelector('.wow');style = getComputedStyle(elem);if (style.visibility=='hidden') {style = document.createElement('style');document.head.appendChild(style);style.sheet.insertRule('.wow { visibility:initial;}');}}</script>

I know this place is for asking questions but I just wanted to share this little snipped for everyone using wow. How do you solve these wow issues (flickering before animating / js fails)?


text:
Q: Strip HTML, Keep Bold/Strong Tags I have a small bit of regex that strips out all HTML, and works great. What I need to do now, is strip out all HTML, but KEEP the <b> and <strong> tags in tact.
Any help would be greatly appreciated.
shortDesc = System.Text.RegularExpressions.Regex.Replace(shortDesc, @"<[^>]*>", String.Empty);

Thanks!

A: *

*Stop trying to parse HTML with a regular expression

*Use something like HTML Agility Pack

A: Here is a simple extension of your regex that should work pretty well:
Regex re = new Regex(@"<(?!/?(?:strong|b)\b)[^>]*>",
    RegexOptions.IgnoreCase);
text = re.Replace(text, "");

A: From what I gathered in your comments, a careful usage of regular expressions (though usually shunned for obvious reasons) could be employed, provided that you meet the following requirement:

*

*The HTML is not malformed.

*It won't contain "<" and ">" as part of *anything other than opening / closing tags *.

If the html page is under your control, it is fairly reasonable to assume that you could meet both conditions, otherwise I wouldn't bother.
In your case, you can use the overloaded instance of the Replace method that accepts a MatchEvaluator delegate along with its other parameters.
Usage example:
MatchEvaluator replaceCallback = new MatchEvaluator(MatchHandler);
Regex RE = new Regex(matchPattern, RegexOptions.Multiline);
string newString = RE.Replace(source, replaceCallback);

MatchHandler example:
public static string MatchHandler(Match theMatch) {
  if (theMatch.Value.StartsWith("<b>") || ...) {
    return theMatch.Value;  //return as is
  }
  //else return empty string
  return "";
}


text:
Q: How to use pubmed_lookup with url to crawl? I have a .txt file which contains many different url.
like this,
https://www.ncbi.nlm.nih.gov/pubmed/24297623
https://www.ncbi.nlm.nih.gov/pubmed/23857717
https://www.ncbi.nlm.nih.gov/pubmed/18166110
https://www.ncbi.nlm.nih.gov/pubmed/23635779

And I also found the guideline in pubmed-lookup
like this,
from pubmed_lookup import PubMedLookup
email = ' '
enter code here
url = 'http://www.ncbi.nlm.nih.gov/pubmed/22331878'
lookup = PubMedLookup(url,email)

So how can I do to read so many urls in my file in order to get the information at once?

A: You could put the urls in a list and loop through them.
with open('text_file.txt', 'r') as f:
   urls = [line.strip() for line in f]

lookup = []
for url in urls:
    lookup.append(PubMedLookup(url,email)


text:
Q: How to fix SonarLint Cognitive Complexity Error for multiple If-Else conditions I have to write a lot of conditions, but SonarLint is giving me error, asking to refactor the method to reduce its cognitive complexity.
How to resolve this. I tried switch-case, but that is also giving the same error.
public enum ExampleEnum {
    UNKNOWN(-1),
    D0_D100(0),
    D100_D200(100),
    D200_D300(200),
    D300_D400(300),
    D400_D500(400),
    D500_D600(500),
    D600_D700(600),
    D700_D800(700),
    D800_D900(800),
    D900_D1000(900);

    private int score;

    ExampleEnum(int score) {
        this.score = score;
    }
}

public static ExampleEnum getScoreType(Integer score) {
    if (Objects.isNull(score) || score < D0_D100.score) {
        return UNKNOWN;
    } else if (score >= D0_D100.score && score < D100_D200.score) {
        return D0_D100;
    } else if (score >= D100_D200.score && score < D200_D300.score) {
        return D100_D200;
    } else if (score >= D200_D300.score && score < D300_D400.score) {
        return D200_D300;
    } else if (score >= D300_D400.score && score < D400_D500.score) {
        return D300_D400;
    } else if (score >= D400_D500.score && score < D500_D600.score) {
        return D400_D500;
    } else if (score >= D500_D600.score && score < D600_D700.score) {
        return D500_D600;
    } else if (score >= D600_D700.score && score < D700_D800.score) {
        return D600_D700;
    } else if (score >= D700_D800.score && score < D800_D900.score) {
        return D700_D800;
    } else if (score >= D800_D900.score && score < D900_D1000.score) {
        return D800_D900;
    } else {
        return D900_D1000;
    }
}

A: Put the logic into a loop. something like:
public static ExampleEnum getScoreType(Integer score) {
    if (Objects.isNull(score) || score < D0_D100.score) {
        return UNKNOWN;
    for (int i =0; i< ExampleEnum.values().length-1;i++) {
        if (ExampleEnum.values()[i].score <= score && ExampleEnum.values()[i+1].score > score )
            return ExampleEnum.values()[i];
    }
    return D900_D1000;
}

A: You can use of the Stream API to remove this redundancy.
For that, you make use of the fact that the natural order of your enum-members reflects the order of the corresponding score.
As the source of the stream, you can use an array returned by the values() call or an EnumSet (which a specialized ordered collection) generated via EnumSet.allOf().
While iterating over the enum-members we need to find the first constant which score is equal or less to the given score. Because score property of your enum represent the lower boundary of the range, only one condition would be sufficient to find out if the given score falls into the range corresponding to a particular enum-member.
This logic can be expressed by using combination of operations filter() + findFirst():
public static ExampleEnum getScoreType(Integer score) {
    if (score == null || score < ExampleEnum.D0_D100.score) {
        return ExampleEnum.UNKNOWN;
    }

    return EnumSet.allOf(ExampleEnum.class).stream()
        .filter(e -> score >= e.score)
        .findFirst()
        .orElse(ExampleEnum.D900_D1000);
}

Note: you're not checking if the given score exceeds the maximum range, in such case the last enum-constant would be returned. But since its name D900_D1000 signifies that it represents a limited range values, you might want to add this check.


text:
Q: Child theme template value for style.css for parent in different folder I am making a child theme in the .../wp-content/themes/ folder however the parent theme that I am building on is in the .../wp-content/plugins/ directory.  I am able to import the parent style.css file using a directory path but when I try to do the same for the Template value, it does not work.  Similarly, the simple name of the parent theme folder does not work either, presumably because the parent theme is in a different directory.
Any ideas on how to fix this?

A: If the parent theme's non-standard location was correctly added with register_theme_directory, and I am pretty sure it must have been, then functions like get_stylesheet_directory_uri and get_template_directory_uri should work.
Reference
http://codex.wordpress.org/Determining_Plugin_and_Content_Directories#Themes


text:
Q: How to calculate the similarity measure of text document? I have CSV file that looks like:
idx         messages
112  I have a car and it is blue
114  I have a bike and it is red
115  I don't have any car
117  I don't have any bike

I would like to have the code that reads the file and performs the similarity difference.
I have looked into many posts regarding this such as 1 2 3 4 but either it is hard for me to understand or not exactly what I want.
based on some posts and webpages that saying "a simple and effective one is Cosine similarity" or "Universal sentence encoder" or "Levenshtein distance".
It would be great if you can provide your help with code that I can run in my side as well. Thanks

A: I don't know that calculations like this can be vectorized particularly well, so looping is simple. At least use the fact that your calculation is symmetric and the diagonal is always 100 to cut down on the number of calculations you perform.
import pandas as pd
import numpy as np
from fuzzywuzzy import fuzz

K = len(df)
similarity = np.empty((K,K), dtype=float)

for i, ac in enumerate(df['messages']):
    for j, bc in enumerate(df['messages']):
        if i > j:
            continue
        if i == j:
            sim = 100
        else:
            sim = fuzz.ratio(ac, bc) # Use whatever metric you want here
                                     # for comparison of 2 strings.

        similarity[i, j] = sim
        similarity[j, i] = sim

df_sim = pd.DataFrame(similarity, index=df.idx, columns=df.idx)

Output: df_sim
id     112    114    115    117
id
112  100.0   78.0   51.0   50.0
114   78.0  100.0   47.0   54.0
115   51.0   47.0  100.0   83.0
117   50.0   54.0   83.0  100.0