Q: How do I combine large csv files in python? I have 18 csv files, each is approximately 1.6Gb and each contain approximately 12 million rows. Each file represents one years' worth of data. I need to combine all of these files, extract data for certain geographies, and then analyse the time series. What is the best way to do this?
I have tired using pd.read_csv but i hit a memory limit. I have tried including a chunk size argument but this gives me a TextFileReader object and I don't know how to combine these to make a dataframe. I have also tried pd.concat but this does not work either.

A: The memory limit is hit because you are trying to load the whole csv in memory. An easy solution would be to read the files line by line (assuming your files all have the same structure), control it, then write it to the target file:
filenames = ["file1.csv", "file2.csv", "file3.csv"]
sep = ";"

def check_data(data):
    # ... your tests
    return True # << True if data should be written into target file, else False

with open("/path/to/dir/result.csv", "a+") as targetfile:
    for filename in filenames :
        with open("/path/to/dir/"+filename, "r") as f:
            next(f) # << only if the first line contains headers
            for line in f:
                data = line.split(sep)
                if check_data(data):
                    targetfile.write(line)

Update: An example of the check_data method, following your comments:
def check_data(data):
    return data[n] == 'USA' # < where n is the column holding the country

A: Here is the elegant way of using pandas to combine a very large csv files.
The technique is to load number of rows (defined as CHUNK_SIZE) to memory per iteration until completed. These rows will be appended to output file in "append" mode.
import pandas as pd

CHUNK_SIZE = 50000
csv_file_list = ["file1.csv", "file2.csv", "file3.csv"]
output_file = "./result_merge/output.csv"

for csv_file_name in csv_file_list:
    chunk_container = pd.read_csv(csv_file_name, chunksize=CHUNK_SIZE)
    for chunk in chunk_container:
        chunk.to_csv(output_file, mode="a", index=False)

But If your files contain headers than it makes sense to skip the header in the upcoming files except the first one. As repeating header is unexpected. In this case the solution is as the following:
import pandas as pd

CHUNK_SIZE = 50000
csv_file_list = ["file1.csv", "file2.csv", "file3.csv"]
output_file = "./result_merge/output.csv"

first_one = True
for csv_file_name in csv_file_list:

    if not first_one: # if it is not the first csv file then skip the header row (row 0) of that file
        skip_row = [0]
    else:
        skip_row = []

    chunk_container = pd.read_csv(csv_file_name, chunksize=CHUNK_SIZE, skiprows = skip_row)
    for chunk in chunk_container:
        chunk.to_csv(output_file, mode="a", index=False)
    first_one = False

A: You can convert the TextFileReader object using pd.DataFrame like so: df = pd.DataFrame(chunk), where chunk is of type TextFileReader. You can then use pd.concat to concatenate the individual dataframes.


Q: In Java or Scala, is there a way to add a callback to an exception so that when the exception is caught, the callback is invoked? Problem statement:
I have an RPC client lib 1 that is used by many services with all code in a mono repo. This RPC client lib 1 throws a set of runtime exceptions (S1).
Now there is another RPC client lib 2 that I try to migrate all services from using lib 1 to lib 2. However, RPC client lib 2 throws a different set of runtime exceptions (S2).
I am trying to get a list of services that are going to be affected if the RPC client exception semantics change from S1 to S2.
Approach 1: read through code of all services that currently use RPC client lib 1. Obviously this approach is not scalable because there are many services and exception handling logic could be complex and not straightforward.
Approach 2: static analysis. However, I am not sure if any static analysis can detect the situation where an exception thrown by the RPC lib is caught at many levels above in the call stack.
Approach 3: explore if there is a way to register a callback to an exception and expect the callback to be invoked when the exception is caught. Ideally when the callback is invoked, it is provided with the information about where the exception is caught.

A: Sounds like AspectJ pointcut "after catching" (not exising). Existing is "after throwing"
https://coderanch.com/t/498256/frameworks/AOP-pointcut-CATCH-block
https://www.eclipse.org/aspectj/doc/next/progguide/printable.html#the-handler-join-point
How to intercept method which handles its own exceptions using AspectJ
Spring AOP - Invoking advice from catch block
Maybe java agents/bytecode manipulation can be helpful
Using Instrumentation to record unhandled exception
You can consider to instrument catch blocks throughout the codebase with Scalameta (or Scalafix)
import scala.meta._

val transformer = new Transformer {
  override def apply(tree: Tree): Tree = tree match {
    case q"try $expr catch { ..case $cases } finally $expropt" =>
      val cases1 = cases.map {
        case p"case $pat if $expropt => $expr" =>
          pat match {
            case p"${pat: Pat.Var}: $tpe" =>
              p"""case $pat: $tpe if $expropt =>
                println("Exception " + ${pat.name} + " is caught")
                $expr
              """
            case p"$pat" =>
              p"""case $pat if $expropt =>
                println("Exception " + ${pat.toString} + " is caught")
                $expr
              """
          }
      }
      q"try $expr catch { ..case $cases1 } finally $expropt"
    case _ => super.apply(tree)
  }
}

transformer(q"""
  try {
    1 / 0
  } catch {
    case e: RuntimeException =>
      println(e)
      throw e
  }
""")

//try {
//  1 / 0
//} catch {
//  case e: RuntimeException =>
//    println("Exception " + e + " is caught")
//    {
//      println(e)
//      throw e
//    }
//}

transformer(q"""
  try {
    1 / 0
  } catch {
    case _ =>
      println("swallowed")
  }
""")

//try {
//  1 / 0
//} catch {
//  case _ =>
//    println("Exception " + "_" + " is caught")
//    println("swallowed")
//}

transformer(q"""
  try {
    1 / 0
  } finally {
    case _ =>
      println("not catching")
  }
""")

//try {
//  1 / 0
//} finally {
//  case _ =>
//    println("not catching")
//}

https://scalameta.org/
https://www.scala-sbt.org/1.x/docs/Howto-Generating-Files.html
Scala conditional compilation
Macro annotation to override toString of Scala function
How to merge multiple imports in scala?
https://scalacenter.github.io/scalafix
For Java sources Spoon (https://spoon.gforge.inria.fr) can be a replacement for Scalameta.

A: Solution 1 can work. If you are only worried about different semantics then it is sufficient to search in client code for occurrences of the exceptions defined by lib1. If client code catches a more generic exception (e.g. Exception or Throwable) then the precise semantics don't matter and you can leave that code alone.
Assumptions:

*

*Lib1's exceptions are specific and are not thrown by other code (e.g. not RuntimeException but Lib1Exception is okay).

*Lib1 and lib2 throw different exceptions but for the same reasons: if lib1 would throw an exception, lib2 would as well (and vice versa).

A: "Approach 3" is a "nogo". I would go with "approach 4": write a wrapper client library (L3?) that throws the exceptions you want.
It may look like somewhat more work initially, but will definitely pay for itself when you change your mind and want to go back to L1, or when there are L4, L5 and L6 you want to try. It is also probably going to be a lot easier to unit-test.


Q: Save Data from internet in asset folder I want to save data from internet in asset folder in Android. I used Eclipse IDE to develop the android application.
How i can achieve this ?
Thanks.

A: The assets directory is readonly. It's defined and initialized at compile time, you cannot add or edit its contents.
Source (note it doesn't mention anything about writing to files...only reading them.)
Use the SDCard for such operations.

A: slote is right . use internal file storage/SD Card or sqLite database to save image


Q: reading wave audio file into an array in android i am a newbie in android but i have tried to the best of my ability, i want to read a wave audio file into an array of shorts, bytes, floats to be able to manipulate it. With Java you can use JavaSound and you good but android is giving me headache


Q: Ruby on Rails - Track API calls made to 3rd party service I have a 3rd party API service that I am interacting with, via my Rails app, and they have quite low daily limits.
Wondering what the best way to track API calls is?

*

*Database

*Redis

*In memory

*Other

I have a service object that makes all the calls. Just need a good way to track each call made and not go over the daily limit.


Q: Refresh Dataframe created by writing to Parquet files in append mode Is there a way that I can refresh a dataframe that is being created by appending to the parquets in pyspark?
Basically I am writing to parquet in append mode, data that I get daily.
If I want to check the parquet file created I load it up in pyspark and do a count of the data. However if new data is appended to the parquet and I try a count again on the dataframe without reloading the dataframe I do not get the updated count. Basically, I have to create a new dataframe everytime there are any changes to my parquet file. Is there a way in Spark, where the changes are automatically loaded once my parquet is updated?


Q: jQuery click function is not attaching click event to anchor HTML
Inside

I have a series of image links with unique ids as below

Javascript / JQuery
The above div is created by a $.get() to a webservice which returns a chunk of HTML in variable response. On success, the $.get() calls the below function:
var thumbnailsDiv = function (response)
    {
        var json = $.parseJSON(response);
        $('#foo-bar-baz').html(json.html);
        alert("Setting click functions on thumbnails");
        $('.foo-bar-thumbnail-image').unbind().click(function () {
            alert("I am thumbnail " + $(this).id);
        }, false);
    };

As you can see above, I'm trying to bind a click function to each of the image links. However this is not working (with or without the unbind()).
After the above code has run, if I inspect the image links in the Dev Tools, I can see that there are two click event attached already to the thumbnails. Neither of these is my function above. The paths for both of them are from other applications libraries embedded on the page: one is labelled 'jQuery' and the other is labelled 'Bubbling' and 'DOM2'. I'm guessing that it is these attached events that mean I can't add my event above, but I don't know enough about jQuery or javascript to know if this is true (I am a server-side developer normally, I don't know front-end stuff at all.)
Any suggestions as to how I get an on-click event working for these elements would be much appreciated, so that I can replace the demo code above with the code I need to run.

A: You just need to bind the click event to the parent element which already exists on the page.
$('#foo-bar-baz').on('click', '.foo-bar-thumbnail-image', function(){
  // what you want to happen when click
  // occurs on elements that match '.foo-bar-thumbnail-image'
  // within '#foo-bar-baz'
  alert("I am thumbnail " + $(this).id);
});

A: You should be using $(document).on('click','.foo-bar-thumbnail-image',function() ... instead of $.click(function()... since the event handler is on elements that were rendered on the page via JS. That's a "delegated" event handler - you can read more about that here https://learn.jquery.com/events/event-delegation/


Q: ValueError: only 1-dimensional arrays can be used import scipy
from matplotlib.pyplot import specgram
sample_rate,X = scipy.io.wavfile.read("a3.wav")
print(X.shape)
specgram(X,Fs=sample_rate,xextend=(0,30))

i am new to python . and first time use python for audio processing . and have struct on following problem . please help .
i want to plot the spectrogram for a wave file.
In above code sample of python I got following Output:
(528038, 2)
ValueError: only 1-dimensional arrays can be used


Q: What does the -> operator do in Objective-C Sorry if this question has been asked before but there were literally no results when i typed it into google. As the title states, I would like to know what the -> operator does. I see it everywhere: [self processTorrent:alert->handle]; but don't know what it does

A: It's the structure dereference ("member b of object pointed to by a") in C. Objective-C is a strict superset of C.
The the usual way to access a member a is as s.a which, given the pointer, is expressed as (*p).a or can instead be accessed by the shorthand:
p->a  using the structure dereference operator.
struct point
{
    int* x;
    int* y;
};

structure point* struct1;

As with any pointer. To change the address it points to:
struct1->x = &varX;

To change the value at the address to which it points:
*(struct1->x) = varX;


Q: How can I calling JavaScript in WebView from Android? I am beginner in Android development and want to create Android app with JavaScript.
I can run my page in WebView.
I can run JavaScript in WebView.
I can call Android Toast message (or Dailog alert ) from JavaScript to Android.
But I can NOT run JavaScript function from Android !
Can you help me to fix my code
[ Download an android studio project ]
http://r7eq.weebly.com

Code of MainActivity.java

package com.example.adnroid_script;

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.JavascriptInterface;
import android.widget.Toast;

public class MainActivity extends Activity {
    public static WebView myWebView = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        myWebView=(WebView) findViewById(R.id.webview);
        myWebView.getSettings().setJavaScriptEnabled(true);
        myWebView.addJavascriptInterface(new jsInterface(), "FromJS");
        myWebView.loadUrl("file:///android_asset/index.html");
    }

    public class jsInterface{
        @JavascriptInterface
        public void ToAndroid(String jsMessage){
            Toast toast = Toast.makeText(getApplicationContext(),"I sent javascript code to myWebView", Toast.LENGTH_LONG);
            toast.show();
            WebView myWebView = (WebView) findViewById(R.id.webview);
            //   ### The bug is here ###   //
            myWebView.loadUrl("javascript:document.write('
Android say : It is working now !
');");
        }
    }
}


Q: Spring boot lazy initialisation is causing issue for datasource I am trying to implement lazy-initialization in my spring boot microservice.
My application is using below items.

*

*Flyway (I have disabled it from yml)

*postgresql

*Kafka

Whenever I deploy this microservice on Jenkins my sping boot application is failing on startup.
The reason is that on my Jenkins i have nothing installed (kakfa, postgresql or flyway)
What i am adivised is we should use lazy loading, I.e Our application should start without this dependencies and my /health endpoint should be UP.
I have made lazy-initialization: true and flyway: enable: false
This is starting my application like a charm!
Now whenever i am trying to call /health endpoint, I am getting below error.

Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory
  method 'dataSource' threw exception; nested exception is
  java.lang.IllegalArgumentException: URL must start with 'jdbc'

Looking into the logs, It seems spring is trying to connect to database when we are calling /health endpoint.
Is there a way to tell spring that check only app is running or not using /health and doesn't check other stuff?
Please let me know if I am missing something to provide if you need it.
Thanks!


Q: Use jQuery to lift element value then return item from array and update another element I have a select element...
<select name="tour" id="tour">
<optgroup label="tour">
<option value="0" selected="selected">Please Select Tour</option>
<option value="Tour1">Tour1</option>
<option value="Tour2">Tour2</option>
</optgroup>
</select>

I have an array...
<?php $array = array(Tour1=>100,Tour2=>200); ?>

I have a field element...
<input type="text" size="5" id="distance" readonly="readonly" name="distance" value="" class="value" />

I'm looking to set up a jQuery script that looks for a change in the value in the select element 'tour', searches for it in my array, returns the associative value, and writes it to the value of my input field 'distance'.
Desired output: When Tour1 is selected, text input field 'distance' will show 100.

A: 1st Pass the PHP array to JavaScript using json_encode:
var phpArray = <?php echo json_encode($array); ?>;

2nd Bind to the change event of that <select>:
$('#tour').on('change', /* see below */);

3rd Update the value:
function (event) {
    $('#distance').val(phpArray[$(this).val()]);
}

A: what you want to do is not possible. PHP is a server side script. What you could do in order to make your scripts working is to pass the php Array to Javascript when loading the page. That way Javascipt is able to read it and to change the input.
Option would be to use AJAX or define a JS array with the php Array's data:
var js_array = <? echo json_encode($you_array); ?>;

For this solution you need to add a  in your HTML page's  if you're pointing to your JS script external.
For a longer explanation why using your php Array in Javascript that easy is not possible, see here: Difference between Javascript and PHP


Q: Spring boot SUM(column) with specification I have an entity, says:
class MyEntity {
    Long id;
    String attr1;
    String attr2;
    String attr3;
    String attr4;
    Double attr5;
}

I use Specification to query the result filtered by attributes like:
class MySpecification implements Specification<MyEntity> {
    private String attr1;
    private String attr2;
    private String attr3;
    private String attr4;

@Override
public Predicate toPredicate(Root<MyEntity> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
    List<Predicate> restriction = new ArrayList<>();
    if (!StringUtils.isEmpty(attr1)) {
        restriction.add(criteriaBuilder.equal(root.get("attr1"), attr1));
    }
    if (!StringUtils.isEmpty(attr2)) {
        restriction.add(criteriaBuilder.equal(root.get("attr2"), attr2));
    }
    // And so on
    Predicate predicate = criteriaBuilder.disjunction();
    predicate.getExpressions().add(criteriaBuilder.and(restriction.toArray(new Predicate[restriction.size()])));
    return predicate;
    }
}

Now I want to get sum of attr5 by the Specification, how can I do that ?
Thank you in advanced.

A: After some research, here is solution:
Create an interface:
interface MyRepositoryCustom {
    <S extends Number> S sum(Specification<MyEntity> spec, Class<S> resultType, String fieldName);
}

Implementation:
@Repository
class MyRepositoryCustomImpl implements MyRepositoryCustom {

    @Autowired
    private EntityManager entityManager;

    @Override
    public <S extends Number> S sum(Specification<MyEntity> spec, Class<S> resultType, String fieldName) {
        CriteriaBuilder builder = entityManager.getCriteriaBuilder();
        CriteriaQuery<S> query = builder.createQuery(resultType);
        Root<MyEntity> root = applySpecificationToCriteria(spec, query);
        query.select(builder.sum(root.get(fieldName).as(resultType)));
        TypedQuery<S> typedQuery = entityManager.createQuery(query);
        return typedQuery.getSingleResult();
    }

    protected <S> Root<MyEntity> applySpecificationToCriteria(Specification<MyEntity> spec, CriteriaQuery<S> query) {
        Root<MyEntity> root = query.from(MyEntity.class);
        if (spec == null) {
            return root;
        }
        CriteriaBuilder builder = entityManager.getCriteriaBuilder();
        Predicate predicate = spec.toPredicate(root, query, builder);
        if (predicate != null) {
            query.where(predicate);
        }
        return root;
    }
}

Main repository should extend both JpaRepository and MyRepositoryCustom:
@Repository
interface MyEntityRepository extends JpaRepository<MyEntity, Long>, MyRepositoryCustom {

}


Q: Need help understanding RESTful apis in PHP For a few weeks, I've been trying to gather as much information on implementation of RESTful apis in PHP as I can but in vain. All the information that is given online only explain the most basic concepts but never did I come across a very real example with complete code on how RESTapi actually works.
For Example, POST is used create a new resource. But how? How is it implemented in real life? How do I do this in cURL? I am aware of the complete basics but am unable to find any concrete and complete example that explains everything. Most of the tutorials simply name the functions they've used but did not bother explaining what is happening exactly, what the flow of the program is, etc.
If someone can help with a complete example (say, a library registration and database) I'll really appreciate it. I'm really confused.

A: I will describe POST method in REST.
Client send HTTP request via POST method with JSON data.
For example, client send some data to create a word "nice".
POST http://localhost/word/1

JSON content
{
  "data": {
    "type": "word",
    "attributes": {
      "word": "nice"
    }
  }
}

In PHP you need get a response and convert to array and insert ot DB. Why insert? Because request method is POST.


Q: Slider AutoplayJquery doesn't work How can I add autoplay in this slider?
https://codepen.io/mikun/pen/YWgqEX
        $('.slide-nav').on('click', function(e) {
  e.preventDefault();
  // get current slide
  var current = $('.flex--active').data('slide'),
    // get button data-slide
    next = $(this).data('slide');

  $('.slide-nav').removeClass('active');
  $(this).addClass('active');

  if (current === next) {
    return false;
  } else {
    $('.slider__warpper').find('.flex__container[data-slide=' + next + ']').addClass('flex--preStart');
    $('.flex--active').addClass('animate--end');
    setTimeout(function() {
      $('.flex--preStart').removeClass('animate--start flex--preStart').addClass('flex--active');
      $('.animate--end').addClass('animate--start').removeClass('animate--end flex--active');
    }, 1200);
  }

});

It's working good, but without an autoplay.


Q: Notice unserialize error in CakePHP via Redis Update:
Per suggestion from the accepted answer below, I tested reading a negative number:
$negativeInt = -1;
Cache::write('my-test-count', $negativeInt, 'short');
$readVal = Cache::read('my-test-count', 'short');
debug($readVal);
exit;

The unseralize error reproduces consistently when trying to read any negative number.  It's now an accepted bug, which I assume will be resolved by 2.8.1

Original Question:
I keep getting this error, but can't figure out why or even how to further troubleshoot.
The line that throws the error should only get hit if Cache::read() returns false.  But, that line would throw an unserialize error itself if I didn't put the @ before it.
Question:
How can I reliably use Redis for counts without getting unserialize Notices on a regular basis?  If the data in the key is "bad", how can I know that without getting the Notice just from doing a ::read.  I've tried making sure my data is (int) (see below), but that doesn't seem to help.

Notice (8): unserialize(): Error at offset 0 of 2 bytes
  [APP/Vendor/pear-pear.cakephp.org/CakePHP/Cake/Cache/Engine/RedisEngine.php,
  line 136]

Upon inspection of the error:
> unserialize - [internal], line ??
> RedisEngine::read() - APP/Vendor/pear-pear.cakephp.org/CakePHP/Cake/Cache/Engine/RedisEngine.php, line 136
> Cache::read() - APP/Vendor/pear-pear.cakephp.org/CakePHP/Cake/Cache/Cache.php, line 358
> Cache::remember() - APP/Vendor/pear-pear.cakephp.org/CakePHP/Cake/Cache/Cache.php, line 567
> Item::getCount() - APP/Model/Item.php, line 812

It appears to be coming from this function:
public function getCount($id) {
    $model = $this;

    // here is where the Cache::read() and debug are in the update below

    return Cache::remember('item' . $id. '_count', function() use ($model, $id) {
        $count = $model->find('count', array(
            'conditions' => array(
                $model->alias . '.status' => 1,
                $model->alias . '.id' => $id
            )
        ));
        return ($count === false) ? 0 : (int)$count;
    }, 'my_counts'); // THIS IS LINE 812
}

public function decrementCount($id, $offset = 1) {
    if(empty($id)) return false;
    $count = @Cache::read('item' . $id . '_count', 'my_counts');
    if($count === false) {
        $this->getCount($id);
    } else {
        Cache::decrement('item' . $id . '_count', $offset, 'my_counts');
    }
}

public function incrementCount($id, $offset = 1) {
    if(empty($id)) return false;
    $count = @Cache::read('item' . $id. '_count', 'my_counts');
    if($count === false) {
        $this->getCount($id);
    } else {
        Cache::increment('item' . $id. '_count', $offset, 'my_counts');
    }
}

UPDATE:
This function gets run in a loop (through 1-20 items).  When I add the following before the Cache::remember(...:
$toReturn = Cache::read('item' . $id. '_count', 'my_counts');
debug($toReturn);

It gives this:

*

*debug: (int) 0

*debug: (int) 0

*Notice (8): unserialize(): Error at...  (from the Cache::read)

*debug: false

*Notice (8): unserialize(): Error at...   (from the Cache::remember

*debug: (int) 0

*Notice (8): unserialize(): Error at...  (from the Cache::read)

*debug: false

*Notice (8): unserialize(): Error at...   (from the Cache::remember

*0

*3

*1

*1
...

A: It seems to be a core bug. I might be able to answer to why this issue occurs.
I am guessing that this issue is caused by int(-1).
When writing data, RedisEngine doesn't serialize the data if it is an integer.
Therefore, int(-1) will be saved without calling serialize().
public function write($key, $value, $duration) {
    if (!is_int($value)) {
        $value = serialize($value);
    }
    ...
}

But when reading data, the implementation seems asymmetric. I don't know Redis well, but I am guessing that Redis stores int(-1) as string(-1). As ctype_digit("-1") returns false, string(-1) would be unserialized wrongly.
public function read($key) {
    $value = $this->_Redis->get($key);
    if (ctype_digit($value)) { // ctype_digit("-1") === false
        $value = (int)$value;
    }
    if ($value !== false && is_string($value)) { // is_string("-1") === true
        $value = unserialize($value);
    }
    ...
}

Thus, you will see "Notice (8): unserialize(): Error at offset 0 of 2 bytes". The size of string(-1) is 2 bytes.
What about opening an issue on github, if you could reproduce that writing int(-1) and reading it throws a notice.
Aside from that, a workaround would be stop using Cache::decrement(). On race conditions, the method will store int(-1).
You may use Cache::write() instead if it is not an important data. For example:
$count = Cache::read('item' . $id. '_count', 'my_counts');
if ($count === false || 0 > $count - $offset) {
    $this->getCount($id);
} else {
    Cache::write('item' . $id. '_count', $count - $offset, 'my_counts');
}

But if it is an important data, then you may need to implement exclusive lock/unlock.
Thank you for reading this to the end and sorry if I am wrong.

A: Solution:
return ($count === false) ? 0 : (int)$count;

Long version:
You shouldn't increment/decrement serialized value.
Cache::remember does something like this:
$key = 'key';
$value = 10;
$serialized = serialize($value); // $serialized = 'i:10;'
$redis->set($key, $serialized);

Cache::read does something like this:
$key = 'key';
$serialized = $redis->get($key); // $serialized = 'i:10;'
$value = unserialize($serialized); // $value = (int) 10
return $value;

But Cache::decrement does something like this:
$key = 'key';
$count = 1;
$redis->decrby($key, $count); // Error, decrby expects plain value, "10", not "i:10;" ( http://redis.io/commands/decrby )

Also, if you decrement successfully, then you will have plain value in redis, so result will be:
$key = 'key';
$serialized = $redis->get($key); // $serialized = '10'
$value = unserialize($serialized); // error, cannot unserialize '10'

EDIT:
After checking source:
https://github.com/cakephp/cakephp/blob/master/src/Cache/Engine/RedisEngine.php
I see that Cake does checks:
    if (!is_int($value)) {
        $value = serialize($value);
    }

So all you need to do to avoid serialization is to make sure that you are storing (int).

A: Just remove third parameter, it should be work
return Cache::remember('item' . $id. '_count', function() use ($model, $id) {
    $count = $model->find('count', array(
        'conditions' => array(
            $model->alias . '.status' => 1,
            $model->alias . '.id' => $id
        )
    ));
    return ($count === false) ? 0 : (int)$count;
});


Q: Recommendations for keeping a build server updated As a guy who frequently switches between QA, build and operations, I keep running into the issue of what to do about operating system updates on the build server.  The dichotomy is the same on Windows, Linux, MacOS or any other o/s that can update itself via the internet:

*

*The QA team wants to keep the build server exactly as it is from the beginning of the product release cycle to the end, since installing updates could destabilize the server and means that successive builds aren't made against the same baseline.

*The ops team wants the software to be deployed on a system with all the latest security patches; this can mean that the software isn't deployed on exactly the same version of the o/s that it was built on.

I usually mitigate this by taking release candidate builds and installing them on a test server that has a completely up-to-date o/s, repeating the automated tests that are run on the build server and doing some additional system level testing to make sure everything looks good before deployment.  However, this seems inefficient to me; does anyone have a better way ?

A: Personally i don't think you have much of an issue here - just apply the latest updates to the build server. The main reasons i say this are:

*

*it is highly unlikely that your code or any of the dependencies on the build server are so tightly coupled to the OS version that installing regular updates is going to affect anything, let alone break it. There can be minor differences between window messages etc between Windows versions, but those are few and far between, and are usually quite well documented out there on teh interweb. If you are using managed technology stacks like WPF/Silverlight or ASP.Net and even mostly Winforms then you will be isolated from these changes - they should only affect you if you are doing hardcore stuff using the WinAPI directly to create your windows or draw your buttons.

*it is a good practice to always engineer your product against the latest version of the OS, because you need to encourage your customer to implement those updates too - IOW you should not be in a position where you have to say to your client to not install update xyz because your application will not run against it - especially if that update is a critical security update

*testing for differences between OS versions should be done by the QA team and should independant of what is on the build server

*you do not want your build server to get in to such a state that it has been so isolated from the company update process that when you finally do apply them all it barfs and spits molten silicon everywhere. IOW, the longer you wait to update, the higher the risk of something going wrong and doing so catastrophically. Small and frequent/incremental updates are lower risk than mass updates once per decade :)
The build server updates that you do have to be cautious about are third party controls or library updates - they can frequently contain breaking changes or considerably altered behavior. They really should be scheduled, and followed up by a round of testing looking for any changes.

A: Virtualize!
Using stuff like VMWare Server you can script the launch and suspend of virtual machines. So you can script VM resume, SSH to launch build, copy, VM suspend, repeat. (I say this, but I abandoned my work on this. Still, I was making progress at the time.)
Also, you can trust your OS vendors. Can't you?
They have an interest in compatibility. If you build on Windows XP it is almost certain to work on XP SP3 and Vista and Windows 7.
If you build on RedHat Enterprise 5, it had better work on 5.1, 5.2, 5.3, 5.4, etc.
In my experience this has worked out OK so far for me and I recommend building on your lowest patch OS versions. With the Linux stuff in particular I have found newer releases linking to more recent libraries not available on older versions.
Of course it doesn't hurt to test your code on a copy of the deployment server. It all depends on how certain you want to be.

A: Take the build server off the network, that way you do not need to worry about installing security updates. Only load the source from CD, thumb drive or whatever other means.
Plug it back in at the end of your release cycle and then let all the updates take place.

A: Well, for the most stable process, I would have two build servers, "Build with Initial config, Build with update config", and two autotest test servers with similar differences. Use virtualization to do this effectively and scriptably.


Q: jsTree select Node which is not in DOM yet I have an jsTree, data comes from HTML
$("#tree_container").jstree();

Now I want to implement deep linking on the tree elements. I am getting the class and data-id from URL parameters and now I want to select the correspondent node.
var id=$("#tree_container").find("li."+get_class+"[data-id='"+get_id+"']").attr("id");
if(id!=undefined && id!=0) {
                treeElem.jstree(true).select_node(id);
            }

This only works if the node is already in the DOM Tree.
(sub-Trees are getting inserted in if the parent node is clicked)
If the node I want is not in the tree ... id is undefined and the select fails.
Thing is, if I put in the id (like "#j1_6") in directly the node is found even if it is not in the DOM tree. It only work with the Id in that format, I try putting other selectors in or even elements ($(".class[data-id='1']"), nothing worked.
My problem is that I do not know how to get the id of the node if it is not in the DOM Tree yet. I did not find a api function or anything to do that.
====== UPDATE ======
I found a workaround ...
When building the HTML tree I now combine the class and data-id to make up the html id of the element (li).
So I have controll over the ids and know them and just do:
treeElem.jstree(true).select_node("#"+get_type+"_"+get_id);
so yeah, as I said for me it is just a workaround...


Q: Store a custom Array List in Shared Preference I want to store a Custom Array List in a Shared Preference , so that I can read the List when I open my app the next time.
I looked at many tutorials and answers but I could not really understand it.
list_addr.java
public class list_addr {

public String title;
public String detail;

public list_addr( String title, String detail) {
    super();

    this.title = title;
    this.detail=detail;

}

public String getTitle() {
    return title;
}
public void setTitle(String title) {
    this.title = title;
}
public String getDetail() {
    return detail;
}
public void setDetail(String detail) {
    this.detail = detail;
}

@Override
public String toString() {
    return title + "\n" ;
}

}

list_adapter.java
enterpublic class list_addr_adapter extends ArrayAdapter<list_addr> {

Context context;
int layoutResourceId;

public list_addr_adapter(Context context, int layoutResourceId, List<list_addr> items) {
    super(context, layoutResourceId, items);
    this.layoutResourceId = layoutResourceId;
    this.context = context;
    //  this.listener=callback;
}

/*private view holder class*/
private class ViewHolder {

    TextView txtTitle;
    TextView txtDetail;
    ImageView imageview;
    CheckBox checkbox;

}
ViewHolder holder = null;

public View getView(final int position, View convertView, ViewGroup parent) {
    final list_addr lists = getItem(position);
    final int pos=position;

    LayoutInflater mInflater = (LayoutInflater) context
            .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.items_sav_addr2, null);
        holder = new ViewHolder();
        holder.txtTitle = (TextView) convertView.findViewById(R.id.textTitle);
        holder.txtDetail = (TextView) convertView.findViewById(R.id.detail);
        holder.imageview = (ImageView) convertView.findViewById(R.id.imageview);
        holder.checkbox=(CheckBox)convertView.findViewById(R.id.chkitem);

        convertView.setTag(holder);
    } else
        holder = (ViewHolder) convertView.getTag();

    holder.txtTitle.setText(lists.getTitle());
    holder.txtDetail.setText(lists.getDetail());

        return convertView;
    }

}

This is how I inflate the list view -
 listView1 = (ListView) findViewById(R.id.listView);
    list_adapter_invoice adapter = new list_adapter_invoice(this,
            R.layout.items_row, MyAdaptertwo.rowitems);

    listView1.setAdapter(adapter);

A: You can only save primitive types in shared preference . If you need to save an ArrayList then you can save it as a String which is Comma seperated . At the time of fetching this use split(",") on this String And you will get a String [] of it .
And if you want to save a list of Object then i Suggest to use a Singleton Class for it . Here is example of Singelton Class .Try this it you want .
public class ReferenceWrapper {
private Context context;
private static ReferenceWrapper wrapper;
private ArrayList<Object> list;

private ReferenceWrapper(Context context) {
    this.context = context;
}

public static ReferenceWrapper getInstance(Activity activity) {
    if (wrapper == null) {
        wrapper = new ReferenceWrapper(activity);
    }
    return wrapper;
}

public ArrayList<Object> getList() {
    return list;
}

public void setList(ArrayList<Object> list) {
    this.list = list;
}

}
And use it like this
ReferenceWrapper wrapper=ReferenceWrapper.getInstance(MainActivity.this);
    wrapper.setList(yourArrarlist);

And get It in any activity
ReferenceWrapper wrapper=ReferenceWrapper.getInstance(MainActivity.this);
ArrarList<Object> list= wrapper.getList(yourArrarlist);

It will return the same ArrayList list you saved recently . Because its only one object is Created
.Let me know if it helps

A: Answer is about write object in File instead of SharedPreference. Hope this may help
    try {
        ArrayList<List_addr> addrList = new ArrayList<>();
        addrList.add(new List_addr("Bangalore", "Its a City"));
        addrList.add(new List_addr("Delhi", "Its also a City"));

        //write object into a file
        FileOutputStream fos = openFileOutput("addrList", Context.MODE_PRIVATE);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(addrList);
        oos.close();

        //read object from the file
        FileInputStream fis = openFileInput("addrList");
        ObjectInputStream ois = new ObjectInputStream(fis);
        ArrayList<List_addr> readAddrList = (ArrayList<List_addr>) ois.readObject();
        ois.close();

        for (List_addr address : readAddrList) {
            Log.i("TAG", "Name " + address.getTitle() + " City " + address.getDetail());
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

Important : Please mind @MeetTitan answer comments.

A:          Step 1:

           Put string array set into the shared preference.
           pref.putStringSet(String key, Set<String> values);

         Step 2:

           Convert array list of pojo into set.
           Set<String> set = new HashSet<String>(list);

         Set 3:

           Retrive using the getStringSet.

A: To save arraylist in shared preferences do the following
 // Create List of address that you want to save
    ArrayList addressList = new ArrayList();
    addressList.add(new list_addr());
   addressList.add(new list_addr());
    SharedPreferences prefs = getSharedPreferences("address", Context.MODE_PRIVATE);
    //save the user list to preference
    Editor editor = prefs.edit();
    try {
    editor.putString("addressList", ObjectSerializer.serialize(addressList));
    } catch (IOException e) {
    e.printStackTrace();
    }
    editor.commit();

and then to retrieve arraylist use this
ArrayList addressList = new ArrayList();
// Load address List from preferences
SharedPreferences prefs = getSharedPreferences("address", Context.MODE_PRIVATE);
try {
addressList = (ArrayList) ObjectSerializer.deserialize(prefs.getString("addressList", ObjectSerializer.serialize(new ArrayList())));
} catch (IOException e) {
e.printStackTrace();
}

And this is the link for objectSerializer class
Object Serializer


Q: How to keep a user signed in on an Electron app using Auth0? There seem to be no complete explanations of how to do this, or even enough fragments for me to piece together what I have to do. After about 16 hours of studying, I am at wit's end.
It seems like I can't use SSO, and I also can't use PKCE because there is no working example anywhere on the web. There is a github repo with an example implementation, but it does not function and after 2 hours playing with it I cannot determine what I need to do to move forward this way.
Thanks for any help.

A: You can add offline_access to your scope (e.g. "scope": "offline_access openid something:else",) and this will yield you a refresh_token.
Auth0 currently supports unlimited refresh_token usage, so when your access_token expires (you either can track expiration time manually using "expires_in": 86400 value in respones or react on 401 response from api) - you can send your refresh token to OAuth2 api endpoint and receive new access token back. They have few descent articles about this matter and what you need to configure for your clients and API as well as what not to do (depending on your client security assumptions).
Take a note - you must secure refresh_token properly - store it in some reliable store and prevent any external scripts from accessing it. I assume with electron app you can do it more reliable than with a public website.


Q: How to check if checkbox is checked in gridviewrow I need help with this code where I check every row in GridView if the CheckBox is checked or not. But there is still false. Can you help me, please?
<asp:GridView ID="GridView1" CssClass="tabulka" runat="server" AutoGenerateColumns="false" />
        <Columns>
            <asp:TemplateField HeaderText="Placení">
                <ItemTemplate>
                    <asp:CheckBox ID="Poslano" runat="server" Text="Vyřešeno"  />
                    <asp:HiddenField ID="id" runat="server" Value='<%# Eval("id").ToString() %>' />
                </ItemTemplate>
            </asp:TemplateField>

         </Columns>
        <FooterStyle BackColor="#CCCCCC" />
        <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" />
    </asp:GridView>

protected void Button1_Click(object sender, EventArgs e)
    {
        foreach (GridViewRow gvRow in GridView1.Rows)
        {
            if (((CheckBox)gvRow.FindControl("Poslano")).Checked) // here is a problem - still false
            {
                Tabor tab = new Tabor();

                tab.Id = Convert.ToInt32(((HiddenField)gvRow.FindControl("id")).Value); // here is good value

            }
        }
    }

A:     Pleae check with below code

   foreach(var gvItem in GridView1.Items)
    {
      CheckBox chkItem = (CheckBox) gvItem.FindControl("Poslano");
      if (chkItem.Checked)
     {
       //Do stuff
     }
    }


Q: calculate a rolling median on a dataframe that has a non-unique date index I have the following dataframe, which has a non-unique index using dates:
                column
2019-01-07         NaN
2019-01-08         NaN
2019-01-08        0.02
2019-01-09       31.45
2019-01-10         NaN
2019-01-10       71.87
2019-01-10       90.18
2019-01-11         NaN
2019-01-12       12.67
2019-01-12        5.68
2019-01-12       11.23
2019-01-12       21.67
2019-01-12       14.77
2019-01-12        5.18
2019-01-13       14.38
2019-01-13         NaN
2019-01-13       71.13
2019-01-13       20.02
2019-01-13      103.10
2019-01-14         NaN
2019-01-15       32.48
2019-01-16       37.37
2019-01-16       31.05
2019-01-16        7.00
2019-01-17         NaN
2019-01-17       39.65
2019-01-18       23.68
2019-01-18        0.08
2019-01-18       41.35
2019-01-19         NaN
2019-01-19       45.85
2019-01-19        3.98
2019-01-19        4.60
2019-01-19         NaN
2019-01-19         NaN
2019-01-20        3.60
2019-01-20        5.03
2019-01-20       15.70

My aim is to calculate a 7 day rolling median using all the values for each date, but ignoring the NaN values.
The resulting dataframe should have a unique date index with the rolling median as a column value for that date, similar to the following:
                column
2019-01-13       17.40
2019-01-14       17.40
2019-01-15       20.85
2019-01-16       20.85
2019-01-17       20.02
2019-01-18       20.85
2019-01-19       31.05
2019-01-20       19.69

I am not sure how to easily achieve this using pandas, so if anyone can provide an answer or point me in the right direction, it will be very much appreciated.
EDIT
To make things clearer, I will explain how the median needs to be calculated for a single date.
Using the date of 2019-01-13, the rolling median will need to use all the values, excluding the NaN values, from the 7 days up to the 13th. This means that the values that need to be included in the median calculation for the 13th are 0.02, 31.45, 71.87, 90.18, 12.67, 5.68, 11.23, 21.67, 14.77, 5.18, 14.38, 71.13, 20.02, 103.10. The resulting median for the 13th would be 17.4.
Hope that helps.

A: A rolling object is iterable, which allows for a solution like this:
# drop NAs and group by date into lists of values
df_per_date = df.dropna().groupby('date').apply(lambda g: g.value.to_list())

# compute medians across windows ('sum' concatenates multiple lists into one list)
medians = [np.median(window.agg(sum)) for window in df_per_date.rolling(5)]

# result
medians = pd.Series(index=df_per_date.index, data=medians)

medians

By the way, I loaded the data like this:
# load the data
df = pd.read_csv(pd.io.common.StringIO("""
2019-01-07         NaN
2019-01-08         NaN
2019-01-08        0.02
2019-01-09       31.45
2019-01-10         NaN
2019-01-10       71.87
2019-01-10       90.18
2019-01-11         NaN
2019-01-12       12.67
2019-01-12        5.68
2019-01-12       11.23
2019-01-12       21.67
2019-01-12       14.77
2019-01-12        5.18
2019-01-13       14.38
2019-01-13         NaN
2019-01-13       71.13
2019-01-13       20.02
2019-01-13      103.10
2019-01-14         NaN
2019-01-15       32.48
2019-01-16       37.37
2019-01-16       31.05
2019-01-16        7.00
2019-01-17         NaN
2019-01-17       39.65
2019-01-18       23.68
2019-01-18        0.08
2019-01-18       41.35
2019-01-19         NaN
2019-01-19       45.85
2019-01-19        3.98
2019-01-19        4.60
2019-01-19         NaN
2019-01-19         NaN
2019-01-20        3.60
2019-01-20        5.03
2019-01-20       15.70
""".strip()), sep='\s+', names=['date', 'value'], parse_dates=['date'])

A: If the data is not too long, cross merge can work:
df['key'] = 1
df = df.reset_index()

(df.merge(df, on='key', suffixes=['','_'])
   .loc[lambda x: x['index'].ge(x['index_']) &
                  x['index'].sub(x['index_']).le('7D')]
   .groupby('index')['column_'].median()
)

Output:
index
2019-01-07       NaN
2019-01-08     0.020
2019-01-09    15.735
2019-01-10    51.660
2019-01-11    51.660
2019-01-12    13.720
2019-01-13    17.395
2019-01-14    17.395
2019-01-15    20.020
2019-01-16    21.670
2019-01-17    21.670
2019-01-18    20.845
2019-01-19    20.020
2019-01-20    21.850
Name: column_, dtype: float64


Q: Error LNK1104 when upgrade from VS2008 to VS2010 My project make C dll deployment in Matlab.
After upgrade from VS C++ 2008 to VS C++ 2010 project, I got this error:
LINK : fatal error LNK1104: cannot open file 'mfc90d.lib'

After searching for solution, I think it should reference to 'mfc100d.lib'. But I don't know HOW to reference.
I tried to reference 'mfc90d.lib', and 'mfc100d.lib'. After that, the error gone, and the other replaced.
LINK : fatal error LNK1104: cannot open file 'mfcs90d.lib'

Even when I put 'mfcs90d.lib' in library paths, nothing happen. The error still there.
Does anyone meet that problem? And how you solve that?
Thank you!


Q: returning and passing 2 one dimensional arrays from a function to another in c++ I have around 5 functions which exchange data among each other, each fuction has to return an array and around two integers. I went through "tuple" but we cant club integers and arrays together and im not very comfortable with "struts".
If i could please be guided of ways of doing the same or passing and returning two arrays ( the integers can be put in an array).
Thank You

A:
returning and passing 2 one dimensional arrays

In C++, you can only return a single value. You cannot return multiple values, and the value that you return cannot be an array.

im not very comfortable with "struts" [sic]

I assume you mean structs. Well, now is the time to become comfortable, because a struct (also known as class) is great way to combine multiple values - even arrays - into a single object that can be returned.

Another option is to pass the function multiple references (or iterators or pointers) to objects that the function can modify instead of returning them.


Q: Google sheets API limits for SAAS applications We want to develop an API integration for Google Sheets in our SAAS platform, we have around 1000 users and each user in our platform will be connecting their own Google Account to the integration.
I see the API limits are 500 requests per 100 seconds per project, and 100 requests per 100 seconds per user.
What I'm not 100% clear on is if these limits apply to our platform integration as a whole (all users on our platform) or the limits apply to each connected Google Account?
I'm assuming the API limit applies to each individual connected Google Account in our integration so each user in our platform will have their own individual requests limits?
I want to be sure though because the alternative of having only 100 requests per 100 seconds is not very scalable across 1000 users in our platform.
Any clarification on this would be highly appreciated!

A: The way the API limits would work for you is that:
Every user would have a limit of 100 requests per 100 seconds per user, since you are performing these requests on the behalf of the user.
If you application was performing these requests instead, then you would reach the 500 requests per 100 seconds.
Hope this clarifies it!


Q: Selecting only first match with CSS document.querySelector("h2") returns only the first element that matches that class selector.
Could this be done in CSS? It is not like doing: h2:first-child as this would select every
 that is the first element of its parent...
Take for example this:

Title

Sub

Title2

Blabla

Introduction

Blabla

Methods

Conclusions

Bla

I know there are ways to select only that
 containing "Sub", but could I ask like in querySelector: get all of them and filter the first, the second or the third one...?


Q: Setting state object dynamically using the data returned using Promise.all and fetch API : React+Typescript I am using fetch API and promise.all for a scenario where I am passing an array of URL'S from where I am fetching the data. The data retrieved from all the above URL'S needs to be set to the state object.
Say I have an array of 5 URL's , the result returned by these must be
assigned to the 5 different values inside my state object.
Using React along with typescript.
Help would be appreciated.
This is what I have tried so far
import * as React from 'react';

const urls = [ 'http://localhost:3001/url1',
               'http://localhost:3001/url2',
               'http://localhost:3001/url3',
             ]

interface IState {
     test: [],
     result: [],
     returnVal: []
}

export default class App extends React.Component<{},IState> {

  constructor(props:any)
  {
    super(props);
    this.state = {
       test: [],
       result: [],
       returnVal: []
  }

  checkStatus(response:any) {
    if (response.ok) {
      return Promise.resolve(response);
    } else {
      return Promise.reject(new Error(response.statusText));
    }
  }

  parseJSON(response:any) {
    return response.json();
  }

  setData(data:any){
    Object.entries(this.state).forEach(([key], index) => {
      this.setState({ [key]: data[index] })
    });
  }

  componentDidMount()
  {
    Promise.all(urls.map(url =>
          fetch(url)
            .then(this.checkStatus)
            .then(this.parseJSON)
            .catch(error => console.log('There was a problem!', error))
        ))
        .then(data => {
           this.setData(data);
        })
  }

  render() {
    return(
      //some rendering code
    )
  }
}

Need to set the data returned from promise to the state object variables.

A: Promise.all(urls.map(url =>
      fetch(url)
        .then(this.checkStatus)
        .then(this.parseJSON)
 ))
 .then(jsons => {
    var newState = {};
    var index = 0;
    for(var key in this.state)
       newState[key] = jsons[index++];
    this.setState(newState);
})


Q: Simple Function to latch_setbit_resetbit I have 32-bit MCU. The port uses 32 digital IO functionality.STM32F469/479  Series.
I am looking for a sample code to Latch a particular bit/particular pin in PORTA
Set/RESET function particular bit In port A.
Can some one guide me on how it can be done using AND/OR/XOR operation?


Q: React - passing data between components This is my first try at a simple React application. Working with the Openweather API and AXIOS. I took Stephen Grider's course on Udemy and I'm trying to create something on my own now, but I still have problems when passing data between components. I have a SearchBar component and I'd love to be able to pass the input value to the parent component's state, so I can then update it with each search and render it into the DOM. However, I keep running into errors. I tried passing a function as a prop to my SearchBar component but I'm getting errors:

setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the App component.
citySearch is not defined

This is confusing to me, as I tried to copy the exact steps from the course, where it seems to be working just fine. But again, I'm very new to this so it is probably just me making some sort of a rookie mistake. Any tips would be much appreciated.
Check my code below:
App.js
import React, { Component } from 'react';
import './App.css';

//Libraries
import axios from 'axios';

//Components
import SearchBar from './Components/search-bar';
class App extends Component {
  constructor(props){
    super(props);

    this.state = {
      city: 'London',
      country: 'uk',
      temperature: 0,
      humidity: 0,
      pressure: 0
    }

    //Axios call
    let city = this.state.city;
    let country = this.state.country;
    axios
      .get(`http://api.openweathermap.org/data/2.5/weather?APPID=${API_KEY}&q=${city},${country}`)
      .then(function(response) {
        this.setState({
          city: response.data.name,
          country: response.data.name,
          temperature: response.data.main.temp,
          humidity: response.data.main.humidity,
          pressure: response.data.main.pressure
        });
      }.bind(this))
      .catch(function(error) {
        console.log(error);
      });

      this.citySearch('London');
  }

  citySearch(city){
    this.setState({city})
  }

  render() {
    return (

Weather App

        <SearchBar onSearchTermChange={citySearch} />

    );
  }
}

export default App;

SearchBar component:
import React, { Component } from 'react';

class SearchBar extends Component {
  constructor(props) {
    super(props);

    this.state = {
      city: ""
    };
  }

  render() {
    return (
      <input
        value={this.state.city}
        onChange={this.onHandleChange}
        className="form-control mt-3"
        placeholder="Enter a city name..."
        type="text"
      />
    );
  }

  onHandleChange(city) {
    this.setState({ city });
    this.props.onSearchTermChange(city);
  }
}

export default SearchBar;

A: You just setState in constructor. If you want to make a call you can put it in componentWillMount() or componentDidMount()
import React, { Component } from 'react';
import './App.css';

//Libraries
import axios from 'axios';

//Components
import SearchBar from './Components/search-bar';
class App extends Component {
  constructor(props){
    super(props);

    this.state = {
      city: 'London',
      country: 'uk',
      temperature: 0,
      humidity: 0,
      pressure: 0
    }
  }

  citySearch(city){
    this.setState({city})
  }

  componentWillMount(){
    //Axios call
    let city = this.state.city;
    let country = this.state.country;
    axios
      .get(`http://api.openweathermap.org/data/2.5/weather?APPID=${API_KEY}&q=${city},${country}`)
      .then(function(response) {
        this.setState({
          city: response.data.name,
          country: response.data.name,
          temperature: response.data.main.temp,
          humidity: response.data.main.humidity,
          pressure: response.data.main.pressure
        });
      }.bind(this))
      .catch(function(error) {
        console.log(error);
      });

      this.citySearch('London');
  }

  render() {
    return (

Weather App

        <SearchBar onSearchTermChange={citySearch} />

    );
  }
}

export default App;

A:
setState(...): Can only update a mounted or mounting component. This
  usually means you called setState() on an unmounted component. This is
  a no-op. Please check the code for the App component.

This is because of your axios call inside the constructor. Put your axios call in componentDidMount should resolve it

citySearch is not defined

It is because React cannot find citySearch function. You should change
<SearchBar onSearchTermChange={citySearch} />
to
<SearchBar onSearchTermChange={this.citySearch} />
In order to use citySearch this way, you should also bind citySearch in your constructor
In summary:

import React, { Component } from 'react';
import './App.css';

//Libraries
import axios from 'axios';

//Components
import SearchBar from './Components/search-bar';
class App extends Component {
  constructor(props){
    super(props);

    this.state = {
      city: 'London',
      country: 'uk',
      temperature: 0,
      humidity: 0,
      pressure: 0
    }

    this.citySearch = this.citySearch.bind(this)
  }

  componentDidMount() {
    //Axios call
    let city = this.state.city;
    let country = this.state.country;
    axios
      .get(`http://api.openweathermap.org/data/2.5/weather?APPID=${API_KEY}&q=${city},${country}`)
      .then(function(response) {
        this.setState({
          city: response.data.name,
          country: response.data.name,
          temperature: response.data.main.temp,
          humidity: response.data.main.humidity,
          pressure: response.data.main.pressure
        });
      }.bind(this))
      .catch(function(error) {
        console.log(error);
      });
  }

  citySearch(city){
    this.setState({city})
  }

  render() {
    return (

Weather App

        <SearchBar onSearchTermChange={this.citySearch} />

    );
  }
}

export default App;

Don't call setState in your constructor, you can just initialize your state like your did. So the original setState in your constructor should be deleted.

UPDATE
To search again everytime you call citySearch.

import React, { Component } from 'react';
import './App.css';

//Libraries
import axios from 'axios';

//Components
import SearchBar from './Components/search-bar';
class App extends Component {
  constructor(props){
    super(props);

    this.state = {
      city: 'London',
      country: 'uk',
      temperature: 0,
      humidity: 0,
      pressure: 0
    }

    this.citySearch = this.citySearch.bind(this)
  }

  componentDidMount() {
    axioSearch();
  }

  axioSearch(city) {
    let city = city || this.state.city;
    let country = this.state.country;
    axios
      .get(`http://api.openweathermap.org/data/2.5/weather?APPID=${API_KEY}&q=${city},${country}`)
      .then(function(response) {
        this.setState({
          city: response.data.name,
          country: response.data.name,
          temperature: response.data.main.temp,
          humidity: response.data.main.humidity,
          pressure: response.data.main.pressure
        });
      }.bind(this))
      .catch(function(error) {
        console.log(error);
      });
  }

  citySearch(city){
    this.axioSearch(city);
  }

  render() {
    return (

Weather App

        <SearchBar onSearchTermChange={this.citySearch} />

    );
  }
}

export default App;

A: First, you should not make your axios calls in the constructor. The component is not yet mounted at this point. Do this in a componentDidMount to ensure that the component is already mounted.
Secodly, you did not bind citySearch to the App class. So in the SearchBar component, it does not know that the citySearch Method should be called from the App class. It is advisable to do this binding in the App class constructor for optimization reasons.
Lastly, I will advise you to write React in a more functional way leveraging state management frameworks like Redux or Flux
The code below should work
import React, { Component } from 'react';
import './App.css';

//Libraries
import axios from 'axios';

//Components
import SearchBar from './Components/search-bar';
class App extends Component {
  constructor(props){
    super(props);

    this.state = {
      city: 'London',
      country: 'uk',
      temperature: 0,
      humidity: 0,
      pressure: 0
    }
    this.citySearch = this.citySearch.bind(this);
    this.citySearch('London');
  }

  citySearch(city){
    this.setState({city})
  }

  componentDidMount() {
    //Axios call
    let {city, country} = this.state;
    axios
      .get(`http://api.openweathermap.org/data/2.5/weather?APPID=${API_KEY}&q=${city},${country}`)
      .then(function(response) {
        this.setState({
          city: response.data.name,
          country: response.data.name,
          temperature: response.data.main.temp,
          humidity: response.data.main.humidity,
          pressure: response.data.main.pressure
        });
      }.bind(this))
      .catch(function(error) {
        console.log(error);
      });
  }

  render() {
    return (

Weather App

        <SearchBar onSearchTermChange={citySearch} />

    );
  }
}

export default App;

For the searchBar component, you didn't bind onHandleChange in the SearchBar component. This will throw errors. You should do this in the searchBar constructor
constructor() {
     ...
     this.onHandleChange = this.onHandleChange.bind(this) //Very important you do this
  }

A: To pass data from child components to the parent component you have to use a callback method.
Check this out. (About how to pass data from parent to child and child to parent).
I know that I'm not touching your code here (I'm sorry), but if you're interested in a different approach this works.
https://medium.com/@ruthmpardee/passing-data-between-react-components-103ad82ebd17


Q: Not able to hide ARSLineProgress in iOS 15 I am new in swift and I am not able to hide ARSLineProgress in iOS 15. Its was working fine below iOS 15.
My code is like this
ARSLineProgress.hide()

The hide() function contain
public static func hide() {
ars_hideLoader(ars_currentLoader, withCompletionBlock: nil)
}

I have download pod file from this page
https://github.com/soberman/ARSLineProgress

Did someone face the same issue

A: This has been fixed on the following PR
https://github.com/soberman/ARSLineProgress/pull/36
The fix is to add CATransaction.commit() to the hide function.  This was not my work.
func ars_hideLoader(_ loader: ARSLoader?, withCompletionBlock block: (() -> Void)?) {
    guard let loader = loader else { return }

    ars_dispatchOnMainQueue {

        let currentLayer = loader.emptyView.layer.presentation()

        let alpha = Double(currentLayer?.opacity ?? 0)
        let fixedTime = alpha * ars_config.backgroundViewDismissAnimationDuration

        CATransaction.begin()
        CATransaction.setCompletionBlock(block)
        let alphaAnimation = CABasicAnimation(keyPath: "opacity")
        alphaAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut)
        alphaAnimation.fromValue = alpha
        alphaAnimation.toValue = 0
        alphaAnimation.duration = fixedTime
        alphaAnimation.isRemovedOnCompletion = true

        loader.emptyView.layer.removeAnimation(forKey: "alpha")
        loader.emptyView.alpha = 0
        loader.emptyView.layer.add(alphaAnimation, forKey: "alpha")

        let scaleAnimation = CABasicAnimation(keyPath: "transform")
        scaleAnimation.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeOut)
        scaleAnimation.fromValue = CGAffineTransform(scaleX: 1, y: 1)
        scaleAnimation.toValue = CGAffineTransform(scaleX: ars_config.backgroundViewDismissTransformScale,
                                                   y: ars_config.backgroundViewDismissTransformScale)
        scaleAnimation.duration = fixedTime
        scaleAnimation.isRemovedOnCompletion = true

        loader.backgroundView.layer.removeAnimation(forKey: "transform")
        loader.backgroundView.layer.add(scaleAnimation, forKey: "transform")

        CATransaction.commit()
    }

    ars_dispatchAfter(ars_config.backgroundViewDismissAnimationDuration) {
        ars_cleanupLoader(loader)
    }
}


Q: Getting average of sums Example collection:
List<Product> list = new List<Product>();
list.Add(new Product { Id = 1, Good = 50, Total = 50 });
list.Add(new Product { Id = 2, Good = 18, Total = 30 });
list.Add(new Product { Id = 2, Good = 15, Total = 30 });
list.Add(new Product { Id = 1, Good = 40, Total = 50 });
list.Add(new Product { Id = 3, Good = 6, Total = 10 });
list.Add(new Product { Id = 1, Good = 45, Total = 50 });
list.Add(new Product { Id = 3, Good = 8, Total = 10 });

Number of products is unknown. What I need as a result is to get a percentage for each distinct product good/total, and then an average for all products. In this case:
Product Id=1, GoodSum = 50 + 40 + 45 = 135, TotalSum = 50 + 50 + 50 = 150, Perc = 135/150
Product Id=2, GoodSum = 18 + 15 = 33, TotalSum = 30 + 30 = 60, Perc = 33/60
Product Id=3, GoodSum = 6 + 8 = 14, TotalSum = 10 + 10 = 20, Perc = 14/20

Avg = Avg(135/150 + 35/60 + 14/20) = Avg(0.9 + 0.55 + 0.7) = 2.15 / 3 = 7.17

Can we do this with Linq, I am only interested in Linq solution.

A: Something like this?
var groups = list.GroupBy(l => l.Id)
                 .Select(g => new {
                                      Id = g.Key,
                                      GoodSum = g.Sum(i=>i.Good),
                                      TotalSum= g.Sum(i=>i.Total),
                                      Perc = (double) g.Sum(i=>i.Good) / g.Sum(i=>i.Total)
                                  }
                        );

 var average = groups.Average(g=>g.Perc);

Note that your answer for Avg should be 0.717 not 7.17.

A: Try this :
var avg = list.GroupBy(G => G.Id)
              .Select(G => (G.Sum(T => T.Good)/G.Sum(T => T.TotalSum)))
              .Average();


Q: Getting DIV ID on AJAX loaded content I have div with unique id and I'm trying to get that div id with jQuery

Quantity

Everything works good, but after loading div with ajax - I just can't get id from loaded div.
$('.quantity').click(function() {
    $.post('quantity.php', { id: $(this).attr('id') }, function(output) {
        $(this).html(output);
    });
});

Any ideas?

A: This should work
$('.quantity').click(function() {
    var that = this;

    $.post('quantity.php', { quantityId: $(that).attr('id') }, function(data) {
        $(that).html(data);
    });
});

But this is how i'd write it
<div class="quantity" data-id='<?=$unique_id?>'>
    Quantity

$('.quantity').on('click', function() {
    var that = this;

    $.post('quantity.php', { quantityId: $(that).data('id') }, function(data) {
        $(that).html(data);
    });
});

And for dynamic divs
<div class="quantity" data-id='<?=$unique_id?>'>
    Quantity

$(document).on('click', '.quantity', function() {
    var that = this;

    $.post('quantity.php', { quantityId: $(that).data('id') }, function(data) {
        $(that).html(data);
    });
});

A: The onclick binding to your div won't work once the div has been refreshed (it binded on document.ready() right?). The solution will be either to rebind the function to your element every time you change it (a bad one) or use the on() function of jquery. Example code:
$(document).on('click', '.quantity', function(){
    var id = $(this).attr('id');

    $.post('quantity.php', { quantityId: id }, function(data){
        $('#'+ id).html(data);
    });
});

UPDATE: As discussed in comments, the on method should bind to the document as a whole and not the the class to actually work as the deprecated live() method.


Q: Align text below input I have a text-input with a list below.
I now want the list to start exactly under the input on the left side.
Here is a jsFiddle.
CSS / HTML / Demo

body {
  text-align: center;
}
#underbox li {
  display: inline-block;
  text-decoration: underline;
}
<input type="text" style="width: 200px;" />

Test

Next

A: Change your styles to:
body{
    text-align: center;
}
input {
    width: 200px;
}
ul {
    text-align: left;
    margin: 0 auto;
    padding: 0;
    width: 200px;
}
#underbox li{
    display: inline-block;
    text-decoration: underline;
}

input and ul => same width /
ul => text-align: center; margin: 0 auto (for set position to center); padding: 0 (disable default style);
jsfiddle

A: something like this:
#underbox {

    width: 200px;
    margin: 0 auto;
    padding: 0;
    list-style-type: none;

}
#underbox li {
    margin-right: 5px;
    text-decoration: underline;
    text-align: left;
    float: left;

}

A: Try to add style to the ul element like that: http://jsfiddle.net/csdtesting/j6f8L7Lp/

body {
  text-align: center;
}
#underbox li {
  display: inline-block;
  text-decoration: underline;
}
ul#underbox {
  padding: 0;
  list-style-type: none;
  margin: 0;
}
<input type="text" style="width: 200px;" />

Test

Next


Q: Create -help- module for web application What is the best solution for create and merge help for my web application ,
I want create HTML help for entire solution and help for each page,
Is there any module for this purpose?

A: You can use SandCastle. It is now maintained as part of SandCastle Help File Builder or SHFB.

http://shfb.codeplex.com/

SandCastle depends on Microsoft Help Workshop, which you have to download separately.
If you want to just create your own help system and not product API documentation, then just use the HTML Help Workshop on its own. It very simple, to use. Just create HTML pages for each help section and compile. Read the documentation.
HTML Help is also available as part of the Visual Studio SDK.

Reference:
  http://msdn.microsoft.com/en-us/library/windows/desktop/ms670169(v=vs.85).aspx
Download:
  http://www.microsoft.com/en-us/download/details.aspx?id=21138

Important:
As of March 2012 there is no HTML Help Workshop 1.4. VS 2010 doesn't use MS Help2 format so there is no Help2 compiler available for it. Starting with VS 2010, the new MS Help Viewer format is used.

Reference:
  http://msdn.microsoft.com/en-us/library/vstudio/hh492077.aspx
MS Help Viewer SDK for Visual Studio:
  http://msdn.microsoft.com/en-us/library/dd627473.aspx

Hope that helps.
I would suggest you to use SandCastle (SHFB), because you get best of all worlds. You can create compiled HLP2 files, Help Viewer Content and also a simple online HTML help.


Q: Any C++ library for Johansen co-integration test? Any Ideas ? Will be highly appreciated.

A: Assuming you mean this test, I think I found a library that will help you.  Check out the Gnu Regression, Econometrics and Time-series Library.


Q: Swift dismissing view with clunky animation I simply have a ViewController that I would like to dismiss. And this is my dismissAction:
@objc private func dismissView(){

    self.dismiss(animated: true, completion: nil)

    UserDefaultsService.shared.updateDataSourceArrayWithWishlist(wishlist: self.wishList)
    let dataSourceArray = UserDefaultsService.shared.getDataSourceArray()
    //  update datasource array in MainVC
    self.dismissWishlistDelegate?.dismissWishlistVC(dataArray: dataSourceArray, dropDownArray: self.dropOptions, shouldDeleteWithAnimation: false, wishlistToDelete: self.wishList)

}

Proble:
The dismiss  animation is very clunky and not fluent at all. I found out that if I remove everything in the function but only call self.dismiss it is working perfectly fine. What is the issue here? Any idea on how I can fix this?

A: You can try to light-weight load in main thread by
DispatchQueue.global().async {
   UserDefaultsService.shared.updateDataSourceArrayWithWishlist(wishlist: self.wishList)
}

And instead of let dataSourceArray = UserDefaultsService.shared.getDataSourceArray() use self.wishList directly in the last line


Q: Update recyclerview on Edittext text change I have a Edittext and a recyclerview below it in fragment. The recyclerview row item has a textview. I have set the adapter and everything is working fine. I would like to change each item of the recyclerview with text in edittext and somehow it's not working. I tried with  itemArrayAdapter.notifyDataSetChanged() on getListForRv() method.
@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_fonts, container, false);

    itemList = new ArrayList<FontItem>();

    EditText editText = view.findViewById(R.id.edit_text);
    itemArrayAdapter = new ItemArrayAdapter(R.layout.recyclerview_item, itemList);

    recyclerView = (RecyclerView) view.findViewById(R.id.font_list);

    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    recyclerView.setItemAnimator(new DefaultItemAnimator());
    recyclerView.setAdapter(itemArrayAdapter);
    getListForRv(10);

    editText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            getListForRv(90);
        }

        @Override
        public void afterTextChanged(Editable s) {
            getListForRv(90);

        }
    });

    return view;
}

private void getListForRv(int k) {
    for (int i = k; i < 1000; i++) {
        itemList.add(new FontItem("Item " + i));
    }
    itemArrayAdapter.notifyDataSetChanged();
}

A: call your getListForRv() on edit text afterTextChanged methode.

A: notifyDataSetChanged will refresh all itemview, if you want to synchronize all edittext
I have two  solution:

*

*databinding : you can use ObservableField

*Create a listener and make sure all item keep the listener,when editext was changed, call the listener then all itemview will accept the change

A: Finally I managed to solve this by doing the following, don't know if it's a bad practice but works for me:
  @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_fonts, container, false);

        itemList = new ArrayList<FontItem>();

        EditText editText = getActivity().findViewById(R.id.edit_text);
        itemArrayAdapter = new ItemArrayAdapter(R.layout.recyclerview_item, itemList);

        recyclerView = (RecyclerView) view.findViewById(R.id.font_list);

        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.setAdapter(itemArrayAdapter);
        getListForRv(10);

        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
                recyclerView.setItemAnimator(new DefaultItemAnimator());
                recyclerView.setAdapter(itemArrayAdapter);
                getListForRv(90);
                itemArrayAdapter.notifyDataSetChanged();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        return view;
    }

    private void getListForRv(int k) {
        if (!itemList.isEmpty())
            itemList.clear();
        for (int i = k; i < 1000; i++) {
            itemList.add(new FontItem("Item " + i));
        }
    }


Q: Why my pycharm can not debug forever? My computer version is Win7.
And what ever .py I debug, this pycharm will show me en error like this:

ValueError: bad marshal data (string ref out of range)
So what's wrong with pycharm, I tried to user newest version of pycharm but I helpless, the same error will show again.
I used to reinstall my win7 (becauser I have Shadow Mode software) and it work for a period.
Is there body have a good solution?

A: I don't think the problem is directly related to the pydev debugger in this case... my bet is that for some reason you're having corrupted .pyc files (don't know why thought).
Try cleaning your .pyc files from your pycharm installation and your own files and run it again (you may try running with pydev which has the same debugger backend if you want to see if you reproduce the issue there).


Q: In React, what is a better place to store big data arrays? I'm building an interactive plot in React where the user can select multiple variables and add them to a single plot. Each of these "variables" represent scientific data and are stored as arrays with 100k to 3 million elements.
I don't feel very inclined to store these variables in the React state as their contents never change and I'd prefer to control when the UI needs to re-render manually instead of letting React automagically traverse these arrays trying to find out if they have changed, which renders my application unresponsive.
Is there any preferred way of storing this data and sharing it with React? Right now I just store everything in a global variable.

A: There aren't many places you can store it though. If the data never changes, there's no downside in storing it in state, no changes means no re-renders. It sounds like there's quite a bit of it, so you can't store it in local storage due to limits. If you build a data set inside React by doing a bunch of API calls, revisit the API itself - it should return the data you care for, rarely a bunch of data segments you have to splice together yourself.


Q: Proxy in development mode of React won't redirect I'm building an app with create-react-app.
I have local Apache server running on port 80 to execute my backend API PHP scripts.
I have added
"proxy": "http://localhost:80" to my package.json,
but on this axios requests:
 getAllCategories = () => {
      const url = process.env.PUBLIC_URL+`/api/api/categories/categories.php`;
      axios.get(url)
        .then(res => {
        const categories = res.data.data;
        this.setState({ categories });
      }).catch(err => {
        console.log('Axios fetch error:',err);
      })
    }

My request are directed to
Request URL: http://localhost:3000/api/api/categories/categories.php

according to Chrome Devtools and I'm not getting the data required.
In the build mode on remote server everything works fine with those paths indicated.
How can I configure proxy in dev mode to access my API files?

A: Have you tired path like this?
axios.get(`/api/api/categories/categories.php`)
...

A: If you are using create-react-app install http-proxy-middleware  as a dev dependency and in your src folder create a file called setupProxy.js (it must be spelt exactly like that).
In that file:
const proxy = require('http-proxy-middleware');

module.exports = function(app) {
  app.use(proxy('/api', { target: 'http://localhost:80' }));
};

You will need to restart the app for it to take effect.
Your api calls should not need the process.env


Q: Update table field by summing field from another table I am trying to update a table filed taking value from another table by summing a field based on EmpID.
In tblEmpInfo EmpID is primary key. I have saw few post on this site but couldn't adopt to my file. Here is my code till yet.
UPDATE tblEmpInfo AS c
INNER JOIN (SELECT EmpID, SUM(ProfidentFund) AS total FROM tblTransactions GROUP BY EmpID)  AS x ON c.EmpID = x.EmpID
SET c.ProfidentFund = x.total;

Above code give me following warning and do not update value to tblEmpInfo

tblEmpInfo screenshot.

tblTransactions screenshot.

And my expected output.

A: You can try the below -
UPDATE  c
SET c.ProfidentFund = x.total
from tblEmpInfo AS c
INNER JOIN
(SELECT EmpID, SUM(ProfidentFund) AS total FROM tblTransactions GROUP BY EmpID)  AS x
    ON c.EmpID = x.EmpID


Q: Self Join using a Group By clause getting "Invalid Identifier" error I'm trying to put together a Self Join using a Group By clause to see which person is getting paid the highest in their respective jobs but I keep getting this error
00904. 00000 -  "%s: invalid identifier"
Below is my code that I am currently trying to fix:
Select a.*,b.sal
From EMP a,(Select job,MAX(sal)
            From EMP
            Group By job) b
Where a.empno = b.empno

I did some research and I couldn't find anything that pertained to what I am doing (maybe becayse what I am doing is too simple?) but nonetheless I am looking for anything that will point me in the right direction.  Thanks in advance.

A: You don't have a column called empno that you are returning in the subquery. I think you want something like this which will return the max(sal) for each employee based on the job:
Select a.*, b.sal
From EMP a
inner join
(
  Select job, MAX(sal) sal
  From emp
  Group By job
) c
   on a.job = b.job

A: Try this instead:
Select a.*
From EMP a
INNER JOIN
(
   Select job, MAX(sal) MaxSal
   From EMP
   Group By job
) b ON a.job = b.job AND a.sal = b.MaxSal


Q: findViewById retrurns wrong element? I can't understand why findViewById returns the wrong element, here is the class:
public class EventDetailsFragment extends FragmentActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.event_details);
        Log.d("First", findViewById(R.id.tuxtView1).getClass().toString());
        Log.d("Second", findViewById(R.id.tuxtView2).getClass().toString());
        Log.d("Third", findViewById(R.id.imageView1).getClass().toString());
    }
}

And here is the xml:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/green"
android:orientation="horizontal"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="10dp">

    <RelativeLayout
    android:id="@+id/relativeLayout1"
    android:layout_width="0dp"
    android:layout_height="175dp"
    android:layout_gravity="center_horizontal"
    android:layout_weight="1"
    android:background="#fff"
    android:gravity="right" >

        <ImageView
        android:id="@+id/imageView1"
        android:layout_width="110dp"
        android:layout_height="match_parent"
        android:layout_weight="1"
        android:src="@drawable/ic_event_image" />

        <TextView
        android:id="@+id/tuxtView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="10dp" />
        <TextView
        android:id="@+id/tuxtView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/tuxtView2"
        android:layout_toRightOf="@+id/imageView1"
        android:textColor="#555"
        android:textSize="20dp" />

    </RelativeLayout>

</LinearLayout>

The logcat ouput is:
12-26 23:43:20.249: D/First(6789): class android.widget.TextView
12-26 23:43:20.249: D/Second(6789): class android.widget.ImageView
12-26 23:43:20.249: D/Third(6789): class android.widget.TextView

So the point is, why do I get a imageview with id R.id.tuxtView2 and a textview with id R.id.imageView1. The application crashes if I want to assign a text value to R.id.tuxtView2, casted as a TextView.

A: Try to reload your project, maybe something wrong with R.java, or verify you are calling the good file with setContentView.
By refreshing/cleaning your project the R.java file will be reloaded and will find the named widgets.

A: I copied your code and made a dummy app. I got these results:
12-27 00:03:48.332: D/First(9165): class android.widget.TextView
12-27 00:03:48.332: D/Second(9165): class android.widget.TextView
12-27 00:03:48.332: D/Third(9165): class android.widget.ImageView

Apparently there is nothing wrong with the code

A: I've tried almost everything here, but nothing worked until I added a new component to the activity and, after running, noticing that the new component didn't show. It suggested my app wasn't updating with the runs. It worked by manually uninstalling the old version of the app an then running again.


Q: strange Java compilation error with typed interface I have come across a very strange compilation error.  At first I thought it was a bug in IntelliJ, but now I've tried with Eclipse and see the same thing.
I have the following interface:
public interface PluginDriver<T extends Plugin> {
   PluginBuilder<T> getBuilder();
   Set<PluginParam> getParams();
   Set<String> getStrings();
}

where Plugin is an abstract class:
public abstract class Plugin

and we also have a POJO as follows:
public class PluginParam { ... }

Now I have a DriverManager to return an instance of a PluginDriver, and here I will try to use that:
PluginDriver driver = DriverManager.getDriver(transformer.getPlugin());
PluginBuilder builder = driver.getBuilder();
for (PluginParam o : driver.getParams()) {
    //type mismatch - cannot convert from element type Object to PluginParam
}
for (String s : driver.getStrings()) {
    //type mismatch: cannot convert from element type Object to String
}

The for loop commands don't compile, for reasons that I don't understand.  The interface specifies concrete return types for those methods, not type T.
Now, if I change the following line:
PluginDriver<Plugin> driver = DriverManager.getDriver(transformer.getPlugin());

everything suddenly plays nicely.
Similarly, if I remove the type arguments from the interface, it will work.
I could understand that the getBuilder() method might not work if we hadn't correctly typed the PluginDriver.
But how could it possibly complain about the getStrings() method?
==EDIT
This is not a duplicate of Combining Raw Types and Generic Methods, since that question refers to a method with typed parameters.  The method I'm asking about is untyped.

A: The JLS says,
"The type of a constructor (§8.8), instance method (§8.4, §9.4), or non-static field (§8.3) of a raw type C that is not inherited from its superclasses or superinterfaces is the raw type that corresponds to the erasure of its type in the generic declaration corresponding to C."
http://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.8
When you declared a variable of the raw interface type, you forced the member methods to have raw types also. That's what screwed up the class cast.
The documentation rules.

A: Here:
PluginDriver driver = DriverManager.getDriver(transformer.getPlugin());

You are creating a raw type. Bad idea.
Can lead to all sorts of problems - see here.
Thus the answer is simple: never do that! When you are using generic types, then make sure that you have a "generic" on (one/both) sides of your declaration/definition!


Q: How to change the colors of xdebug output? The red and yellow standard colors of xdebug can hurt your eyes after a few hours.
http://www.designified.com/blog/article/76/restyling-xdebug-output describes how to replace the style with javascript requiring jquery.
I was looking for a more straight forward way and finally found one.

A: The solution is the !important tag, it overrides the existing style values. Use the following css code to avoid eye cancer when using xdebug:
.xdebug-error {
    font-size: 12px !important;
    width: 95% !important;
    margin: 0 auto 10px auto !important;
    border-color: #666 !important;
    background: #ddd !important;
}

.xdebug-error th, .xdebug-error td {
    padding: 2px !important;
}

.xdebug-error th {
    background: #ccc !important;
}

.xdebug-error span {
    display: none !important;
}

.xdebug-error_description th {
    font-size: 1.2em !important;
    padding: 20px 4px 20px 100px !important;
    background: #ccc no-repeat left top !important;
}

.xdebug-error_callStack th {
    background: #666 !important;
    color: #ddd !important;
}

A: Have a nice xdebug!
Yes you can. Try this css below.
table.xdebug-error {
  width: auto;
  background: white;
  border: none;
  border-spacing: none;
  border-collapse: collapse;
  box-shadow: 0px 3px 10px 0px black;
  position: fixed;
  top: 0px;
  right: 0px;
  z-index: 8888;
  font: 14px verdana;
  transform-origin: top right;
  transform: scaleX(0.4);
  opacity: 0.3;
  transition: all 200ms ease;
}
table.xdebug-error caption,
table.xdebug-error th,
table.xdebug-error td {
  text-align: left;
  vertical-align: middle;
}
table.xdebug-error a img {
  border: 0;
}
table.xdebug-error :focus {
  outline: 0;
}
table.xdebug-error pre {
  margin: 0;
}
table.xdebug-error tbody tr td,
table.xdebug-error tbody tr th {
  border: none;
  border-bottom: 1px solid rgba(0,0,0,0.2);
  font-weight: normal;
}
table.xdebug-error tbody tr td {
  padding: 3px !important;
  vertical-align: top;
}
table.xdebug-error tbody tr th {
  padding: 13px !important;
}
table.xdebug-error tbody tr td:nth-of-type(1) {
  width: 5% !important;
}
table.xdebug-error tbody tr th[bgcolor='#f57900'] {
  font-weight: normal;
  background: steelblue;
  color: white;
}
table.xdebug-error tbody tr th[bgcolor='#f57900'] span {
  display: none;
}
table.xdebug-error tbody tr font[color='#00bb00'] {
  color: #005e00;
}
table.xdebug-error tbody tr td small {
  display: none;
}
table.xdebug-error tbody tr td i {
  padding-left: 12px;
}
table.xdebug-error:hover {
  transform: none;
  opacity: 1;
}

CONS:

*

*Depending on your other css defs, you may have to fiddle a bit until it looks as promised.

*It's not as beautiful as a Laravel/Symfony error

PROS:

*

*You can see the actual page, despite the error. (Message will be dimmed and pushed on the right side, appearing on mouse hover.)

*It's nothing more than CSS

*You can even add it to your page via CSS Live Editor Plugin or something similar; therefore, no need to add to your own code

*It won't break your styling, won't stuff a whole lot of text into a tiny container where the error happened, etc. - because it's position:fixed.

*Pleasant to the eye - you'll end up throwing errors just to see it again :)

A: Another option is to disable xdebug from overloading var_dump.
In the php.ini [XDebug] section add xdebug.overload_var_dump=0
Formatting the output is then up to you; one such way could be wrapping var_dump in your own debug function that prints <pre> tags.

A:
// notice the line height, the padding(cellspacing), monospace font, font size, making readability better at least for me.
//
// A FILENAME : xdebug_stack_trace.css
//
// This is how the xdebug_stack_trace.css is called from the index.php page
//
// <style><?php require_once("./resources/css/xdebug_stack_trace.css");?></ style>
//
// notice that on the line above there is a space between the slash
// and the 'style', on the ending 'style' tag, otherwise the display
// get all messed up when this page gets loaded.
//
// make sure that when you copy the 'style' line from here to the
// index page, that you remove the extra space at the ending 'style'
// tag of the index page.
// +---------+---------+---------+---------+---------+---------+---------+
// orange/black td header line
// +---------+---------+---------+---------+---------+---------+---------+
.xdebug-error th
{
    font-family:monospace;
    font-weight:normal;
    font-size:15px;
    padding: 6px 6px 6px 6px;
    border:1px solid black;
    background: #FFCC99;    // orange
    color:#000000;          // black
}
// +---------+---------+---------+---------+---------+---------+---------+
// black/white th header line
// +---------+---------+---------+---------+---------+---------+---------+
.xdebug-error > tr:first-child > th:first-child,
.xdebug-error > tbody > tr:first-child > th:first-child
{
    line-height:1.6em;
    padding: 10px 10px 10px 10px;
    border:1px solid #000000;
    background: #000000;          // black
    color:#FFFFFF;
}
// +---------+---------+---------+---------+---------+---------+---------+
// green/black td content one or more lines
// +---------+---------+---------+---------+---------+---------+---------+
.xdebug-error td
{
    font-size:14px;
    padding: 6px 6px 6px 6px;
    border:1px solid green;
    background: #D1FFE8;          // light green
}
// +---------+---------+---------+---------+---------+---------+---------+


Q: Why Azure takes so long to setup a Load Balancer? I have set up an application gateway in almost five different regions in Azure and every time Azure take around 15-20 mins to complete the setup.
Whereas AWS will do it in a couple of minutes, why Azure requires such a long time?

A: You should try using Application Gateway V2, its a lot faster to create. updates are almost instantaneous (well, at least compared to V1). But I believe V1 is using windows VM's underneath, so it creates a set of vms for you, then it configures them. Each update would be a "sliding window" update, with 1 vm being recreated at a time.
As far as I know.

A: Application Gateway is a layer 7 load balancer which, as far as I understand, is a Windows VM (or collection of Windows VMs, depending on selected size) under the covers, which take some time to come up and be configured. In my experience, this time is usually around 15-30 minutes, depending on region and local time of day, capacity, etc.
Azure Load balancers on the other hand are layer 4 load balancers, which typically take in the order of 1-2 minutes to come up.

A: So, yes talking about the load balancer if you say it normally takes less than a minute to get deployed. But coming onto the Application gateway yeah it takes 15-20 minutes every time the reason being:

*

*Configuration Settings: Microsoft has the set of the vacant load balancers ready at their backend and when they receive a request to deploy a particular load balancer in any region, they just assign it an IP as requested by the user and it gets deployed within a minute. But coming onto the Application gateway, azure need to start deploying the load balancer [App Gateway in this case] from the scratch, need to attach it to the VNET so deployed and making it ready for the backend pools IP Address configuration and all, which basically take time about [15-20 minutes]. Now, Azure has brought up the V2 of the Application Gateway, a lot faster to create usually 5 minutes. And also talking about updates they are also really quick and instantaneous.

*Subscriptions: Secondly, the reason that it takes time is subscription. Suppose, you have the MSDN, free subscription in your Azure account. And another individual sitting at any different place is using the enterprise applications subscription [basically a pay as you go] in his azure account. Now, both of you raise a request to deploy an Application gateway in the same region at the same time then, Microsoft will give the person request with the enterprise subscription the higher priority than your free subscription request. Which is another reason that it results in a delay. As I am using the enterprise edition so it takes 2 minutes for a VM to deploy which gets deployed in 5-6 minutes if using the free subscription!
Thanks!