text:
Q: JavaScript switch for changing background colour with css() I have a very simple function which should change the page background colour based on specific links being clicked, but I can't figure out why it's not working.
Here is a demo of what I have so far: http://jsfiddle.net/cF74Y/
It seems like it must be such a trivial mistake, but I can't see it. Any help would be greatly appreciated.

A: You are compare string with number, change switch (currentItem) to switch (+currentItem) will make your demo work.
Addition: You could pass the currentItem as a parameter instead of using global variable.
Here is the working demo.

A: I think you're complicating things too much, can't you just do this?
html:

red

green

blue

yellow

jQuery:
$('a.color').click(function(){
    $('body').css('background-color', $(this).text());
});

Demo: http://jsfiddle.net/elclanrs/8yev9/
Edit: And if you need to assign a color by index use an array, I don't think you need that ugly switch statement, seems pretty useless to me, all that code can be reduced to just this:
var colors = ['red', 'blue', 'green', 'yellow'];
$('a.color').click(function(){
    $('body').css('background-color', colors[$(this).parent().index()]);
});

Demo: http://jsfiddle.net/elclanrs/8yev9/1

A: try this:
var index = parseInt($(this).attr('id'),10);

then it will work.
Reason: the return type of .attr() function is a string and it  make true case 1 always. just use parseInt function.

A: Maybe you have to give the parameter 'currentItem' with the function call.
changeBg(currentItem); // call

And your function will look like this:
function changeBg(currentItem) {
    var bg = 'null';
    switch (currentItem) {
        case 1 :
            bg = '#6A6A6A';
[..]

A: here is a working copy
http://jsfiddle.net/cF74Y/34/

A: use parseInt to compare with case.With this its unable to compare.See fiddle.
http://jsfiddle.net/cF74Y/43/


text:
Q: Faster than Grep on Python? So, the bash command that I'd be normally using in a Bash Script would be something like:
$ cat huge2GBfile.txt | grep -w "pattern1/|pattern2/|pattern3" > out.txt

It will output the lines in huge2GBfile where it has found pattern1,2,3. I was wondering if this is achievable through python. I know that I can use
os.system(cmd)

But I'd like to know if there is something similar in Python (I am a complete noob) and if it is faster than using cat+grep.
Thanks!
Initial thoughts, would something like
for line in f:
     if pattern in line:
          out.write(line)

be faster?

A: Even with an algorithm that is better than the logic grep uses (as someone already commented they are highly optimised, grep is 30 years old!), there is still the fact that they are utilities written in C, and compiled natively for the system.
Python is an interpreted language, and can be a couple of orders of magnitude slower than native C, so I would argue that the answer is no, there is nothing in python that could be faster.
If you want to process the output of a grep command line by line, an option would be to build your python script similar to a unix command line tool, so that it can read from stdin and write to stdout, so you could use something like :
grep pattern file | python myscript.py

How do you read from stdin in Python?

redpajama_set_name: RedPajamaStackExchange


text:
Q: WebEx error: Java is not working I am trying to join a WebEx meeting. However, when I try to do that, it gives me an error:

Java is not working.

To have the best experience joining meetings, Java must be installed on your computer and enabled in your browser and the Java Control Panel. Install and enable Java, restart your browser if needed, and then join the meeting again.

This error shows up on both Firefox and Chrome on Ubuntu 14.04, and only occurs when I use WebEx.
How can I fix this error?

A: Chrome on Linux will not work with Java, as NPAPI support was dropped in Chrome 35.0. As such, you will need to use Firefox.
It seems like you do not have the Java browser plugin installed. You can install Java JDK 8 and the browser plugin from the Web Upd8 Java PPA. Open the terminal and enter these commands in, line by line:
sudo apt-add-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java8-installer

After that, you will have to add your WebEx domain to the Java plugin's Exception Site List. To do this, open "Oracle Java 8 Plugin Control Panel" and click "Edit Site List" under the Security tab:

After that, click "Add" and enter the domain that your WebEx meeting has: (I'm using the WebEx test meeting as an example here)

After you're done, click OK and OK to exit and save changes. Open Firefox and browse to your WebEx meeting link. When you're prompted to allow Java to run ("Activate Java"), click either "Allow Now" or "Allow and Remember", depending on your preference.
At this point, the Java loading screen will show, and a security warning should pop up soon. Check "I accept the risk and want to run this application", and click Run:

A progress bar will show up and the WebEx meeting center will show up soon too, if everything has been successful.


text:
Q: Generate declaration file with single module in TypeScript Given the following folder structure:
src/
├── foo.ts
├── bar.ts
├── baz.ts
├── index.ts

Where foo.ts, bar.ts, and baz.ts each export a default class or thing: i.e. in the case of foo.ts:
export default class Foo {
    x = 2;
}

Can we automatically generate a declaration file which declares one module my-module and exports foo.ts, bar.ts, and baz.ts as non-defaults?
I.e. I want tsc to generate the following:
build/
├── foo.js
├── bar.js
├── baz.js
├── index.js
├── index.d.ts

Where index.d.ts contains:
declare module 'my-module' {
    export class Foo {
        ...
    }
    export class Bar {
        ...
    }
    export class Baz {
        ...
    }
}

I see that mostly all NPM modules have a declaration file like this and maybe with separate files.
How would I accomplish this?

A: In your tsconfig.json file, set "declaration" to true. Then when you run typescript on your project it will automatically generate declaration files for you.


text:
Q: Add ajax checkbox filtering + date range in codeigniter + d3.js chart I would like to filter my MSQL data by date range + company Name.
I can perfectly get the graph with the date range.
My current problem is that I would also filter by company name.
I can not list the company by group and make filter by
Company name + date Range.
Someone could look at my codes and give me help please.Thank you!
my controller
public function get_chart_data() {

        if (isset($_POST['start']) AND isset($_POST['end'])) {
        $start_date     = $_POST['start'];
        $end_date       = $_POST['end'];
        $company_name   = $_POST['company_name'];
        $results = $this->chart_model->get_performance($start_date, $end_date, $company_name);

        if ($results === NULL) {

        echo json_encode('No record found');

        } else {

        print_r(json_encode($results));

        }

        } else {
        echo json_encode('Date must be selected.');
        }

    }

my Model
function get_performance($start_date, $end_date,$compnay_name) {
        $sql  = $this->db->select_sum('performance_profit', 'total')
              ->select_max('performance_date', 'day_date')
              ->from('performance')
              ->where('performance_company', $company_name)
              ->where('performance_date >=', $start_date)
              ->where('performance_date <=', $end_date)
              ->group_by('DATE(performance_date)')
              ->order_by('DATE(performance_date)', 'DESC');
              //->limit(1);

        $query = $this->db->get($ql);
          if ($query->num_rows() > 0) {
           $data = array();
             foreach ($query->result_array() as $key => $value) {
               $data[$key]['label']    = $value['day_date'];
               $data[$key]['value']    = $value['total'];
               //$data[$key->company_id] = $value['company_id']
          }

        return $data;

          }
        return NULL;

        }

my view
//company select
<select name="company_name" onchange="showdrop()" id="company_name">
//company list
</select>

//Sugar moment and Date Picker display
 <input type="text" name="range" id="range">

//Graph display

My AJAX/JQUERY
    $(function() {

    // Set the default dates, uses sugarjs' methods
    var startDate   = Date.create().addDays(-6),    // 6 days ago
        endDate     = Date.create();                // today

    var range = $('#range');
    var company_name = $("#company_name").val();

    // Show the dates in the range input
    range.val(startDate.format('{MM}/{dd}/{yyyy}') + '-' + endDate.format('{MM}/{dd}/{yyyy}'));

    // Load chart
    ajaxLoadChart(startDate,endDate);

    range.daterangepicker({

        startDate: startDate,
        endDate: endDate,

        ranges: {
            'Today': ['today', 'today'],
            'Yesterday': ['yesterday', 'yesterday'],
            'Last 7 Days': [Date.create().addDays(-6), 'today'],
            'Last 30 Days': [Date.create().addDays(-29), 'today']
            // You can add more entries here
        }
    },function(start, end){

        ajaxLoadChart(start, end);

    });

    // The tooltip shown over the chart
    var tt = $('
').appendTo('body'),
            topOffset = -32;

    var data = {
        "xScale": "time",
        "yScale": "linear",
        "main": [{
                className: ".stats",
                "data": []
            }]
    };

    var opts = {
        paddingLeft: 50,
        paddingTop: 20,
        paddingRight: 10,
        axisPaddingLeft: 25,
        tickHintX: 9, // How many ticks to show horizontally

        dataFormatX: function(x) {

            // This turns converts the timestamps coming from
            // ajax.php into a proper JavaScript Date object

            return Date.create(x);
        },
        tickFormatX: function(x) {

            // Provide formatting for the x-axis tick labels.
            // This uses sugar's format method of the date object.

            return x.format('{MM}/{dd}');
        },
        "mouseover": function(d, i) {
            var pos = $(this).offset();

            tt.text(d.x.format('{Month} {ord}') + ', Nbre Device: ' + d.y)
            .css({top: topOffset + pos.top,left: pos.left})
            .show();
        },
        "mouseout": function(x) {
            tt.hide();
        }
    };

    // Create a new xChart instance, passing the type
    // of chart a data set and the options object

    var chart = new xChart('line-dotted', data, '#chart', opts);

    // Function for loading data via AJAX and showing it on the chart
    function ajaxLoadChart(startDate, endDate) {

        // If no data is passed (the chart was cleared)

        if (!startDate || !endDate) {
            chart.setData({
                "xScale": "time",
                "yScale": "linear",
                "main": [{
                        className: ".stats",
                        data: []
                    }]
            });

            return;
        }

        // Otherwise, issue an AJAX request

        $.post('http://index.php/get_chart_data', {
            start: startDate.format('{yyyy}-{MM}-{dd}'),
            end: endDate.format('{yyyy}-{MM}-{dd}'),
            company_name:company_name
        }, function(data) {
            if ((data.indexOf("No record found") > -1) || (data.indexOf("Date must be selected.") > -1)) {
                $('#msg').html('' + data + '');
                $('#placeholder').hide();
                chart.setData({
                    "xScale": "time",
                    "yScale": "linear",
                    "main": [{
                            className: ".stats",
                            data: []
                        }]
                });
            } else {
                $('#msg').empty();
                $('#placeholder').show();
                var set = [];
                $.each(data, function() {
                    set.push({
                        x: this.label,
                        y: parseInt(this.value, 10)
                    });
                });
                chart.setData({
                    "xScale": "time",
                    "yScale": "linear",
                    "main": [{
                            className: ".stats",
                            data: set
                        }]
                });
            }
        }, 'json');
    }
});

A: There is a typo at "function get_performance($start_date, $end_date,$compnay_name)"


text:
Q: Stem para Twitter Caros colegas,
Estou tentando fazer uma análise de twitters de uma timeline e precisava stemiatizar os textos para análise. Estou tentando o seguinte procedimento:
setup_twitter_oauth(consumer_key, consumer_secret, access_token, access_secret)
tweets <- userTimeline("Pragmatismo_", n = 3000)
tweets.df <- twListToDF(tweets)
myCorpus <- Corpus(VectorSource(tweets.df$text))
removeURL <- function(x) gsub("http[[:alnum:][:punct:]]*", "", x)
removeNumPunct <- function(x) gsub('[[:punct:]]', '', x)
myCorpus <- tm_map(myCorpus, content_transformer(removeNumPunct))
myCorpus <- tm_map(myCorpus, content_transformer(removeURL))
myCorpus <- tm_map(myCorpus, ptstem)

A questão é que mesmo após o último comando myCorpus <- tm_map(myCorpus, ptstem) o texto não aparece stemizado.
Alguma dica?
Muito obrigado!

A: A principal função de stemming empregada na tm_map é a stemDocument, mas como é apresentado na resposta dessa pergunta, não é possível utilizar a mesma para o português devido a um bug.
O que eu fiz para contornar a situaçao foi utilizar o pacote quanteda:
library(quanteda)
my_dfm <- dfm_wordstem(myCorpus, language = "pt")

Outra opção, seria adaptar se possível o uso da função ptstem::ptstem_words no seu contexto (não testei).


text:
Q: Why did Heather Bram not get cured? In Hair of the Dog they say that the death of the nineth werewolf from the same bloodline makes the damnation disappear. We see the FBI agent get cured when her boyfriend dies.
Why does Heather not get cured as well?

A:
Kill nine, remove the sign.

The cure for lycanthropy in the Dresden Files TV series doesn't cure the entire bloodline, only the reluctant werewolf doing the deed.
Special Agent Kelly Raskin wanted to be rid of the lycanthropy curse, and so she was creating new werewolves in her own bloodline and then killing them. Completing the ritual wouldn't cure other werewolves in the bloodline, just Raskin.

Of note: the Dresden Files novel that most closely corresponds to this episode (Fool Moon) explores four different varieties of lupine theriomorphs. These are not explored in the TV episode:

*

*Werewolf: A person who transforms him- or herself into a wolf through magic. This is generally the only magic that individual knows. Alternatively, a magic-user may transform another person into a wolf, and this is very close to murder, and violates one of the Laws of Magic. There is no means to "cure" this variant, because it's either willful use of magic on oneself (which can also be reversed at-will), or else imposed transmogrification, leaving the subject effectively dead. (The "Alphas" are werewolves, and become Harry's allies in later novels.)

*Hexenwolf: A person uses a magical artifact or talisman to transform into a wolf. "Curing" this variant of werewolf is simply a matter of removing the talisman, although an individual may develop a dependence on it. (The two FBI agents in the book are both hexenwolves.)

*Lycanthrope: Not actually a theriomorph (shape-changer), lycanthropes are humans that act as a channel to a spirit of rage. They appear human, but often act like animals. There is no "cure," as it's simply the way the people are. Harry encounters a street gang of lycanthropes in the novel.

*Loup-Garou: loup-garous are cursed, and the curse follows the bloodline (and prevents the bloodline from dying out). A loup-garou is the only werewolf variant in the novel which transforms on the full moon and is particularly vulnerable to silver (in fact, it's their only real vulnerability, and that silver must be inherieted, to boot). While transformed, a loup-garou will attack and kill anything and anyone within sight. The loup-garou curse requires serious magical mojo along the lines of the faerie queens (Mab/Titania), and breaking it would be beyond Harry's power (that said, while resilient, a loup-garou isn't invulnerable). The character Harley MacFinn is a loup-garou, whose family line was cursed by Saint Patrick.

At the end of the novel, Harry speculates on the existence of a fifth type of lupine shapechanger: Jim Butcher leaves it up to the reader, but hints at the possibility that the character Tera West is a wolf that transforms into a human, rather than a human that transforms into a wolf. Tera West taught the Alphas the magic required to become werewolves. This "wolfwere" is canonized in the Dresden Files RPG.


text:
Q: Fatal error: Uncaught Error: Call to undefined method MongoDB\Driver\Manager Here are some necessary version related details of the packages I have installed on a dream-compute (godaddy) server machine with Ubuntu 16.04 with root access
Apache Server version: Apache/2.4.18 (Ubuntu)
php version 7
mongo db version v3.2.10    and
$ pecl search mongo

.Matched packages, channel pecl.php.net:
=======================================
Package Stable/(Latest) Local
mongo   1.6.14 (stable)       MongoDB database driver
mongodb 1.1.9 (stable)  1.1.9 MongoDB driver for PHP

I have set up a website that was previously running on a different server with PHP 5.6 and an old mongo-php driver.
Previously I was using MongoClient class in the connection string but after some searching I changed it to MongoDB\Driver\Manager in my connection class of the php website.
I have also included extension=mongodb.so in the /etc/php/7.0/apache2/php.ini file
The rest of the website is working fine, only when i browse to a page which has a mongodb call at the back-end gives me the following error (from php error log file):
PHP Warning:  Module 'mongodb' already loaded in Unknown on line 0
PHP Fatal error:  Uncaught Error: Call to undefined method MongoDB\Driver\Manager::selectDB() in /var/www/html/iot/includes/class.abstract-data-collection.php:118

I am not an expert in linux and hence I am stuck here. Anyone have any idea what should I try to actually get to the problem, should I need to change the php code or is there anything I am missing in the configuration?
TA


text:
Q: How can i get selected value in multiple dropdown in admin form Code:
$fieldset->addField('race', 'multiselect', array(
        'label'     => Mage::helper('tuition')->__('Race'),
        'values'   => Example_Tuition_Block_Adminhtml_Student_Grid::getValueArray4(),
        'name' => 'race',
        "class" => "required-entry",
        "required" => true,
    ));

in grid.php
static public function getOptionArray4()
{
    $data_array=array();
    $data_array[0]='Indian';
    $data_array[1]='Chinese';
    $data_array[2]='Malay';
    $data_array[3]='Eurasian';
    $data_array[4]='Others';
    return($data_array);
}
static public function getValueArray4()
{
    $data_array=array();
    foreach(Example_Tuition_Block_Adminhtml_Tutor_Grid::getOptionArray4() as $k=>$v){
       $data_array[]=array('value'=>$k,'label'=>$v);
    }
    return($data_array);

}

and save data like this
$post_data['race'] = implode(',',$post_data['race']); // 0,1,2,3

Now i want to get selected value in admin form how can i do this

Here i want to get selected that value which is saved in database but i m getting only one selected value

A: in form.php
Here you can set value
if (Mage::getSingleton("adminhtml/session")->getStudentData())
    {

        $data = Mage::getSingleton('adminhtml/session')->getStudentData();
        $data['race'] = isset($data['race']) ? explode(',', $data['race']) : array(); // using this you can get value of multiple dropdown selected

        $form->setValues($data);
        Mage::getSingleton("adminhtml/session")->setStudentData(null);

    }
    elseif(Mage::registry("student_data")) {

        $data = Mage::registry('student_data')->getData();
        $data['race'] = isset($data['race']) ? explode(',', $data['race']) : array();  // using this you can get value of multiple dropdown selected

        $form->setValues($data);
    }


text:
Q: about config preferences and js I wonder if it is possible to get values of certain preferences set in about:config using javascript?
Incentive is to get value of preferences set in firefox addon i've created when user lands on addon front end. Basically, I'm trying to identify users landing on FE without asking them to login explicitly.

A: Yes, you can.
First, you need to know that Mozilla uses the XPCOM interfaces for the preferences system.
Three used interfaces are nsIPrefService, nsIPrefBranch and nsIPrefBranch2.
The preferences service is instantiated in the same way you instantiate any XPCOM service.
Two examples to make it clear:
// Get the root branch
var prefs = Components.classes["@mozilla.org/preferences-service;1"]
                    .getService(Components.interfaces.nsIPrefBranch);

.
// Get the "extensions.myext." branch
var prefs = Components.classes["@mozilla.org/preferences-service;1"]
                    .getService(Components.interfaces.nsIPrefService);
prefs = prefs.getBranch("extensions.myext.");

And there are 3 types of preferences, they're string, integer and boolean. There are six methods in nsIPrefBranch that read and write preferences: getBoolPref(), setBoolPref(), getCharPref(), setCharPref(), getIntPref() and setIntPref().
More examples on that:
// Get the "accessibility." branch
var prefs = Components.classes["@mozilla.org/preferences-service;1"]
                    .getService(Components.interfaces.nsIPrefService).getBranch("accessibility.");

// prefs is an nsIPrefBranch.
// Look in the above section for examples of getting one.
var value = prefs.getBoolPref("typeaheadfind"); // get a pref (accessibility.typeaheadfind)
prefs.setBoolPref("typeaheadfind", !value); // set a pref (accessibility.typeaheadfind)

You can also use complex types. By using nsISupportsString, that is used to handle strings in preferences, so, use this when the preference value may contain non-ASCII characters.
Example:
// prefs is an nsIPrefBranch

// Example 1: getting Unicode value
var value = prefs.getComplexValue("preference.with.non.ascii.value",
      Components.interfaces.nsISupportsString).data;

// Example 2: setting Unicode value
var str = Components.classes["@mozilla.org/supports-string;1"]
      .createInstance(Components.interfaces.nsISupportsString);
str.data = "some non-ascii text";
prefs.setComplexValue("preference.with.non.ascii.value",
      Components.interfaces.nsISupportsString, str);

I hope you solve your doubt with this.
More on this page.


text:
Q: How to show tableView to top when scrolled In my project,
In the view 'Top' side is for one UIView and below it a tableView. I want to show tableView to top when scrolled and hide the tableView.
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
    self.topView.isHidden = true  }

Please give me solution for how to show tableView to top when tableView scrolled.
Below is the screenshot
[![enter image description here][1]][1]
in this view bottom is tableView and top is UIView.
Below is the storyboard screenshot.

A: The simplest solution is to set that topView as tableHeaderView.
self.tableView.tableHeaderView = topView

Now when you scroll the tableView topView will goes up with it. Also no need to implement scrollViewDidScroll now.

A: Select your tableview in your Controller of Storyboard

*

*Select your TableView

*Go to Attributes Inspector on the right panel of Utilities

*Set Style to Grouped


text:
Q: log4j on jboss - subpackage level I have JBoss 6.1 and using jboss-logging.xml
I would like to set different log level for one package, and one his subpackage, example:
- com.foo.bar (in DEBUG)
- com.foo.bar.subpack.subsubpack (in INFO)
I have tried with this:
<logger category="com.foo.bar">
 <level name="DEBUG"/>
</logger>
<logger category="com.foo.bar.subpack">
 <level name="INFO"/>
</logger>

But in the log I continue to see all the debug message from the class in the subpack

A: I guess the messages are readen twice by the loggers. Disable additivity :
<logger category="com.foo.bar" additivity="false">
 <level name="DEBUG"/>
</logger>
<logger category="com.foo.bar.subpack">
 <level name="INFO"/>
</logger>

Edit :
Otherwise, check the name by whitch your are instanciating your logger.
According to https://logging.apache.org/log4j/1.2/manual.html#Logger_hierarchy, if you write Logger.getLogger("PIPPO"), and if the logger with name "PIPPO" does not exist in your configuration(s) file(s), the RootLogger will be instanciated by default.

A logger is said to be an ancestor of another logger if its name followed by a dot is a prefix of the descendant logger name. A logger is said to be a parent of a child logger if there are no ancestors between itself and the descendant logger.

To apply your configuration, you have to instanciate the logger by calling it with a name like "com.foo.bar.subpack.YourClass".

A: I find the problem: using the constructor Logger.getLogger("PIPPO"), in the xml the category is "PIPPO":
<logger category="PIPPO">
   <level name="INFO"/>
</logger>

This tag control the level message  of the class


text:
Q: how to add infoWindowAdapters for multiple markers having different values?  Marker drMark=mMap.addMarker(new MarkerOptions().position(drLoc).title("Lahore").icon(BitmapDescriptorFactory.fromResource(R.drawable.marker)));
 Marker selfMark=mMap.addMarker(new MarkerOptions().position(curLocation).title("Lahore").icon(BitmapDescriptorFactory.fromResource(R.drawable.passengermarker)));

I am trying to add infoWindow to multiple markers in maps Activity. But the infoWindow adapter is showing the same data on all the markers after being initialized in onMapsReady. I want to show infoWindow on all the markers with their own information i.e. marker infoWindows to be initialized individually so that data becomes relevant.

A: one way of doing it is by using tags for markers to differentiate between the markers in the infoWindowAdapter section. It is an easier way to do this job I thought.
selfMark=mMap.addMarker(new MarkerOptions().position(curLocation).title("Lahore").icon(BitmapDescriptorFactory.fromResource(R.drawable.passengermarker)));
                selfMark.setTag("user");

 drMark=mMap.addMarker(new MarkerOptions().position(drLoc).title("Lahore").icon(BitmapDescriptorFactory.fromResource(R.drawable.marker)));
                    drMark.setTag("driver");

this section for InfoWinfoAdapter:
     mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
                            @Override
                            public View getInfoWindow(Marker marker) {
                                return null;
                            }

                                @Override
                                public View getInfoContents(final Marker marker) {
                                View view = getLayoutInflater().inflate(R.layout.driver_inf, null);

                                final TextView tvEmail = view.findViewById(R.id.emailDrive);
                                final TextView tvname = view.findViewById(R.id.nameDrive);
                                final TextView tvlocality = view.findViewById(R.id.localityDrive);
                                    if(marker.getTag().equals("driver")){
                                        tvEmail.setText("Driver");
                                    }
                                    else if (marker.getTag().equals("user")){
                                        tvEmail.setText("Passenger");
                                    }

                                tvname.setText(dC.getName());
                                Geocoder gc = new Geocoder(passengerAct.this, Locale.getDefault());
                                try {
                                    List<Address> adr = gc.getFromLocation(marker.getPosition().latitude, marker.getPosition().longitude, 1);
                                    Address address = adr.get(0);
                                    tvlocality.setText(address.getLocality() + "," + address.getCountryName());
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                                return view;
                            }
                        });


text:
Q: ToolStrip LineStyles .Net Is there something similar in .NET components and if not, how to reproduce it?
alt text http://lh6.ggpht.com/_1TPOP7DzY1E/S9Ap9jAPheI/AAAAAAAADK0/rNwXMyz0I9U/s800/Capture8.png
Thanks!

A: No there is no such control, but the ToolStripControlHost Class will allow you to create your own custom ToolStrip controls.
Update: Check this class I quickly whipped up
Public Class LineStyleMenuItem
    Inherits Windows.Forms.ToolStripMenuItem

Private style As Drawing2D.DashStyle
Public Property LineStyle() As Drawing2D.DashStyle
    Get
        Return style
    End Get
    Set(ByVal value As Drawing2D.DashStyle)
        style = value
    End Set
End Property

    Public Sub New(ByVal style As Drawing2D.DashStyle)
        Me.style = style
    End Sub

    Private Sub LineStyleMenuItem_Paint(ByVal sender As Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint
        Const line_width As Integer = 6
        Const padding As Integer = 6
        Dim y As Single = CSng((Me.Height / 2) - (line_width / 2))
        Dim p As New Drawing.Pen(Color.Black, line_width)
        p.DashStyle = style
        e.Graphics.DrawLine(p, padding, y, Me.Width - padding, y)
        p.Dispose()
    End Sub

End Class

You can use it by adding items to a Toolstrip Dropdown control:
    dropdownbutton.DropDownItems.Add(New LineStyleMenuItem(Drawing2D.DashStyle.Dash))
    dropdownbutton.DropDownItems.Add(New LineStyleMenuItem(Drawing2D.DashStyle.DashDot))
    dropdownbutton.DropDownItems.Add(New LineStyleMenuItem(Drawing2D.DashStyle.DashDotDot))
    dropdownbutton.DropDownItems.Add(New LineStyleMenuItem(Drawing2D.DashStyle.Dot))
    dropdownbutton.DropDownItems.Add(New LineStyleMenuItem(Drawing2D.DashStyle.Solid))

And access the clicked item style like so:
Private Sub dropdownbutton_DropDownItemClicked(ByVal sender As Object, ByVal e As System.Windows.Forms.ToolStripItemClickedEventArgs) Handles dropdownbutton.DropDownItemClicked
    MsgBox(CType(e.ClickedItem, LineStyleMenuItem).LineStyle)
End Sub


text:
Q: Minecraft Name Changed and Can't Undo My Minecraft Gamertag (under Settings/Profile/Gamertag) changed from Steve to one of the autofill random names (tonedketchup613).  This random name was what came up when I recently signed on to Xbox and created a profile to play on the servers.  I changed the random Xbox name to my own homemade name, but somehow my Minecraft game still has the random name tonedketchup613 as the Gamertag.
I tried the button "Edit Gamertag", but that just takes me to Xbox which properly reflects my homemade name.  I logged into my Mojang account and that has a completely different homemade name/profile and is fine.
How do I edit the name showing under Settings/Profile which shows when I play Minecraft (not on the external Xbox servers), but locally?
(Note: I seem to have 3 Minecraft related names...  Minecraft Game, Mojang, and Xbox - I need help with the first.)

A: Syncing
Sign out and back in into Minecraft. This should resync the account and that will hopefully fix any name errors.

A: It's in Settings/Profile. If it has a text box, you aren't signed in properly and may need to redownload Minecraft.


text:
Q: Next.js Sub-Pages for parameterized routes Right now, my routing looks like this:
https://app.com/users         opens pages/users/index.js
https://app.com/users/:userid opens pages/users/[id].js
I want to create  route, for example:
https://app.com/users/:id/friends -> show all friends for the user
or even
https://app.com/users/:id/friends/:friendId -> show a specific friend
I have tried
pages
    users
        index.js
        [id].js
        friends
            index.js
            [friendId].js

but i can only reach users/friends and not `users/:id/friends``
How do i set my pages directory so i can use this sort of routing?
Also, I want to be able to access id and friendId in the context of getServerSideProps...

A: If you don't get the answer description well, pls follow the diagram I made.
If you want this https://app.com/users/:id/friends, then you should create something like this:
pages/users/index.js/[id]/index.js/friends.js
So to make this clear, you have a folder name pages (where all pages folder and files are), then you have a user folder (this takes an index.js which means user path). Now in the user folder, you have to create a folder named [id], in this folder you should create a file name index.js, this index.js stand for the :id. The last thing is to create the friend.js in the [id] folder.
Something like this.
pages ----------------- Main folder
    users ------------- A folder inside `pages` folder
       index.js ------- A file inside `users` folder == `https://app.com/users`
       [id] ----------- A folder inside `users` folder
          index.js ---- A file inside `[id]` folder ==`https://app.com/users/:id`
          friends.js -- A file inside `[id]` folder == `https://app.com/users/:id/friends`

If you want something like this https://app.com/users/:id/friends/:friendId
Then you will have to do something like this:
pages ------------------------- Main folder
    users --------------------- A folder inside `pages` folder
       index.js --------------- A file inside `users` folder == `https://app.com/users`
       [id] ------------------- A folder inside `users` folder
          index.js ------------ A file inside `[id]` folder ==`https://app.com/users/:id`
             [friends] -------- A folder inside `[id]` folder
                index.js ------ A file inside `[friends]` folder
                friendId.js --- A file inside `[friends]` folder

A: You can use Dynamic Routing syntax in your folders instead of a file in order to nest them (create a folder [id] instead of a file [id].js). For your specific example it would look like this:
pages
    users
       index.js
       [id]
          friends
               [friendId].js


text:
Q: string array to find and offset values I'm trying to delcaire mulitiple variable to be found within a cloumn and then offset a value to the next column. the below code only works with the first variable "a*" but not the others.
How might I go about fixing this?
Sub a()

Dim rng As Range
Dim sFind(10) As String

sFind(0) = "a*"
sFind(1) = "b*"
sFind(2) = "c*"
sFind(3) = "d*"
sFind(4) = "e*"
sFind(5) = "f*"
sFind(6) = "g*"
sFind(7) = "h*"
sFind(8) = "i*"
sFind(9) = "j*"

For Each rng In Range("J2", Range("J65536").End(xlUp))
    If Not rng.find(sFind(), LookIn:=xlValues) Is Nothing Then
        rng.Offset(0, 1).Value = "1"
    End If
Next rng

End Sub

A: I suspect you've got the loop the wrong way round. This should work
Sub a()
    Dim rng As Range
    Dim sFind(10) As String
    Dim i as Long

    sFind(0) = "a*"
    sFind(1) = "b*"
    sFind(2) = "c*"
    sFind(3) = "d*"
    sFind(4) = "e*"
    sFind(5) = "f*"
    sFind(6) = "g*"
    sFind(7) = "h*"
    sFind(8) = "i*"
    sFind(9) = "j*"

    With Range("J2", Range("J65536").End(xlUp))
        For i = LBound(sFind) To UBound(sFind)
            Set rng = .Find(what:=sFind(i), LookIn:=xlValues)
            If Not rng Is Nothing Then
                rng.Offset(0, 1).Value2 = 1
            End If
        Next i
    End With
End Sub

A: One way is to modify inner code and add a loop like below which will check for all entries.
For i = lbound(sFind) to ubound(sFind)
    If Not rng.find(sFind(i), LookIn:=xlValues) Is Nothing Then
        rng.Offset(0, 1).Value = "1"
        Exit For
    End If
Next i


text:
Q: CGEventPost does not always move the mouse macOS I have been encountering issues when trying to move the mouse programmatically in macOS Sierra using Quartz Event Services in a Python environment.
For Example:
When I run this script:
from Quartz.CoreGraphics import CGEventCreateMouseEvent
from Quartz.CoreGraphics import CGEventPost
from Quartz.CoreGraphics import kCGMouseButtonLeft
from Quartz.CoreGraphics import kCGEventMouseMoved
from Quartz.CoreGraphics import kCGHIDEventTap

def MouseMove(x, y):
        event = CGEventCreateMouseEvent(None, kCGEventMouseMoved, (x, y), kCGMouseButtonLeft)
        CGEventPost(kCGHIDEventTap, event)

MouseMove(100, 100)

Everything works great and the mouse gets moved to (x: 100, y: 100).
HOWEVER, for some reason this procedure does not manage to move the mouse in certain applications. Specifically in my case my MacBook is running Call of Duty: Modern Warfare 2 on Steam and moving the mouse in this manner does not register in this application but interestingly enough I am still able to generate mouse clicks in the application using CGEventPost just not mouse movements.
So I've done some research to try to figure out why this is happening and the closest thing I could find online relating to my problem is this question on SO and the reason I mention this is because I'm wondering if like in the linked question I need to call a method similar to something like CGEventSetIntegerValueField only instead of updating the kCGMouseEventClickState update a mouse event pertaining to the movement of the mouse so that the application will know that the mouse has indeed moved. However I have not found such a method in the CGEventField documentation and I just feel like I'm missing something or maybe this isn't even involved with problem but this is the only lead I could find.
Please help. I would appreciate any suggestions anyone might have.

A: I found the answer.
I changed this line:
event = CGEventCreateMouseEvent(None, type, (x, y), kCGMouseButtonLeft)
CGEventPost(kCGHIDEventTap, event)

To this:
CGPostMouseEvent((x, y), True, 0, False)

And of course imported: CGPostMouseEvent
As a result, moving the mouse works everywhere and in all applications. The reason why it works is because it turns out CGPostMouseEvent occurs on a deeper level of the local machine than CGEventPost.


text:
Q: Scala: Retrieving contents of a URL with specified headers and interface [ip] address I would like to know how to get the source of a URL (like Source.fromURL) with specified headers and specified IP address (the machine where the code is executed has not one but several ip addresses bind).
How can I achieve this?
Thank you.

A: I think you could do that the same way:
import io.Source
import java.net.URL

val stackOverflowURL = "http://69.170.135.92:80"
val requestProperties = Map(
  "User-Agent" -> "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
)
val connection = new URL(stackOverflowURL).openConnection
requestProperties.foreach({
  case (name, value) => connection.setRequestProperty(name, value)
})

print(Source.fromInputStream(connection.getInputStream).getLines.mkString("\n"))

A: Based on this other answer, it looks to me like in current versions of java (6 /7) there's no nice way to make an HTTP request that is bound to a particular local address.  (The direct proxy approach that used to work appears to be explicitly blocked now.) That answer makes it look like one relatively easy way is to use the Apache commons HttpClient, which lets you specify the local address to bind to.


text:
Q: SQL Server Consecutive Invoices excluding after 36 month gap I'm struggling with a problem of using a formula to identify loyal customers and I'm hoping for some insight.
The Loyal Customer criteria are as follows:

*

*The Customer must have been invoiced at least 4 times within 36
months, with invoices falling in the following time ranges:

*

*First Invoice (A) – This does not necessarily have to be the first time the
customer is ever invoiced, just the first invoice that falls into
this pattern

*Second Invoice (B) – Has to occur from 1-12 months
after Invoice A

*Third Invoice (C) – Has to occur from 13-24 months
after Invoice A

*Fourth Invoice (D) – Has to occur from 25-36 months
after Invoice A

*Once these criteria are met, all invoices with a    date greater than
or equal to A are considered loyal customer    invoices

*

*Only invoices with positive sub totals should be counted    as qualifying
invoices (A, B, C, or D), but all invoices should be    counted once
the customer meets the qualifying criteria

So far, I'm OK with this. Here is the query I'm using (It's pretty slow, but I'm not running it very frequently so I'm not particularly concerned with speed):
;WITH

T1 AS
(
SELECT
CUSTOMER_ID,
INVOICE_DATE,
DATEPART(YEAR, INVOICE_DATE)*12 + DATEPART(MONTH, INVOICE_DATE) AS YM
FROM INVOICE
WHERE Sub_Total > 0
),

T2 AS
(
SELECT DISTINCT
A.CUSTOMER_ID,
A.INVOICE_DATE A_DATE
FROM T1 A
JOIN T1 B ON A.CUSTOMER_ID = B.CUSTOMER_ID AND (B.YM > A.YM AND B.YM <= (A.YM + 12))
JOIN T1 C ON A.CUSTOMER_ID = C.CUSTOMER_ID AND (C.YM > B.YM AND C.YM BETWEEN (A.YM + 13) AND (A.YM + 24))
JOIN T1 D ON A.CUSTOMER_ID = D.CUSTOMER_ID AND (D.YM > C.YM AND D.YM BETWEEN (A.YM + 25) AND (A.YM + 36))
)

SELECT DISTINCT
I.CUSTOMER_ID,
C.CUSTOMER_NAME,
I.INVOICE_ID,
cast(i.Invoice_Date as Date) as Invoice_Date,
DATEPART(YEAR, I.INVOICE_DATE)*12 + DATEPART(MONTH, I.INVOICE_DATE) AS YM,
DATEPART(MONTH, I.INVOICE_DATE) AS Mo,
DATEPART(YEAR, I.INVOICE_DATE) AS Yr,
I.SUB_TOTAL
FROM INVOICE I
JOIN T2 ON T2.CUSTOMER_ID = I.CUSTOMER_ID AND I.INVOICE_DATE >= A_DATE
JOIN CUSTOMER C ON C.CUSTOMER_ID = I.CUSTOMER_ID
ORDER BY I.CUSTOMER_ID, INVOICE_DATE

However, what's causing me to get stuck is another criteria stating that if a loyal customer goes 36 months without being invoiced they are no longer considered loyal, and any invoices following the 36-month gap should not be counted. If the customer completes the 4 qualifying invoices identified above (A, B, C, and D) again after the 36-month gap it is considered a new set of loyal invoices.
Example:

+--------------------+--------------------+-----------------+
| Invoice Month/Year | Qualifying Invoice | Count as Loyal? |
+--------------------+--------------------+-----------------+
| 01/04              | N/A                | No              |
| 03/05              | A                  | Yes             |
| 09/05              | B                  | Yes             |
| 12/05              | N/A                | Yes             |
| 06/06              | C                  | Yes             |
| 04/07              | D                  | Yes             |
| 06/07              | N/A                | Yes             |
| 07/10              | N/A                | No              |
| 08/10              | N/A                | No              |
| 09/11              | A                  | Yes             |
| 10/11              | B                  | Yes             |
| 01/13              | C                  | Yes             |
| 04/14              | D                  | Yes             |
| 06/14              | N/A                | Yes             |
+--------------------+--------------------+-----------------+

I apologize if I've made this too complex. Ultimately, I'm hoping to gain some insight into how to exclude all invoices after a 36-month gap except those that meet the loyal customer criteria again.

A: Here's a way to calculate the gaps, using a CTE. If you have SQL2012 or higher, the lag window function makes this simpler.
Good luck incorporating the information!
with x as (
  select
    invoice_id,
    customer_id,
    invoice_date,
    row_number() over (partition by customer_id order by invoice_date) rn
    -- SQL2012 has lag which is easier, can compute the gap directly (untested)
    -- datediff(month, lag(invoice_date, 1) over (
    --       partition by customer_id
    --       order by invoice_date
    -- ), invoice_date) as gap
  from
    invoice
  where
    sub_total > 0
) select
  x1.*,
  datediff(month, x2.invoice_date, x1.invoice_date) gap
from
  x x1
    left join
  x x2
    on x1.customer_id = x2.customer_id and x1.rn = x2.rn + 1;

Example SQLFiddle


text:
Q: Jquery .css issue on chrome i have a script that creates divs with some background image then moves them, it runs great on all other browsers but chrome has is too laggy. I check my codes and i see that when i remove following codes, it works great on chrome too.
//imageCount = count of image placed for animation, this loop gets source of
//each image, create divs, then makes each image to background of a div

for(imageNum=0;imageNum<imageCount;imageNum++)
{
var imageSrc= $("#image img:eq("+imageNum+")").attr("src");

 //save image sources for later use
images.push(imageSrc);

 //creating divs
$("#main_cont").append("

");

  //here is my problem
//when i delete .css part works great

$("#main_cont .img_cont:eq("+imageNum+")").width(tWidth).height(tHeight).css({
    backgroundImage: "url("+imageSrc+")",
    backgroundRepeat: "no-repeat",
    backgroundSize: tWidth +"px "+ tHeight +"px "

});

  //this part is not about my question, each div's position for animation
var offset = $("#main_cont .img_cont:eq("+imageNum+")").offset();

yPos.push(offset.top);
xPos.push(offset.left);

}

a simple version of my codes on jsfiddle: http://jsfiddle.net/uUj4h/2/ (may take a min to load cause of big images)
if i can't find a solution, i will use images in a div instead of background but for my animation but i need divs.

A: background-size is a CSS3 property, so it might have a greater toll on the browser's speed.
I might suggest using the images within a
 for speed.

A: Did you try the obvious:
$("#main_cont .img_cont:eq("+imageNum+")").css({
    width: tWidth,
    height: tHeight,
    background: "url("+imageSrc+") no-repeat top left"
});

and just setting background-size in your css.
Fiddle : http://jsfiddle.net/adeneo/6TeBk/2/
Or you could try just appending it as an img tag to the start of your element:
var imageSrc = new Image();
    imageSrc.src = $("#image img:eq("+imageNum+")").attr("src");
    imageSrc.width = tWidth;
    imageSrc.height = tHeight;

$("#main_cont .img_cont:eq("+imageNum+")").css({ width: tWidth, height: tHeight}).append(imageSrc);


text:
Q: Is this an acceptable practice for WordPress theme development? I don't think this is the right way to do things, maybe I'm wrong or missing something but to me it seems unnecessary. Is this correct? What are the implications if any of doing things this way?
In the functions file all the functions are wrapped in a class:
class This_Theme
{
   function example_fucntion(
      echo 'example';
   );
}

Then in the theme they call the function statically:
This_Theme::example_function();

Isn't this pointlessly wrapping the function in a class to call it statically? Wouldn't it make more sense to just leave out the class?

A: It is a matter of opinion and coding style. This kind of coding style is very popular in wordpress plugin and theme development therefor I will not fault anyone for doing it but I agree that the practice of having classes that have only static method or used as a singleton in the context of wordpress is just BS.
This was justified when PHP versions with name spacing weren't popular enough, and wrapping code in a class basically provided the name spacing, but now that the last version without name spacing was EOLed almost 5 years ago the practice is ridiculous, and just makes some kinds of coding aspects harder and too verbose.
But in the end this is the developers code, and he needs to write the code in a way that will be cleaner and more maintainable for him and if he prefer OOP coding over functional then there is nothing terribly wrong with that.


text:
Q: USB Audio Oddity I'm looking for suggestions to either fix or further diagnose an audio problem I'm having.  The components involved are a Mac Mini (Late 2012) running 10.13.6 and a Focusrite Scarlett 18i8 USB audio interface.
Starting two days ago, audio output would stop after some amount of playback, ranging from a few seconds to 10 minutes.  While playback is broken, recording has been working correctly.  The system has had no software upgrades or installations in the past few weeks.
Switching the Scarlett to a different USB port caused everything to start working again temporarily.  When it failed on the new port, switching back to the original also worked temporarily.
Suggested fixes such as trashing audio preferences and doing a SMC reset have had no effect.
Attaching the Scarlett to an obsolete MacBook Pro (Mid 2009) running 10.11.6 doesn't seem to produce any problems.
EDIT:
I was able to update to Mojave (thereby avoiding the Catalina trauma) but it resulted in no change to the symptoms.

A: I had a similar issue on High Sierra with a Line6 interface; slightly different as the audio would fail if I left the machine alone for a while. It didn't sleep, my machines never do, but after some unknown period of time the audio would fail.
When it did this it would also cause any video to fail too - endlessly spinning pizza wheel when on VLC or YouTube etc.
My temporary fix at the time was to toggle my output's output frequency in Audio MIDI Setup, 44.1 to 48 & back again [or vice versa] which would be fine for another day or so.
The issue went away with Mojave [as did many other issues High Sierra was plagued with].

A: I had the same experience with High Sierra, where a USB audio interface (not the same one) also would stop working after a while. Switching USB ports and/or rebooting would fix it - temporarily. The problem appeared seemingly out of nowhere, and wouldn't go away.
I fixed it by upgrading to Mojave, and haven't seen it since.


text:
Q: Set resolution for camera in IOS for AI I am working on a project where I start the camera and then capture images live to image processing. This project has guided me TensorFlow - Image Classification. One thing I can't figure out despite looking in the documentation and searching on Google is how to set the resolution of the camera.
Is it possible to either get it, or to set it programmatically? Here is the code where I create the camera:
 private func addVideoDeviceInput() -> Bool {

        /**Tries to get the default back camera.
         */
        guard let camera  = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back) else {
            return false
        }
        do {
            let videoDeviceInput = try AVCaptureDeviceInput(device: camera)
            if session.canAddInput(videoDeviceInput) {
                session.addInput(videoDeviceInput)
                return true
            }
            else {
                return false
            }
        }
        catch {
            fatalError("Cannot create video device input")
        }
    }

A: Yes, check out sessionPreset.
session.sessionPreset = .photo /// here!
if session.canAddInput(videoDeviceInput) {
    session.addInput(videoDeviceInput)
    return true
}


text:
Q: How to create only capital letters in the beginning of words? I need to make a method that makes capital letters only at the beginning of words, is something easy maybe but I haven't been able to make it work so far. Cause the use case I have tested it are diff,  Cause I don't have only the case where the first character is a string it can be a number or something else.
The result I want :
test => Test
test start now => Test start now.
2test start now => 2test start now
_test => _test
-test => -test

A: *

*Check if the first char is Alphabetic

*Change the letter to upper case

    List<String> values = Arrays.asList("test => Test",
            "test start now => Test start now.",
            "2test start now => 2test start now",
            "_test => _test",
            "-test => -test");

    @Test
    public void firstLetterUpperCase() {
        // Iterate the values
        values.stream()
                // Check if the first char is Alphabetic
                .filter(text -> Character.isAlphabetic(text.charAt(0)))
                // Capital first letter and print
                .forEach(text -> System.out.println(text.substring(0, 1).toUpperCase() + text.substring(1)));
    }

Output
Test => Test
Test start now => Test start now.

A: String text = "text";
String capitalize = text.substring(0, 1).toUpperCase() + text.substring(1);

It takes first character, and does toUpperCase(), then add the rest of the string.
If first character is not a letter, toUpperCase() won't change it.

*

*"-".toUpperCase() is "-"

*"1".toUpperCase() is "1"

*"a".toUpperCase() is "A"

*"A".toUpperCase() is "A"

A: You could also use org.apache.commons.text.WordUtils.capitalize(String str, char... delimiters) Javadoc from apache.commons-text to captalize words.
Against your request, it capitalizes all words in a string/sentence not only the first character.
To uppercase the first character of a String use org.apache.commons.lang3.StringUtils
.capitalize(String str) (Javadoc) from the apache.commons-lang package.


text:
Q: set cell or row background color in a google spreadsheet using google_drive gem on ruby I'm trying to set a background color for a cell and a row and am using the 'google_drive' gem.
It looks like that the 'spreadsheet' gem does have this option
format = Spreadsheet::Format.new :color=> :blue, :pattern_fg_color => :yellow, :pattern => 1

if the 'google_drive' gem also has this option, please let me know!
Thanks in Advance.

A: The problem is that you are trying to set the background color by setting :color => :blue. Instead, set :pattern_bg_color => :blue.
All options:
:bottom_color, :top_color, :left_color, :right_color, :pattern_fg_color, :pattern_bg_color, :diagonal_color
Hope this helps!


text:
Q: Pig: which jar to register for using REGEX_EXTRACT_ALL method? I want to use the built in method REGEX_EXTRACT and REGEX_EXTRACT_ALL methods of Pig.  Which jar should i include for this?  Any links?

A: The functions are named RegexExtract(...)/RegexExtractAll() in 0.7 and
case sensitivity matters

A: And they are builtin in 0.9 now.


text:
Q: minimax code returns always 0 I wrote an Alpha-Beta pruning from Wikipedia. I am trying to write a connect-four AI. The function should return column number, then my main function makes a move.

A: Your problem is in this line I believe:
if(temp[i][column-1] == '0')

temp is an int array. You should compare just 0. '0' means the character 0, which Java will interpret as an integer (48). Anyways, you should use this:
if(temp[i][column-1] == 0)


text:
Q: How to access model.android properties outside model Along the lines of this:
Build.Gradle
apply plugin: 'com.android.model.application'

model {
    android {
        compileSdkVersion = 19
        ...
    }

    android.buildTypes {
        debug
        release
    }
    ...
}

//How to access model.android.buildTypes outside model?
$(model.android.buildTypes).each { buildType ->
    task "task$buildType" << {
        ...
    }
}

This document briefly explains the $() syntax within the model for accessing other model.android.* properties: gradle experimental
I'm using gradle 2.10
My attempts with "${}" and $("") syntax are not working, and usually fail along the lines of:

Could not find property 'android' on task ':app:model'.

I believe property access outside of that block used to work with 'apply plugin: com.android.application' instead of the new model.
Since model is a task, I looked up Task (see the dynamic properties section) and tried model.property(android) but that didn't work either. I'm guessing it's in there somewhere but I can't query for a list of properties.
I understand this is gradle-experimental; any tips on where to look in the gradle source code for an answer would be graciously accepted!

A: Turns out the android.* properties are exposed as properties on the project (e.g. project.buildTypes).
Example:
task ptest() << {
  println buildTypes.collect{it}.join('\n')
  println platforms.collect{it}.join('\n')
  println flavors.collect{it}.join('\n')
}

Output:
user@debian:~/dev/androidinputrouter$ ./gradlew :app:ptest
:app:ptest
build type 'debug'
build type 'release'
platform 'arm64-v8a'
platform 'armeabi'
platform 'armeabi-v7a'
platform 'mips'
platform 'mips64'
platform 'x86'
platform 'x86_64'
flavor ''


text:
Q: How to extract all
* list from html using chromedriver selenium with WebDriverWait? from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

. . .
x = (
    WebDriverWait(driver, 120)
    .until(
        EC.presence_of_element_located(
            (
                By.XPATH,
                '//*[@id="root"]/div[2]/div[3]/div/div[6]/div/section[1]/div[2]/ul',
            )
        )
    )
    .find_element(
        by=By.TAG_NAME,
        value="li",
    )
)
print(x)

The output I wanted to extract all list from <ul> tag from html, but the output was <selenium.webdriver.remote.webelement.WebElement (session="2cb650732c8ccc1fbe4eb77febc4a449", element="3556f3cc-216a-49c6-9edf-5d478551cfdc")>.
The list that I want to extract

A: To get a list instead of single element try to replace
EC.presence_of_element_located

with
EC.presence_of_all_elements_located


text:
Q: Searching for specific words in a text string - SQL I wondered if someone might be able to help me. I know that I am doing something wrong and over-complicating this but i'm not sure what.
I would like to pick out text from questions 205,227 and 278 when someone uses the words Autism, ASD, Aspergers etc... to answer the question.
What is happening is I am only getting single word phrases, rather than when someone writes the word in a string e.g. 'I have autism' will not appear in the output. Only when someone writes Autism. I have noticed it is case sensitive too and I wondered whether this can be coded so that I don't have to write all words in every combination of upper and lower case.
The main things I need are the specific questions (question.id) and to be able to search for the occurrence of specific words and phrases within the responses of these questions (texter_survey_response_value.value).
    select
    texter_survey_response.response_id, question_id, conversation_id,
    texter_survey_response_value.value as scrubbed_feedback
    from
    texter_survey_response
    join texter_survey_response_value on texter_survey_response.response_id =
    texter_survey_response_value.response_id
    where
    texter_survey_response_value.question_id IN (205, 227, 278)
    and texter_survey_response_value.value = 'Autism'
    or texter_survey_response_value.value = 'ASD'
    or texter_survey_response_value.value = 'Autistic'
    or texter_survey_response_value.value = 'Aspergers'
    or texter_survey_response_value.value = 'Autism Spectrum'
    or texter_survey_response_value.value = 'Autistic Spectrum Disorder'
    or texter_survey_response_value.value = 'Autistic Spectrum'
    or texter_survey_response_value.value = 'Autism Spectrum Disorder'
    and texter_survey_response_value.value is not null

A: If you use =, it will only search for exact matches. You can achieve a contains-search with like by adding % to both sides of your search phrases. You can work around the case-sensitive nature of most like implementations by only working with upper or lower case.
select
  texter_survey_response.response_id, question_id, conversation_id,
  texter_survey_response_value.value as scrubbed_feedback
from
  texter_survey_response join texter_survey_response_value
    on texter_survey_response.response_id = texter_survey_response_value.response_id
where
  texter_survey_response_value.question_id IN (205, 227, 278)
  and texter_survey_response_value.value is not null
  and (
    UPPER(texter_survey_response_value.value) like '%AUTISM%' or
    UPPER(texter_survey_response_value.value) like '%AUTISTIC%' or
    UPPER(texter_survey_response_value.value) like '%ASPERGERS%' or
    UPPER(texter_survey_response_value.value) like '%ASD%');

You didn't write what database you use, so you might have to call a different procedure than UPPER.
Hope this helps :)


text:
Q: FORMS, no further idea how to implement a TextField with a CupertinoApp This drives me nuts. I am trying to get a CupertinoTextField into a Form. But no matter what I try, everything turns out as a dead end.
The complication of my case is, the form in embedded into the Flushbar package, which provides kind of a snackbar to my CupertinoApp. And this is a stateless widget ;-(
 return Flushbar(
      backgroundColor: Common.inputBlue,
      userInputForm : Form(
        key: _formKey,
        child: Column(
            children: <Widget> [
              _DelayStatusFormField(
                initialValue: task.delayStatus,
                onSaved: (value) => otherFormDataSubmit.delayStatus = value,
                //onSaved: (value) => this.delayStatus = value,
              ),
              CupertinoTextField(
                controller: _delayTec,
                onChanged: (text) {
                  state.didChange(text);
                },
              ),
            ]),
         ),
 );

In the onChanged section I intend to implement some validation, so I need kind of a rebuild.  But setState obviously doesn't work without a proper state.
Using TextFormField also looks kind of dodgy, because I do not only have to embed this in Material( but in loads of further localization Widgets.
The most desirable solution, is this one where I tried several variants: embed the CupertinoTextField in a FormField class
class _DelayFormField extends FormField<String> {
  _DelayFormField({
    FormFieldSetter<String> onSaved,
    String initialValue,
    bool enabled,
    GlobalKey key,
  }) : super(
      onSaved: onSaved,
      initialValue: initialValue,
      key: key,
      builder: (FormFieldState<String> state) {
        //TextEditingController inputTec = TextEditingController(text: initialValue);
        return Column(children: [
          SizedBox(
              width: 100, height: 30,
              child: CupertinoTextField(
                //controller: inputTec,
                enabled: true,
                onChanged: (text) {
                  initialValue = text;
                  state.didChange(text);
                },
              )),
        ]);
      }
  );
}

The problem here, I the TextEditingController is reinitialized on any rebuild with initialVale, loosing my input. I have got around this by assigning the input to initialVale, but the cursor is then always set leading to the prefilled digits. So you type the number backwards. Since everything is in the class' initialization, I cannot find a spot where to initialize the TextEditingController outside of the build method.
Any other idea on how to solve this? Getting such a class working would be great, since one could then simply re-use this class, frequently.


text:
Q: how to query mongodb by passing parameter exports.search = function(req, res){Song.find({genre: req.param.genre}).exec(function(err, songs){

        console.log(req.param);
        if (err) {
            return res.send(400, {
                message: getErrorMessage(err)
            });
        }
        else {
            res.jsonp(songs);
        }

    });

};

A: Thanks, everybody for the time to review my code. What I wanted to do was to pass in a parameter into the search function and then retrieve everything in relation to the search so this code works for me......
for the route controller:
app.route('/songs/:genre')
        .get(songs.search);

for the server controller:
 exports.search = function(req, res){
    if( req.params.genre){
        Song.find({genre: req.params.genre }, function(err, songs){
            console.log(req.params.genre);
            res.json(songs);
        });
    }

};


text:
Q: incompatible type address in android I have tried a lot in removing the error but unable to remove one error that is incompatible type address
   public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
EditText ed;
Button btn;
private GoogleMap mMap;
List<Address> addressList;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_maps);
    ed=(EditText)findViewById(R.id.ed);
    btn=(Button)findViewById(R.id.btn);

    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}

public  void  onsearch()
{
    String location=ed.getText().toString();

    if(location!=null|| !location.equals("")){
        Geocoder geocoder=new Geocoder(this);
        try {
          addressList=geocoder.getFromLocationName(location,1);

        } catch (IOException e) {
            e.printStackTrace();
        }
        Address address=addressList.get(0);
        LatLng latLng=new LatLng(address.getLatitude(),address.getLongitude());
        mMap.addMarker(new MarkerOptions().position(latLng).title("marker"));
        mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));

    }

}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        return;
    }
    mMap.setMyLocationEnabled(true);
    LatLng sydney = new LatLng(-34, 151);
    mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
    mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}

}
please help as in error dialog box shows
.dialog box shows found android.location.address requires List import com.google.android.gms.identity.intents.Address

A: It sounds like you have the wrong import statement. It would be helpful if you provided the error stack trace and the full source including imports though.


text:
Q: Dojo node properties I am just a beginner on Dojo and JavaScript programming, and hope someone can give me a hint on this.
I would like to modify the store property of dijit.form.ComboBox on runtime.
(I have created a combobox with id "cmbCat" and a data store with id "catData". It work perfectly if embed to store="catData" in my HTML page)
My first approach to do this is using the dojo.attr("cmbCat", {store: "catData"});
However, it didn't work.
My second approach is using cmbCat.store = catData;
This work fine.
I am just wondering when should I use dojo.attr and when to use dot property? and if they are identical why is my dojo.attr is not working?
Thanks so much for helping me on this!
Nick

A: According to the documentation of dojo.attr,

A getter and setter for DOM attributes, events and CSS styles

So you should use dojo.attr when getting/setting values of DOM attributes, events and CSS styles. In this case, the store property is not applicable to use dojo.attr.

A: I have found that some widgets are a bit different than others in this sense, but for the newer versions of dojo you should use the set method for widgets, not attr.
cmbCat.set('store', catData);

It is also important to understand what happens when you call the set/get method of the widget as opposed to just using dot syntax.
The set and get methods can be mapped to custom setters and getters which some widgets implement. If you just call the property with the dot syntax, the custom setters and getters will not be called. I think on older versions of dojo, attr was used for this purpose on widgets, but that functionality is being deprecated and is not really dependable. The attr method in the context of widgets will be removed in Dojo 2.0 and was deprecated in Dojo 1.4. http://mail.dojotoolkit.org/pipermail/dojo-interest/2010-April/045199.html
You can see a bit more about setters and getters here: http://dojotoolkit.org/reference-guide/quickstart/writingWidgets.html#custom-setters-getters
In my code using 1.5 I have been using the set method to set the stores on selects, and also to set the titles for content panes, content, etc. It works quite well.
Also, assuming catData is in your scope when you create the widget, you have a simple error here:
dojo.attr("cmbCat", {store: "catData"});

Since "catData" is a string, your are assigning a string to the store property. That won't work programatically, you need catData to be a variable referencing a copy of dojo.data.ItemFileWriteStore or similar.


text:
Q: Split a Map> into Two Sperate Maps with Overlapping Keys Based on Items I'm trying to figure out how to efficiently split a map into two maps. The original map looks like the following, but is much larger:
val sourceMap = <Map<String, List<Item>> = mapOf(
   "key1", listOf(Item(owned: Boolean = true), Item(owned: Boolean = false)),
   "key2", listOf(Item(owned: Boolean = false), Item(owned: Boolean = false)),
   "key3", listOf(Item(owned: Boolean = true), Item(owned: Boolean = true))
)

I want to split this maps into two maps, that associates the key to all the "owned = true" items in one map and "owned = false" items into the other. Which would look like:
val ownedMap = Map<String, List<Item>> = mapOf(
   "key1", listOf(Item(owned: Boolean = true)),
   "key3", listOf(Item(owned: Boolean = true), Item(owned: Boolean = true))
)

val unOwnedMap = Map<String, List<Item>> = mapOf(
   "key1", listOf(Item(owned: Boolean = false)),
   "key2", listOf(Item(owned: Boolean = false), Item(owned: Boolean = false)),
)

Edit: Ideally the answer will allow for all sorting to happen in one pass of the original sourceMap.

A: Here's the code that might help.
First, we create two maps where we will add the resulting sorted values. After that, we iterate over the sourceMap. SourceMap contains values in the form String, MutableList.
Next, we iterate over the list of items. And if the item has an owned parameter with value true, we add that item to ownedMap, otherwise to unOwnedMap.
val ownedMap = mutableMapOf<String, MutableList<Item>>()
val unOwnedMap = mutableMapOf<String, MutableList<Item>>()

sourceMap.forEach { (key, list) ->
    list.forEach { item ->
        if (item.owned) {
            ownedMap.addToListInMap(key, item)
        } else {
            unOwnedMap.addToListInMap(key, item)
        }
    }
}

fun <K, V> MutableMap<K, MutableList<V>>.addToListInMap(key: K, value: V) {
    if (this[key] != null) {
        this[key]?.add(value)
    } else {
        this[key] = mutableListOf(value)
    }
}

You can also write without an extension function. Then it will look like this:
val ownedMap = mutableMapOf<String, MutableList<Item>>()
val unOwnedMap = mutableMapOf<String, MutableList<Item>>()

sourceMap.forEach { (key, list) ->
    list.forEach { item ->
        if (item.owned) {
            if (ownedMap[key] != null) {
                ownedMap[key]?.add(item)
            } else {
                ownedMap[key] = mutableListOf(item)
            }
        } else {
            if (unOwnedMap[key] != null) {
                unOwnedMap[key]?.add(item)
            } else {
                unOwnedMap[key] = mutableListOf(item)
            }
        }
    }
}


text:
Q: Unable to connect with SQL Server using Node.js I have created an application using Node.js to connect with SQL Server. Below is the code:
app.get('/SalesStatistics', function (req, res) {
    var Connection = require('tedious').Connection;
// config for your database
var config = {
    user: "****",
    password: "*****",
    server: "abc",
    database: "xyz"
};

var connection = new Connection(config);
connection.on('connect', function (err) {
    // If no error, then good to proceed.
    console.log("Connected");
    executeStatement();
});
var Request = require('tedious').Request;
var TYPES = require('tedious').TYPES;

function executeStatement() {
    request = new Request("select * from employee;", function (err) {
        if (err) {
            console.log(err);
        }
    });
    var result = "";
    request.on('row', function (columns) {
        columns.forEach(function (column) {
            if (column.value === null) {
                console.log('NULL');
            } else {
                result += column.value + " ";
            }
        });
        console.log(result);
        result = "";
    });
    request.on('done', function (rowCount, more) {
        console.log(rowCount + ' rows returned');
    });
    connection.execSql(request);
}

});
Received the below error in console:
message: 'Requests can only be made in the LoggedIn state, not the Connecting state'
code: EIINVALIDSTATE
Also tried the sample from Github site, but still I could not connect to SQL Server. Please let me know if any other possibility.

A: I just encountered the same problem awhile ago running the same code above with similar environment.
It turn out that I did not configure the sql server (using Sql Server Management Manager) to accept TCP connection to port (1433). After I done that, everything work fine.


text:
Q: Why is the memory sum of my processes lower than the actual used memory? The sum of all running processes and used memory don't add up. It should be about 10GB used, but it's 33 with swap. What am I missing and where did the memory go?

top -n1 -b -o "%MEM"

top - 14:12:13 up 4 days, 14:34,  1 user,  load average: 2.88, 1.68, 1.40
Tasks: 475 total,   1 running, 473 sleeping,   0 stopped,   1 zombie
%Cpu(s):  2.7 us,  2.0 sy,  0.0 ni, 94.5 id,  0.0 wa,  0.4 hi,  0.4 si,  0.0 st
MiB Mem :  15720.5 total,    240.2 free,  12496.3 used,   2984.0 buff/cache
MiB Swap:  40960.0 total,  29546.3 free,  11413.7 used.   1585.2 avail Mem

    PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND
 420661 aleksan+  20   0 9976208   2.8g   9232 S  53.3  18.0  57:12.01 qemu-sy+
 194572 aleksan+  20   0   14.1g   2.3g   2064 S   0.0  14.9  64:40.09 java
 420783 aleksan+  20   0 4097980 856672  62712 S   0.0   5.3   6:51.14 Isolate+
 422028 aleksan+  20   0  267.5g 599920 178416 S   0.0   3.7   6:08.70 Rider.B+
 434079 aleksan+  20   0 3192940 412608  96276 S   0.0   2.6   0:33.46 Isolate+
 407972 aleksan+  20   0 8830056 385000 120472 S   0.0   2.4  11:59.39 firefox
 179359 aleksan+  20   0 1129.1g 261820  60924 S   0.0   1.6  38:42.86 slack

free -g

               total        used        free      shared  buff/cache   available
Mem:              15          12           0           1           2           1
Swap:             39          11          28

df -h

Filesystem      Size  Used Avail Use% Mounted on
devtmpfs        4.0M     0  4.0M   0% /dev
tmpfs           7.7G   39M  7.7G   1% /dev/shm
tmpfs           3.1G  2.6M  3.1G   1% /run
/dev/nvme0n1p4  444G  166G  276G  38% /
tmpfs           7.7G   15M  7.7G   1% /tmp
/dev/nvme0n1p4  444G  166G  276G  38% /home
/dev/nvme0n1p2  974M  273M  634M  31% /boot
/dev/nvme0n1p1  599M   29M  571M   5% /boot/efi
tmpfs           1.6G  716K  1.6G   1% /run/user/1000
/dev/nvme0n1p4  444G  166G  276G  38% /run/timeshift/backup

cat /proc/meminfo

MemTotal:       16097796 kB
MemFree:          175784 kB
MemAvailable:    1247900 kB
Buffers:              56 kB
Cached:          2442848 kB
SwapCached:      1709900 kB
Active:          6085628 kB
Inactive:        6024496 kB
Active(anon):    5282164 kB
Inactive(anon):  5705444 kB
Active(file):     803464 kB
Inactive(file):   319052 kB
Unevictable:       65308 kB
Mlocked:            5908 kB
SwapTotal:      41943032 kB
SwapFree:       30263284 kB
Zswap:                 0 kB
Zswapped:              0 kB
Dirty:              2044 kB
Writeback:             0 kB
AnonPages:       9666652 kB
Mapped:           681552 kB
Shmem:           1315408 kB
KReclaimable:     291168 kB
Slab:             615504 kB
SReclaimable:     291168 kB
SUnreclaim:       324336 kB
KernelStack:       41520 kB
PageTables:       120196 kB
NFS_Unstable:          0 kB
Bounce:                0 kB
WritebackTmp:          0 kB
CommitLimit:    49991928 kB
Committed_AS:   34806112 kB
VmallocTotal:   34359738367 kB
VmallocUsed:      127080 kB
VmallocChunk:          0 kB
Percpu:            20416 kB
HardwareCorrupted:     0 kB
AnonHugePages:    161792 kB
ShmemHugePages:   192512 kB
ShmemPmdMapped:        0 kB
FileHugePages:         0 kB
FilePmdMapped:         0 kB
CmaTotal:              0 kB
CmaFree:               0 kB
HugePages_Total:       0
HugePages_Free:        0
HugePages_Rsvd:        0
HugePages_Surp:        0
Hugepagesize:       2048 kB
Hugetlb:               0 kB
DirectMap4k:      332800 kB
DirectMap2M:     9873408 kB
DirectMap1G:     6291456 kB


text:
Q: Rails 4 API uninitialized constant API::CoursesController Hey all so Im creating an Api for my rails app to use with an android client but when im setting up the api im getting this error:
"uninitialized constant API::CoursesController"
app/controllers/api/courses_controller.rb
class API::CoursesController < ApplicationController::Base
  courses = Course.all
  render json: courses, status: 200
end

routes.rb
Rails.application.routes.draw do
  resources :courses
  resources :categories
  resources :quizzes
  resources :quiz_questions
  resources :quiz_answers

  namespace :api do
    resources :courses
  end
end

config/initializers/inflections.rb
ActiveSupport::Inflector.inflections(:en) do |inflect|
  inflect.acronym 'API'
end

when I go to the link http://localhost:3000/api/courses I get this:
uninitialized constant API::CoursesController

Rails.root: /Users/faisalchoura/Documents/uni/rocket/server

activesupport (4.2.3) lib/active_support/inflector/methods.rb:276:in `const_get'
activesupport (4.2.3) lib/active_support/inflector/methods.rb:276:in `block in constantize'
activesupport (4.2.3) lib/active_support/inflector/methods.rb:259:in `each'
activesupport (4.2.3) lib/active_support/inflector/methods.rb:259:in `inject'
activesupport (4.2.3) lib/active_support/inflector/methods.rb:259:in `constantize'
actionpack (4.2.3) lib/action_dispatch/routing/route_set.rb:72:in `controller_reference'
actionpack (4.2.3) lib/action_dispatch/routing/route_set.rb:62:in `controller'
actionpack (4.2.3) lib/action_dispatch/routing/route_set.rb:41:in `serve'
actionpack (4.2.3) lib/action_dispatch/journey/router.rb:43:in `block in serve'
actionpack (4.2.3) lib/action_dispatch/journey/router.rb:30:in `each'
actionpack (4.2.3) lib/action_dispatch/journey/router.rb:30:in `serve'
actionpack (4.2.3) lib/action_dispatch/routing/route_set.rb:821:in `call'
rack (1.6.4) lib/rack/etag.rb:24:in `call'
rack (1.6.4) lib/rack/conditionalget.rb:25:in `call'
rack (1.6.4) lib/rack/head.rb:13:in `call'
actionpack (4.2.3) lib/action_dispatch/middleware/params_parser.rb:27:in `call'
actionpack (4.2.3) lib/action_dispatch/middleware/flash.rb:260:in `call'
rack (1.6.4) lib/rack/session/abstract/id.rb:225:in `context'
rack (1.6.4) lib/rack/session/abstract/id.rb:220:in `call'
actionpack (4.2.3) lib/action_dispatch/middleware/cookies.rb:560:in `call'
activerecord (4.2.3) lib/active_record/query_cache.rb:36:in `call'
activerecord (4.2.3) lib/active_record/connection_adapters/abstract/connection_pool.rb:653:in `call'
activerecord (4.2.3) lib/active_record/migration.rb:377:in `call'
actionpack (4.2.3) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'
activesupport (4.2.3) lib/active_support/callbacks.rb:84:in `run_callbacks'
actionpack (4.2.3) lib/action_dispatch/middleware/callbacks.rb:27:in `call'
actionpack (4.2.3) lib/action_dispatch/middleware/reloader.rb:73:in `call'
actionpack (4.2.3) lib/action_dispatch/middleware/remote_ip.rb:78:in `call'
actionpack (4.2.3) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'
actionpack (4.2.3) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
railties (4.2.3) lib/rails/rack/logger.rb:38:in `call_app'
railties (4.2.3) lib/rails/rack/logger.rb:20:in `block in call'
activesupport (4.2.3) lib/active_support/tagged_logging.rb:68:in `block in tagged'
activesupport (4.2.3) lib/active_support/tagged_logging.rb:26:in `tagged'
activesupport (4.2.3) lib/active_support/tagged_logging.rb:68:in `tagged'
railties (4.2.3) lib/rails/rack/logger.rb:20:in `call'
actionpack (4.2.3) lib/action_dispatch/middleware/request_id.rb:21:in `call'
rack (1.6.4) lib/rack/methodoverride.rb:22:in `call'
rack (1.6.4) lib/rack/runtime.rb:18:in `call'
activesupport (4.2.3) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'
rack (1.6.4) lib/rack/lock.rb:17:in `call'
actionpack (4.2.3) lib/action_dispatch/middleware/static.rb:116:in `call'
rack (1.6.4) lib/rack/sendfile.rb:113:in `call'
railties (4.2.3) lib/rails/engine.rb:518:in `call'
railties (4.2.3) lib/rails/application.rb:165:in `call'
rack (1.6.4) lib/rack/lock.rb:17:in `call'
rack (1.6.4) lib/rack/content_length.rb:15:in `call'
rack (1.6.4) lib/rack/handler/webrick.rb:88:in `service'
/Users/faisalchoura/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/webrick/httpserver.rb:138:in `service'
/Users/faisalchoura/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/webrick/httpserver.rb:94:in `run'
/Users/faisalchoura/.rvm/rubies/ruby-2.2.1/lib/ruby/2.2.0/webrick/server.rb:294:in `block in start_thread'

Can you help me please I've been stuck on this for a while now
Thanks!

A: Namespaces should be done with modules.
module API
  class CoursesController < ApplicationController::Base
  end
end

A: Just realized it was a silly mistake completely forgot to put the code in the index method and just left it in the class.
this
class API::CoursesController < ApplicationController
  def index
    courses = Course.all
    render json: courses, status: 200
  end
end

solved the problem


text:
Q: Format SQL String I have various values in a SQL View with the following format :
SoftwareName_Language_Architecture_Type_Version_{GUID}_INSTALL.Log
Ex: Java-v6.27_ALL_x86_MSI_pV1.0_{26A24AE4-039D-4CA4-87B4-2F86416027FF}_INSTALL.Log
I want this result in differents column :
SoftwareName
Architecture
Language

I'm stuggling with multiple _ characters using various functions RIGHT,LEFT,CHARINDEX,TRIM and all.

A: This is hard to do in SQL, as there is not split function.  It is easy to do in other programming languages.    I'd consider getting the output of your SQL into a file and then processing that file with a programming language like python, for example:
>>> field='Java-v6.27_ALL_x86_MSI_pV1.0_{26A24AE4-039D-4CA4-87B4-
>>> print '\n'.join(field.split('_'))
Java-v6.27
ALL
x86
MSI
pV1.0
{26A24AE4-039D-4CA4-87B4-2F86416027FF}
INSTALL.Log

Or in Bash
echo 'Java-v6.27_ALL_x86_MSI_pV1.0_{26A24AE4-039D-4CA4-87B4-2F86416027FF}_INSTALL.Log'|sed "s/_/\n/g"
Java-v6.27
ALL
x86
MSI
pV1.0
{26A24AE4-039D-4CA4-87B4-2F86416027FF}
INSTALL.Log

And you can do both the SQL and the bash from the command line with something like this:
cat getstuff.sql | mysql -uuser -ppass -hhost db | sed "s/_/\n/g"


text:
Q: SCNScene from collada file node.geometry is nil The problem is in the title. I need to access the SCNGeometry of a SCNNode and then edit the SCNMaterial collection of the SCNGeometry but when I inspect the node almost all its properties are set to nil including the geometry property. The weird thing is that all the nodes have been loaded from a .dae file and are all rendered fine in the scene. Any insight would be much appreciated.

A: are you sure that you are retrieving the correct node? What API do you use to do that? What do you see in the SceneKit editor that's built into Xcode?


text:
Q: Microsoft Excel to forecast when a value is hit I'm a coder, not a statistician, and reading the blogs on LINEST, FORECAST, TREND are all baffling to me.
I'm pretty sure I want to use FORECAST, and from my reading this is how it is used:
= FORECAST (New X Value, Known Y values, Known X values)
So here's my data:
1/1/2017 10,000
1/2/2017 12,000
1/5/2017 17,000
1/6/2017 18,000

I have dates on my x-axis and values on the y-axis. The question I'm trying to answer is when will the value be n, say 30,000.
We can assume that my data should be forecast linearly. I can also say that it will never go down, but I don't think that that matters
The FORECAST help says that it wants an x as the first parameter, so it is going to tell me for a particular X what my value will be. So I put this in:
=FORECAST(1/10/2017,B33:B36,A33:A36)

and get this back
24,764

And that's certainly a plausible number. So how do I get X out for a given Y?

A: The simplest thing to do would be to flip your X and Y axes.
Currently you are looking at the what the value will be on a given date, but flipping the axes will show you the date it will reach a given value, essentially giving you a prediction.
So let's say your target value is 50,000. Use the formula:
=FORECAST(50000,A33:A36,B33:B36)

You may need to format the cell as Date, otherwise you'll get a big number in there.
In this case, this formula on that data told me you'd reach 50,000 on the 25th of January of this year. Yesterday.


text:
Q: How do I create a dynamic class for a div variable? I have the following code in an ERB file:

    <% @lists.each do |list| %>

            <%= link_to list.title, list %>
            <%= link_to 'Edit', edit_list_path(list) %>
            <%= button_to "Destroy", list_path(list), :method => :delete %>

    <% end %>

I want to make the <tr class="even" line dynamic. Each tr should get the class either "even" or "odd" depending on a counter variable that gets incremented every time my loop starts over. However, I cannot figure out the best way to implement this.

A: Use this nice helper :)
<tr class="<%= cycle("even", "odd") %>">


text:
Q: For a .equals, is there an equivalent or alternative? I'm supposed to write a program, where the user inputs a string where it counts for the number of each vowel, and how many non-vowels there are.
import java.util.*;

public class Strings {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner MyScan = new Scanner(System.in);

        int countnon = 0;
        for (int i = 0; i < test.length(); i++) {
            if (test.substring(i, i + 1).equals("a") || test.substring(i, i + 1).equals("e")
                    || test.substring(i, i + 1).equals("i") || test.substring(i, i + 1).equals("o")
                    || test.substring(i, i + 1).equals("u")) {
                break;
            } else {
                countnon++;
            }
        }
        System.out.println(countnon + " occurences of non-vowels");
        MyScan.close();
    }
}

For some reason, the last piece of code, the one with the countnon variable, doesn't give the right value for the number. What did I do wrong? I tried to debug some of the code, but I couldn't find where I went wrong.

A:     int countnon = 0;
    for (int i = 0; i < test.length(); i++) {
        if (test.substring(i, i + 1).equals("a") || test.substring(i, i + 1).equals("e")
                || test.substring(i, i + 1).equals("i") || test.substring(i, i + 1).equals("o")
                || test.substring(i, i + 1).equals("u")) {
            break;  // HERE
        } else {
            countnon++;
        }
    }

You've used break, so you'll stop as soon as you find the first vowel. This means that you'll only get the right answer if all of your non-vowels appear before the vowels in the string.
Use continue instead.
Or, use nothing at all: an empty block would suffice.
Or, invert your condition:
if (!string.equals("a") && !string.equals("e") /* etc */) {
  countnon++;
}


text:
Q: Outer join in ActiveRecord for complicated join I have a query that looks like this:
Flight.joins(:airline,
             flight_legs:[:departure_airport,:arrival_airport,
                aircraft:[aircraft_model:[:aircraft_make]]]).where('flights.user_id = ?',@current_user.id).order("#{sort_column} #{sort_direction}")

Kinda big, yeah. Problem that I'm getting here is that because it's an INNER JOIN, the rows returned do not include those which don't have all of the listed joins.
Is there an easy way to get all of the listed rows, and allow me to still query the individual linked tables with where queries?

A: I think this will solve your problem
Flight.joins("LEFT JOIN airlines ON airlines.id=flights.airline_id LEFT JOIN flight_legs ON flight_legs.id= flights.flight_leg_id LEFT JOIN departure_airports ON flight_legs.departure_airport_id=departure_airport_id LEFT JOIN arrival_airports ON arrival_airports.id=flight_legs.arriavak_airport_id LEFT JOIN aircrafts ON flights.aircraft_id=aircrafts.id LEFT JOIN aircraft_models ON aircraft_model.id=aircrafts.aircraft_model_id LEFT JOIN aircraft_makes ON aircraft_makes.id=aircraft_model.aircraft_make_id").where('flights.user_id = ?',@current_user.id).order("#{sort_column} #{sort_direction}")


text:
Q: SQL aggregate by date I have an issue finding some price value in an SQL query. I put a comment where the error is. It shouldn't average, but find first and last date values for open and close.
SELECT
    DATEADD(MINUTE, DATEDIFF(MINUTE, 0, aa.date) / 5 * 5, 0) AS [Date],
    AVG(aa.[open]) AS [Open], /** this is wrong it should be open from minimal date of the group*/
    MAX(aa.hight) AS [High],
    MIN(aa.low) AS Low,
    AVG(aa.[close]) AS [Close],   /** this is wrong it should be close from maximal date of the group date */
    SUM(aa.[volume]) AS [Volume]
FROM
    (select top (10000) * from [dbo].[kraken_btc] ) AS aa
GROUP BY
    DATEADD(MINUTE, DATEDIFF(MINUTE, 0, aa.[date]) / 5 * 5, 0)
ORDER BY
    Date

I deleted all the useless added stuff and post response for other as it should have been given, this other question helped me
How to aggregate prices in OHLC-data

A: So the solution was:
-- SET
DECLARE @Period int ;
SET @Period = 5 ;
select
DATEADD(MINUTE, DATEDIFF(MINUTE, 0,[Date]) / @Period * @Period, 0) AS AGG_DATE,
min([Date]) Min_Date,
max([Date]) Max_Date,
max(high) as Highest,
min(low) as Lowest,
min(case when rn_asc = 1 then [open] end) as [Open],
min(case when rn_desc = 1 then [close] end) as [Close]
from    (
        select  row_number() over (partition by  DATEADD(MINUTE, DATEDIFF(MINUTE, 0,[Date]) / @Period * @Period, 0)
        order by [Date]) as rn_asc,
        row_number() over (partition by DATEADD(MINUTE, DATEDIFF(MINUTE, 0,[Date]) / @Period * @Period, 0)
        order by [Date] desc) as rn_desc,               *
        from   OHLC
        ) as SubQueryAlias
group by
       DATEADD(MINUTE, DATEDIFF(MINUTE, 0,[Date]) / @Period * @Period, 0)


text:
Q: Проблемы с update запросом Есть таблица с 4 записями.
У меня есть массив с 2 подходящими мне записями из этой таблицы.
Я делаю update запрос ориентируясь по ним. В условии запроса есть пункт, что если записи не используются сейчас другими пользователями, то я могу сделать апдейт.
В общем если  записи не юзаются, то я успешно делаю свой запрос и юзаю их.
В самом update-запросе обновляется поле date, а в условии запроса идёт проверка, в которой мы сопоставляем текущую дату и дату из таблицы, и если различие есть в менее чем 5 минут между датами, то значит запись уже кем-то юзается.
И если одна запись или обе уже юзаются, то нужно чтобы скрипт опять попытался сделать запрос и присвоить себе записи, на случай если они освободятся конечно, и так до тех пор, пока мы не заюзаем записи.
Вот что я сейчас имею:
// Извлекаем все записи из rotation в массив

$Query123 = mysqli_query($CONNECT, "SELECT `first_name`, `uidvk`, `rot` FROM `rotation`");

$array = array();

while($Row123 = mysqli_fetch_assoc($Query123)) {
 $array[] = $Row123;
}

// тут будет проверка всех имеющихся записей к API ВКонтакте.
// Далее оставим в массиве только подходящие записи.
// Обновляем первые 2 попавшиеся записи в базе.

mysqli_query($CONNECT, "UPDATE `rotation` SET `date` = NOW(), `yes` = '$_SESSION[USER_UIDVK]' WHERE `date` < DATE_SUB(now(),INTERVAL 5 MINUTE) LIMIT 2"); // ну тут ещё будем ориентироваться както по обновлению записей только из массива.

// И вот если доступных для работы записей нет, то нужно проводить операцию всё время по новой. Пока не обновим 2 нужные записи.
// И вот ещё проблемка о которой я думаю заключается в том. что в будущем надо будет обновлять не 2 записи, а 10.
// и в том случае если 9 из 10 записей подходят для обновления, а одна не подходит, то нужно чтоб по второму кругу
// проблем никаких не сделалось, тобишь чтоб не обновилось уже 19 записей вместо 10. и нужно чтоб у всех было одно и то же время.
Помогите пожалуйста..

A: Попробуйте вот так:
affected_rows_total = 0
do {
  affected_rows = do_query( Ваш скрипт обновления LIMIT 1);
  affected_rows_total += affected_rows;
} while affected_rows_total != 2

P.S. это всё sql-команда
Обновление
Всё просто. Мы знаем что нам надо обновить N строк. В мускуле заводим цикл обновление необходимых записей. При обновлении, нам возвращается количество затронутых строк. Мы их суммируем и смотрим: равна ли итоговая сумма затронутых строк числу строк, которые надо затронуть(N). Если да - выходим из цикла и прекращаем работу sql-скрипта.


text:
Q: phonegap app crashes after installing plugin After the fix i found for my previous issue: phonegap-cordova-3-4-clean-build-gets-apple-mach-linker-error
So now, if I make a blank project
$ cordova create hello com.example.hello HelloWorld
$ cordova platform add ios
$ cordova build ios

Now I need to do follow these instructions previous question
After that everything works fine.
BUT now I'm gonna install an plugin (doesn't matter what plugin).
For now i choose the logger (org.apache.cordova.console)
$ cordova plugin add org.apache.cordova.console

Now if i build and run the app. It crashes on startup.
see: screenshot
I enabled on Zombie Objects in xcode.
Even if I install previous versions of phonegap(cordova). I still need to do all these steps. Before I just create, add platform, build and run and it was done.
Nothing is working anymore, please helpe me out here. It's really annoying.
EDIT: If i comment the line console.log('Received Event: ' + id); in js/index.js the app will start, but if I call console.log it crashes.

A: objc_msgSend causes EXC_BAD_ACCESS with plugins on arm64
So i found why this happened:
I needed to replace in the fie ios/CordovaLib/Classes/CDVCommandQueue.m
objc_msgSend(obj, normalSelector, command);

in
((void (*)(id, SEL, id))objc_msgSend)(obj, normalSelector, command);

now everything works fine again.
source

A: I found something. If I build for ios. the js (console-via-logger.js) is doing the id wrong
screenshot
If I change
cordova.define("org.apache.cordova.console.console", function(require, exports, module) { /*

to
cordova.define("org.apache.cordova.console", function(require, exports, module) { /*

it works.
Has this something todo with me or cordova?
cordova -v: 3.4.0-0.1.3
npm -v: 1.4.5


text:
Q: Invalid IL code when using callvirt with Mono.Cecil - C# I'm trying to execute this code:
Assembly.LoadFrom(Path.Combine(Application.dataPath, "Mods/VapidModLoader.dll")).GetType("Vapid.ModLoader.ModLoaderActivator").GetMethod("Activate").Invoke(null, null);

In my attempt of doing so, I wrote this using Mono.Cecil.
ILProcessor processor = gameAwakeMethod.Body.GetILProcessor();
processor.Body.Instructions.Clear(); // Clear old instructions

processor.Body.Instructions.Insert(0, processor.Create(OpCodes.Call, ImportMethod(game, typeof(Application), "get_dataPath")));
processor.Body.Instructions.Insert(1, processor.Create(OpCodes.Ldstr, "Mods/VapidModLoader.dll"));
processor.Body.Instructions.Insert(2, processor.Create(OpCodes.Call, ImportMethod(game, typeof(Path), "Combine")));
processor.Body.Instructions.Insert(3, processor.Create(OpCodes.Call, ImportMethod(game, typeof(Assembly), "LoadFrom")));
processor.Body.Instructions.Insert(4, processor.Create(OpCodes.Ldstr, "Vapid.ModLoader.ModLoaderActivator"));
processor.Body.Instructions.Insert(5, processor.Create(OpCodes.Callvirt, ImportMethod(game, typeof(Assembly), "GetType")));
processor.Body.Instructions.Insert(6, processor.Create(OpCodes.Ldstr, "Activate"));
processor.Body.Instructions.Insert(7, processor.Create(OpCodes.Callvirt, ImportMethod(game, typeof(Type), "GetMethod")));
processor.Body.Instructions.Insert(8, processor.Create(OpCodes.Ldnull));
processor.Body.Instructions.Insert(9, processor.Create(OpCodes.Ldnull));
processor.Body.Instructions.Insert(10,processor.Create(OpCodes.Callvirt, ImportMethod(game, typeof(MethodBase), "Invoke")));
processor.Body.Instructions.Insert(11,processor.Create(OpCodes.Pop));

My ImportMethod method looks like this
private static MethodReference ImportMethod(AssemblyDefinition assembly, Type type, string name)
{
    var importedType = assembly.MainModule.Import(type);
    return assembly.MainModule.Import(importedType.Resolve().Methods.First(f => f.Name == name));
}

This is the error I get:

InvalidProgramException: Invalid IL code in PlanetRotateMouse:Start
  (): IL_0023: callvirt  0x0a000235

This is what the IL Code looks like when compiled

Sorry if I don't have enough details, but I included everything related and I don't have too too much knowledge in these subjects. Any help would or explanations as to what's going wrong would be greatly appreciated. Thank you!