text:
Q: How to infer individual with more than 2 property in owl I have an ontology with Person and Animal_Lover classes. People are Animal_Lover if they have more than 2 pet. How can I do this in my ontology?
<?xml version="1.0"?>
<rdf:RDF xmlns="http://www.example.com/test"
 xml:base="http://www.example.com/test"
 xmlns:test="http://www.example.com/test#"
 xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
 xmlns:owl="http://www.w3.org/2002/07/owl#"
 xmlns:xml="http://www.w3.org/XML/1998/namespace"
 xmlns:xsd="http://www.w3.org/2001/XMLSchema#"
 xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#">
 <owl:Ontology rdf:about="http://www.example.com/test"/>

 <owl:ObjectProperty rdf:about="http://www.example.com/test#hasPet"/>

    <owl:Class rdf:about="http://www.example.com/test#Animal_Lover">
    <owl:equivalentClass>
        <owl:Restriction>
            <owl:onProperty rdf:resource="http://www.example.com/test#hasOwner"/>
            <owl:minQualifiedCardinality rdf:datatype="http://www.w3.org/2001/XMLSchema#nonNegativeInteger">2</owl:minQualifiedCardinality>
            <owl:onClass rdf:resource="http://www.example.com/test#Mammal"/>
        </owl:Restriction>
    </owl:equivalentClass>
    <rdfs:subClassOf rdf:resource="http://www.example.com/test#Person"/>
 </owl:Class>

 <!-- http://www.example.com/test#Mammal -->

 <owl:Class rdf:about="http://www.example.com/test#Mammal"/>

 <!-- http://www.example.com/test#Person -->

 <owl:Class rdf:about="http://www.example.com/test#Person">
    <rdfs:subClassOf rdf:resource="http://www.example.com/test#Mammal"/>
 </owl:Class>
    <!-- http://www.example.com/test#Smith -->

 <owl:NamedIndividual rdf:about="http://www.example.com/test#Smith">
    <rdf:type rdf:resource="http://www.example.com/test#Person"/>
    <test:hasPet rdf:resource="http://www.example.com/test#Lulu"/>
    <test:hasPet rdf:resource="http://www.example.com/test#Nala"/>
    <test:hasPet rdf:resource="http://www.example.com/test#Tank"/>
 </owl:NamedIndividual>

</rdf:RDF>

I want Smith to be inferred and become Animal_Lover.
But This code does not work in owl( or GraphDB).
What is the problem?
Thanks for your help.

A: There are three problems:

*

*First, it is quite possible that "Nala" and "Tank" are two nicknames of the pet Lulu. So perhaps Smith only has one pet, whose name is Lulu and that people like to call Nala, or Tank, for some reasons.

*Second, the inference can only happen if you use the hasOnwer property. You are using hasPet instead.

*Third, you did not say that Lula, Nala, and Tank are mammals. If they are fishes, then you can't infer that Smith is an animal lover (!)


text:
Q: How do I fix this error loading an ontology in owlready2 I am trying to load the ontology but I get an error that you can see in the post, the code is shown below.
Code:
from owlready2 import *
import os
onto = get_ontology("file://C:/Users/achev/Documents/Carro.owl")
onto.load()
n_classes = len(list(onto.classes()))
print(n_classes)

Error:
File "c:/Users/achev/Desktop/Proyecto de grado/Python/prueba.py", line 4, in <module>
    onto = get_ontology("file://C:/Users/achev/Documents/Carro.owl").load()
  File "C:\ProgramData\Anaconda3\lib\site-packages\owlready2\namespace.py", line 810, in load
    if self.world.graph.indexed: self._load_properties()
  File "C:\ProgramData\Anaconda3\lib\site-packages\owlready2\namespace.py", line 849, in _load_properties
    raise TypeError("'%s' belongs to more than one entity types (cannot be both a property and a class/an individual)!" % Prop.iri)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Deploying/copying binaries to AWS Instance Is there way to programmatically copy dotnet libraries to AWS EC2 instance? the idea is to copy dotnet libraries to EC2 instance and execute unit tests.
Any idea on how we can achieve this?

A: I would say to push your binaries to s3 and then as part of the instance start up have them copy over or prepare a script on the instance using aws cli to copy them over as needed.


text:
Q: Mockito MissingMethodInvocationException with my function I am using Springboot with Mockito for test.
I want mock a function that she return a string.
Code impl:
EDIT
public String replaceContent(String url, String replace, String value) {
    return url.replace(replace, value);
}

public ResponseEntity<List<MonitorOperativeFront>> getOperativesMonitor(String userCode) {

log.info(" ---> LogInfo: start ");

String url = this.replaceContent(this.urlBase,this.stringReplace,userCode);

log.info(" ---> LogInfo: call to: " + url);
List<MonitorOperativeFront> list= null ;

MonitorOperative[] operative = this.restTemplate.getForObject(url, MonitorOperative[].class);
list.add(new MonitorOperativeFront(operative[0].getId()));
log.info(" ---> LogInfo: Success ");

return new ResponseEntity<>(list, HttpStatus.OK);

}

Code Test:
@Mock
Mockito mk;
@InjectMocks
MonitorServiceImpl monitorService;

    @Test
    public void testG() throws Exception {
        String url = "prueba/test";
        this.mk.when( monitorService.replaceContent("prueba/{id}", "{id}", "test"))
                .thenReturn(url);
    ResponseEntity<List<MonitorOperativeFront>> operative2 = monitorService.getOperativesMonitor("n11111");
    assertEquals(true,true);

Err:
org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
For example:
    when(mock.getArticles()).thenReturn(articles);

Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
   Those methods *cannot* be stubbed/verified.
   Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.

I checked that my function return success "prueba/test" but in mockito I get a error and I don't know resolve...

A: The @Mock should be the class which has the Method you would like to mock. If you would like to mock the replaceContent you have to write
@Mock
MonitorServiceImpl monitorServiceMock;

@InjectMocks
SomeUserOfMonitorServiceImpl monitorServiceImplUser;

@Test
public void testG() throws Exception {
   String url="http://dsgdfgdf/"
   Mockito.when( monitorServiceMock.replaceContent("prueba/{id}", "{id}", "test"))
            .thenReturn(url));
   //Do Something which calls the monitorService.replaceContent
   monitorServiceImplUser.doSomething();


text:
Q: Is there a technique to remove an item of value 'this' from an array? I am creating a To-Do list with the ability to remove specific items from the list. I am currently trying to use 'localStorage' to essentially save the list on page refresh. However, when I delete an item from the list, the 'localStorage' does not work as intended and instead removes the first item in the array when you next load the page.
JS & jQuery:
$(document).ready(function () {
    $(document).on('click', '.delete-task', function () { // We use 'on' as the element is dynamically added
        console.log("'Delete' button pressed");

        var foo = $(this).closest('li');
        console.log(foo);

        $(this).closest('li').fadeOut(250, function() {

            arr.splice(foo, 1);

            $(this).remove(); // Dynamically remove the DOM element from the list
            localStorage.setItem('items', JSON.stringify(arr));

            console.log(arr);
            console.log(localStorage.getItem('items'));

        });
    });
});

If interested, the HTML format of an item within the 'ul' list looks similar to this:

5x

I am expecting the selected item from the list to be removed and store within the localStorage correctly when you next load the page.
Update:
As @Slim pointed out, 'foo' is a JS object and not an index.
My question is, how do I find the index of the specified item (the 'li') within the 'arr' array?

A: You could try to find the parent of foo using .parent() ( https://api.jquery.com/parent/ ) and then find the index of given li by using .index() ( https://api.jquery.com/index/ )
...
var index = foo.parent().index( foo );
arr.splice(index, 1);
...

Also, you should try to cache jQuery object. Calling multiple times $(this) is calculating the same thing multiple times.
For example:
...
var $self = $(this)
var foo = $self.closest('li');
console.log(foo);
$self.closest('li').fadeOut(250, function() {
...

Also, good idea is to name variables containing jQuery objects starting with $ - it's quite a common pattern.

A: simulate this

Coffee x

Tea    x

Milk   x

use id value here
$(document).on('click', '.delete-task', function () {

     var id = $(this).parents('li').attr('data-id');

      for (var k in arr) {
        if (typeof arr[k] !== 'function') {
        if (arr[k].id == id) {
              //your codes
               break;
             }
           }
         }

  });

I also recommend you use : https://github.com/localForage/localForage


text:
Q: How to update mat-autocomplete options from another component? I have two components called Employee and Form in my application. There are 2 mat-autocomplete: State and City lists in EmployeeComponent. I fill and pass these mat-autocomplete controls to the FormComponent using "formData" parameter:
Employee Component:
html
<form #form [formData]="formControls"></app-form>

ts
formControls = [];
states: StateDto[] = [];
cities: CityDto[] = [];

// fill employee list
getStates() {
    this.demoService.getStates().subscribe((data: StateDto) => {
      this.states = data;
    });
}

getCities() {
    this.demoService.getCities().subscribe((data: CityDto) => {
      this.cities = data;
    });
}

// create for data array
this.formData = [
  {
    id: 'states',
    type: 'custom-autocomplete',
  },
  {
    id: 'cities',
    type: 'custom-autocomplete',
  }
]

// set form control's list data
this.formControls = this.formData.map(item => {
  if (item.id === 'states') {
    item.options = this.states;
  }
  else if (item.id === 'cities') {
    item.options = this.cities;
  }
  return item;
});

Form Component:
html
@Input() formData = [];
options = {};

ngOnInit() {
    //code omitted for brevity
    this.autocompleteControl.forEach(item => {
        // here I set each autocomplete's options
        this.options[item.id] = item.options;
    });
}

At this point, when I select a state I want the cities list is cleared and the filled by the cities of the selected state. So, where should I manage this? On EmployeeComponent or on FormComponent? And hoca should I set the cities list options with an elegant solution?

A: First of all, you use 2 mat-autocomplete. That means the same functionality and behavior. In this situation, I prefer to use a reusable component for that part.
html in parent component
@Component({
  selector: 'app-custom',
  template: "
{{a}}
",
})
export class CustomComponent {
  @Input() data: string[] = [];
}

html in parent component

City

  <app-custom [data]="city"></app-custom>

State

  <app-custom [data]="state"></app-custom>

ts in parent component
export class AppComponent {
  city: string[] = ['A', 'B', 'C'];
  state: string[] = ['AAA', 'BBB', 'CSS'];
}

Code


text:
Q: Why isn't Dawn Summers in Chaos Bleeds? It's been about 2-3 years since I've seen Buffy I finished Buffy seasons 1-4 and Angel season 1. I played Chaos Bleeds ~a decade ago. I'm now watching Buffy season 5 and Angel season 2.
I know what's up with Dawn Summers because I've read about her on Wiki but haven't gotten to that part of season 5 yet.
Why isn't Dawn in Chaos Bleeds? I looked it up online but couldn't find answers. I may be looking in the wrong places or using the wrong keywords.
Update: Now there's

and

A: According to the novelization, Dawn is "staying with her friend Janice" during the events portrayed, something Buffy is grateful for given the threat level.

"Let's go." She moved ahead, hefting the bag of Slayer goodies she'd
  grabbed at her house in her left hand. She hadn't had time for a
  shower, but a few extra weapons were never a bad idea and she took
  care of it. Dawn wasn't home, and for a moment she'd been terrified.
  Then she remembered that her little sister was staying with her friend
  Janice. It was a risk having Dawn away from home, but on this night
  that wasn't exactly a bad thing either. Her sister needed protecting,
  and better that she be with a regular family for the night than be at
  home alone when Kakistos was out and roaming the streets.

The Buffy wikia, however, disputes the canonicity of the novel as it states that the events take place in the sixth season while the prequel comic states that they take place in the fifth season and "Since the comic was written by the same writers as the game, Christopher Golden and Tom Sniegoski, this setting should take priority."


text:
Q: Example of a non-measurable $A$ set such that $\mu_{*}(A)=\mu^{*}(A^{c})=0$
Prove that there exists a non-measurable  $A\subseteq \mathbb{R}$ such that  $$\mu_{\ast}(A\cap E)=0 \quad \text{y} \quad \mu^{\ast}(A\cap E)=\mu(E)$$
for all set measurable $E$ with $\mu(E)>0$.

My approach:  Let $A\subseteq \mathbb{R}$ such that $$\mu_{*}(A)=\mu_{*}(A^{c})=0$$
so, we have $A$ is non-measurable set. Indeed, suppose that $A$ is measurable, so $A^{c}$ is also measurbale and since that $\mathbb{R}=A\cup A^{c}$, so we have $$+\infty=\mu(\mathbb{R})=\mu(A)+\mu(A^{c})=\mu_{*}(A)+\mu_{*}(A^{c})=0 \quad  !!$$
So, $A$ is non-measurable set.
Now, we need to prove that if $E$ is measurable with $\mu(E)>0$, so we have $$\mu_{*}(A\cap E)=0\quad \mu^{*}(A\cap E)=\mu(E)$$
Now, since that $\mu_{*}(A^{c})=0 \implies \mu^{*}(A\cap E)=\mu(E)$.
Finally, since that $A\cap E\subset A \implies \mu_{*}(A\cap E)=\mu_{*}(A)=0$
Is my prove correct?
Should I add something else to my prove?
I still have to prove that such a set $A$ exists, correct? How could I prove that?

Here: $\mu$ is Lebesgue measure, $\mu_{*}$ is inner measure, $\mu^{*}$ is outer measure and measure it means Lebesgue measure.


text:
Q: Modify query to exclude soft deleted records Python code part that contains query:
conn = pymysql.connect(host='127.0.0.1', user=sql_username,

        passwd=sql_password, db=sql_main_database,

        port=tunnel.local_bind_port)

query = '''select * from users;'''

df_user = pd.read_sql_query(query, conn)

I need to to modify query to exclude the soft deleted records. How modified query should look like?


text:
Q: Zedboard_Adv7511_HDMI Project Vivado Tcl building error When I was trying to run ADI's project https://wiki.analog.com/resources/fpga/xilinx/kc705/adv7511 in Vivado 2017.4, then got this message
ERROR: [BD 41-1075] Cannot create address segment for </axi_hdmi_clkgen/s_axi/reg0> in </sys_ps7/Data> at 0x079000000 [ 4G ].  The proposed address exceeds the base address limitations <0x40000000 [ 1G ]> of the interface(s) </sys_ps7/M_AXI_GP0> through which this peripheral is accessed by this address space
Then I tried to allocate every address of every peripheral by using the auto address assignment in Address Editter.

Then I altered zed_system_bd.tcl

but still got the same kind of error.  According to ZYNQ_TRM, GP0 mapping at 0x4000_0000 to 0x7FFF_FFFF.
Can anyone please tell me what I can do?


text:
Q: Ajax is not supporting IE 9 I'm having this problem with my AJAX, where it's not working in IE 9,7 but it is working fine with Opera 8.0+, Firefox, Safari,chrome .So I don't see why it would be wrong.Here i put my complete code.Can anyone help me out?

<LINK href="text1.css" rel="stylesheet" type="text/css">

    <form action="" name="tstest">

MFS CALL RECORDINGS

Funds

                    <select name="Funds" id=fund multiple>
                        <option value="Select">Select</option>
                        <option value="PMF">Principal</option>
                        <option value="PRAMERICA">Pramerica</option>
                        <option value="JM">JM</option>
                        <option value="DHL">DHL</option>
                        <option value="EMF">Edelweiss MF</option>
                        <option value="MORGAN">Morgan</option>
                        <option value="DAIWA">Daiwa</option>
                        <option value="TAURUS">Taurus</option>
                        <option value="AXIS">AXIS</option>
                        <option value="BPMF">BPMF</option>
                        <option value="PLMF">Peerless MF</option>
                        <option value="LIC NOMURA">LIC NOMURA</option>
                        <option value="PNB">PNB</option>
                    </select>

Agents

                    <select name="Agents" id="agent" multiple>
                        <option value="Select">Select</option>
                        <option value="Gyanesh">Gyanesh</option>
                        <option value="Satish">Satish</option>
                        <option value="Sailesh">Sailesh</option>
                        <option value="ArchanaMuluguru">Archana</option>
                        <option value="Santosh">Santosh</option>
                        <option value="Afreen">Afreen</option>
                        <option value="Salman">Salman</option>
                        <option value="Balaji">Balaji</option>
                        <option value="Priyanka">Priyanka</option>
                        <option value="KavithaGolla">Kavitha</option>
                        <option value="Rajvardhan">Rajvardhan</option>
                        <option value="Srinivasp">Srinivasp</option>
                        <option value="Surekha">Surekha</option>
                        <option value="Mazhar">Mazhar</option>
                        <option value="Pneeraja">Pneeraja</option>
                        <option value="Samiullah">Samiullah</option>
                        <option value="Nisar">Nisar</option>
                        <option value="Kareem">Kareem</option>
                        <option value="Shesherao">Shesherao</option>
                        <option value="KuttiSirisha">KuttiSirisha</option>
                        <option value="Sunitha">Sunitha</option>
                        <option value="Pavanir">Pavanir</option>
                        <option value="Divyav">Divyav</option>
                        <option value="Leela">Leela</option>
                        <option value="Avinash">Avinash</option>
                        <option value="BHARATI">Bharati</option>
                        <option value="Anil">Anil</option>
                        <option value="Sravan">Sravan</option>
                        <option value="Sudhakar">Sudhakar</option>
                        <option value="Madan">Madan</option>
                        <option value="Raghu">Raghu</option>
                        <option value="Rahul">Rahul</option>
                        <option value="Srinivas B">Srinivas B</option>
                        <option value="Akhilesh">Akhilesh</option>

                    </select>

From Date

                    <input type="Text" name="timestamp" id="fromDate" value="">

To Date

                    <input type="Text" name="timestamp1" id="toDate" value="">

                    <input type="Button" id="val" value="Submit" align="middle" method="GET" onclick="fetch_javaScript()" />

    </form>

Your Result Will Display Here

A: The issue stems from the lack of a DOCTYPE in your page in IE this drops the page to IE5 compatibility mode e.g. quirks mode. to fix it just add a DOCTYPE like so:
<!doctype html>

<LINK href="text1.css" rel="stylesheet" type="text/css">

This will put you in standards mode which will act like a modern browser.


text:
Q: What exactly is "personnel working"? Source: Russia's middle class: We don't blame Putin
Example:

There's been a "renaissance" of engineers and personnel working for Russia's defense industry, he says, an elite class in the Soviet Union that fell apart in the chaos of the early post-Soviet period. Now they're back, and the Kremlin is paying attention. The group has almost nothing to do with the market economy, Lukyanov says, and they support Putin.

What exactly do they mean by personnel working?

A: The meaning is similar to "[engineers and personnel] who work for ...". Note that the participle working refers not to personnel only, but to engineers and personnel. Let's rephrase:

There's been a "renaissance" of engineers and personnel who work for Russia's defense industry, he says, an elite class in the Soviet Union that fell apart in the chaos of the early post-Soviet period. Now they're back, and the Kremlin is paying attention. The group has almost nothing to do with the market economy, Lukyanov says, and they support Putin.

Engineers and personnel of what kind? - Of the kind that works for the defense industry.
Following the dissolution of the USSR, there was a lack of funding, and these engineers and personnel suffered from low salaries and the necessity to look for other jobs. Now Putin's government is focused on restoring this sphere: manufacture of armaments, military vehicles, etc. Thus, these engineers and personnel who work for the defense industry undergo 'a renaissance'.

"Working for Russia's defense industry" is a present-participle phrase connected to "engineers and personnel". It is also called 'participial phrase'.

A: They mean the personnel are working for Russia's defense industry.  Just like the engineers are working for Russia's defense industry.


text:
Q: Compare the correlation between differents techniques 1/ Given the following tibble, i have tested three different techniques (PCR,TECH_A and TECH_B). The idea is to see how TECH_A and TECH_B compare to PCR in detecting a specific gene. I mean if they are in agreement.
N is equivalent to "-" (menaing negative). For exemple first line says that PCR was negative TECH_a and tech_A were negative so they return the same result that is negative.
> dat
# A tibble: 5 x 4
# Groups:   PCR [2]
  PCR   TECH_A TECH_B CASES
  <chr> <chr>  <chr>  <int>
1 N     -      -          1
2 N     -      +         23
3 N     +      +          8
4 P     -      +          2
5 P     +      +          4

Here is the data:
dat <-
structure(list(PCR = c("N", "N", "N", "P", "P"), TECH_A = c("-",
"-", "+", "-", "+"), TECH_B = c("-", "+", "+", "+", "+"), CASES = c(1L,
23L, 8L, 2L, 4L)), row.names = c(NA, -5L), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"), na.action = structure(c(`2` = 2L,
`6` = 6L, `8` = 8L, `10` = 10L, `12` = 12L, `15` = 15L, `18` = 18L,
`20` = 20L, `22` = 22L, `24` = 24L, `26` = 26L, `28` = 28L, `30` = 30L,
`31` = 31L, `34` = 34L, `35` = 35L, `38` = 38L, `39` = 39L, `42` = 42L,
`44` = 44L, `46` = 46L, `48` = 48L, `50` = 50L, `52` = 52L, `54` = 54L,
`56` = 56L, `58` = 58L, `60` = 60L, `62` = 62L, `64` = 64L, `67` = 67L,
`69` = 69L, `71` = 71L), class = "omit"), groups = structure(list(
    PCR = c("N", "P"), .rows = list(1:3, 4:5)), row.names = c(NA,
-2L), class = c("tbl_df", "tbl", "data.frame"), .drop = TRUE))

Any idea on how to compare the two last technologies to PCR and see if they correlate or not ??

A: Correlation between two binary values is like accuracy I guess (how many agree). Besides that you can also look at false positive rate, false negative etc, whichever is more important for your case.
Below I did the comparison between PCR and Tech A/ Tech B, using the confusion matrix to basically sort out the stats for each technique, and you can see Tech A agrees ok with PCR..
For TECH_A first:
cm = table(rep(dat$PCR,dat$CASES),rep(dat$TECH_A,dat$CASES))
# rename for convenience
rownames(cm) = c("-","+")

             Accuracy : 0.7368
                 95% CI : (0.569, 0.866)
    No Information Rate : 0.6842
    P-Value [Acc > NIR] : 0.3062

                  Kappa : 0.2963

 Mcnemar's Test P-Value : 0.1138

            Sensitivity : 0.9231
            Specificity : 0.3333
         Pos Pred Value : 0.7500
         Neg Pred Value : 0.6667
             Prevalence : 0.6842
         Detection Rate : 0.6316
   Detection Prevalence : 0.8421
      Balanced Accuracy : 0.6282

Then for B:
cm = table(rep(dat$PCR,dat$CASES),rep(dat$TECH_B,dat$CASES))
rownames(cm) = c("-","+")

Confusion Matrix and Statistics

     -  +
  -  1 31
  +  0  6

               Accuracy : 0.1842
                 95% CI : (0.0774, 0.3433)
    No Information Rate : 0.9737
    P-Value [Acc > NIR] : 1

                  Kappa : 0.0101

 Mcnemar's Test P-Value : 7.118e-08

            Sensitivity : 1.00000
            Specificity : 0.16216
         Pos Pred Value : 0.03125
         Neg Pred Value : 1.00000
             Prevalence : 0.02632
         Detection Rate : 0.02632
   Detection Prevalence : 0.84211
      Balanced Accuracy : 0.58108

       'Positive' Class : -


text:
Q: Celery-Django: Unable to execute tasks asynchronously I'm trying to run some tasks in the background while users browse my site, but whenever I call a function using Celery it seems to be executed synchronously instead of asynchronously.
e.g., when I call function.delay() the entire site hangs until function.delay() returns. Other methods of calling functions in a similar manner (apply_async, subtasks) exhibit the same problem.
I'm guessing something in either Django or Celery is misconfigured, but I don't know what it is.
Celery configuration in settings.py:
import djcelery
djcelery.setup_loader()

CELERY_RESULT_BACKEND = "amqp"
CELERYBEAT_SCHEDULER = "djcelery.schedulers.DatabaseScheduler"
BROKER_HOST = "localhost"
BROKER_PORT = 5672
BROKER_USER = "test"
BROKER_PASSWORD = "test"
BROKER_VHOST = "testhost"

TEST_RUNNER = "djcelery.contrib.test_runner.run_tests"

CELERY_IMPORTS = ("myapp.tasks",)

BROKER_BACKEND = "memory"
CELERY_ALWAYS_EAGER = True

Trying to start the Celery daemon with "./manage.py celeryd", I get the following output:
[2011-09-23 09:25:38,026: WARNING/MainProcess]

 -------------- celery@iMac.local v2.2.7
---- **** -----
--- * ***  * -- [Configuration]
-- * - **** ---   . broker:      memory://test@localhost:5672/testhost
- ** ----------   . loader:      djcelery.loaders.DjangoLoader
- ** ----------   . logfile:     [stderr]@WARNING
- ** ----------   . concurrency: 4
- ** ----------   . events:      OFF
- *** --- * ---   . beat:        OFF
-- ******* ----
--- ***** ----- [Queues]
 --------------   . celery:      exchange:celery (direct) binding:celery

[2011-09-23 09:25:38,035: WARNING/MainProcess] celery@iMac.local has started.

A: Try removing
CELERY_ALWAYS_EAGER = True

You are explicitly asking celery to execute tasks synchronously. It'll always wait for the result.
This setting is useful for writing unit tests etc.
Read http://ask.github.com/celery/configuration.html


text:
Q: C free() allocated memory twice, will it cause segfault? If we twice free() the same char pointer which is allocated with malloc(), will it cause segfalut?
void Allocate()
{
   char *y;
   y = (char *) malloc (sizeof(char) * 200);
   free (y);
   strcpy(y,"helloworld");
   free (y);
}

int main()
{
     Allocate();
     return 0;
}

A: It's undefined behavior, so don't do it.
Even more, don't use the memory after calling free() in it, this is a total no-no:
free (y);
strcpy(y,"helloworld");

The above is also undefined behavior.
Also, don't cast the return value of malloc() in C.

A: Freeing the same memory twice will result in undefined behaviour, as will writing to memory which has been freed (see the strcpy).
The C Standard defines Undefined Behaviour in Section §1.3.12 as

behaviour, such as might arise upon use of an erroneous program construct or erroneous data, for which this International Standard imposes no requirements [3].
Undefined behaviour may also be expected when this International Standard omits the description of any explicit definition of behavior.
(3) = permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or with- out the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).

As to what's happening I would guess the following:

*

*You free y

*You then strcpy over what was once y which may corrupt the heap; this itself is unlikely to segfault, but might (see above)

*You then allocate z, which uses the possibly corrupted heap, and may segfault or misallocate the memory (i.e. return an address which cannot be used).

*You then strcpy into a possibly misallocated bit of memory and thus may segfault.

*You then free y again, with a heap which is possibly corrupt, which may segfault etc.
If you really want to know, use debug libc and gdb to find out.

A: Freeing same pointer twice may cause heap corruption.  In your program after deallocating you are trying to copy a string which will cause segfault.


text:
Q: How do I connect to Interbase 6 on a remote location from .NET? What drivers should I use? Are they free?
How should the connectionstring look like?
Thanks

A: With regard to drivers, Interbase 6 is the same as Firebird 1.0. You can get ADO.net drivers here, and yes, they are free:
http://www.firebirdsql.org/dotnetfirebird/
Note, that Interbase 6 uses a network protocol that transmits many more bytes than necessary, and makes a huge number of network connections for even simple things. It is highly recommended to upgrade to a newer version, like Firebird 2.1, which is backwards compatible, but where the network protocol works much better, and faster.

A: you'd better not use Interbase 6 which is very old.
You can use newest version of Interbase of the fork of Interbase open source named Firebird
Here you can can some connectionstring for firebird


text:
Q: Arduino publish/subscribe to PubNub I am trying to create an IoT based smart house system. It contains of my android application which sends and receives messages from/to PubNub (subscribes and publishes on certain channels) and Arduino UNO board with some LEDs and movement sensor (PIR). My android app seems to be working fine, it sends and receives messages, but the problem is with Arduino. In the beginning it receives messages from PubNub but after couple (exactly 2) publishes it stops receiving messages, it can just publish. Here is my arduino code:
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

char pubkey[] = "<pub key>";
char subkey[] = "<sub key>";
char channel[] = "publish";
char channel1[] = "subscribe";
char uuid[] = "Arduino";
volatile int pirpin = 2;
iotbridge arduino;

void initialize(){
    Serial.begin(9600);
Serial.println("Serial set up");
pinMode(6, OUTPUT);
digitalWrite(6, LOW);
pinMode(pirpin, INPUT);
while (!Ethernet.begin(mac)) {
    Serial.println("Ethernet setup error");
    delay(1000);
}
Serial.println("Ethernet set up");
}

void do_something(String value){
      Serial.println("in the callback");
      Serial.println(value);
}
void pin_ISR() {
arduino.send(channel1, "\"Movement\"");
digitalWrite(6, HIGH);
delay(50);
}
void setup()
{
initialize();

arduino.init( pubkey, subkey, uuid);
Serial.println("PubNub set up");
attachInterrupt(0, pin_ISR, RISING);
}

void loop()
{
String returnmessage;
Ethernet.maintain();

Serial.println("waiting for a message");
returnmessage = arduino.connect(channel);

    // callback function of sorts, to work with the received message
do_something(returnmessage);
Serial.println();
}

I am just testing the receiving and sending messages so it does not contain LED control. It uses interrupt on pin2 and when it becomes HIGH Arduino publishes a message, which should be received by android app. Thank you for your help in advance.


text:
Q: ¿Como crear una funcion de mysql? Se supone que tengo que crear una función a partir de esta sentencia:
select count(idepoc) as "Total" from padecimientos where idepoc=1;
pero cuando la creo me marca un error.
esta es la funcion que creo:
delimiter //
 create function TotalEPOC() returns int
 begin
 declare EPOC int;
 select count(idepoc) into EPOC from padecimientos where idepoc=1;
 return EPOC;
 end//
delimiter ;

Este es el error que me marca:


text:
Q: Proper way of getting function arguments with spaces and specials characters First time here, but dealing with batch codes from a long time.
I'd like to get some help developing a proper way to get correct parameters in a batch function.
In some functions, I usually need to get the parameters the way they are really passed, not "eating" any comma and not getting the script broked by any special characters.
If the function has one parameter only, it's easy and everything is there in %* the way it should.
But I usually I need to get some auxiliary paramters like variables or paths first and, so, I set the argument that might have some special stuff to the last position.
This is the only way I've found to use and treat complex arguments. But implementing this is always a trouble.
When I thought that I've found a best way by using FOR /F and tokens with *, I got problems when the first arguments (like paths) have spaces (or any other delimiter) because quotes are ignored then.
The only way I can achieve what I want by now is getting each numbered argument and its length then subtracting from all arguments, getting then the "rest argument" that I want, but that is some kind expensive, because I have to call String Len code many times.
Is there a way to use FOR /F delimiting by space but respecting quoted parameters with spaces?
Or anyone else knows a better and proper way of achieving what I want?!
Here's some code to illustrate the problem:
:: When no space in first arguments everything works
CALL :MyFunc arg1 argument2 c:\path\to\arg3 c:\path\toarg4 ,run, anything "here" even specials "&" like "|<>" and single" quotes
:: But spaces broke first arguments
CALL :MyFunc arg1 "argument 2" c:\path\to\arg3 "c:\spaced path\to arg4" ,run, anything "here" even specials "&" like "|<>" and single" quotes
GOTO :EOF

:MyFunc
SETLOCAL EnableDelayedExpansion
ECHO Checking if everything is there
ECHO %*
ECHO.
SET params=%*
ECHO Traditional way of parsing parameters works for first params:
ECHO 1:%1 2:%2 3:%3 4:%4
ECHO But how to get rest this way?
ECHO.
ECHO Trying to get through FOR /F and tokens with * to get rest
FOR /F "tokens=1,2,3,4*" %%a IN ("!params!") DO SET "arg1=%%~a" & SET "arg2=%%~b" & SET "arg3=%%c" & SET "arg4=%%~d" & SET "argrest=%%e"
ECHO It will work for non spaced first params but not for parameters with spaces quoted because delims is space
ECHO Parsing Desired Arguments With FOR:
ECHO 1:!arg1! 2:!arg2! 3:!arg3! 4:!arg4! Rest:!argrest!
ECHO.
GOTO :EOF

Result:
Checking if everything is there
arg1 argument2 c:\path\to\arg3 c:\path\toarg4 ,run, anything "here" even specials "&" like "|<>" and single" quotes

Traditional way of parsing parameters works for first params:
1:arg1 2:argument2 3:c:\path\to\arg3 4:c:\path\toarg4
But how to get rest this way?

Trying to get through FOR /F and tokens with * to get rest
It will work for non spaced first params but not for parameters with spaces quoted because delims is space
Parsing Desired Arguments With FOR:
1:arg1 2:argument2 3:c:\path\to\arg3 4:c:\path\toarg4 Rest:,run, anything "here" even specials "&" like "|<>" and single" quotes

Checking if everything is there
arg1 "argument 2" c:\path\to\arg3 "c:\spaced path\to arg4" ,run, anything "here" even specials "&" like "|<>" and single" quotes

Traditional way of parsing parameters works for first params:
1:arg1 2:"argument 2" 3:c:\path\to\arg3 4:"c:\spaced path\to arg4"
But how to get rest this way?

Trying to get through FOR /F and tokens with * to get rest
It will work for non spaced first params but not for parameters with spaces quoted because delims is space
Parsing Desired Arguments With FOR:
1:arg1 2:argument 3:2" 4:c:\path\to\arg3 Rest:"c:\spaced path\to arg4" ,run, anything "here" even specials "&" like "|<>" and single" quotes

Thank you so much!


text:
Q: Why is typescript telling me "Cannot compile external modules unless the --module flag is provided? I am getting Typescript error message indicated in title above.  Included here is one example of what it doesn't like... If I click on the error message it takes me to the I in IGLOBALS definition below.
export interface IGlobals {
    HomePageUrl: string;
    loginPageUrl: string;
    TimeOut: number;
    Changed(url: string)
}

I am using VS2013 with these settings.  No matter what value I choose for "Module System" I still get this error.  I'm running Version 1.5.0 beta of Typescript (which could be the issue, not sure)...

A: Wrap your code in a module...
module MyModule{
    export interface IGlobals {
        HomePageUrl: string;
        loginPageUrl: string;
        TimeOut: number;
        Changed(url: string)
    }
}


text:
Q: How to retrieve data from Wikipedia API using JSON? Here I am fetching the data from Wikipedia using following code. but it is not working for me.
var playListURL = 'http://en.wikipedia.org/w/api.php?format=json&action=query&titles=India&prop=revisions&rvprop=content&callback=?';

$.getJSON(playListURL ,function(data) {
    $.each(data.pages, function(i, item) {
        alert(i);
    });
});

DEMO LINK :- http://jsfiddle.net/rushijogle/dyeqy/

A: Use the following code to get the data:
$.getJSON(playListURL ,function(data) {
        $.each(data.query.pages, function(i, item) {
            alert(item.title);

        });
    });

A: Demo is at  http://jsfiddle.net/dyeqy/3/
var playListURL = 'http://en.wikipedia.org/w/api.php?format=json&action=query&titles=India&prop=revisions&rvprop=content&callback=?';

$.getJSON(playListURL ,function(data) {
    var hash = data
    var page_value = ""
    $.each(data["query"]["pages"],function(k,v){
        alert(k)
        $.each(v,function(key,val){
          alert(key)
        });
    });
});

Like this you can take the revisions values also.

A: It should be data.query.pages instead of data.pages
Working Fiddle


text:
Q: MLP regression, error: TypeError: '<=' not supported between instances of 'numpy.ndarray' and 'int' I am trying to fit a MLP regression model.
My data looks like
>>> x
array([[-0.10423869, -0.26620437, -0.15806682, ...,  0.14673972,
        -0.08155304, -0.18497986],
       [-0.09611467, -0.25407929, -0.14541038, ...,  0.12948089,
        -0.08478664, -0.18818328],
       [-0.11439996, -0.27334441, -0.19392899, ..., -0.05813874,
        -0.0083624 , -0.1901444 ],
       ...,
       [-0.05907788, -0.19151134, -0.00739118, ..., -0.00207883,
        -0.20569605, -0.09713173],
       [ 0.2577889 , -0.19076356, -0.16640778, ...,  0.19883847,
        -0.19295281,  0.28263902],
       [-0.04733956, -0.33666808, -0.24709939, ..., -0.2130735 ,
        -0.22681055,  0.15976231]])
>>> y
array([[0.],
       [0.],
       [0.],
       ...,
       [0.],
       [0.],
       [0.]])

I want to do 5 cross-validation first to find the best parameters,here is what I wrote for just fit 50 of x_train and y_train, just to check:
mlp = MLPRegressor()
parameter_space = {
    'max_iter': [1000,2000,5000],
    'activation': ['relu'],
    'alpha': [0.0001,0.001,0.01],
    'hidden_layer_sizes': [(8,8,),(50,50,),(100,100,)],
    'solver': ['sgd', 'adam'],
    'learning_rate': ['constant','adaptive']
}
k = 5
kf = KFold(n_splits=k, random_state=None)
model = MLPRegressor(parameter_space)
acc_score = []
for train_index , test_index in kf.split(x):
    x_train , x_valid = x[train_index,:],x[test_index,:]
    y_train , y_valid = y[train_index] , y[test_index]
    model.fit(x_train[1:50], y_train[1:50])

However, it shows this error:
Traceback (most recent call last):
  File "<stdin>", line 4, in <module>
  File "/local/xx/anaconda3/lib/python3.9/site-packages/sklearn/neural_network/_multilayer_perceptron.py", line 673, in fit
    return self._fit(X, y, incremental=False)
  File "/local/xx/anaconda3/lib/python3.9/site-packages/sklearn/neural_network/_multilayer_perceptron.py", line 358, in _fit
    if np.any(np.array(hidden_layer_sizes) <= 0):
TypeError: '<=' not supported between instances of 'numpy.ndarray' and 'int'

Both x_train[1:50] and y_train[1:50] are <class 'numpy.ndarray'>.. How should I fix this?
Thank you

A: The parameter_space dictionary can be passed to the estimator to be unpacked. To do so, add 2 stars before the parameter like so **parameter_space when passing. The parameter_space variable has to have the parameters in the supported data types. For example,
parameter_space = {
    'max_iter': 1000,
    'activation': 'relu',
    'alpha': 0.0001,
    'hidden_layer_sizes': (8,50,100),
    'solver': 'sgd',
    'learning_rate': 'constant'
}

model = MLPRegressor(**parameter_space)

The above model gave the desired output without any errors. For more information on MLPRegressor refer here.


text:
Q: python: run two scripts with arguments simultaneously What I have is:
import main
import branies

if __name__ == "__main__":
    WEEKDAYS = [1,2,3,4,5]
    for day in WEEKDAYS:
        pd = foo(day)
        main.main(pd)
        branies.main(pd)

I intend to run both main.main and branies.main simultaneously with the argument pd
what i tried:
subprocess.run("python3 main.py -a {0} & python3 branies.py -a {0}".format(pd), shell=True)

but this fails to pass the argument, error:
Traceback (most recent call last):
Traceback (most recent call last):
  File "main.py", line 361, in <module>
  File "branies.py", line 355, in <module>
    main()
    main()
TypeError: main() missing 1 required positional argument: 'pd'
TypeError: main() missing 1 required positional argument: 'pd'

debugging:
print("python3 main.py -a {0} & python3 branies.py -a {0}".format(pd))

output:
python3 main.py -a 2020-02-24 & python3 branies.py -a 2020-02-24

EDIT:
import main
import branies

both main and branies are two python scripts with functions main(pd=None) in them which expects the parameter pd

A: I'm not quite sure what you want to accomplish, but perhaps something like this would do it:
script1.py and script2.py (I think your main.py and branies.py):
import sys
from time import sleep
from datetime import datetime

def main(pd):
    sleep(5) # doing some computations
    print(f"time={datetime.now()}, arg={pd}") # also adding "script {1 or 2}" to print statement

if __name__ == '__main__':
    arg = sys.argv[1]
    main(arg)

main.py:
import subprocess

for pd in [1,2,3]:
    subprocess.run(
        f"python3 script1.py {pd} & python3 script2.py {pd}",
    shell=True)

From terminal: python main.py; output:
time=2020-08-16 11:39:17.911350, script 1, arg=1
time=2020-08-16 11:39:17.911350, script 2, arg=1
time=2020-08-16 11:39:22.931387, script 1, arg=2
time=2020-08-16 11:39:22.931387, script 2, arg=2
time=2020-08-16 11:39:27.951381, script 1, arg=3
time=2020-08-16 11:39:27.951358, script 2, arg=3


text:
Q: Postgres: Always use default column value, even if insertion is attempted I'm creating a user table using postgres. My table is the following...
create table if not exists "user" (
    user_id bigserial primary key,
    username varchar(20) not null,
    "password" varchar(100) not null,
    created_datetime timestamp default (now() at time zone 'utc')
);

Is it possible for create_datetime to only use the default column, even if an insert script attempts to inserts a timestamp into created_datetime? Preferably postgres would even thrown an error if an insert script tries to insert a timestamp into the create_datetime column.

A: Create a trigger that will fill that column disregarding any value provided in INSERT:
create or replace function t_user_created_datetime() returns trigger as $$
begin
  new.created_datetime := now() at time zone 'utc';
  return new;
end;
$$ language plpgsql;

create trigger t_user_created_datetime
  before insert on "user"
  for each row execute procedure t_user_created_datetime();

Check:
test=# insert into "user"(user_id, username, "password", created_datetime) values(1, 'test', 'test', '1900-01-01'::timestamp);
INSERT 0 1
test=# select * from "user";
 user_id | username | password |      created_datetime
---------+----------+----------+----------------------------
       1 | test     | test     | 2017-07-27 18:21:24.501701
(1 row)

With such trigger, you can remove default (now() at time zone 'utc') from the table's definition, because it becomes useless.
If you do want to see an error when the column's value is explicitly set in INSERT, then change the trigger function to something like this:
create or replace function t_user_created_datetime() returns trigger as $$
begin
  if new.created_datetime is not null then
    raise exception 'It is forbidden to explicitly set "created_datetime" during INSERT to "user" table.';
  end if;
  new.created_datetime := now() at time zone 'utc';
  return new;
end;
$$ language plpgsql;

In this case, the column created_datetime must not have default
 because otherwise you'll see that error always.
P.S. I stronly recommend consider using timestamptz – it is also 8 bytes, like timestamp, but case save a lot of efforts if you need (or will need in the future) to deal with multiple time zones.

A: Revoke the insert and update privileges on the table from all the roles:
revoke insert, update
on table "user"
from public, application_role
cascade

Then grant the insert and update privileges to the application role on the other columns only:
grant
    insert (user_id, username, "password"),
    update (username, "password")
on table "user"
to application_role

Only the table owner will be able to insert and update on the created_datetime  column.

A: To make the set of answers complete. Use rules.
First we will create the service function to be able to raise exceptions from SQL statements:
create or replace function public.fn_raise(msg text, cond boolean = true)
  returns bool
  immutable
  language plpgsql
as $$
begin
  if cond then
    raise exception '%', msg;
  end if;
  return false;
end $$;

Next lets create the test table:
create table t(i int, d timestamptz not null default current_timestamp);

And, finally, rule:
create or replace rule rul_t_insert as on insert to t
where new.d <> current_timestamp
do also
  select fn_raise(format('Can not insert %s into table t', new.d), new.d <> current_timestamp);

Lets test it:
postgres=# insert into t(i) values(1) returning *;
┌───┬───────────────────────────────┐
│ i │               d               │
╞═══╪═══════════════════════════════╡
│ 1 │ 2017-07-28 12:31:37.255392+03 │
└───┴───────────────────────────────┘

postgres=# insert into t(i,d) values(1,null) returning *;
ERROR:  null value in column "d" violates not-null constraint
DETAIL:  Failing row contains (1, null).

postgres=# insert into t(i,d) values(2,'2000-10-10') returning *;
ERROR:  Can not insert 2000-10-10 00:00:00+03 into table t

I the question mentioned only insert but if you also want to block updates of this field, you could to create another rule:
create or replace rule rul_t_update as on update to t
where new.d <> old.d
do also
  select fn_raise(format('Can not change t.d to %s', new.d), new.d <> old.d);

Test:
postgres=# update t set i = 3 where i = 1 returning *;
┌───┬───────────────────────────────┐
│ i │               d               │
╞═══╪═══════════════════════════════╡
│ 3 │ 2017-07-28 12:31:37.255392+03 │
└───┴───────────────────────────────┘

postgres=# update t set i = 4, d = current_timestamp where i = 3 returning *;
ERROR:  Can not change t.d to 2017-07-28 12:39:18.963852+03


text:
Q: Jenkins can't find docker-compose
I created a Jenkins pipeline where I need to pull repository from Bitbucket, do a production build with Jenkins and then push the image to Docker hub. This Jenkins setup is run from docker image jenkins/jenkins:lts **on server not locally**.
In Global Tool installation I've installed NodeJS tool, with the following input for Global npm packages to install: docker-compose@1.29.0 yarn@1.22.10
Basically in the first stage I am running sh "yarn" which installs dependencies and that works as it should.
But the next stage that has sh "yarn production:build" throws this error:
/var/jenkins_home/workspace/og_Online_Tools_cicd_jenkinsfile@tmp/durable-21c42918/script.sh: docker-compose: not found
in the package-json of the project the production:build script is "production:build": "u=username p=password ef=.env docker-compose up --build"

I am running it like this in Jenkinsfile:
...
stage('Install dependencies') {
   steps {
      nodejs('Node 14.16') {
         sh "yarn"
      }
   }
}
stage('Run production build') {
   steps {
      nodejs('Node 14.16') {
         script {
            dockerImage = sh "yarn production:build"
         }
      }
   }
}
...

I've tried with:
...
stage('Install dependencies') {
   steps {
      nodejs('Node 14.16') {
         sh "yarn"
         sh "yarn --version"
         sh "npm install -g docker-compose"
         sh "docker-compose --version"
      }
   }
}
...

and the npm install goes through but it still throws an error on docker-compose.
There is also this console output from the build:
+ yarn production:build
yarn run v1.22.10
$ u=username p=password ef=.env docker-compose up --build
/bin/sh: 1: docker-compose: not found
error Command failed with exit code 127.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Appreciating any insight.
Thanks
/////UPDATE//////
I've entered the jenkins docker container and run curl command for docker-compose however it only created a docker-compose file in /usr/local/bin.
Next build attempts were throwing access denied for /usr/local/bin.
Now docker-compose installs correctly via npm install -g however on docker-compose --version I am getting:
+ docker-compose --version
/var/jenkins_home/workspace/og_Online_Tools_cicd_jenkinsfile@tmp/durable-a04e890d/script.sh: 1:
/var/jenkins_home/workspace/og_Online_Tools_cicd_jenkinsfile@tmp/durable-a04e890d/script.sh: docker-compose: not found

When I run echo "PATH=$PATH" I get:
PATH=/var/jenkins_home/tools/jenkins.plugins.nodejs.tools.NodeJSInstallation/Node_14.16/bin:/opt/java/openjdk/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

Thanks again


text:
Q: Badoo like Swipeable Cards So I've been in this for a while now and have been unable to figure out how to implement 4-way swipe recognition in android. I've found different links pointing to different solutions but none of them fulfill my requirements.
What I wish to accomplish is to attain a "Badoo" like swipe gesture. Badoo is a Tinder like application. On swiping up/down the user's pictures are scrolled, and on left/right, the card is liked/disliked.
The animation I wish to achieve is that on left/right the card follows the set left/right path and moves to like/dislike. On up/down the pictures snap to their next/previous ones.
I've tried countless libraries over github that for swipeable cards and am now trying to implement a custom view for my requirements.
Currently I'm trying to insert a VerticalViewPager inside a CardView. The problem here is that the VerticalViewPager is intercepting all touch events therefore I am unable to swipe my card right/left.
This is my OnTouch event for the CardView item:
public boolean onTouch(View v, MotionEvent event) {
    switch (event.getAction()) {
    case MotionEvent.ACTION_MOVE:
        pager.requestDisallowInterceptTouchEvent(true);
        break;
    case MotionEvent.ACTION_UP:
    case MotionEvent.ACTION_CANCEL:
        pager.requestDisallowInterceptTouchEvent(false);
        break;
    }
    return true;
}

This is what I'm trying to achieve. This is what Badoo looks like:
Badoo Screenshot 1: https://drive.google.com/open?id=0BzGcu10X5GRrTDZHRm4xT0tnQ1k
Badoo Screenshot 2: https://drive.google.com/open?id=0BzGcu10X5GRrc2pvRTZKS2p2UEU
If anyone knows of any similar libraries with a similar 4-way swipe gesture please let me know.
EDIT:
I've made a parent view for the card and the ViewPager, the CardView (cardViewParent) has a child cardView and cardView's child is a VerticalViewPager (mViewPager):
cardViewParent.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent event) {
                Toast.makeText(context, "incardviewPARENT", Toast.LENGTH_SHORT).show ();

               float rawX = 0, rawY = 0;

               switch (event.getAction()) {

                   case MotionEvent.ACTION_DOWN:
                        //gesture has begun
                        float x;
                        float y;
                        //cancel any current animations

                       mActivePointerId[0] = event.getPointerId(0);

                       x = event.getX();
                        y = event.getY();
                        rawX = event.getRawX();
                        rawY = event.getRawY();

                       initialXPress[0] = x;
                        initialYPress[0] = y;
                        initialRawXPress[0] = rawX;
                        initialRawYPress[0] = rawY;

                       break;

                   case MotionEvent.ACTION_MOVE:
                        //gesture is in progress

                       final int pointerIndex = event.findPointerIndex(mActivePointerId[0]);
                        //Log.i("pointer index: " , Integer.toString(pointerIndex));
                        if (pointerIndex < 0 || pointerIndex > 0) {
                            break;
                        }

                       final float xMove = event.getX(pointerIndex);
                        final float yMove = event.getY(pointerIndex);
                        float rawDY = Math.abs(event.getRawY() -
                        initialRawYPress[0]);
                        float rawDX = Math.abs(event.getRawX() - initialRawXPress[0]);

                       //calculate distance moved
                        final float dx = xMove - initialXPress[0];
                        final float dy = yMove - initialYPress[0];
                        Log.d("RAW DY:", "" + rawDY);

                       if(rawDY > 100 && !animationStart[0])
                        {
                            // vertical swipe detected
                            mViewPager.setSwipeable(true);
                            cardStack.setSWIPE_ENABLED(false);
                           // mViewPager.dispatchTouchEvent(event);
                            return false;
                        }

                       if((rawDY <100 && rawDX > 100) ||
                       animationStart[0]) {

                           //horizontal swipe

                           animationStart[0] = true;
                            cardStack.setSWIPE_ENABLED(true);
                            mViewPager.setSwipeable(false);
                           // cardStack.dispatchTouchEvent(event);
                            return false;

                       }

               }

               return true;

           }
        });

If an Upwards Swipe Motion is detected then I'm enabling the ViewPager's swipe motion, else the CardStack's (swipe deck) swipe is enabled. The problem is that the swipe motion doesn't start in any direction.


text:
Q: IoC with AOP (PostSharp) in MonoDroid I'm working on a MonoDroid app, and there really isn't a good DI solution yet (at least that I know of).
I've gotten PostSharp to work on MonoDroid, and I'm using the Location Intercept aspect as a way to inject dependencies into fields/properties without using a service locator (outside of the aspect anyway).
Here's what I'm working with so far: https://github.com/mgroves/MonodroidStockPortfolio/blob/develop/MonoStockPortfolio/Framework/IoCAttribute.cs
It's rough, and definitely needs refactoring, but you get the idea from the basic structure.  However, I'm not completely convinced that this approach is the best way.  How would you go about using DI/IoC in a MonoDroid app, with or without PostSharp?

A: It's more "classic container" rather than AOP, and MonoDroid isn't a platform I've tested it on (it's been tested on Mono, MonoTouch, Silverlight, Windows Mobile and WinPhone7 though), but TinyIoC should work if it fits the bill:
http://hg.grumpydev.com/tinyioc/wiki/Home


text:
Q: cakephp 3 using scopes when logging I configured a logger for my orders in app.php
'orders' => [
    'className' => 'Cake\Log\Engine\FileLog',
    'path' => LOGS,
    'file' => 'orders',
    'levels' => ['info'],
    'scopes' => ['orders'],
]

and then in one model of mine I did:
 Log::info("There's an order", 'orders');

I expected the log message being written only in orders.log but it shows in debug.log too.
according to documentation:

If there is a configured logger for that scope, the log messages will
  be directed to those loggers. If a log message is written to an
  unknown scope, loggers that handle that level of message will log the
  message.

What am I doing wrong?

A: As I wandering around, I found this: https://github.com/DaoAndCo/cakephp-logging
To restrict scope to one logger, add this to default logger config:
'scopes' => false

Like this:
'debug' => [
    'className' => 'Cake\Log\Engine\FileLog',
    'path' => LOGS,
    'file' => 'debug',
    'levels' => ['notice', 'info', 'debug'],
    'scopes' => false,
    'url' => env('LOG_DEBUG_URL', null),
],
'error' => [
    'className' => 'Cake\Log\Engine\FileLog',
    'path' => LOGS,
    'file' => 'error',
    'levels' => ['warning', 'error', 'critical', 'alert', 'emergency'],
    'scopes' => false,
    'url' => env('LOG_ERROR_URL', null),
],

That's it! Work like a charm! I also did test it.

A: 'queries' => [ 'className' => FileLog::class, 'path' => LOGS, 'file' => 'queries', 'url' => env('LOG_QUERIES_URL', null), 'scopes' => ['queriesLog'], ],


text:
Q: iOS Push Notification SSL Certificate Is the certificate generated to send push notifications specific to the server, or I can use it on any other server, if I change my server?
Thank you.

A: You can use it in any server. Apple push notification SSL certificate is not specific to any server.
Example: parse.com, xtify.com etc.

A: You can use it on any server -- its the certificate and its corresponding private key that matters, not the IP from which the connection is made.

A: You can use it in any server. Apple push notification SSL certificate is not specific to any server.
https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/APNSOverview.html#//apple_ref/doc/uid/TP40008194-CH8-SW1


text:
Q: Por que uma função anônima é encarada como objeto em PHP? $f = function() {
    echo "OK";
};

echo gettype($f);

Retorna Object quando teoricamente olhando era pra retornar function.
-
Em JS:
var f = function() {};
typeof f;

Retorna function.

A: Como o PHP lida com funções anônimas
No PHP, uma função anônima é um objeto do tipo Closure.
A documentação da linguagem diz o seguinte sobre a classe Closure:

Class used to represent anonymous functions.

No seu exemplo, a função em questão armazenada na variável $f é um objeto, pois é uma instância de Closure, por isso o resultado do teste de tipo diz que o valor em questão é um objeto e não uma função (como acontece no caso do Javascript).

A: Introdução
É discricionário de cada linguagem definir como organizar toda sua estrutura, ou seja, cada uma faz como achar que funciona melhor para ela. Seria possível todos os dados terem apenas um tipo, poderia ser um object ou outro. Mas isso fica ruim para organizar códigos mais complexos, por isso quase todas as linguagens, e todas mainstream tem outros tipos, até para saber mais facilmente o que fazer. Consegue imaginar como seria difícil executar operações quando não se tem nenhuma informação de tipo?
Tipagem
Segundo a teoria de tipos as linguagens de tipagem dinâmica, como são PHP e JS, só tem um tipo, mas elas possuem tags de tipos internas e informalmente lidamos com elas como se fossem tipos diferentes, só tenha certo que isso é formalmente errado. Vou falar do jeito que todo mundo entende.
Então alguns tipos possuem tags mais específicas, inclusive todo valor que tem a tag Object tem outra tag mais interna que diz o tipo deste Object, mas para efeitos de tipagem só o nível do Object é mostrado.
Por alguma razão quiseram separar o que é um Object e o que são outros tipos. Eu considero isso um erro. Mas faz sentido porque essas linguagens foram criadas sem pensar que teriam essa complexidade que elas têm hoje. Não seria mais fácil tudo ser Object e só ter as tags internas dele? Assim você poderia lidar só com as tags e esquecer os tipos, porque no fundo tudo é o mesmo.
Pois bem, não fizeram assim e decidiram que alguns tipos de dados fossem no mesmo nível que Object. Isso não é exclusivo dessas duas linguagens, de forma geral todas as linguagens de tipagem dinâmica são assim. As linguagens de tipagem estática colocam tudo no mesmo nível até porque elas não usam tags de tipos, e sim são tipos mesmo. Infelizmente elas erram em não ter um tipo comum único, como C# tem, esta acertou. Até Java cometeu esse erro.
Motivação
JavaScript considerou que uma função era tão importante para ela que merecia ter um tipo isolado, assim como tem String, Number, Array`, etc. No fundo todos eles são de alguma forma um objeto.
PHP não achou isso tão importante. Como esse mecanismo foi criado posteriormente pode até ter alguma questão de compatibilidade, mas só estou especulando, acredito que nem tenha esse tipo de problema. E é o que eu falo, PHP não foi criada e não é evoluída por pessoas quem entendem muito os conceitos computacionais. As pessoas não gostam de ouvir isso, mas é um fato até mesmo declarado pelo criador. Então eles criaram uma sintaxe nova para função anônima, portanto consideram importante, mas não suficiente para tiparem isso de forma especial. Não parece desequilibrado?
Mas não tem nada que obrigue retornar um tipo mais específico.
Como obter o quer
Se realmente quer saber a tag do tipo Object você tem que usar get_class():
$f = function() {
    echo "OK";
};
echo get_class($f);

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Note que retorna Closure porque não é só uma função, é uma clausura, assim como também o é em JS. Cada um dá o nome que quiser, conceitualmente PHP está mais certo, porque em ambas isso é uma clausura e não apenas uma função.

A: Porque não existe tipo de dado "function". A função gettype() no php retorna o tipo da variável. Os tipos de dados de retorno da função gettype são:

*

*"boolean"

*"integer"

*"double" (por razões históricas "double" é é retornado no caso de float, e não simplesmente "float")

*"string"

*"array"

*"object"

*"resource"

*"NULL"

*"unknown type"

A sua função está como uma função anônima, uma closure. Uma closure tem retorno de objetos deste tipo. Se você der um var_dump em sua variável f era irá retornar: object(Closure)#1 (0) { } . Também pode validar que ele é um objeto deste jeito var_dump(is_object($f)); ele irá retornar TRUE, pois é um objeto. Também deste jeito informando que é uma closure echo get_class($f);.


text:
Q: Error "Uncaught TypeError: this.containerDim is undefined" when i open more than 1 tab use firefox, it working normal when i use chrome I am using firefox to open my page but when I open multiple tabs, the browser console error "Uncaught TypeError: this.containerDim is undefined". If I only open 1 tab then it works fine. This doesn't happen in chrome. Can someone answer for me?
Here is full code error

/*** picture view plugin ****/
(function ($, window, document, undefined) {
    "use strict";

    //an empty function
    var noop = function () {};

    var $body = $('body'),
        $window = $(window),
        $document = $(document);

    //constants
    var ZOOM_CONSTANT = 15; //increase or decrease value for zoom on mouse wheel
    var MOUSE_WHEEL_COUNT = 5; //A mouse delta after which it should stop preventing default behaviour of mouse wheel

    //ease out method
    /*
        t : current time,
        b : intial value,
        c : changed value,
        d : duration
    */

    function easeOutQuart(t, b, c, d) {
        t /= d;
        t--;
        return -c * (t * t * t * t - 1) + b;
    };

    //function to check if image is loaded
    function imageLoaded(img) {
        return img.complete && (typeof img.naturalWidth === 'undefined' | img.naturalWidth !== 0);
    }

    var imageViewHtml = '

' + '
' + '

' + '
' + '

' + '

';
    //var imageViewHtml = '

';

    var slider_zoom = '
' + '

' + '
';

    function Slider(container, options) {
        this.container = container;
        this.onStart = options.onStart || noop;
        this.onMove = options.onMove || noop;
        this.onEnd = options.onEnd || noop;
        this.sliderId = options.sliderId || 'slider' + Math.ceil(Math.random() * 1000000);
    }

    Slider.prototype.init = function () {
        var self = this,
            container = this.container,
            eventSuffix = '.' + this.sliderId;

        //assign event on snap image wrap
        this.container.on('touchstart' + eventSuffix + ' mousedown' + eventSuffix, function (estart) {
          estart.preventDefault();
            var touchMove = (estart.type == "touchstart" ? "touchmove" : "mousemove") + eventSuffix,
                touchEnd = (estart.type == "touchstart" ? "touchend" : "mouseup") + eventSuffix,
                eOrginal = estart.originalEvent,
                sx = eOrginal.clientX || eOrginal.touches[0].clientX,
                sy = eOrginal.clientY || eOrginal.touches[0].clientY;

            var start = self.onStart(estart, {
                x: sx,
                y: sy
            });

            if (start === false) return;

            var moveListener = function (emove) {

                emove.preventDefault();

                eOrginal = emove.originalEvent;

                //get the cordinates
                var mx = eOrginal.clientX,
                    my = eOrginal.clientY;

                self.onMove(emove, {
                    dx: mx - sx,
                    dy: my - sy,
                    mx: mx,
                    my: my
                });

            };

            var endListener = function () {
                $document.off(touchMove, moveListener);
                $document.off(touchEnd, endListener);
                self.onEnd();
            };

            $document.on(touchMove, moveListener);
            $document.on(touchEnd, endListener);
        });

        return this;
    }

    function ImageViewerss(container, options) {
        var self = this;

        if (container.is('#iv-container-ss')) {
            self._fullPage = true;
        }

        self.container = container;
        options = self.options = $.extend({}, ImageViewerss.defaults, options);

        self.zoomValue = 100;

        if (!container.find('.snap-view').length) {
            //container.append(slider_zoom)
            container.prepend(imageViewHtml);

        }

        container.addClass('iv-container-ss');

        if (container.css('position') == 'static') container.css('position', 'relative');

        self.snapView = container.find('.iv-snap-view-ss');
        self.snapImageWrap = container.find('.iv-snap-image-wrap-ss');
        self.imageWrap = container.find('.iv-image-wrap-ss');
        self.snapHandle = container.find('.iv-snap-handle-ss');
        self.zoomHandle = container.find('.iv-zoom-handle-ss');
        self._viewerId = 'iv' + Math.floor(Math.random() * 1000000);
    }

    ImageViewerss.prototype = {
        constructor: ImageViewerss,
        _init: function () {
            var viewerss = this,
                options = viewerss.options,
                zooming = false, // tell weather we are zooming trough touch
                container = this.container;

            var eventSuffix = '.' + viewerss._viewerId;

            //cache dom refrence
            var snapHandle = this.snapHandle;
            var snapImgWrap = this.snapImageWrap;
            var imageWrap = this.imageWrap;

            var snapSlider = new Slider(snapImgWrap, {
                sliderId: viewerss._viewerId,

                onStart: function () {

                    if (!viewerss.loaded) return false;

                    var handleStyle = snapHandle[0].style;

                    this.curHandleTop = parseFloat(handleStyle.top);
                    this.curHandleLeft = parseFloat(handleStyle.left);
                    this.handleWidth = parseFloat(handleStyle.width);
                    this.handleHeight = parseFloat(handleStyle.height);
                    this.width = snapImgWrap.width();
                    this.height = snapImgWrap.height();

                    //stop momentum on image
                    clearInterval(imageSlider.slideMomentumCheck);
                    cancelAnimationFrame(imageSlider.sliderMomentumFrame);
                },
                onMove: function (e, position) {
                    var xPerc = this.curHandleLeft + position.dx * 100 / this.width,
                        yPerc = this.curHandleTop + position.dy * 100 / this.height;

                    xPerc = Math.max(0, xPerc);
                    xPerc = Math.min(100 - this.handleWidth, xPerc);

                    yPerc = Math.max(0, yPerc);
                    yPerc = Math.min(100 - this.handleHeight, yPerc);

                    var containerDim = viewerss.containerDim,
                        imgWidth = viewerss.imageDim.w * (viewerss.zoomValue / 100),
                        imgHeight = viewerss.imageDim.h * (viewerss.zoomValue / 100),
                        imgLeft = imgWidth < containerDim.w ? (containerDim.w - imgWidth) / 2 : -imgWidth * xPerc / 100,
                        imgTop = imgHeight < containerDim.h ? (containerDim.h - imgHeight) / 2 : -imgHeight * yPerc / 100;

                    snapHandle.css({
                        top: yPerc + '%',
                        left: xPerc + '%'
                    })

                    viewerss.currentImg.css({
                        left: imgLeft,
                        top: imgTop
                    })

                    viewerss.compareImg.css({
                        left: imgLeft,
                        top: imgTop
                    })
                }
            }).init();

            /*Add slide interaction to image*/
            var imageSlider = viewerss._imageSlider = new Slider(imageWrap, {
                sliderId: viewerss._viewerId,
                onStart: function (e, position) {
                    if (!viewerss.loaded) return false;
                    if (zooming) return;
                    var self = this;
                    snapSlider.onStart();
                    self.imgWidth = viewerss.imageDim.w * viewerss.zoomValue / 100;
                    self.imgHeight = viewerss.imageDim.h * viewerss.zoomValue / 100;

                    self.positions = [position, position];

                    self.startPosition = position;

                },
                onMove: function (e, position) {
                    if (zooming) return;
                    this.currentPos = position;

                    snapSlider.onMove(e, {
                        dx: -position.dx * snapSlider.width / this.imgWidth,
                        dy: -position.dy * snapSlider.height / this.imgHeight
                    });
                },

            }).init();

            /*Add zoom interation in mouse wheel*/
            var changedDelta = 0;
            imageWrap.on("mousewheel" + eventSuffix + " DOMMouseScroll" + eventSuffix, function (e) {

                if(!options.zoomOnMouseWheel) return;

                if (!viewerss.loaded) return;

                //clear all animation frame and interval
                viewerss._clearFrames();

                // cross-browser wheel delta
                var delta = Math.max(-1, Math.min(1, (e.originalEvent.wheelDelta || -e.originalEvent.detail))),
                    zoomValue = viewerss.zoomValue * (100 + delta * ZOOM_CONSTANT) / 100;

                if(!(zoomValue >= 100 && zoomValue <= options.maxZoom)){
                    changedDelta += Math.abs(delta);
                }
                else{
                    changedDelta = 0;
                }

                if(changedDelta > MOUSE_WHEEL_COUNT) return;

                e.preventDefault();

                var contOffset = container.offset(),
                    x = (e.pageX || e.originalEvent.pageX) - contOffset.left,
                    y = (e.pageY || e.originalEvent.pageY) - contOffset.top;

                viewerss.zoom(zoomValue, {
                    x: x,
                    y: y
                });
            });

            //zoom in zoom out using zoom handle
            var slider = viewerss.snapView.find('.iv-zoom-slider-ss');
            var zoomSlider = new Slider(slider, {
                sliderId: viewerss._viewerId,
                onStart: function (eStart) {

                    if (!viewerss.loaded) return false;

                    this.leftOffset = slider.offset().left;
                    this.handleWidth = viewerss.zoomHandle.width();
                    this.onMove(eStart);

                },
                onMove: function (e, position) {
                    var newLeft = (e.pageX || e.originalEvent.touches[0].pageX) - this.leftOffset - this.handleWidth / 2;

                    newLeft = Math.max(0, newLeft);
                    newLeft = Math.min(viewerss._zoomSliderLength, newLeft);

                    var zoomValue = 100 + (options.maxZoom - 100) * newLeft / viewerss._zoomSliderLength;

                    viewerss.zoom(zoomValue);

                }
            }).init();

            //calculate elments size on window resize
            if (options.refreshOnResize) $window.on('resize' + eventSuffix, function () {
                //viewerss.refresh()
            });

        },

        //method to zoom images
        zoom: function (perc, point) {
            perc = Math.max(100, perc);

            if ((mouse_hover_depth & show_snap_view) | (!show_snap_view & hover_my & !hover_hang2)){
                point = {
                    x: point_x_depth,
                    y: point_y_depth
                };
                console.log("check run if");
                console.log("containerDim 00: "+this.containerDim.w);
            }else{
                console.log("check run else");
                point = point || {
                    x: this.containerDim.w / 2,
                    y: this.containerDim.h / 2
                };
                console.log("containerDim 01: "+this.containerDim.w);
                console.log("containerDim 02: "+this.containerDim.h);
            }

            point_x_ir = point.x;
            point_y_ir = point.y;

            var self = this,
                maxZoom = this.options.maxZoom,
                curPerc = this.zoomValue,
                curImg = this.currentImg,
                compareImg = this.compareImg,
                containerDim = this.containerDim,
                curLeft = parseFloat(curImg.css('left')),
                curTop = parseFloat(curImg.css('top'));
                console.log("containerDim 1: "+containerDim);

            self._clearFrames();

            var step = 0;

            //calculate base top,left,bottom,right
            var containerDim = self.containerDim,
                imageDim = self.imageDim;
                console.log("self.imageDim: "+self.imageDim);
                console.log("self.containerDim 2: "+self.containerDim);
                console.log("containerDim 2: "+containerDim);
            var baseLeft = (containerDim.w - imageDim.w) / 2,
                baseTop = (containerDim.h - imageDim.h) / 2,
                baseRight = containerDim.w - baseLeft,
                baseBottom = containerDim.h - baseTop;

            function zoom() {
                step++;

                if (step < 20) {
                    self._zoomFrame = requestAnimationFrame(zoom);
                }

                var tickZoom = Math.min(maxZoom, easeOutQuart(step, curPerc, perc - curPerc, 20));

                var ratio = tickZoom / curPerc,
                    imgWidth = self.imageDim.w * tickZoom / 100,
                    imgHeight = self.imageDim.h * tickZoom / 100,
                    newLeft = -((point.x - curLeft) * ratio - point.x),
                    newTop = -((point.y - curTop) * ratio - point.y);

                /
                //fix for left and top
                newLeft = Math.min(newLeft, baseLeft);
                newTop = Math.min(newTop, baseTop);

                //fix for right and bottom
                if((newLeft + imgWidth) < baseRight){
                    newLeft = (self.containerDim.w - imgWidth) ; //newLeft - (newLeft + imgWidth - baseRig
                }

                if((newTop + imgHeight) < baseBottom){
                    newTop = (self.containerDim.h - imgHeight) ; //newLeft - (newLeft + imgWidth - baseRig
                }

                curImg.css({
                    height: imgHeight + 'px',
                    width: imgWidth + 'px',
                    left: newLeft + 'px',
                    top: newTop + 'px'
                });

                compareImg.css({
                    height: 'auto',
                    width: imgWidth + 'px',
                    left: newLeft + 'px',
                    top: newTop + 'px'
                });

                self.zoomValue = tickZoom;

                self._resizeHandle(imgWidth, imgHeight, newLeft, newTop);

                //update zoom handle position
                self.zoomHandle.css('left', ((tickZoom - 100) * self._zoomSliderLength) / (maxZoom - 100) + 'px');
            }

            zoom();
        },

        _clearFrames: function () {
            //clearInterval(this._imageSlider.slideMomentumCheck);
            cancelAnimationFrame(this._imageSlider.sliderMomentumFrame);
            cancelAnimationFrame(this._zoomFrame)
        },
        //ko có vẫn chạy đc
        resetZoom: function () {
            this.zoom(this.options.zoomValue);
        },

        //calculate dimensions of image, container and reset the image
        _calculateDimensions: function () {
            //calculate content width of image and snap image
            var self = this,
                curImg = self.currentImg,
                compareImg = self.compareImg,
                container = self.container,
                snapView = self.snapView,
                imageWidth = curImg.width(),
                imageHeight = curImg.height(),
                contWidth = container.width(),
                contHeight = container.height(),
                snapViewWidth = snapView.innerWidth(),
                snapViewHeight = snapView.innerHeight();

            //set the container dimension
            self.containerDim = {
                w: contWidth,
                h: contHeight
            }

            //set the image dimension
            var imgWidth, imgHeight, ratio = imageWidth / imageHeight;

            imgWidth = (imageWidth > imageHeight && contHeight >= contWidth) || ratio * contHeight > contWidth ? contWidth : ratio * contHeight;

            imgHeight = imgWidth / ratio;

            self.imageDim = {
                w: imgWidth,
                h: imgHeight
            }

            compareImg.css({
                width: imgWidth + 'px',
                height: 'auto',
                left: (contWidth - imgWidth) / 2 + 'px',
                top: (contHeight - imgHeight) / 2 + 'px',
                'max-width': 'none',
                'max-height': 'none'
            });
            curImg.css({
                width: imgWidth + 'px',
                height: imgHeight + 'px',
                left: (contWidth - imgWidth) / 2 + 'px',
                top: (contHeight - imgHeight) / 2 + 'px',
                'max-width': 'none',
                'max-height': 'none'
            });

            //set the snap Image dimension
            var snapWidth = imgWidth > imgHeight ? snapViewWidth : imgWidth * snapViewHeight / imgHeight,
                snapHeight = imgHeight > imgWidth ? snapViewHeight : imgHeight * snapViewWidth / imgWidth;

            //ko có cũng ko sao
            self.snapImageDim = {
                w: snapWidth,
                h: snapHeight
            }
            self.snapImg.css({
                width: snapWidth,
                height: snapHeight
            });

            //calculate zoom slider area
            self._zoomSliderLength = snapViewWidth - self.zoomHandle.outerWidth();

        },

        refresh: function () {
            if (!this.loaded) return;
            this._calculateDimensions();
            this.resetZoom();
        },
        _resizeHandle: function (imgWidth, imgHeight, imgLeft, imgTop) {
            var curImg = this.currentImg,
                imageWidth = imgWidth || this.imageDim.w * this.zoomValue / 100,
                imageHeight = imgHeight || this.imageDim.h * this.zoomValue / 100,
                left = Math.max(-(imgLeft || parseFloat(curImg.css('left'))) * 100 / imageWidth, 0),
                top = Math.max(-(imgTop || parseFloat(curImg.css('top'))) * 100 / imageHeight, 0),
                handleWidth = Math.min(this.containerDim.w * 100 / imageWidth, 100),
                handleHeight = Math.min(this.containerDim.h * 100 / imageHeight, 100);

            this.snapHandle.css({
                top: top + '%',
                left: left + '%',
                width: handleWidth + '%',
                height: handleHeight + '%'
            });
        },
        load: function (image, hiResImg, compare, hiResCompare) {
            var self = this,
                container = this.container;

            container.find('.iv-snap-image-ss,.iv-large-image-ss').remove();
            var snapImageWrap = this.container.find('.iv-snap-image-wrap-ss');
            snapImageWrap.prepend('');
            this.imageWrap.prepend('');

            if (hiResImg) {
                this.imageWrap.append('')
            }

            if(compare) {
                this.imageWrap.append('');
            }

            var currentImg = this.currentImg = this.container.find('.iv-large-image-ss');
            var compareImg = this.compareImg = this.container.find('.iv-large-compare');
            this.snapImg = this.container.find('.iv-snap-image-ss');
            self.loaded = false;

            //show loader
            container.find('.iv-loader-ss').show();
            currentImg.hide();
            compareImg.css('opacity', 0);
            self.snapImg.hide();

            //refresh the view
            function refreshView() {
                self.loaded = true;
                self.zoomValue = 100;

                //reset zoom of images
                currentImg.show();
                self.snapImg.show();
                self.refresh();
                self.resetZoom();

                //hide loader
                container.find('.iv-loader-ss').hide();
            }

            if (imageLoaded(currentImg[0])) {
                refreshView();
            } else {
                $(currentImg[0]).on('load', refreshView);
            }

        },
        setCompareAlpha: function(alpha) {
            /*Add shift binding for image compare toggle*/
            this.compareImg.css('opacity', alpha)
        }
    }

    ImageViewerss.defaults = {
        zoomValue: 100,
        snapView: true,
        maxZoom: 300,
        refreshOnResize: true,
        zoomOnMouseWheel : true
    }

    window.ImageViewerss = function (container, options) {
        var imgElm, imgSrc, compareElm, compareSrc, hiResImg, hiResCompare;
        if (!(container && (typeof container == "string" || container instanceof Element || container[0] instanceof Element))) {
            options = container;
            container = $('#iv-container-ss');
        }

        container = $(container);

        if (container.is('img')) {
            imgElm = container;
            imgSrc = imgElm[0].src;
            hiResImg = imgElm.attr('high-res-src') || imgElm.attr('data-high-res-src');
            container = imgElm.wrap('

').parent();
            imgElm.css({
                opacity: 0,
                position: 'relative',
                zIndex: -1
            });
        } else {
            imgSrc = container.attr('src') || container.attr('data-src');
            compareSrc = container.attr('compare-src') || container.attr('data-compare-src');
            hiResImg = container.attr('high-res-src') || container.attr('data-high-res-src');
        }

        var viewerss = new ImageViewerss(container, options);
        viewerss._init();

        if (imgSrc) viewerss.load(imgSrc, hiResImg, compareSrc, hiResCompare);

        return viewerss;
    };

}((window.jQuery), window, document));

Here is the error code(The error line is the first line of the code below) :
 //calculate base top,left,bottom,right
 var containerDim = self.containerDim,
    imageDim = self.imageDim;
    console.log("self.imageDim: "+self.imageDim);
    console.log("self.containerDim 2: "+self.containerDim);
    console.log("containerDim 2: "+containerDim);
 var baseLeft = (containerDim.w - imageDim.w) / 2,
    baseTop = (containerDim.h - imageDim.h) / 2,
    baseRight = containerDim.w - baseLeft,
    baseBottom = containerDim.h - baseTop;

I'm call it like this:
if (mouseDown) {
   ismouse = true
} else {
     if (ismouse) {
        $('.iv-large-image-ss').css('top', $('.iv-large-image').css('top'));
        $('.iv-large-image-ss').css('left', $('.iv-large-image').css('left'));
        ismouse = false
     }
     viewerss.zoom(rate);
}

"rate" is a number that I want to assign to represent the zoom level.

A: I tried to clear the firefox cache and ran the code above, but every time I open a new tab I have to clear the cache to run. I don't know why! :((


text:
Q: React native based app Which framework should I follow to create react-native based apps or what is the best appropriate way if I want to use Redux  for creating new apps.
I just want to build an app using react native along with redux and I am not sure what library should I use for that ?
 I know little about Redux thunk and saga but as a newbie I am confused what could be use for my app that gives me more flexible .

A: From my personal expirience, to develop I use Atom once installed you can add more plugins in order to customize it.
For debug purposes I use a couple of Chrome plugins like React Developers Tools and Redux Dev Tools
As I said, these are my options but there are so many others...


text:
Q: Locating a file with Java I'm working with the File class for the first time and am a little confused.
I wrote this basic code to see if a file on my desktop could be detected:
public static void main(String[]args){
    File test= new File("abc.pdf");
    if(test.exists()==true){
        System.out.println("got it!");
    }
    else{System.out.println("try again");}
}

I know I'm missing a big step since the program can't seem to detect it. Can anyone tell me what else I need to look up? Thanks.

A: You need to specify absolute path. e.g:
File file = new File("C:\\abcfolder\\abc.pdf");

In order to get the desktop absolute path:
String desktopPath = WindowsUtils.getCurrentUserDesktopPath();

Then:
File file = new File(desktopPath+"\\abc.pdf");

A: If you're running this in Eclipse, it will look for the file in the project folder.
If you're running this from a command line, it will look in the current folder.
If you're running this from a jar file, it will look in the folder with the jar file, at least on Windows.
If you're running this somewhere else, it depends on how you're running it. In most IDEs it will be the project folder.


text:
Q: App rejection issue when submit to Facebook for review I have integrated Facebook SDK for the first time. I have submitted it to Facebook for review and its got rejected. Now let me tell you the steps I followed and the issue where I am going through.

*

*Created an app with Facebook email, public_profile permission and went live (as its not required the review as per the document and its working fine)

*Now due to change (enhancement) in the business requirement, I had to add user_friends permission also in the existing app. I have gone through many links and read about the facebook app review and Facebook test apps I have created a test app for the actual app and integrated the user_friends permission (as it works for test app)

*Since the previous live app was with general permission (email, public_profile) I have not submitted this for review. So, this time I have submitted the test app for review and it got rejected (fb reviewer message
-- unable to login)

Question:
But it's still working. I am able to login properly. Cant understand what and where the problem is? I have googled for solution and found that we need to submit actual app for review. But how, the actual app is already live without user_friends permission, so in that case it will again get rejected.
Any help will be appreciated, Thanks in advance.


text:
Q: Invalid prop `data` supplied to `MaterialTable`, expected one of type [function] I am working in a jhipster application, with data coming from postgress sql. The api is http://localhost:8080/api/agreements and I am trying to display the data in a react material table but I am getting this error "Invalid prop data supplied to MaterialTable, expected one of type [function]" on my console after writing my functions.
Let me walk you through my codes below:
Inside the React component
  const apiUrl = 'http://localhost:8080/api/agreements';
  const [data, setData] = useState([]);

    useEffect(() => {
    getAgreementsData();
    }, []);

    const getAgreementsData = () => {
    fetch(apiUrl)
  .then(res => res.json())
  .then(res => setData(res));

};
Inside the JSX
      <MaterialTable
      title="Agreements"
      data={data}
      columns={columns}/>

The columns are displaying but the data is not.
And this warning is on the console " GET http://localhost:8080/api/agreements 401 (Unauthorized)"

A: I later resolved the error by using axios get instead of fetch.
     useEffect(() => {
     getAgreementsData();
      }, []);

     const getAgreementsData = () => {
     axios.get(apiUrl).then(res => setData(res.data));
      };

A: i also have thiss error , i cant parse my data into table. but i find where it is problem.
i parse my data like object ->
export const CLIENT_DATA ={
 name: "Frontend site",
 contactPersonName: "Lukasz Swarz",
 contactPersonEmail: "lukasz@gmail.com",
 contactPersonPhone: "065438677282",
 description: "This is project, for car sell!",
 statusClient: "Active"

};
but you must do this with array brackets :
export const CLIENT_DATA =[{
 name: "Frontend site",
 contactPersonName: "Lukasz Swarz",
 contactPersonEmail: "lukasz@gmail.com",
 contactPersonPhone: "065438677282",
 description: "This is project, for car sell!",
 statusClient: "Active"

}];
in my case, this being problem, basic error,but take me a lot of time


text:
Q: Tikz table with reference
I need to draw a table with the same arrows. The reason I do not want to use the graphics software is that I need to add dynamic references inside the cells using latex.
I would appreciate if somebody cloud help me with this.

A: You could use a matrix to create the table and for the arrows there is the shapes.symbols. And fit, backgrounds and calc allow you to dynamically adjust these things.
\documentclass[tikz,border=3.14mm]{standalone}
\usetikzlibrary{matrix,fit,backgrounds,calc,shapes.symbols}
\begin{document}
\begin{tikzpicture}[font=\sffamily]
 \matrix[matrix of nodes,row sep=-\pgflinewidth,column sep=-\pgflinewidth,
 standard size/.style={minimum height=6mm,text width=pi*1cm,anchor=center},
 nodes={draw,standard size,fill=white},
 row 1/.style={nodes={standard size,fill=purple,text=white}},]
 (mat)
 { aaa & bbb & ccc \\
  aaa & bbb & ccc \\
   |[fill=red,text=white]| aaa & bbb & ccc \\
   aaa & bbb & ccc \\
   |[fill=red,text=white]| aaa & |[fill=blue,text=white]|  bbb & |[fill=red,text=white]|  ccc \\
   aaa & bbb & ccc \\
  };
 \begin{scope}[on background layer]
  \node[fit=(mat),inner sep=8mm,fill=cyan!50!gray,rounded corners=8pt](fit){};
 \end{scope}
 \foreach \X/\Y [count=\Z] in {AAA/orange,BBB/green!80!gray,CCC/cyan!50!gray}
 {\path let \p1=($(mat-1-\Z.north east)-(mat-1-\Z.north west)$),
 \p2=($(fit.north)-(mat-1-\Z.north west)$)
 in node[shape=signal,signal to=east,signal from=west,
 anchor=south west,fill=\Y,
 minimum width=\x1+\y2/2-\pgflinewidth,minimum height=\y2-2*\pgflinewidth]
 at (mat-1-\Z.north west) {\X};}
\end{tikzpicture}
\end{document}

And of course it works with references/links "out of the box".
\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{matrix,fit,backgrounds,calc,shapes.symbols}
\usepackage{hyperref}
\begin{document}
\begin{figure}[htb]
\begin{tikzpicture}[font=\sffamily]
 \matrix[matrix of nodes,row sep=-\pgflinewidth,column sep=-\pgflinewidth,
 standard size/.style={minimum height=6mm,text width=pi*1cm,anchor=center},
 nodes={draw,standard size,fill=white},
 row 1/.style={nodes={standard size,fill=purple,text=white}},]
 (mat)
 { aaa \cite{Einstein} & bbb & ccc \\
  aaa \cite{Witten:1982fp} & bbb & ccc \\
   |[fill=red,text=white]| aaa \cite{AlvarezGaume:1983ig} & bbb & ccc \\
   aaa & bbb & ccc \\
   |[fill=red,text=white]| aaa & |[fill=blue,text=white]|  bbb & |[fill=red,text=white]|  ccc \\
   aaa & bbb & ccc \\
  };
 \begin{scope}[on background layer]
  \node[fit=(mat),inner sep=8mm,fill=cyan!50!gray,rounded corners=8pt](fit){};
 \end{scope}
 \foreach \X/\Y [count=\Z] in {AAA/orange,BBB/green!80!gray,CCC/cyan!50!gray}
 {\path let \p1=($(mat-1-\Z.north east)-(mat-1-\Z.north west)$),
 \p2=($(fit.north)-(mat-1-\Z.north west)$)
 in node[shape=signal,signal to=east,signal from=west,
 anchor=south west,fill=\Y,
 minimum width=\x1+\y2/2-\pgflinewidth,minimum height=\y2-2*\pgflinewidth]
 at (mat-1-\Z.north west) {\X};}
\end{tikzpicture}
\caption{A Ti\emph{k}Zy table.}
\label{tab:TikZy}
\end{figure}

\begin{thebibliography}{9}
\bibitem{Einstein}
A.~Einstein, \textit{Zur Elektrodynamik bewegter K{\"o}rper},
Annalen der Physik, 322(10):891--921, 1905.

\bibitem{Witten:1982fp}
  E.~Witten, \textit{An SU(2) Anomaly},
  Phys.\ Lett.\ B \textbf{117}, 324  (1982).

\bibitem{AlvarezGaume:1983ig}
  L.~Alvarez--Gaum\'{e} and E.~Witten,
  \textit{Gravitational Anomalies},
  Nucl.\ Phys.\ B \textbf{234}, 269 (1984).
\end{thebibliography}
\end{document}


text:
Q: Disable Automatic Gain control in Google Hangouts I'm using the latest version of OSX with Google Chrome and Hangouts. I'm having trouble with the Hangout's automatic gain control, in that I don't want to use it. The gain control is too dumb to understand that we're using a table top mic and that background noise isn't relevant.
I have found guides that tell you to edit com.google.GoogleTalkPluginD.plist, and I've followed them to a T, but they haven't affected the issue. It seems that hangouts is now separated from the Google Talk Plugin. All the information related to this issue was from 2011, and hangouts have changed vastly since then.
Is there any new settings file? It seems like the only option might be an inline level mixer. Thanks!

A: There is an extension available for this: Disable Automatic Gain Control


text:
Q: Deleting ':' in a value I have this value:
y = c0:ad:0c:5a:f4:42:89:41:c5:6c:d7:48:8b:91:a2:f6:34:9c

I want to delete all of the ':' characters.
I have tried different ways, such as lists, without success.
Could anyone help me?
(Sorry for my English)

A: Just use y.replace(':', ''):
In [13]: y = 'c0:ad:0c:5a:f4:42:89:41:c5:6c:d7:48:8b:91:a2:f6:34:9c'

In [14]: y.replace(':', '')
Out[14]: 'c0ad0c5af4428941c56cd7488b91a2f6349c'

A: I'd use str.translate:
y = "c0:ad:0c:5a:f4:42:89:41:c5:6c:d7:48:8b:91:a2:f6:34:9c"
y.translate(None,':')

It's fast :-)
>>> import timeit
>>> def replace(x):
...     return x.replace(":","")
...
>>> def translate(x):
...     return x.translate(None,':')
...
>>> y = "c0:ad:0c:5a:f4:42:89:41:c5:6c:d7:48:8b:91:a2:f6:34:9c"
>>> replace(y) == translate(y)
True
>>> timeit.timeit('replace(y)','from __main__ import replace,y')
1.3739330768585205
>>> timeit.timeit('translate(y)','from __main__ import translate,y')
0.9205348491668701

It also scales up to allow the deletion of multiple characters, but it doesn't do substrings.  For example, you can remove words with str.replace, but you can't easily/efficiently remove 'x' or 'y' or 'z'.

A: You could try splitting and rejoining the string. Also, there are ways using Regex, but that is probably overkill.
y = "c0:ad:0c:5a:f4:42:89:41:c5:6c:d7:48:8b:91:a2:f6:34:9c"

print("".join(y.split(sep=":")))

A: One more possibility(just in case you need list of values from the original value) to do this using string.split and string.join is:
y = c0:ad:0c:5a:f4:42:89:41:c5:6c:d7:48:8b:91:a2:f6:34:9c
y = ''.join(y.split(':'))

A: I'm not a python guy, but I would use replace().
http://www.tutorialspoint.com/python/string_replace.htm
y = "c0:ad:0c:5a:f4:42:89:41:c5:6c:d7:48:8b:91:a2:f6:34:9c";
y.replace(":","");

A: and why not
print ''.join([x for x in y if x!=":"])

different solutions for different approach. Maybe this solution can do some other things not in question.