text:
Q: pt - Http Post request error ionic probleme No 'Access-Control-Allow-Origin' Estou com problemas na origem de acesso no ionic 3
já habilitei header('Access-Control-Allow-Origin: *'); no PHP e no apache .htaccess porem o erro continua a persistir, fiz uns testes com a extensão postman e ocorreu tudo bem, apenas no ionic que nao funciona retornando junto o erro forbidden 403..
O código no  config.xml ..
<access origin="*" />
<allow-navigation href="https://grsoftapp.tk/*" />
<allow-intent href="http://*/*" />
<allow-intent href="https://*/*" />

Auth-service.ts
import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';

let apiUrl = 'https://dionemax.tk/api/';

@Injectable()
export class AuthService {

constructor(public http: Http) {
  console.log('Hello AuthService Provider');
}
postData(credentials, type){

return new Promise((resolve, reject) =>{
  let headers = new Headers();

  this.http.post(apiUrl+type, JSON.stringify(credentials), {headers: headers}).
  subscribe(res =>{
    resolve(res.json());
  }, (err) =>{
    reject(err);
  });

});

}
}
Já tentei usar:
headers.header('Access-Control-Allow-Origin' , '*');
headers.append('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT');
headers.append('Accept','application/json');
headers.append('content-type','application/json');

e também proxy:
{
 "name": "proxy-example",
 "app_id": "",
 "proxies": [
 {
  "path": "/api",
  "proxyUrl": "https://dionemax.tk/api"
}
]
}

tentei com meta tag também..
<meta http-equiv="Content-Security-Policy" content="default-src *; img-src * 'self' data:; script-src 'self' 'unsafe-inline' 'unsafe-eval' *; style-src  'self' 'unsafe-inline' *">

E nenhum resultado sempre o mesmo erro, oq estou fazendo errado?

A: Se realmente o cabeçalho está dando acesso total, eu sugiro utilizar o pacote http do ionic e não do angular. Este é um pacote nativo.
https://ionicframework.com/docs/native/http


text: Q: JWT authentication stay logged in I am implementing an authentication system with vuejs on the front and nodejs on the back. When the user logs in a JWT is returned and gets saved on browser's local storage or cookie. Then, I assign a default header with bearer token to all the requests. If I close the tab and open it again, my application looks the local storage and if is a JWT there, it follows the same logic. So until now all good, but what happens if the user closes the application and comes back tomorrow? The same logic will be followed again, but the difference is that my default authentication header will contain an expired JWT and I will get a 401 error. So, the question is, how should I implement an auto login flow because it is bad UX to ask the user for his credentials every time he comes back to my application. Of course I should ask if the last time he visited it was a month ago, but I dont think I should do it every day. One way is to make my JWT expire in one Month but I dont think that is secure enough. Is there any kind of "official" way to implement auto login?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Difference between try block placement in java I'm curious as to what difference will it make if I placed the try block outside of a for loop versus inside of the for loop? As in if I were to write it like this:
try{
     for(int a : array){
          //some code here
     }
}catch(Exception e){}

Versus something like
for(int a : array){
     try{
          //some code here
     } catch(Exception e){}
}

Will there be a difference in how the exception is processed?
I understand that by putting the try inside the forloop, the try statement will execute and test the code each time the for loop loops. But what about when putting the for inside the try statement?
I hope what I wrote makes sense

A: Yes. Wrapping the loop around the try block, means the loop will continue in the face of the exception; trying the next iteration. With the try block around the loop any exception will terminate the loop. In either case (in real code), you should not silently swallow exceptions.


text:
Q: If inside select clause Assume I have following SQL select clause:
SELECT * FROM some_table_1 t1
  join some_table t2 on t2.some_id =  t1.id and
  t2.school_id = 56 and
  t1.is_valid = 1 and
  t2.status in (15, 16, 17, 18);

But I have also to check, if t2.status = 18, then I have also to check if t2.date < 01.01.2015
How can I add this condition to this select?

A: It sounds like you only want to join on rows that have a status of 18 when the date (which is a bad name for a column, since it's an Oracle reserved word. I'm also going to assume it's of DATE datatype) is less than 1st Jan 2015. If so, then the following should do the trick:
SELECT *
FROM   some_table_1 t1
       join some_table t2 on t2.some_id =  t1.id
                             and t2.school_id = 56
                             and t1.is_valid = 1
                             and (t2.status in (15, 16, 17)
                                  or (t2.status = 18 and t2.date < to_date('01.01.2015', 'dd.mm.yyyy.')));

A: Just add an or checking for 'not 18', or matching your second condition:
SELECT *
FROM   some_table_1 t1
join   some_table t2
on     t2.some_id = t1.id
and    t2.school_id = 56
and    t1.is_valid = 1
and    t2.status in (15, 16, 17, 18)
/* added part */
where  ( t2.status != 18
         or t2.date < to_date('01.01.2015', 'dd.MM.yyyy')
       )

A: You can add:
where t2.status <> 18 or t2.date < date '2015-01-01'


text:
Q: Restrict users from entering unwanted texts in datetime field I have a datetime field ( thru date picker) in Visual force page , while on submitting the form , i receive the entered date in the Apex class for validation purpose. How to check whether the user has entered a date or some other text , How can i check this .
<apex:inputText id="moveindate" value="{!moveindate}" onclick="DatePicker.pickDate(false, this, true);" />

A: If you are using apex:inputField that is bound to a date-time field, you do not need to validate anything. The system will automatically validate the input for you based on the user's locale. Otherwise, if it is a normal text field, you should use DateTime.parse inside a try-catch block. If the date is invalid, you'll get an exception, if not, it is a valid date-time. The best part is, it automatically tries to validate the input based on the user's locale, so some users might use 'mm/dd/yyyy' or 'dd/mm/yyyy', or some other format (of course, you're using the date picker, so that should help), and the system will usually understand their intent.

A: If you are using a input text try the code below, adjust your pattern matcher according to your desired format. Datepicker by default gives mm/dd/yyy hh:mm AM/PM.
This article will give your more insight on pattern matcher : http://salesforcesource.blogspot.com/2010/01/utilizing-apex-pattern-and-matcher.html
Page:
<apex:page controller="pattern_match">
<apex:pageMessages ></apex:pageMessages>
<apex:form >
<apex:inputText id="moveindate" value="{!moveindate}" onclick="DatePicker.pickDate(false, this, true);" />
<apex:commandButton value="check number" action="{!checkfornumber}"/>
</apex:form>
</apex:page>

Controller:
public class pattern_match {
    public string moveindate{get;set;}
    public String date_format{get;set;}
    public Pattern MyPattern  {get;set;}
    public pattern_match (){
        moveindate = '';
    }

    public pagereference checkfornumber(){
    MyPattern = Pattern.compile('(0?[1-9]|1[012])/(0?[1-9]|[12][0-9]|3[01])/((19|20)\\d\\d) ([0-1]?[0-9]|[2][0-3]):([0-5][0-9]) (AM|PM)');
    Matcher MyMatcher = MyPattern.matcher(moveindate);
        if(!MyMatcher.matches()){
        ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,'Error: valid string is mm/dd/yyyy hh:mm AM/PM.');
                    ApexPages.addMessage(myMsg);
        }
    return null;
    }
}


text:
Q: Is there a way to scale a fixed position background image without media queries? I'm guessing there is a limit to how much an image can shrink while keeping its aspect ratio before moving its position. Right now I am using a background fixed image, problem is that on the small screen when image scales down all you left is only a portion of it.
#page-header2
{
    height: 200px;
    background: url("https://images4.alphacoders.com/848/thumb-1920-848687.png")no-repeat center center/cover;

    background-position: 0 -280px;
    background-attachment: fixed;
    color: #fff;
    border-bottom: 1px #eee solid;
    padding-top: 50px;
}

You can see it live on a codepen https://codepen.io/russiandobby/pen/YzKaVpL. My question is is there anyway to keep the astronaut in a picture even on small screens without media queries?

A: Probably the easiest way is to use viewports:
width: 100vw;
height: 100vh;
background: url(../images/yourimagehere.jpg);
background-size: cover;
background-position: center, center;

I'm not a huge fan of viewports, but they do tend to work.... You might have to set the height to auto.
width: 100vw;
height: auto;

A: Try to using srcset. Following is the example i copied from https://developer.mozilla.org/en-US/docs/Learn/HTML/Multimedia_and_embedding/Responsive_images
<img srcset="elva-fairy-320w.jpg 320w,
         elva-fairy-480w.jpg 480w,
         elva-fairy-800w.jpg 800w"
 sizes="(max-width: 320px) 280px,
        (max-width: 480px) 440px,
        800px"
 src="elva-fairy-800w.jpg" alt="Elva dressed as a fairy">


text:
Q: javascript variables I need to access javascript variable:
var geocoder = new google.maps.Geocoder();
function geocodePosition(pos) {
  geocoder.geocode({
    latLng: pos
  }, function(responses) {
    if (responses && responses.length > 0) {
      updateMarkerAddress(responses[0].formatted_address);
    } else {
      updateMarkerAddress('Cannot determine address at this location.');
    }
  });
}

function updateMarkerStatus(str) {
  document.getElementById('markerStatus').innerHTML = str;
}

function updateMarkerPosition(latLng) {
  document.getElementById('info').innerHTML = [
    latLng.lat(),
    latLng.lng()
  ].join(', ');
}

function updateMarkerAddress(str) {
  document.getElementById('address').innerHTML = str;
}

function initialize() {

  geocoder.geocode( { 'address': 'london'}, function(results, status) {
   rr = results[0].geometry.location;
});

 var latLng = new google.maps.LatLng(rr);

  var map = new google.maps.Map(document.getElementById('mapCanvas'), {
    zoom: 8,
    center: latLng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });
  var marker = new google.maps.Marker({
    position: latLng,
    title: 'Point A',
    map: map,
    draggable: true
  });

  // Update current position info.
  updateMarkerPosition(latLng);
  geocodePosition(latLng);

  // Add dragging event listeners.
  google.maps.event.addListener(marker, 'dragstart', function() {
    updateMarkerAddress('Dragging...');
  });

  google.maps.event.addListener(marker, 'drag', function() {
    updateMarkerStatus('Dragging...');
    updateMarkerPosition(marker.getPosition());
  });

  google.maps.event.addListener(marker, 'dragend', function() {
    updateMarkerStatus('Drag ended');
    geocodePosition(marker.getPosition());
  });

// Onload handler to fire off the app.
google.maps.event.addDomListener(window, 'load', initialize);

This is whole script I need to get near address first so pass somehow address to convert to ltlng

A: You have to access it or pass it somewhere in the callback, like this:
var rr;
geocoder.geocode( { 'address': 'london'}, function(results, status) {
  rr = results[0].geometry.location;
  alert(rr);
});

Or pass it to another function to do additional work with the data:
geocoder.geocode( { 'address': 'london'}, function(results, status) {
  anotherFunction(results[0].geometry.location);
});

That anonymous function is the callback for the geocode() function, meaning it runs later, so rr is getting set after your alert() currently.

A: The call is asynchronous meaning that the geocoder.geocode will return immediately and only inside the anonymous callback function you are able to access it.
geocoder.geocode( { 'address': 'london'}, function(results, status) {
   alert(results[0].geometry.location);
});


text:
Q: Сортировка по полю, разбитому на несколько значений Есть таблица с некоторыми записями:
id || params
----------------------------------
01 || 120__08.06.2019,10.07.2019,0
02 || 121__09.02.2019,,1
03 || 122__14.05.2019,20.06.2019,0
04 || 123__,,
05 || 124__21.06.2019,,1

params на примере #1 расшифровывается как:
1) 120 - внутренний порядковый номер (не нужен)
2) 08.02.2019 - дата начала фактуры (может быть пустой)
3) 10.03.2019 - дата конца фактуры (может быть пустой)
4) 0 - если ноль, то имеется дата конца, если 1 - фактура бессрочная и даты нет

нужно получить все записи, отсортированные по условиям:

*

*сначала: если даты начала и даты конца нет

*затем: DESC по дате конца, если (4) параметр равен 1, то считаем дату конца максимальной

Т.е. итоговый результат ожидается:
Сегодня 27.05.2019
id || params
----------------------------------
04 || 123__,,
03 || 122__14.05.2019,20.06.2019,0
01 || 120__08.06.2019,10.07.2019,0
02 || 121__09.02.2019,,1
05 || 124__21.06.2019,,1

Структуру таблицы изменять, к сожалению, запрещено. Заранее спасибо за решение или помощь.

A:
затем: DESC по дате конца, если (4) параметр равен 1, то считаем дату конца максимальной

Если в этой фразе DESC опечатка и подразумевалась сортировка по возрастанию, то вот решение для MySQL 8.0
SELECT
  *
FROM
  data
ORDER BY
  params RLIKE '^[0-9]+__,*$' DESC,
  params RLIKE ',1$',
  STR_TO_DATE(
    CAST(REGEXP_SUBSTR(params, '[0-9]{1,2}\.[0-9]{2}\.[0-9]{4},0$') AS CHAR),
    '%d.%m.%Y,0'
  )

DB Fiddle
А вот для MySQL 5.7, у которого нет функции REGEXP_SUBSTR
SELECT
  *
FROM
  data
ORDER BY
  params RLIKE '^[0-9]+__,*$' DESC,
  params RLIKE ',1$',
  STR_TO_DATE(
    SUBSTRING_INDEX(
      SUBSTRING_INDEX(params, ',', 2),
      ',',
      -1
    ),
    '%d.%m.%Y,0'
  )

DB Fiddle


text:
Q: Css animation not working in safari (no problems in Chrome/Firefox) I have the following animation in css:
It works perfectly in chrome and firefox. In Safari (desktop and mobile) the font-family doesn't change. I have tried using a different font with no success.

.logo {
  color: #fff;
  font-family: "Roboto", sans-serif;
  font-size: 5em;
  animation: animate 1.5s linear infinite;
}

@keyframes animate {
  0%,
  100% {
    text-shadow: -4.5px -4.5px 0 #0ff, 4.5px 4.5px 0 #f00;
  }
  25% {
    font-family: "Courier New", serif; */
    font-weight: 700;
    color: #55acee;
    text-shadow: 4.5px 4.5px 0 #0ff, -4.5px -4.5px 0 #f00;
  }
}

Logo


text:
Q: Ice Cream Flavors Probability Problem(Need to check my answer) A store sells 26 flavors or ice cream(A-Z). We choose six flavors at random(repeats allowed). Find the probability that there are 2 of flavor A and at least 2 of flavor B.
My approach:
Of the six we choose, 2 for sure need to be flavor A. Then of the four remaining, at least two of them to be flavor B.
$$\sum_{i=2}^{4}{6 \choose 2}{4 \choose i}\left(\frac{1}{26}\right)^2\left(\frac{1}{26}\right)^i\left(\frac{24}{26}\right)^{4-i}$$
Is this correct?

A:
Is this correct?

Yes it is.  $$\dfrac{\dbinom 62\sum\limits_{\imath=2}^4\dbinom 4\imath 24^{4-\imath}}{26^6}$$
You could also specify that you need 2 from 6 scoops to be of flavour A and up to 2 from 4 remaining scoops to be selected from the 24 other flavours. $$\dfrac{\dbinom 62\sum\limits_{\imath=0}^2\dbinom 4\imath 24^{\imath}}{26^6}$$


text:
Q: Property of group of order $231$ If $G$ is a group of order $231$, prove that the $11$-Sylow subgroup is in the center of $G$.
My efforts:
Since $o(G)=231=3\times 7\times 11$ then using third Sylow's theorem we get the following result: $N_{11}=N_{7}=1$ and $N_3=1 \ \text{or}\  7$, where $N_p$ - the number of Sylow $p$-subgroups.
Let $H_7, \ H_{11}$ be Sylow $7$ and $11$-subgroups. Then it is easy to show that $H_7\cap H_{11}=\{e\}$ and $H_7, H_{11}$ are normal in $G$. Thus, $H_7H_{11}$ is an abelian subgroup of order $77$ in $G$.
The following inclusion is true: $Z_G\subset Z_{H_7H_{11}}=H_7H_{11}$ so $Z_G|77$ $\Rightarrow$ $|Z_G|\in \{1,7,11,77\}$.
Suppose that $N_3=1$ then $H_3$ is normal in $G$ and $H_3H_7$ is an abelian subgroup of order $21$. Applying the same method in that case we got the following options: $|Z_G|\in \{1,3,7,21\}$.
Combining this one with above we get that $|Z_G|=1, 7$. However in both cases, Sylow $11$-subgroup cannot lie in the $Z_G$.
Is this approach correct?
I have met this problem in this forum but its solution was different. I would like to complete my own solution but I am not able to do it with the case $N_3=7$.
Would be grateful for elementary solution.

A:
The following inclusion is true: $Z_G\subset Z_{H_7H_{11}}=H_7H_{11}$
  so $Z_G|77$ $\Rightarrow$ $|Z_G|\in \{1,7,11,77\}$.

I don't understand that part. What if, say, $G$ was $\mathbb{Z}_{231}$? Then $Z_G$ would be $G$ itself and certainly not included in $Z_{H_{11}H_7}$... right?
What is true using your proof below is that $$(H\cap Z_G) \subset Z_H$$ whenever $H$ is a subgroup of $G$.

Another approach:
$G$ acts by conjugation on $H_{11}$ because there is only one $11$-Sylow as you have proved. What you want is to show that this action is trivial.
Since $H_{11}$ is cyclic it is abelian, and therefore $H_{11}$ lies in the kernel of the action morphism $$G\rightarrow \operatorname{Aut}(H_{11})$$
Hence this morphism factors through $G/H_{11}$. But now $G/H_{11}$ is of order $21$ and $\operatorname{Aut}(H_{11})$ is of order $10$, therefore there are no non-trivial morphisms $$G/H_{11}\rightarrow \operatorname{Aut}(H_{11})$$
QED.


text:
Q: In agreement with, In accordance with I have a question about "in agreement with" and "in accordance with".  Dictionaries think they are approximately the same.  But for these sentence pairs:

1a. He acted in agreement with the rules.
  1b. He acted in accordance with the rules.
2a. His behavior was in agreement with the smirk on his face.
  2b. His behavior was in accordance with the smirk on his face.

, are there differences between the a-b pairs?

A: Very little, from what I can determine. This comes down to the definitions of the words and/or how they're used colloquially.
When I read the first pair, however, B implies to me that the subject does not particularly agree with the rules, but conforms to them for the sake of avoiding trouble. A implies that he is following the rules and also agrees with them as a part of his principles.
I can't determine any meaningful difference in the second pair, though. However, "in agreement with" does sound a little strange to my ear, but that's probably because I've never seen or heard something that isn't a document being used as the object of the prepositional phrase "with the..." which is a part of "in agreement with."

A: Agree is a transitive verb, requiring an active agreement, not a passive state of being in agreement with. When it is said 'we agreed' or 'we are agreed' then it is after the fact of actively agreeing.
1a. He and the rules did not agree about anything, actually or tacitly, ergo incorrect.
1b. Correct because the rules and his behaviour were consistent in what was required and what was done.
2a & 2b. His behaviour did not agree with his smirk, nor did his behaviour consult his smirk and then consequently behave accordingly, ergo both incorrect.
Better: His behaviour was consistent with the smirk on his face, meaning an observer could look at either his smirk or his behaviour and intuit or expect or understand the other.


text:
Q: (SpriteKit Objective-C) Scene Stretched Out After Transition When I transition from MainMenuScene.m to SceneLvl1.m, the transition works perfectly fine. But when transitioning back from SceneLvl1.m to MainMenuScene.m, all the sprites are distorted. They're stretched out to almost 3x their original width! Here's my transitioning code:
// Main Menu initialization.
    MainMenuScene *mainMenu = [[MainMenuScene alloc] init];

// Move to the main menu.
[self.scene.view presentScene:mainMenu
                       transition:[SKTransition fadeWithColor:[SKColor blackColor]
                                                     duration:3.0]];

So, what could I be doing wrong, here?

A: This might sound a stupid question, but are you calling simply init in it?
Any scene initialization should use initWithSize, right?
Try replacing with
    MainMenuScene *mainMenu = [[MainMenuScene alloc] initWithSize:self.view.frame.size];


text:
Q: rsync command in bash script using --from-files giving rsync: link_stat errors I been getting a lot of rsync:link stat error saying the directory does not exist then afterwards it would end up copying all the files in the remote server folder instead of files less than the time specified in the find command. Not sure if its a spacing issue or how bash interprets the parenthesis. Notice occasionally it works without issue.
Command:
rsync --no-perms --ignore-existing -vt --files-from=<(ssh admin@rig700 'find /usr/bin/rig/cache -mmin -720 -type f -exec basename {} \;') admin@rig700:/usr/bin/rig/cache /usr/bin/rig/store

A: You are explicitly calling basename on each file found by find, even if they are found in subdirectories beneath /usr/bin/rig/cache. This mean that a file like /usr/bin/rig/cache/subdir/myfile would be reported as myfile in the list given to the --files-from= option of rsync.  This file obviously does not exist in /usr/bin/rig/cache, so I would expect rsync to complain about it.
What you could do instead is to use -print0 instead of -exec basename {} \; with find, which would give the full paths of all found files, delimited by \0 (nul) characters.  Then use --files-from= with this result, and also use --from0 to specify that it's a nul-delimited list of pathnames.
Then, as the source path for rsync, use admin@rig700:.
So, I've suggested two things here:

*

*Use \0 to delimit the pathnames reported by find (this is the only character that is safe to use for delimiting pathnames on a Unix system, as newlines are allowed in pathnames).

*Make find report the full pathname of files that should be copied, and then use those path as-is with rsync.

In the end, your command would be
rsync -e 'ssh -q' --no-perms --ignore-existing -vt \
    --from0 --files-from=<(
        ssh -q admin@rig700 'find /usr/bin/rig/cache -mmin -720 -type f -print0'
    ) --no-relative  admin@rig700: /usr/bin/rig/store

The --no-relative (or --no-R) option is needed so that the pathnames read via --files-from are taken as absolute pathnames.  Without this option, a pathname such as /usr/bin/rig/cache/somefile.txt would have its initial / stripped off and be relative to your home directory on the remote host.
I've also used ssh -q, both for executing the find command on the remote system, and with the -e (--rsh) option of rsync.  I did this because your remote host seems to otherwise print a welcome banner.  This banner confuses rsync and so we must disable the printing of it, both for executing the find command and for rsync.
Summary:

*

*Don't run basename for the files found by find.  Instead get the complete paths for them from the remote system and use --no-relative with rsync.

*Make sure that the remote host's welcome banner is not printed.


text:
Q: 2 column layout with 1 aspect ratio container and a full height div I'm trying to create a 2 column layout, with one column 2/3rds wide, and the second 1/3rd.
The first column should be taken up by a video container that maintains an aspect ratio of 4:3. I think I've done that correctly by setting the padding of the video container to 75%.
I'd like the 3rd column to contain a div that expands to the full height of the row. It doesn't seem able to.
I just wanted to ask if this was because the column layout gains its height from the video container (which in turn is based on it's width)? Or have I just overlooked something simple? I'd like to stop randomly adding 'height: 100%' to everything in the vague hope that it works and actually understand what I'm missing!

Column Containing 4:3 Video

        Div in column 2

css
.container {
  border: 1px dotted red;
}

.row {
  background: #aeaeae;
  width: 100%;
  height: 100%;
}
.row::after {
  content: "";
  display: table;
  clear: both;
}

[class^="col-"] {
  height: 100%;
  float: left;
}
[class^="col-"]:not(:last-child) {
  margin-right: 10px;
}

.col-1-of-3 {
  width: calc((100% - 2 * 10px}) / 3);
}

.col-2-of-3 {
  width: calc(((100% - 2 * 10px) / 3) * 2 + 10px);
}

.video-container {
  height: 0;
  overflow: hidden;
  padding-top: 75%;
  position: relative;
  width: 100%;
}

.video {
  background: red;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  text-align: center;
  color: #fff;
}

.full-height-div {
  max-width: 100%;
  height: 100%;
  border: 1px dotted #fff;
}

codepen: https://codepen.io/anon/pen/jxzMag?editors=1100

A: You can use flexbox instead of floats to create the layout: A Complete Guide to Flexbox
By default, the elements in a flex row layout are stretched to 100% of the row height
Example: https://codepen.io/anon/pen/gzzvyO
.container{
  border: 1px dotted red;
}

.row{
  background: #aeaeae;
  display: flex;
}

.col-2-of-3{
  width: 67%;
  flex-grow: 0;
}

.col-1-of-3{
   flex-grow: 1;
   margin-left: 10px;
}

.video-container {
  height: 0;
  overflow: hidden;
  padding-top: 75%;
  position: relative;
  width: 100%;
}

.video{
  background: red;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  text-align: center;
  color: #fff;
}

.full-height-div{
  height: 100%;
  border: 1px dotted #fff;
}


text:
Q: Line break not appearing in  in IE8 This is my html

The above empty div creates a line break in IE6 & IE7.  In IE8 it is not creating any line breaks.  I do not think the style of this div is the problem.  I am not able to find a post related to this Stackoverflow.  Please clarify or point me to the right post.
EDIT:  Here's the link to the fiddle http://jsfiddle.net/spsaravanaselvan/RuvHg/.  I have two textboxes for sample.  In IE7 standard document mode, there is a small space between the textboxes but not in IE8.

A:

Is how you would normally create a line-break, closing off a div like that may not be valid as well. 'clear:both' is normally used to make sure a new element falls below floating elements, don't know why you'd use it as new line.


text:
Q: How to use the Homebrew's Ruby package instead of the Ruby package that comes with MacOS? How can I switch from using the version of Ruby that comes with MacOS to the most recent version of Ruby that I downloaded using Homebrew?
My version of MacOS appears to have ruby 2.3.7p456 (2018-03-28 revision 63024) [universal.x86_64-darwin18] already installed with the system at usr/bin/ruby. I tried running brew install ruby to get the most recent version of Ruby however when I run ruby -v the same old version shows up. I figured I probably had to add it to my path so I went to my ~/.bash_profile and added
export PATH="/usr/local/Cellar/ruby/2.6.1/bin/ruby:$PATH"

but still ruby -v shows the old version. I closed the terminal, reopened the terminal, ran source ~/.bash_profile with no luck.

A: Figured out my mistake.
export PATH="/usr/local/Cellar/ruby/2.6.1/bin/ruby:$PATH"

Should have been
export PATH="/usr/local/Cellar/ruby/2.6.1/bin:$PATH"

then just run
source ~/.bash_profile

and confirm with ruby -v or type -a ruby

A: @prettycoder's answer almost did it for me. I needed to do an rbenv init as well to get the proper version of ruby when running ruby -v:
brew install rbenv
brew upgrade ruby-build
rbenv install 2.6.5
rbenv global 2.6.5
 or
rbenv local 2.6.5
rbenv init

A: I would recommend using a version manager, e.g. rbenv
 brew install rbenv
 brew upgrade ruby-build
 rbenv install 2.6.1
 rbenv global 2.6.1
 or
 rbenv local 2.6.1

Details about rbenv here: https://github.com/rbenv/rbenv

A: Instead of
export PATH="/usr/local/Cellar/ruby/2.6.1/bin:$PATH"

It is better to use this
export PATH="/usr/local/opt/ruby/bin:$PATH"

Which is a symbolic link of ../Cellar/ruby/2.6.1. You can use readlink to print it.
Then you don't need to worry about upgrading ruby.


text:
Q: "rvest" not fetching the product details using html_nodes() I was using rvest for scraping the details of the product (Names, Price, and Availability) on amazon's product search results. I was able to fetch the webpage with read_html(), but I am not able to fetch the details of the product (Names, Price, and Availability). The page has <span> tag with class as class = "a-size-medium a-color-base a-text-normal". I have used html_nodes("span.a-size-medium a-color-base a-text-normal"), but got NA.
Here is the reproducible code:
library(rvest)
library(xml2)

url <- "https://www.amazon.in/s?k=Smartphone&rh=n%3A1389401031&ref=nb_sb_noss"

page <- read_html(url)

data <- page%>%
  html_node("span.a-size-medium a-color-base a-text-normal") %>%
  html_text()

print(data)

A: You just need to change the css selector a little bit. I was able to get the names and the prices, the availability was a little bit trickier :/
library(rvest)
library(xml2)

url <- "https://www.amazon.in/s?k=Smartphone&rh=n%3A1389401031&ref=nb_sb_noss"

page <- read_html(url)

name <- page %>% html_nodes(".a-size-medium.a-color-base.a-text-normal") %>% html_text()

price <- page %>% html_nodes(".a-price-whole") %>% html_text()


text:
Q: change class on different li's I have 18 images that gets displayed like 6 images in each row. I want to assign different class to every second last and last image in a row.
eg :-
1    2    3    4    5    6
7    8    9    10   11   12
13   14   15   16   17   18

Here class should be different for the  5   6    11    12    17    18
I am able to make equation for this as leaving 5   6
it could be 5n + (n-1)          6n
starting from n=2
   5(2) + (2-1)    6(2)  =    11    12
   5(3) + (3-1)    6(3)  =    17    18

I am not sure how to implement this using jquery.
AS 5   6   should be as it is and then equation for 11,12,17,18 and starting n=2

 Sponsor Name HereLorem ipsum dolor sit amet, consectetur edt adipiscing elit. Nullam dignissim enim ut co. Lorem ipsum dolor sit amet, consectetur bel adipiscing elit nullam digniss

In em I want to add class popup-left

A: You don't need jQuery for this.
The following selector will apply the styles you require:
li:nth-child(6n) img, li:nth-child(6n-1) img
{
    /* styles here */
}

See Updated Demo

A: If I well understood (and assuming you have li elements)
$('li:nth-child(6n+4)').addClass('class1');
$('li:nth-child(6n+5)').addClass('class2');

or just define that selectors as straight css (but in this case it won't work on IE<9)
li:nth-child(6n+4) {
  ...
}

li:nth-child(6n+5) {
  ...
}

if needed change li with your real element (img, p or anything else)


text:
Q: Selecting the dataframe I have dataframe like this:
   Tahun  Jan   Feb     Mar     Apr     Mei     Jun     Jul     Ags     Sep     Okt     Nov     Des
0  2020   0.39  0.28    0.10    0.08    0.07    0.18    -0.10   -0.05   -0.05   0.07    0.28    0.45
1  2021   0.26  0.10    0.08    0.13    0.32    -0.16   0.08    0.00    0.00    0.00    0.00    0.00

I want to select the current value that != 0.00 which the value is on July 2021. So, the expected output is the dataframe:
Tahun  Month  Value
2021   Jul    0.08

I did:
dfs = df.where(df != 0.00).stack()
r, c = dfs.last_valid_index()
x = dfs.loc[r, [c, 'Tahun']]

and the output looks like:
1  Tahun    2021.00
   Jul         0.08
dtype: float64

How to convert that? thanks

A: You can use your solution with set Tahun to index first:
df = df.set_index('Tahun').rename_axis('Month', axis=1)

s = df.where(df != 0.00).stack()

df2 = s.loc[[s.last_valid_index()]].reset_index(name='Value')
print (df2)
   Tahun Month  Value
0   2021   Jul   0.08

Or solution with melt, but for correct ordering is convert Months to ordered Categorical:
df = df.melt(id_vars=["Tahun"],
        var_name="Month",
        value_name="Value")

cats = ['Jan', 'Feb', 'Mar', 'Apr','Mei', 'Jun', 'Jul', 'Ags', 'Sep', 'Okt', 'Nov', 'Des']
df['Month'] = pd.Categorical(df['Month'], ordered=True, categories=cats)
df = df.sort_values(['Tahun','Month'])

df2 = df[df['Value'].ne(0)].tail(1)
print (df2)
    Tahun Month  Value
13   2021   Jul   0.08


text:
Q: openX alternatives, maybe self hosted I've been using openX self hosted ad management software lately, but it's sooo slow.
Goal: I need to be able to show an ad for 10 clicks then disable the ad, and do it daily.
Problem: When I set openX at 10 clicks per day, its so slow that it may disable the ad after like 30 clicks instead, that's no good.
Can anybody recommend an ad management software that can do what I want, and is free or cheap?  Im looking at adzerk atm, which is free, but my campaigns are pending, and thats silly.
Im on the hunt for an openX alternative.

A: Revive Adserver : http://www.revive-adserver.com
Best & Free Open Source Ad Server (Previously known as OpenX Source).
Currently Revive Ad Server  Team maintains the code & continuously fixing bugs , security updates ,adding  new features etc .
You can scale more than 1 Billion Impressions per Day using cluster setup
Example :
https://www.serverstack.com/managed-apps/openx
You can upgrade the current OpenX source 2.8.X version to Revive Ad Server
Also easily customize the source code as per 10 click per day
Regards,
Chinnu.G

A: Broadstreet: http://broadstreetads.com
We've moved quite a few high-traffic publishers over from OpenX with an automated migration. We were big fans of OpenX in the past, but finally faced the reality of its technology stack (including Revive's) and built an alternative: http://broadstreetads.com/blog/why-openx-is-slow/


text:
Q: submit button not working in GeckoFX I have this code:
<input type="button" onmousedown="IamTyping(0);" style="font-size:16px;" value="enter">

and tried this in C#:
GeckoInputElement enter = new GeckoInputElement(myBrowser.Document.GetElementByTagName("input").DomObject);
enter.click();

C# doesn't have any error, but it doesn't work!

A: try the following code
GeckoInputElement enter = (GeckoInputElement)myBrowser.Document.GetElementsByTagName("input")
    .First(inp => ((GeckoInputElement)inp).Value == "enter");

DomEventArgs ev = browser.Document.CreateEvent("MouseEvent");
ev.DomEvent.InitEvent(new nsAString("mousedown"), true, true);
enter.GetEventTarget().DispatchEvent(ev);

ev = browser.Document.CreateEvent("MouseEvent");
ev.DomEvent.InitEvent(new nsAString("mouseup"), true, true);
enter.GetEventTarget().DispatchEvent(ev);

enter.click();


text:
Q: Clarifai Video returns Bad Request I've successfully uploaded Images and wanted to see how Clarifai behaves with Videos. According to the DOC/Github, we only have to point to a movie file and change the parameter is_video=True
model.predict_by_filename("/Users/xxx/Desktop/h264.mov", is_video=True)

Doing this it kinda tries to upload (network traffic shows up), but then i am getting the following error:
clarifai.rest.client.ApiError: POST models/aaa03c23b3724a16a56b629203edc62c/versions/aa9ca48295b37401f8af92ad1af0d91d/outputs FAILED. code: 400, reason: Bad Request, error_code: 10020, error_description: Failure, error_details: None

A: Have thought of using mjpeg instead of h264 as it is "stills" encapsulated as a movie file. Then you can process stills instead of video and your worlflow is greatly improved.


text:
Q: Integral of time with respect to Brownian motion I am trying to compute $\int_0^T t\ dB_t$ where $B$ is the standard Brownian motion.
To this end I define the sequence of simple predictable functions
$$ f_n = \sum_{i=0}^{2^nn-1}t_i^n1_{(t_i^n,t_{i+1}^n]}(t) \quad \text{where} \quad t_i^n = i2^{-n}$$
Then I show that $\lVert f_n-t\rVert_{\mathcal{L}^2(B)} \rightarrow 0$. The convergence in $\mathcal{L}^2(B)$ is equivalent to showing that
$$\lim_{n\rightarrow\infty} E \int_0^m (f_n-t)^2\ d[B]_t = 0 \quad \forall{m} \in \mathbb{N}$$
First, I fix $m$ and choose $n > m$. I also drop the expectation.
\begin{align}E \int_0^m (f_n-t)^2\ d[B]_t \leq&  \int_0^n (f_n-t)^2\ dt\\
= & \frac{1}{3}n2^{-2n} \end{align}
Now I let $n \rightarrow \infty$. Since $m$ was arbitrary, I have convergence in $\mathcal{L}^2(B)$.
Following the definition of stochastic integration of simple predictable processes I write
$$\int_0^Tf_n\ dB_t = \sum_{i=0}^{2^nn-1}t_i^n(B_{T\wedge t_{i+1}^n}-B_{T\wedge t_i^n})$$
I start having problems at this point. I need to get rid of the wedge sign and I do that intuitively. For a given $T$, I choose $n > T$ so that for some $m \in \mathbb{N}$
$$\sum_{i=0}^{2^nn-1}t_i^n(B_{T\wedge t_{i+1}^n}-B_{T\wedge t_i^n}) = \sum_{i=0}^{m-1}t_i^n(B_{t_{i+1}^n}-B_{t_i^n}) + t_{m}(B_T-B_{t_m^n})$$
Now I let $n$ go to infinity. But I don't see in full rigour how this is the same thing as
setting up a mesh $\pi: 0 = t_0 < t_1 < \ldots < t_r = T$ where $t_i = \frac{iT}{r}$ and letting $r$ go to infinity in
$$\sum_{i=0}^{r-1}t_i(B_{t_{i+1}}-B_{t_i})$$
Because eventually I need to show that the latter sum converges to something in $L^2$ as $r\rightarrow \infty$.
So this was my first question. The second one is how do I show that the sum
$$\sum_{i=0}^{r-1}t_i(B_{t_{i+1}}-B_{t_i})$$ converges to something (I don't know what that is yet) in $L^2$.
We are given a hint to use summation by parts. So I use the hint to get
$$\sum_{i=0}^{r-1}t_i(B_{t_{i+1}}-B_{t_i}) = TB_T - \frac{1}{r}\sum_{i=0}^{r-1}B_{t_{i+1}}$$
I have no clue what to do with the second part of this sum.
My apologies if there is any nonsense, gibberish in what I wrote as I myself am confused in this arduous process of learning stochastic calculus.

A: *

*Because of continuity of Brownian motion, it doesn't matter how we choose the partition as long as the mesh size converges to $0$. The continuity of Brownian motion implies that the term
$$t_m (B_T-B_{t_m})$$ converges (almost surely and in $L^2$) to $0$ if we let $n \to \infty$. Since we know that the result does not depend on the chosen partition, the best choice (regarding notation) is $t_i := \frac{i}{n} T$, $i=0,\ldots,n$,

*Hint: $$\frac{1}{r} \sum_{i=0}^{r-1} B_{t_{i+1}} = \sum_{i=0}^{r-1} B_{t_{i+1}} (t_{i+1}-t_i).$$ Do you recognize the expression at the right-hand side? Think of $$\sum_{i=0}^{r-1} f(t_{i+1}) (t_{i+1}-t_i)$$

A: For the second question I came up with this answer. We have that for each $r \geq 1$ $$\sum_{i=0}^{r-1}t_i(B_{t_{i+1}}-B_{t_i}) \sim \mathcal{N}\left(0,\frac{T^3}{6}\left(1-\frac{1}{r}\right)\left(2-\frac{1}{r}\right)\right)$$
Furthermore, $$\sum_{i=0}^{r-1}t_i(B_{t_{i+1}}-B_{t_i}) \rightarrow \int_0^Tt\ dB_t \quad \text{in} \quad L^2$$
We have the result that if a sequence of normal random variables $(X_r)_r$ converges to $X$ in distribution, then $X$ is normal as well. We have $L^2$ convergence so weak convergence is implied. So then $\int_0^Tt\ dB_t$ must have a normal distribution for which mean is $0$ and variance is given as
$$\sigma^2 = \lim_{r\rightarrow\infty} \frac{T^3}{6}\left(1-\frac{1}{r}\right)\left(2-\frac{1}{r}\right) = \frac{T^3}{3}.$$

Here is a much easier to way compute the variance.
First of all $\int_0^Tt\ dB_t$ is a martingale. It immediately follows that its mean is $0$. To compute the variance we make use of Ito isometry, i.e.
$$E\left[\left(\int_0^Tt\ dB_t\right)^2\right] =  E\left[\int_0^Tt^2\ d[B]_t\right] = \frac{T^3}{3}$$


text:
Q: How can one deploy Apollo Server with Create-React-App? I'm trying to deploy my application to a production environment, but having some trouble wiring it all together.
I've got a create-react-app for my frontend, which is served up by a simple express/serve server. On the backend, I've got NGINX proxying successfully to my API server, which is using Apollo to serve my data. The API is running on port 4000.
The Apollo-Server is as-follows, and works fine:
import { resolve } from "path";
import dotenv from "dotenv";
const envi = process.env.NODE_ENV;
dotenv.config({ path: resolve(__dirname, `../.${envi}.env`) });

import "reflect-metadata";
import { connect } from "./mongodb/connect";
import { buildSchema } from "type-graphql";
import { ApolloServer } from "apollo-server";
import { SenateCommitteeResolver, HouseCommitteeResolver } from "./resolvers";
import { populateDatabase } from "./util";

(async () => {
  // Connect to MongoDB
  await connect();
  console.log(` Databases connected`);
  const schema = await buildSchema({
    resolvers: [HouseCommitteeResolver, SenateCommitteeResolver],
    emitSchemaFile: resolve(__dirname, "schema.gql"),
  });

  // If development, set database docs
  envi === "development" && (await populateDatabase());

  // Launch the server!
  const server = new ApolloServer({
    schema,
    playground: true,
  });

  // Server listens at URL
  const { url } = await server.listen(4000);
  console.log(` Server ready, at ${url}`);
})();

I'm trying to connect my express server to the Apollo Server, but that's where I'm running into problems. The application is supposed to connect using Apollo's Client and HTTP Link, because I'm using Apollo Client on the frontend too:
import React, { useEffect } from "react";
import { AppRouter } from "./routers";
import ReactGA from "react-ga";
import { ApolloProvider } from "@apollo/client";
import client from "./graphql/client";

import "./styles/index.scss";

function App(): React.ReactElement {
  return (
    <ApolloProvider client={client}>
      <AppRouter />
    </ApolloProvider>
  );
}

export default App;

And here's the client file:
import { ApolloClient, InMemoryCache, createHttpLink } from "@apollo/client";

const httpLink = createHttpLink({ uri: process.env.REACT_APP_API as string });
const cache = new InMemoryCache();

const client = new ApolloClient({
  link: httpLink,
  cache,
  connectToDevTools: true,
});

export default client;

However, when the user navigates to the site and the site itself tries to make a request to my backend, I'm getting a CORS error:
Access to fetch at 'https://www.cloture.app/' from origin 'https://cloture.app' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

What's going wrong? How can I connect Apollo's client with my Apollo Server on the backend?

A: Adding it here, because the suggestion requires some code.
Try adding :
const server = new ApolloServer({
    schema,
    playground: true,
    cors: {
      origin: "*" // it will allow any client to access the server, but you can add specific url also
    }

  });


text:
Q: Liouville measure in the energy level Again banged my head trying to make sense of the Mechanics course and hit a rock bottom with another problem. I would really appreciate the step by step explanation  for the results of it.
We have a symplectic manifold (M, ω), a Hamilton function H : M -> $\mathbb{R}$ and c a regular value of H and consider the level $E_c := H^{-1}(c)$.
a) Show that $E_c$ is a manifold and give its dimension. Also show that for any $x\in E_c$ the tangent space at $E_c$ is given by $T_xE_c = kerdH_x$
From this we are given the following facts: let the Liouville volume 2n-form
 $\Omega$:= $\omega \wedge \omega \wedge...\wedge \omega$ the n-fold
wedge product. The flow $\phi^t$ of the Hamiltonian vector field $X_H$ preserves
$\Omega$. Also, the level $E_c$ is preserved by the same $\phi^t$.
,Consider $x\in E_c$ and tangent vectors $\xi_1, \xi_2; ...\xi_{2n-1} \in T_xE_c$; having to define $ \Omega_{c,x}(\xi_1, \xi_2; ...\xi_{2n-1})$
To this end we write the equation
$ \Omega_{x}(\eta, \xi_1, \xi_2; ...\xi_{2n-1}) = dH_x(\eta)\wedge \Omega_{c,x}(\xi_1, \xi_2; ...\xi_{2n-1})  $, $\eta \in T_xM$ is arbitrary.
b)Show that this equation determines $\Omega$ in a unique way, independent of $\eta$
c)Also show that $\Omega_c$ is a nondegenerate (2n-1) form, i.e. a volume form
on $E_c$
d) Finally show that $\phi^t|E_c$ preserves $\Omega_c$


text:
Q: Несколько исполняемых файлов для проекта VS2017 У меня есть решение (.sln) с 1 проектом. Можно ли как-то заставить VS2017 генерировать по этому проекту несколько исполняемых файлов (.exe), а именно: 1) win32 приложение; 2) win64 приложение; 3) приложение, использующее другой platform toolset (для старых версий Windows)?
Я знаю, как сделать это по отдельности, то есть каждый раз менять настройки и перезаписывать существующие файлы, но это, очевидно, неудобно.


text:
Q: Error installing virtualbox-6.1 dpkg error I am using .deb package downloaded from Oracle website, and I even had it installed properly earlier. But now there's not really any change to the system however it throws below error. Also I can see the icon of it in the menu but it does not open. Using Ubuntu 20.04.1
What could be the problem?
$ sudo dpkg -i Software/virtualbox-6.1_6.1.14-140239~Ubuntu~eoan_amd64.deb
Selecting previously unselected package virtualbox-6.1.
(Reading database ... 240840 files and directories currently installed.)
Preparing to unpack virtualbox-6.1_6.1.14-140239~Ubuntu~eoan_amd64.deb ...
Unpacking virtualbox-6.1 (6.1.14-140239~Ubuntu~eoan) ...

dpkg: dependency problems prevent configuration of virtualbox-6.1:
virtualbox-6.1 depends on libqt5opengl5 (= 5.0.2); however:
Package libqt5opengl5 is not installed.
virtualbox-6.1 depends on libqt5printsupport5 (=5.0.2); however:
Package libqt5printsupport5 is not installed.
virtualbox-6.1 depends on libsdl1.2debian (= 1.2.11); however:
Package libsdl1.2debian is not installed.
virtualbox-6.1 depends on python (<< 2.8); however:
Package python is not installed.
virtualbox-6.1 depends on python (= 2.7); however:
Package python is not installed.
virtualbox-6.1 depends on python:any (= 2.6.6-7~);
however:
dpkg: error processing package virtualbox-6.1 (--install):  dependency problems - leaving unconfigured
Processing triggers for systemd (245.4-4ubuntu3.2) ...
Processing triggers for gnome-menus (3.36.0-1ubuntu1) ...
Processing triggers for desktop-file-utils (0.24-1ubuntu3) ...
Processing triggers for mime-support (3.64ubuntu1)...
Processing triggers for hicolor-icon-theme (0.17-2) ...
Processing triggers for shared-mime-info (1.15-1) ...

Errors were encountered while processing:  virtualbox-6.1

A: Read output. "dependency problems"
libqt5opengl5
libqt5printsupport5
libsdl1.2debian
...
etc.
sudo apt install -f -y


text:
Q: Find the $P[X_1 \leq X_2]$ given that $X_1$ and $X_2$ are exponential random variables $X_1$ and $X_2$ are 2 independent exponential random variables of parameters of 1 and 2 respectively. If so then
$P[X_1 \leq X_2]=?$
This is what i have to find! What i did was:
If i set $X_1=t \to P[t\leq X_2]$ then
$P[X_1 \leq X_2]=\int_0 ^\infty P[X_2\geq t] f_{x_1}(t)dt]=$
$\int_0^\infty e^{-\lambda_2t}\lambda_1 e^{-\lambda_1 t}dt$
where $\lambda_1=1$ and $\lambda_2=2$ and the rest is just computations!
WHat i wanted to know was:
First of all Is the line of thinking correct?
And Second: Can i apply this way of solving things if $X_1$ and $X_2$ are lets say Bernoulli, Binomial, Geometric, Poisson distributions and for the others?

A: Yes I see what you are doing and that works.
Alternatively, joint pdf $f(X_1, X_2) = f(X_1) f(X_2)$ as $X_1$ and $X_2$ are independent.
$X_1 \leq X_2 \implies 0 \leq X_1 \leq X_2, 0 \leq X_2 \leq \infty$
So integral becomes,
$\displaystyle \lambda_1 \lambda_2 \int_0^{\infty} \int_0^{x_2} e^{-(\lambda_1 x_1 + \lambda_2 x_2)} \ dx_1 \ dx_2 $
Here we have $\lambda_1 = 1, \lambda_2 = 2$ so,
$P(X_1 \leq X_2) = \displaystyle 2 \int_0^{\infty} \int_0^{x_2} e^{-(x_1 + 2 x_2)} \ dx_1 \ dx_2 $

A: Doing a drawing of the problem you see that the integration area is the infinite triangle over $X=Y$ thus
$$P(X<Y)=\int_0^{\infty}e^{-x}\left[  \int_x^{\infty}2e^{-2y}dy \right]dx=\frac{1}{3}$$


text:
Q: Search photos in Instagram where I'm on a photo I want to get photos (where I'm marked) using Instagram API. Is this possible?
I am looking for a way to get it without listing all photos from my followers(Retrieve all photos where I have been tagged).

A: //Try This Instagram API ,,,,,,,,,,,,
https://api.instagram.com/v1/users/self/media/recent/?access_token=%@

A: The existing Instagram API endpoints don't support finding media tagged by user. I thought that the existing endpoint for finding recent media by tag might work:
GET/tags/tag-name/media/recent

but it only returned media with matching hashtags. It doesn't search for usernames.


text:
Q: Would APC work well for a highly dynamic PHP website? This might be a trivial question for some, but I could not find the answer myself yet.
If I understand correctly APC does two things. Keep the PHP pages in byte code so they are delivered faster. It can also cache data so we can query them faster.
I'm interested in the byte code feature, which if I understand correctly comes by default. I will not need to modify my code much for this to work.
My question is this: Our website is a social network site and our PHP pages are highly dynamic. They are affected by many factors every time they are called.
Would we still benefit from using APC?
Thanks,
Haluk

A: Yes that is exactly the type of situation that APC works great in (although it benefits all types of pages). It's essentially a "compiler" for PHP code.
Unless the PHP code behind is changing more often than the page is loaded (I don't think that would EVER happen), APC will benefit you.
For any static pages (or static parts of pages), you might want to look into caching the output to files on the system. That way, when you need to display that component, instead of running PHP code you can just serve up the cached HTML.

A: It wont work so well for the dynamic parts of your website, unless you cache them individually, but you will benefit from the bytecode cache without any changes to your code
Further reading

*

*http://techportal.inviqa.com/2010/10/07/understanding-apc/

*http://devzone.zend.com/article/12618-Using-APC-with-PHP


text:
Q: HtmlUnit's WebClient fails on second identical loadWebResponse() call I'm attempting to write tests for a very long and kludgy "getPost" method in a webapp I'm working on for my job. I'm using JUnit, HtmlUnit, and Jetty's ServletTester to approximate sending a request to a servlet and receiving a response. I've managed to get it mostly working, but I'm having a problem. I'm trying to test the login functionality. If the user logs in successfully, the server should send some JSON back to the client with the user's information. If the user is already logged in, the server should send back "result": "failure" and an error message.
My problem comes when I try to test the second requirement. I can log in successfully, and get the correct data back. However, when I try to send the request again, it returns 404: not found. I tried breaking the code up into different tests, but I have to be able to call login twice in order to test the second requirement. Later tests in the JUnit file run just fine, and the servlet is staying connected the same time. I tried making a second, identical request, but that also failed. I've searched the internet to no avail. In short, I'm stumped.
Here's what I'm working with (unnecessary code has been edited out):
//In MyFunServlet class:
private final static String USERID_ATTRIBUTENAME = "userid";
void doPost(HttpServletRequest request, HttpServletResponse response) {
    String action = request.getParameter("opt");
    final HttpSession session = request.getSession();

    if(action != null){
       Long userId = (Long)session.getAttribute(USERID_ATTRIBUTENAME);
       if(userId != null){
           //do stuffz
       } else {
           if(action.equals("login")) {
               User user = LoginUser(request, response);
               try{
                   JSONObject json = new JSONObject();
                   if(request.getAttribute("result") == "success"){
                       json.put("result", "success");
                       json.put("id", user.getId());
                       json.put("name", user.getName());
                   } else {
                       json.put("result", "failure");
                       json.put("message", request.getAttribute("message"));
                   }
                   SendJSONResponse(json, request, response);
               }catch(Exception e){
               }
            } else {
                System.out.print("Unknown opt: " + action);
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            }
        }
    }
}

private void LoginUser(HttpServletRequest request, HttpServletResponse response){
    final HttpSession session = request.getSession();
    User user = null;
    Long userId = (Long)session.getAttribute(USERID_ATTRIBUTENAME);
    if(userId != null){
        request.setAttribute("result", "failure");
        request.setAttribute("message", "The user is already logged in.");
    } else {
        final String email = request.getParameter("accountEmail");
        final String password = request.getParameter("accountPassword");
        if(email != null) {
            user = helperClass.magicallyGetUserByEmail(email);
            if(user != null){
                if(user.getPassword().equals(password)){
                    session.setAttribute(USERID_ATTRIBUTENAME, user.getId();
                    request.setAttribute("result", "success");
                }
            }
        } else {
           request.setAttribute("result", "failure");
        }
    }
    return user;
}

private void SendJSONResponse(JSONObject json, HttpServletRequest request,
                                HttpServletResponse response) {
    String contentStr = json.toString();
    response.setContentType("application/json");
    response.setStatus( HttpServletResponse.SC_OK);
    response.setContentLength(contentStr.length());
    response.getWriter().print(contentStr);
    response.flushBuffer();
}

For reference purposes, this file is 1084 lines long. The doPost method is about 900 of those. Disclaimer: this is not my code. I did not write it. I only have to test it.
Now for the test:
//In MyFunServletTest.java:
//using JUnit 4

public class MyFunServletTest {
    static ServletTester tester;
    static String baseUrl;

    WebClient webClient = new WebClient();

    User user;
    WebRequest loginRequest;

    @BeforeClass
    public static void initClass(){
        tester = new ServletTester;
        tester.setContextPath("/");
        tester.addServlet(MyFunServlet.class, "/fun.service");
        baseUrl = tester.createSocketConnector(true);
        tester.start();
    }

    @AfterClass
    public static void cleanClass() {
        tester.stop();
    }

    @Before
    public void preTest(){
        //taking values from our magical test user
        user = new User();
        user.setEmail("blah@blah.com");
        user.setPassword("secure");

        loginRequest = new WebRequest(baseUrl + "/fun.service", HttpMethod.POST);
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new NameValuePair("opt","login"));
        params.add(new NameValuePair("accountEmail", user.getEmail());
        params.add(new NameValuePair("accountPassword", user.getPassword());
        loginRequest.setRequestParameters(params);

    }

    @Test
    public void testLogin() {
        WebResponse response = webClient.loadWebResponse(loginRequest);
        JSONObject responseJSON = new JSONObject(response.getContentAsString());

        //this test passes
        assertEquals("success", responseJSON.getString("result"));

        response = webClient.loadWebResponse(loginRequest);

        //this test fails
        assertTrue(404 != response.getStatusCode());

        //this then causes an error, as response.getContentAsString() is null.
        esponseJSON = new JSONObject(response.getContentAsString());
    }
}

Help? Where am I missing something?
Thanks.

A: Without the ability to run the test myself, I can only offer some approaches:

*

*Try creating two JSONObject objects to store the two responses separately, and compare the two (either print them or using the debugger), see if anything looks odd there.

*If that doesn't tell you anything, create two separate identical request instances and use each.

*Then try tracing through the call to loadWebResponse to see exactly what URL is being requested (cranking up the log level might tell you this, too).
If the 404 is correct, then the second request is somehow being mangled, but the question would be WHERE.


text:
Q: How to restore previous activity actions on Notification Click I have an Activity that is performing some download function. The activity will pop up a progress dialog and disable user interaction while downloading as well as create a notification progress.
I want the user to be able to click on the notification and return the user to the activity that has the dialog showing the progress and disabled user interaction (basically what happens when the user goes to the home screen and then reopens the app).
My current attempts seem to relaunch the activity, download still occurring, but dialog is gone and user interaction is disabled. How can I fix this?
My approaches:
set intent action
private static void buildNotification()
{
    //create intent  for onClick
    Intent resultIntent = new Intent(activity,  activity.GetType());
    resultIntent.SetAction(Intent.ActionMain);
    resultIntent.AddCategory(Intent.CategoryLauncher);
    PendingIntent resultPendingIntent = PendingIntent.GetActivity(activity, 0, resultIntent, PendingIntentFlags.UpdateCurrent);

    //set builder

    builder.SetContentIntent(resultPendingIntent);
    notificationManager = activity.GetSystemService(Context.NotificationService) as NotificationManager;
}

set intent flags
private static void buildNotification()
{
    //create intent  for onClick
    Intent resultIntent = new Intent(activity,  activity.GetType());
    resultIntent.SetFlags(ActivityFlags.SingleTop | ActivityFlags.ClearTop);
    PendingIntent resultPendingIntent = PendingIntent.GetActivity(activity, 0, resultIntent, PendingIntentFlags.UpdateCurrent);

    //set builder

    builder.SetContentIntent(resultPendingIntent);
    notificationManager = activity.GetSystemService(Context.NotificationService) as NotificationManager;
}

A: I ended up putting just SingleTop flag on the intent. Hopefully this helps someone:
private static void buildNotification()
{
        //create intent  for onClick
    Intent resultIntent = new Intent(activity, activity.GetType());
    resultIntent.SetFlags(ActivityFlags.SingleTop);
    PendingIntent resultPendingIntent = PendingIntent.GetActivity(activity, 0, resultIntent, PendingIntentFlags.UpdateCurrent);

    //set builder

    builder.SetContentIntent(resultPendingIntent);
    notificationManager = activity.GetSystemService(Context.NotificationService) as NotificationManager;
}

By the way I'm using Xamarin.Android


text:
Q: Macbook Pro runs very hot when using VirtualBox I am using a Macbook Pro and switch to running a Windows VM through VirtualBox for some work I am doing for a client.
I notice that, very quickly, the Macbook heats up to extremely hot temperatures (just touching the case is almost hot enough to start hurting). Has anybody else run into this issue? Are there any resolutions to fixing it? I know the Mac can technically handle it, but I don't like mixing heat and my computer - especially for multiple hours a day.
Edit
I want to be clear (since I wasn't above). The MacBook runs at normal temperatures when I run anything else. The only time it gets hot is when I use VirtualBox running Windows. (Even VBox running Linux VMs is fine.)

A: I've had instances where my MacBook runs pretty hot with either VMs or intensive applications. My answer was to install smcFanControl which installs a menubar icon where I can monitor the temperature and turn up the fan either before I run a VM or when it gets hot.


text:
Q: Get exact reuest header in node http Is there a way to see/inspect the complete request header send by the native node http module? I'm doing sth. like that:
const req = Http.request(http_request_options, res => {...

and I' like to see if there are any cookies send with this request.

A: I think Node's documentation will tell you of any headers it will add. Reviewing it, it looks like by default it will add the Host header, but I didn't see any others unless you add auth in the options. (And a quick test using the methods below confirmed that.)
Also, request returns a ClientRequest object, which has methods you can use to inspect it, such as getRawHeaderNames (new in v15.13) and getHeader, which you could use to see what headers are present.
Externally, you could always set up a quick HTTP server (perhaps also using Node) to see what headers you receive...


text:
Q: Conversion from string to char - c++ For a program I'm writing based on specifications, a variable is passed in to a function as a string. I need to set that string to a char variable in order to set another variable. How would I go about doing this?
This is it in the header file:
void setDisplayChar(char displayCharToSet);

this is the function that sets it:
void Entity::setElementData(string elementName, string value){
    if(elementName == "name"){
            setName(value);
    }
    else if(elementName == "displayChar"){
    //      char c;
      //      c = value.c_str();
            setDisplayChar('x');//cant get it to convert :(
    }
    else if(elementName == "property"){
            this->properties.push_back(value);
    }
}

Thanks for the help in advanced!

A: you just need to use value[0] and that returns the first char.
char c = value[0];

A: You can get a specific character from a string simply by indexing it. For example, the fifth character of str is str[4] (off by one since the first character is str[0]).
Keep in mind you'll run into problems if the string is shorter than your index thinks it is.
c_str(), as you have in your comments, gives you a char* representation (the whole string as a C "string", more correctly a pointer to the first character) rather than a char.
You could equally index that but there's no point in this particular case.


text:
Q: How can you modify the MS Dynamics AX Business Data Lookup Snap-in to select the company to logon to? Can anyone provide some coding (C#) modification that can be done or any other practical way? or of course point me somewhere that has done it already.

A: I assume the Snap-In is using the settings from the Business Connector. Find Dynamics AX Configuration utility in the Administators Controlpanel, and point the Business Connector to whatever AOS you want it to connect, and try fill inn chosen company there.


text:
Q: adding button on video background in html and css. Z-index not functioning trying to add a  button on fullscreen video background in html and css. Z-index not functioning tried each element separately and they work. But they dont stack on top of each other. i might be missing an important link that i am unaware of.
adding the html and css code
<!DOCTYPE html>

<title>homepage</title>

<link type="text/css" rel="stylesheet" href="stylesheet2.css"/>

    <video id ="videobg" preload="auto" autoplay="true" lopp="loop">
<source src="secret.3gp" > video not supported<video/>
</video>

CSS FILE

#button{
left: 490px;
  top: 560px;
  position:fixed;
  z-index:1
}
#videobg{
    min-width:100%;
    min-height:100%;
    width: auto;
    height:auto;
    position:fixed;
    z-index:-1;
}

A: Try just wrapping the video in a div.  This worked for me: jsfiddle.
   <!DOCTYPE html>

            <link type="text/css" rel="stylesheet" href="stylesheet2.css"/>
            <title>homepage</title>

                <video id ="videobg" preload="auto" autoplay="true" loop>
                    <source src="secret.3gp" >
                </video>

CSS FILE
#button{
left: 490px;
  top: 560px;
  position:fixed;
  z-index:1
}
#videobg{
    min-width:100%;
    min-height:100%;
    width: auto;
    height:auto;
    position:fixed;
    z-index:-1;
}


text:
Q: Getting SPContext inside event receiver I created an Event Receiver, but the problem is that I can't get a reference to the SPContext: SPContext.Current returns null. I need it to add some lists to the site. Does anyone have an idea of how I could get it?
Also I tried putting break points inside the event receiver, but FeatureActivates never triggers for some reason. What is the correct event to use when a list is activated right after de deployment?

A: I figured that the scope of the feature matters. If you deployed the feature in the site scope then you can get the web using this line of code:
SPWeb web = (properties.Feature.Parent as SPSite).OpenWeb();

A: I know this thread is kind of old, but really you should use:
SPWeb web = properties.OpenWeb()

as per SP best practices:  http://msdn.microsoft.com/en-us/library/ee724407.ASPX
It ensures you have no objects to dispose and keeps you from hitting a casting error.

A: You can't get SPContext inside handlers - this is by design. You should use event properties passed as argument to the handler to get reference to current web, list item etc.
For example in feature activated handler you can do it like this:
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
    SPWeb web = properties.Feature.Parent as SPWeb;
    //Some code with web
}

If Feature Scope is Site then
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
        SPSite site = properties.Feature.Parent as SPSite;
        //Some code with web
}


text:
Q: mp4 video starts at different time on Quicktime/AVplayer vs Chrome/Firefox I have a very strange issue. My OSX app is generating an mp4 video based on a screen cast. For some reason, if I open this video in Quicktime or any OSX-based AVPlayer, it will start about 14-15 frames in advance of frame 0. If I open the mp4 with Chrome or Firefox, it will actually start playing at frame 0.
What could cause this ignoring of beginning frames? Here's a screenshot  of a timer countdown comparing Quicktime vs Firefox at time zero. Notice how the Firefox player starts at 9:55, while the Quicktime player skips ahead to 9:54.

Here's my sample mp4 file if you'd like to see for yourself.
Thanks

A: This is an interesting question and your example is a great illustration of the effect.
Using ffprobe to look at the file you linked to above gives:
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'c44116b.mp4':
  Metadata:
    major_brand     : qt
    minor_version   : 0
    compatible_brands: qt
    creation_time   : 2015-04-25 15:54:30
  Duration: 00:00:03.70, start: 0.957000, bitrate: 1164 kb/s
    Stream #0:0(und): Video: h264 (Main) (avc1 / 0x31637661), yuv420p(tv, bt709), 480x360 [SAR 1:1 DAR 4:3], 899 kb/s, 22.99 fps, 22.99 tbr, 6k tbn, 12k tbc (default)
    Metadata:
      creation_time   : 2015-04-25 15:54:30
      handler_name    : Core Media Data Handler
      encoder         : H.264

You can see here that ffprobe is reporting a 'start' of 0.957000, which would correspond to your 1 second offset.
This does not explain why certain players abide by this and others ignore it (Windows Media player also appears to start form the beginning, rather than the offset). UPDATE: Roman points out below that this is a known behaviour and it has been discussed on the ffmpeg list (see Roman's answer). This may be due to the history of the mp4 container format, which grew from the Apple QuickTime spec.
The purpose of the start parameter appears to be to allow a track be offset for synchronisation purposes. Why this would exist in your video with just one track is not clear.
UPDATE: This is probably more info that anyone wants, but for those interested...
Following up on Roman's answer I took a look at the mp4 file in more detail using MP4 Browser. From this we can see firstly the 'timescale' of the movie:

And then the edit atom (or edit box as atoms are also sometimes called in the mp4 world):

The time field in the edit atom tells the player to skip the first 5742 'samples' and start from there. Using this info with the timescale, which tells us how many samples there are per second, we can calculate the time it should delay:

*

*5742/6000 = 0.957

This corresponds with the 'start time' that ffprobe reports and also with the delay that the OP reported.

A: The file has an Edit atom, which defines a portion of the file to play as a track.
Some demultiplexers take it into consideration (start from 54:24) and others ignore (start from 55:24).
A similar case is discussed here in FFmpeg ticket: adher to start media time in QuickTime edts/elst.

Quicktime and VLC subsequently play the file back according to the edit list, but ffmpeg uses the entire timeline.


text:
Q: Change in momentum in Impulse of deformation and reformation I was reading some text on coefficient of restitution when I encountered this ,

In the following you all would notice that in Impulse of deformation for particle $m_2$ we can see that change in momentum would be $m_2v - m_2u_2 = m_2(v-u_2)$ but what about particle $m_1$.
When we write change in momentum for $m_1$ it should have been $m_1v-m_1u_1$ ie: $m_1(v-u_1)$ but then why is it written $m_1(u_1-v)$ . The same thing is happening in the Impulse of reformation part.
I can't seem to identify where I am going wrong in my explanation. So can somebody please give me the right explanation.

A: The impulse on $m_1$ is opposite and equal that was on $m_2$ (action and reaction pairs). $J_d$ is the magnitude of impulse so actually $-J_d = m_1(v-u_1)$ implying $J_d = m_1(u_1-v)$.


text:
Q: Received(queue) or Executing multiple tasks at same time in celery I added 10 tasks in celery process. It picks one by one (default celery process). After the completion of first task it picks the second task received and executed .
Those tasks are not depending on each other. so I want to run simultaneously or I want to received all the 10 tasks in queue(celery console) and executing one by one.
 -------------- celery@rana-04 v5.1.2 (sun-harmonics)
 --- ***** -----
 -- ******* ---- Windows-10-10.0.18362-SP0 2021-08-16 13:18:28
 - *** --- * ---
 - ** ---------- [config]
 - ** ---------- .> app:         rana:0x2507baac198
 - ** ---------- .> transport:   amqp://guest:**@localhost:5672//
 - ** ---------- .> results:
 - *** --- * --- .> concurrency: 8 (solo)
 -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker)
 --- ***** -----
 -------------- [queues]
            .> celery           exchange=celery(direct) key=celery

Celery Command :
celery -A rana worker --loglevel=INFO --without-gossip --without-mingle --without-heartbeat -Ofair --pool=solo

Any command changes or configurations needed ? Thanks in advance

A: I think you should not use --pool=solo in your command. Because the pool of worker just can hold one task at the same time.


text:
Q: php file_exists does not work for array I posted this question earlier but I have now used the feedback and simplified the php program to show how it still fails.
using the file_exists with an array always fails:
Here is a simple program I wrote that shows the failure:
[root@dsmpp1 steve]# ls -l data
 total 4 -rw-r--r-- 1 root root 0 Sep 19 11:41 test_file
[root@dsmpp1 steve]# cat test_file.php
`#!/usr/bin/php -q
    <?php
    $i=1;
    $testarray=array();
    $testarray[$i]="test_file";
    echo "testarray $testarray[$i]\n";
     **if(file_exists("/home/steve/data/testarray[$i]")) {**
    echo "file exists\n"; }
    else { echo "file does not exist\n"; } `
[root@dsmpp1 steve]# php -q test_file.php
testarray test_file
file does not exist
[root@dsmpp1 steve]#

I used the double quotes around the directory and file name as suggested earlier
and it is still not working.

A: Shouldn't it be:
$testarray[$i]="test_file.php";

instead of:
$testarray[$i]="test_file";

A: try
if(file_exists("/home/steve/data/{$testarray[$i]}")) {**

You were missing the $ before testarray
You might also need to wrap this in brackets because you are using two variables. so use {$testarray[$i]}

A: You are missing a $ before testarray in the if clause. try this:
if(file_exists("/home/steve/data/".$testarray[$i])) {


text:
Q: boomi atom is running but not visible on browser I have started the dell boomi atom on my ubuntu18.04 machine. i have pulled the boomi/atom image through docker and running it on 9090 port. Though the container is up and running, i am unable to see the boomi on my browser with 9090 port. when i check the container logs i am getting the "/home/boomi/startatom.sh: line 20: atom: command not found" and "/home/boomi/startatom.sh: line 28: atom: command not found" error.
I manually downloaded the atomdocker64-install.sh file and run it. there also i am getting the same error.


text:
Q: How would I do a side NavBar that also has words sideways I Seen examples where the words are horizontal but not when words are vertical. Is there a way to achieve this in Flutter?

A: You can use RotatedBox
new RotatedBox(
  quarterTurns: 1,
  child: new Text("Lorem ipsum")
)


text:
Q: Why does supplying an empty list to this Haskell function give compiler error? This code is from the book "Learn You a Haskell for Great Good!":
maximum' :: (Ord a) => [a] -> a
maximum' [] = error "maximum of empty list"
maximum' [x] = x
maximum' (x:xs)
    | x > maxTail = x
    | otherwise = maxTail
    where maxTail = maximum' xs

It works fine on non-empty lists, but supplying an empty list:
main = print $ maximum' []

gives this compiler error:

Ambiguous type variable 'a0' arising from a use of 'maximum''
prevents the constraint '(Ord a0)' from being solved.

Why is that? Shouldn't the code actually catch it when an empty list is supplied? I don't understand the error message.

A:
Ambiguous type variable 'a0' arising from a use of 'maximum'' prevents the constraint '(Ord a0)' from being solved.

This means that when you call maximum' [], the type of [] is not clear: it could be [Int] or [()] or something else.
In this particular case, the result happens to be the same for different types of the list. The compiler can't prove it here, and in general that's not the case. Consider this function:
readAndPrepend :: (Read a, Show a) => String -> [a] -> String
readAndPrepend s xs = show (read s : xs)

If you call readAndPrepend "42" [], it's ambiguous what the result should be:
ghci> readAndPrepend "42" ([] :: [Int])
"[42]"
ghci> readAndPrepend "42" ([] :: [Double])
"[42.0]"
ghci> readAndPrepend "42" ([] :: [()])
"[*** Exception: Prelude.read: no parse
ghci>

In other words, the a type variable is "unsolved", like a free x in a mathematical equation.
What you need to do is pick a type that you want the list to be and specify it explicitly:
main = print $ maximum' ([] :: [()])


text:
Q: Show TS6133 (declared but never read) as warning instead of error Previously when working on react projects using typescript, there are instances where I would declare a variable without reading it and it would notify about it as a warning on console. VSCode would also notify via a yellow squiggly line.
On the project I am working on, Unused variables are displayed as errors which 'breaks' the app. I would like that unused variables be notified as a warning and not an error.
Some of the things tried include modifying tsconfig.json.
{
    "noUnusedLocals": false,
    "noUnusedParameters": false,
}

While this notifies me of unused variables in the console, and doesn't 'break' the app, VSCode doesn't notify of unused variables.
tsconfig.json
{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react-jsx",
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "strictPropertyInitialization": true,
    "noImplicitThis": true,
    "alwaysStrict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true
  },
  "include": ["src"]
}

.eslintrc.json
{
  "root": true,
  "extends": ["react-app", "react-app/jest"],
  "parser": "@typescript-eslint/parser",
  "plugins": ["@typescript-eslint"],
  "rules": {
    "@typescript-eslint/no-unused-vars": ["warning"]
  }
}

package.json
{
  "name": "project",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@material-ui/core": "^4.11.3",
    "@material-ui/icons": "^4.11.2",
    "@material-ui/styles": "^4.11.3",
    "@testing-library/jest-dom": "^5.11.4",
    "@testing-library/react": "^11.1.0",
    "@testing-library/user-event": "^12.1.10",
    "material-ui-image": "^3.3.1",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-router-dom": "^5.2.0",
    "react-scripts": "4.0.3",
    "typescript": "^4.1.2",
    "web-vitals": "^1.0.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "lint": "eslint . --ext .js,.jsx,.ts,.tsx --max-warnings 0"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@types/jest": "^26.0.20",
    "@types/node": "^14.14.31",
    "@types/react": "^17.0.2",
    "@types/react-dom": "^17.0.1",
    "@types/react-router-dom": "^5.1.7",
    "@typescript-eslint/eslint-plugin": "^4.15.2",
    "@typescript-eslint/parser": "^4.15.2",
    "eslint": "^7.20.0",
    "prettier": "2.2.1"
  }
}

Error Message:
D:/path/to/project/src/components/ThemeProvider.tsx
TypeScript error in D:/path/to/project/src/components/ThemeProvider.tsx(23,7):
'someVariable' is declared but its value is never read.  TS6133

    21 |   },
    22 | });
  > 23 | const someVariable = {};
       |       ^
    24 |
    25 | const ThemeProvider = ({ children }: { children: ReactNode }) => {
    26 |   return <MUIThemeProvider {...{ theme }}>{children}</MUIThemeProvider>;

A: If you enable the ESLint rule, you specify that violations should be a warning, not an error. If needed, change your build process so that only errors (not warnings) prevent the build from succeeding.
https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/no-unused-vars.md
"@typescript-eslint/no-unused-vars": ["warning"]

A: Creating a .env file solved the issue for me. These are the variables I set in the .env
TSC_COMPILE_ON_ERROR=true
ESLINT_NO_DEV_ERRORS=true

More info can be found in cra's documentation


text:
Q: How to use ImageMagick's convert to rescale an image, adding letterboxing to produce a fixed size result? I have some arbitrarily-sized images for which I want to produce fixed-size 800x600 thumbnails, which keep the original image ratio and add white letterboxing to make up the rest of the space.  I'd like the letterboxing to be as minimal as possible, which means that the process would do the following:

*

*choose whichever axis is largest

*if x is largest, scale the image (keeping the ratio) so that new x is 800.

*if y is largest, scale the image (keeping the ratio) so that new y is 600.

*the result, at this point, will not be 800x600 (unless the original happened to be exactly 4:3 ratio), so centre the result in an 800x600 rectangle and add a white background.

I can do the first 3 steps with convert -resize 800x600 $input $output so I suppose I could overlay that on top of another image using some other imagemagick tool, but it would be great if I could do it in one hit.  Anyone know if this is possible?

A: I actually just figured it out: it does require an 800x600 white image to merge with, but that's fine.
convert ~/white.jpg ~/input.png  -resize 800x600 -gravity center -composite ~/output.jpg

If there's a general opinion that posting a question and then answering it myself is a waste of time, then i'm happy to delete the question.


text:
Q: ViewPager inside ScrollView - vertical scroll doesn't work So, I have this ScrollView with one child - a LinearLayout that has two children: a TextView and a ViewPager. ViewPager contains layout with many elements, that's why i need the ability to scroll vertically. Only pages in ViewPager may be scrolled horizontally (that is: I'd like to swipe horizontally only within the ViewPager). That one TextView must not scroll horizontally but should scroll together with my ViewPager.
Simple? No.
I've seen extremely similar issues at StackOverflow popping up (here, here and here and here).
None of the suggested solutions work for me :(
What I see is this <- my sweet UI :), However I cannot scroll vertically :(
Embedding ScrollViews inside ViewPager is not an option - desing of the UI forbids this.
Maybe it's something with my programmatically filling each page in view pager? Hmmm...
Any suggestions would be appreciated.
My code:
activity_main.xml:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"

                android:id="@+id/scrollView"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:background="@android:color/white"
                android:fillViewport="true" >

                <LinearLayout
                    android:id="@+id/linearLayoutGeneral"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical">

                    <TextView
                    android:id="@+id/tvText"
                    android:layout_width="fill_parent"
                    android:layout_height="200dp"
                    android:text="Test text" />

                <android.support.v4.view.ViewPager
                            android:id="@+android:id/viewpager"
                            android:layout_width="fill_parent"
                            android:layout_height="fill_parent" >
                </android.support.v4.view.ViewPager>

                </LinearLayout>
</ScrollView>

each page in ViewPager has this layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/layoutData"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >
    </LinearLayout>

</LinearLayout>

single element's layout in such a page:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="40dp"
    android:gravity="center"
    android:orientation="vertical"
    android:background="@android:color/white" >

    <TextView
        android:id="@+id/textView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Large Text"
        android:background="@android:color/black"
        android:textColor="@android:color/white"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

A single page Fragment is also very simple:
public class DayFragment extends Fragment {

    private static final String TAG = DayFragment.class.getSimpleName();

    public String tag;

    LinearLayout data;

    View mView;

    final int ROWS_NUM = 60;

    public DayFragment() {

    }

    /**
     * (non-Javadoc)
     *
     * @see android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater,
     *      android.view.ViewGroup, android.os.Bundle)
     */
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        if (container == null) {
            // We have different layouts, and in one of them this
            // fragment's containing frame doesn't exist. The fragment
            // may still be created from its saved state, but there is
            // no reason to try to create its view hierarchy because it
            // won't be displayed. Note this is not needed -- we could
            // just run the code below, where we would create and return
            // the view hierarchy; it would just never be used.
            return null;
        }

        mView = (LinearLayout) inflater.inflate(R.layout.day, container, false);

        setUpControls();

        generateData();

        String text = getArguments().getString("text");
        Log.d(TAG, "creating view with text: " + text);

        return mView;
    }

    private void setUpControls() {
        data = (LinearLayout) mView.findViewById(R.id.layoutData);
    }

    private void generateData() {
        for (int i = 0; i < ROWS_NUM; i++) {
            View v = createRow(i);
            data.addView(v);
        }
    }

    private View createRow(int num) {
        LayoutInflater inflater = (LayoutInflater) getActivity()
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflater.inflate(R.layout.row, null);

        TextView tv = (TextView) v.findViewById(R.id.textView);
        tv.setText("Data nr: " + num);

        return v;
    }

    public static DayFragment newInstance(String text) {
        Log.d(TAG, "newInstance with text: " + text);
        DayFragment f = new DayFragment();

        f.tag = text;

        // Supply text input as an argument.
        Bundle args = new Bundle();
        args.putString("text", text);
        f.setArguments(args);

        return f;
    }

}

A: I had the problem that ViewPager behaved weird and I found out the reason for that it is because sometimes the ScrollView regains focus and the ViewPager then loses focus. If you have a ViewPager in a ScrollView and you want it always to stay in focus when you touch it and the ScrollView never getting a focus, setting the requestDisallowInterceptTouchEvent does that. Did that help?
    mViewPager= (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(adapter);
    mViewPager.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            mViewPager.getParent().requestDisallowInterceptTouchEvent(true);
            return false;
        }
    });

A: Extending on to Marius's answer to allow vertical scrolling on the parent:
I noticed that when you call the 'requestDisallowInterceptTouchEvent' method on the initial scroll, it will block scrolling vertically on the parent view when scrolling vertically on top of the view pager.
My solution was to only trigger that method after the user started scrolling horizontally for a specified distance (the 'margin' variable).
mViewPager.setOnTouchListener(new View.OnTouchListener() {
    public boolean onTouch(View v, MotionEvent e) {
        // How far the user has to scroll before it locks the parent vertical scrolling.
        final int margin = 10;
        final int fragmentOffset = v.getScrollX() % v.getWidth();

        if (fragmentOffset > margin && fragmentOffset < v.getWidth() - margin) {
            mViewPager.getParent().requestDisallowInterceptTouchEvent(true);
        }
        return false;
    }
});

A: mPager.setOnTouchListener(new View.OnTouchListener() {

    int dragthreshold = 30;
    int downX;
    int downY;

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            downX = (int) event.getRawX();
            downY = (int) event.getRawY();
            break;
        case MotionEvent.ACTION_MOVE:
            int distanceX = Math.abs((int) event.getRawX() - downX);
            int distanceY = Math.abs((int) event.getRawY() - downY);

            if (distanceY > distanceX && distanceY > dragthreshold) {
                mPager.getParent().requestDisallowInterceptTouchEvent(false);
                mScrollView.getParent().requestDisallowInterceptTouchEvent(true);
            } else if (distanceX > distanceY && distanceX > dragthreshold) {
                mPager.getParent().requestDisallowInterceptTouchEvent(true);
                mScrollView.getParent().requestDisallowInterceptTouchEvent(false);
            }
            break;
        case MotionEvent.ACTION_UP:
            mScrollView.getParent().requestDisallowInterceptTouchEvent(false);
            mPager.getParent().requestDisallowInterceptTouchEvent(false);
            break;
        }
        return false;
    }
});

A: I had same problem
try my code to, you we should to disable vertical scroll and sent event to Scrollview :
private int dragThreshold = 10, int downX = 0, int downY = 0;

vPager.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if(event.getAction() == MotionEvent.ACTION_DOWN || event.getAction() == MotionEvent.ACTION_UP){
                downX = (int) event.getRawX();
                downY = (int) event.getRawY();
                return false;
            }else if(event.getAction() == MotionEvent.ACTION_MOVE){
                int distanceX = Math.abs((int) event.getRawX() - downX);
                int distanceY = Math.abs((int) event.getRawY() - downY);

                ExceptionHelpers.dLog("OnTouchListener", "distance X : "+distanceX+" , distance Y : "+distanceY);

                if(distanceY > distanceX && distanceY > dragThreshold){
                    v.getParent().requestDisallowInterceptTouchEvent(false);
                    return true;
                }
            }
            v.getParent().requestDisallowInterceptTouchEvent(true);
            return false;
        }
    });

Also you can set Min Horizontal Scroll By Add :
else {
      distanceX > distanceY && distanceX > dragThreshold)
}

And remember, Building workers do -> Try and Try and Try
developers (us) do -> Think And Think and Try
Good Lock

A: Try this
    public  static class XScrollDetector extends GestureDetector.SimpleOnGestureListener {
        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        return Math.abs(distanceY) < Math.abs(distanceX);
       }
   }

and for the viewpager
    final GestureDetector mGestureDetector= new GestureDetector(this,new XScrollDetector());
    mViewPager.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {

            mScrollView.requestDisallowInterceptTouchEvent(mGestureDetector.onTouchEvent(event));
            return false;

        }
    });

A: I've tried a lot of things, but some things haven't worked for me and some are too complicated and have dirty codes.
I solved this ViewPager in ScrollView problem this way.
you can update the viewPager size in ViewPager.onMeasure() or ViewPager.OnPageChangeListener()
The method onMeasure() will be called everytime when the ui changes in fragment. But I had a lots of varying ui (e.g. TabButton), I updated the view pager size only when user scroll pages.
    mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            // will work when ViewPager shows first fragment.
            if (position != currentPosition) {
                currentPosition = position;
                updateViewPagerSize(position);
            }
        }

        @Override
        public void onPageSelected(int position) {

        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

depending on the situations, you might have to give a focus something to make ScrollView works.
public void updateViewPagerSize(int position) {
    View view = mPager.getChildAt(position);
    view.measure(ViewPager.LayoutParams.WRAP_CONTENT, ViewPager.LayoutParams.WRAP_CONTENT);
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, view.getMeasuredHeight());
    mPager.setLayoutParams(params);
    edtText.requestFocus(); //you might have to give a focus something to use scroll.
}

A: Horizontal and vertical scrolling in one Activity is normally a problem. The ViewPager handles this very well. I do not know if there is a good solution for your problem. But I would suggest to get rid of the ScrollView and TextView in your main layout.
Use the ViewPager as your starting point for your layout and put the vertical ScrollView inside of the ViewPager Fragments.

A: Disallow the ScrollView to intercept touch events. This requires the user to touch outside the ViewPager to scroll up or down.
mScrollView = (ScrollView) findViewById(R.id.scroll_view);
mViewPager= (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(adapter);
mViewPager.setOnTouchListener(new View.OnTouchListener() {

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        mScrollView.requestDisallowInterceptTouchEvent(true);
        return false;
    }
});


text:
Q: IOS Push Notifications using Parse I'm trying to ping all users in a certain channel within a certain distance from the current user's location. The problem I am stuck on is my inability to satisfy both constraints. One or the other works by itself. With both, the message is sent to nobody somehow. Am I missing something here? Thanks in advance!
func findDriver(loc: CLLocationCoordinate2D) {
    let driverQuery = PFInstallation.query()
    driverQuery?.whereKey("channels", equalTo:"drivers")
    let geoPoint = PFGeoPoint(latitude: loc.latitude, longitude: loc.longitude)
    driverQuery?.whereKey("location", nearGeoPoint: geoPoint)

    let push = PFPush()
    push.setQuery(driverQuery)
    push.setMessage("Looking for Drivers!")
    push.sendPushInBackground()

}

A: Maybe try to do AND for query ?
here is the link: https://www.parse.com/questions/combining-or-queries
func findDriver(loc: CLLocationCoordinate2D) {
let driverQuery = PFInstallation.query()
driverQuery?.whereKey("channels", equalTo:"drivers")
let geoPoint = PFGeoPoint(latitude: loc.latitude, longitude: loc.longitude)
driverQuery?.whereKey("location", nearGeoPoint: geoPoint)

let comboQuery = PFQuery.query()
comboQuery?.whereKey("channels", matchesKey:"channels", inQuery:driverQuery)
comboQuery?.whereKey("location", matchesKey:"location", inQuery:geoPoint)

let push = PFPush()
push.setQuery(comboQuery)
push.setMessage("Looking for Drivers!")
push.sendPushInBackground()

}


text:
Q: Finding records that match sthg in 2nd of two rows that are part of a set I have a database of parts of words, and each word has two rows. So basically there's a data set of two rows for each word. I want to find words that end in a vowel (in order to later delete them). Here's an example row:
ID      wordID  Segment SegType

2475    1170    d       consonant
2476    1170    i       vowel
2477    1171    a       vowel
2578    1171    d       consonant

The first two are a bad dataset (wordID 1170) - these I want to find and later delete. The last two are a good dataset (wordID 1171), these I want to keep. To do this, it would be easiest to get a list of wordIDs and later use them to delete the bad sets.
So how can I select the wordID for each set that ends in a vowel (that is, the second of the two rows of the set has the value vowel)? The ID of the second part is always higher than of the first part, but not reliable odd or even (I've tried queries using that already).

A: If I understand correctly, you can use GROUP BY and HAVING:
select wordId
from t
group by wordId
having max(case when segtype = 'vowel' then id end) = max(id)

The having clause finds the id of the row with a vowel segment for each wordIdand the maximumidfor eachwordId.  AwordId` is in the result set if these ids are the same.

A: Try the following query:
SELECT a.wordID
FROM words a JOIN words b ON a.wordID = b.wordID
WHERE a.ID > b.ID and a.segType = 'vowel';

This basically performs the SELF JOIN on wordID column and returns all the ids which have higher value than their join counterpart and 'vowel' as segType.

A: w2 Query - This query is returning the last value for each dataset by grouping on wordID.
w2 is joined with the original table w1(words) on wordID and filtered on last value calculated from the above w2 query.
SELECT w1.*
  FROM words w1
 INNER JOIN
(
SELECT wordID,LAST_VALUE(SegType) OVER( PARTITION BY wordID ORDER BY id ) AS lv
  FROM words
GROUP BY wordID
) w2
ON w1.wordID = w2.wordID
WHERE w2.lv = 'vowel';


text:
Q: Creation of triggers and effect on the table using the temporary table I want to create a trigger in SQL Server 2012 by following the below steps :

*

*When changing column either jandata, febdata, janarea or febarea in table called project (pkid,prjid,jandata,febdata,janarea,febarea)

*Then I need to perform certain calculations which I can perform and then store new data in a temporary table

*I need to check in items table if the itemid exists then i need to update the column values in the table else i need to insert the values
So right now I am stuck with the first step how to create a trigger and insert values in temporary table
I used this code
CREATE TRIGGER sysgenitemsvalue
UPDATE ON project
BEGIN
    create table #temp
    (
    pkid int,
    JANORG  int,
    FEBORG  int,
    ORGID int,
    PROJID int,
    BUDGETYEAR int
    )

    INSERT INTO #temp(pkid, JANORG, FEBORG, ORGID, PROJID, BUDGETYEAR)
        SELECT
            v.pkid,
            CASE
                WHEN v.JANORG <> '0' THEN v.JANORG
                WHEN v.JANAREA <> '0' THEN v.JANAREA
                ELSE p.JANORG
            END "JANORG",
            CASE
                WHEN v.FEBORG <> '0' THEN v.FEBORG
                WHEN v.FEBAREA <> '0' THEN v.FEBAREA
                ELSE p.FEBORG
            END  "FEBORG",
            o.org_id, o.pt_id, o.budgetyear
        FROM
            project v, proj p, org o
        WHERE
            o.pkid = v.orgpt_id
            AND o.pt_id = p.projid
            AND p.orgid = o.org_id
            AND p.budgetyear = o.budgetyear


text:
Q: SetWindowActivationScope. Cocoa equivalent? A Carbon window could be made to appear always active (regardless of whether it is the active window) by:
SetWindowActivationScope( window, kWindowActivationScopeIndependent );
Any idea how I can achieve same with a Cocoa window?