text:
Q: javascript regex, word not followed and not preceded by specific char I guess I'm not very good at regular expressions, so here is my problem (I'm sure it's easy to solve, but somehow I can't seem to find how )
var word = "aaa";
text = text.replace( new RegExp(word, "g"),
                     ""+word+"");

this is working in most cases.
What I want to do is for the regex ONLY TO WORK when word is not followed by the char / and not preceded with char ".

A: You can use this regex: -
'([^"])' + word + '(?!/)'

and replace it with - "$1g"
Note that Javascript does not support look-behinds. So, you need to capture the previous character and ensure that it is not ", using negated character class.
See demo at http://fiddle.re/zdjt

A: You're going to want to use a negative look-ahead.
Regex: '[^"]' + word + '(?!/)'
Edit: While it doesn't matter as it appears you already found your answer by avoiding look-behinds, Rohit noticed something I didn't. You're going to need to capture the [^\"] and include it in the replace so that it does not get discarded.
This wasn't necessary for the look-head since look-arounds by definition aren't included in captures.

A: First of all, the question can be interpreted as

*

*match word not preceded AND not followed ("aaa and aaa/ should match, same as "aaa/) and as

*match word not preceded OR not followed with some char(s) ("aaa, aaa/ should not match, while "aaa/ should).

If you are using a JavaScript environment that supports ECMAScript 2018, you can use a lookbehind solution:

const word = 'aaa',                     // Word to find
    left = '"',                         // Left-hand negative marker
    right = '/',                        // Right-hand negative marker
    text = 'aaa aaa/ "aaa "aaa/ aaaaa'; // Test string

// Relace any 'word' that does not start with " OR does not end with /
var regex = new RegExp(String.raw`\b(?<!${left})${word}\b(?!${right})`, 'g')
console.log( text.replace(regex, "$&") );
// => aaa aaa/ "aaa "aaa/ aaaaa

// Replace any 'word' that does not start with " AND does not end with /
var regex = new RegExp(String.raw`\b${word}\b(?!(?<=${left}${word})${right})`, 'g')
console.log( text.replace(regex, "$&") );
// => aaa aaa/ "aaa "aaa/ aaaaa

If you are using a JavaScript environment that does not support ECMAScript 2018, you can use

var word = 'aaa',                       // Word to find
    left = '"',                         // Left-hand negative marker
    right = '/',                        // Right-hand negative marker
    text = 'aaa aaa/ "aaa "aaa/ aaaaa'; // Test string

// Relace any 'word' that does not start with " OR does not end with /, one match expected
var regex = new RegExp("([^" + left + "\\w]|^)(" + word + ")\\b(?!" + right + ")", 'g')
console.log( text.replace(regex, "$1$2") );
// => aaa aaa/ "aaa "aaa/ aaaaa

// Same as above, but in case "left" is a sequence of chars, not a single char, or a longer pattern:
var regex = new RegExp("(" + left + ")?\\b(" + word + ")\\b(?!" + right + ")", 'g')
console.log( text.replace(regex, function(x,g,gg) { return g ? x : "" + gg + "";}) );
// => aaa aaa/ "aaa "aaa/ aaaaa

// Replace any 'word' that does not start with " AND does not end with /, three matches expected
var regex = new RegExp("(" + left + word + right + ")|\\b" + word + "\\b", 'g')
console.log( text.replace(regex, function(x, g) { return g || "" + x + "";}) );
// => aaa aaa/ "aaa "aaa/ aaaaa

Note:

*

*I use whole word matching here via \b, word boundary (and \w construct in the negated character class in one of the workarounds)

*If right and left chars/strings contain special regex metacharacters, mind to escape them before using as part of a regex

*Same escaping need might arise for the word variable, but in that case, if the word starts or/and ends with a special regex metacharacter, word boundaries (\b) will no longer work, you will need to use adaptive/dynamic word boundaries.


text:
Q: MVC4 many-to-many dynamic model binding Alright. I'm not sure how to explain this correctly, and the title of this question might be wrong. I have a many to many relationship between Reference and Category:
public class Reference
{
    public int Id { get; set; }
    public string Headline { get; set; }
    public virtual ICollection<Category> Categories { get; set; }
}
public class Category
{
    public int CategoryId { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Reference> References { get; set; }
}

On creation of a Reference entry the user should be able to add as many categories (in form of a drop down list with all available categories) as needed. Here's what I've come up with so far for the view for the model binder to figure it all out without any logic in the controller to create related data:

Name

          <select name="Categories[0].Name" value="">
             @{
               var db = new DbContext();
               var categories = db.Categories.ToList();
               foreach (var c in categories)
               {
                    <option value="@c.CategoryId">@c.Name</option>
               }
              }

          </select>

     <input type="submit" value="Add another category" id="AddCat" />

So everytime the user clicks the Add new category button a new drop down list is created with name="Category[int].Name".
This would work with a one-to-many (one category for a reference) relationship and text boxes instead of drop down lists.
This is not very pretty looking MVC (its very webform'ish) :)
How would you do this?
UPDATE - forgot to mention the result when submitting the data.
New Categories are created. If I choose 2 categories for the reference, two new categories are created with Name property from CategoryId of the original categories. Relations are created between the reference and the new categories. Funky huh :)

A: It looks like the Default ModelBinder doesn't really know how to map your Categories to existing Categories in the database. This is where you might want to consider implementing either AutoMapper (https://github.com/AutoMapper/AutoMapper/wiki/Getting-started) or your own structure to map your new Reference with list of existing Categories - you would just need to iterate over the collection of CategoryIDs you are already sending, retrieve them from the DB and overwrite your Reference.Categories.

A: Actually it was very simple. Just had to give the drop down lists name="Category[int].CategoryId" insted of .Name. I then manually loop through the property and binding it. New categories was not created when manually binding.

redpajama_set_name: RedPajamaStackExchange


text:
Q: PyQt5 coding Problam from PyQt5 import QtGui
from PyQt5 import QtWidgets
from PyQt5 import QtCore
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtCore import QRect
import sys

class Mywindow(QMainWindow):

def __init__(self):

super(Mywindow, self).__init__()

self.out = ""

self.con = {'L': '1', 'O': '2', 'V': '3', 'E': '4'}

self.setFixedSize(400, 400)

self.btn1 = QtWidgets.QPushButton(self)

self.lab1 = QtWidgets.QLabel(self)

self.lab2 = QtWidgets.QLabel(self)

self.line1 = QtWidgets.QLineEdit(self)

self.initUI()

self.show()

def initUI(self):

self.btn1.setText("Enter")

self.btn1.move(200, 150)

self.btn1.clicked.connect(self.action)

self.lab1.setText("input :")

self.lab1.setStyleSheet('font-size:20px ;color:blue')

self.lab1.move(100, 150)

self.line1.text()

self.line1.move(80, 200)

def action(self):

for i in self.line1.text():

self.out += self.con[i.upper()]

self.lab2.setText(self.out)

self.lab2.setStyleSheet('font-size:30px ; color :red')

self.lab2.move(200, 250)

if __name__ == '__main__':

app = QApplication(sys.argv)

win = Mywindow()

win.show()

sys.exit(app.exec_())

I have 2 problems in this code:

*

*If I enter the letter in line edit out is coming. But when I clear the line edit and enter again previous output are still there and out put coming together... I wanted method is when i clear the line edit i need out put also clear.

*If I enter out of letter LOVE application will closed. I don't want like that.
This code I make TkInter it's working nicely, but Pyqt5 has showing this problem.

A: You only need to reset self.out value at the begging of each action:
from PyQt5 import QtGui
from PyQt5 import QtWidgets
from PyQt5 import QtCore
from PyQt5.QtWidgets import QApplication, QMainWindow
from PyQt5.QtCore import QRect
import sys

class Mywindow(QMainWindow):
   def __init__(self):
      super(Mywindow, self).__init__()
      self.out = ""
      self.con = {'L': '1', 'O': '2', 'V': '3', 'E': '4'}
      self.setFixedSize(400, 400)
      self.btn1 = QtWidgets.QPushButton(self)
      self.lab1 = QtWidgets.QLabel(self)
      self.lab2 = QtWidgets.QLabel(self)
      self.line1 = QtWidgets.QLineEdit(self)
      self.initUI()

   def initUI(self):
      self.btn1.setText("Enter")
      self.btn1.move(200, 150)
      self.btn1.clicked.connect(self.action)
      self.lab1.setText("input :")
      self.lab1.setStyleSheet('font-size:20px ;color:blue')
      self.lab1.move(100, 150)
      self.line1.text()
      self.line1.move(80, 200)

   def action(self):
      #clear output
      self.out = ''

      for i in self.line1.text():
         self.out += self.con[i.upper()]
         self.lab2.setText(self.out)
         self.lab2.setStyleSheet('font-size:30px ; color :red')
         self.lab2.move(200, 250)

if __name__ == '__main__':
   app = QApplication(sys.argv)
   win = Mywindow()
   win.show()
   sys.exit(app.exec_())

You can also use keyPressEvent to clear or set output dynamically.


text:
Q: How to extract only paragraph part from a link excluding other links from a web page? I am trying to extract sentences from a web page, but I am unable to exclude other links or side icons presented in that web page.
I am trying to find all the occurrences of 'p' from a web page (meaning paragraph) but I am getting other results as well which are not required.
My Code:
  import re
  from nltk import word_tokenize, sent_tokenize, ngrams
  from collections import Counter
  from urllib import request
  from bs4 import BeautifulSoup

  url = "https://www.usatoday.com/story/sports/nba/rockets/2019/01/25/james-harden-30-points-22-consecutive-games-rockets-edge-raptors/2684160002/"
  html = request.urlopen(url).read().decode('utf8')
  raw = BeautifulSoup(html,"lxml")

 partags = raw.find_all('p') #to extract only paragraphs
 print(partags)

I am getting the following output (posting as an image because copying pasting will not look that tidy)
[![enter image description here][1]][1]

https://i.stack.imgur.com/rGC1P.png
But I would like to extract only this kind of sentences from the link, is there any additional filter which I could apply.
[![enter image description here][1]][1]
https://i.stack.imgur.com/MlPUV.png'
Code after Valery's feedback.

partags = raw.get_text()
print(partags)

Output which I am getting(it has links and others in JSON format as well)
This is just sample from the full output:

James Harden extends 30-point streak, makes key defensive stop
{
    "@context": "http://schema.org",
    "@type": "NewsArticle",
    "headline": "James Harden extends 30-point streak, makes key defensive stop to help Rockets edge Raptors",
    "description": "James Harden scored 35 points for his 22nd consecutive game with at least 30, and forced Kawhi Leonard into a missed 3 at buzzer for 121-119 win.",
    "url": "https://www.usatoday.com/story/sports/nba/rockets/2019/01/25/james-harden-30-points-22-consecutive-games-rockets-edge-raptors/2684160002/?utm_source=google&utm_medium=amp&utm_campaign=speakable",
    "mainEntityOfPage": {
        "@type": "WebPage",
        "@id": "https://www.usatoday.com/story/sports/nba/rockets/2019/01/25/james-harden-30-points-22-consecutive-games-rockets-edge-raptors/2684160002/"
    },

A: bs4 docs about this  BeautifulSoup/bs4/doc/#get-text
import requests
from bs4 import BeautifulSoup as bs

response = requests.get("https://www.usatoday.com/story/sports/nba/rockets/2019/01/25/james-harden-30-points-22-consecutive-games-rockets-edge-raptors/2684160002/")
html = response.text
raw = bs(html, "html")

for partag in raw.find_all('p'):

    print(partag.get_text())

Here is Link to results
So calling get_text() on partags (paragraph tags) produces valid text without noise.


text:
Q: How to properly handle errors in an n-tier application? I have struggled with this since day 1.  It probably doesn't help that I've been surrounded by a lot of code that doesn't even handle errors at all.
Anyway, I'm working with WebForms in your traditional n-tier design: UI->BLL->DAL.  Usually what I do (and I know it's not right) is to try/catch my data operations.  If there is an exception I simply throw it to bubble up.
try
'db operations
catch ex as exception
throw
finally
'close connections
end

So then it bubbles up to the BLL and in there is another try/catch where I'll log the error.  Now I want to alert the user that something is wrong so I throw it again, this way it bubbles to the UI.  At the UI level, I will wrap in a try/catch and if there's an error I'll display a friendly message to them.
What are your thoughts?  What can I do better here?

A: As I understand, you have three try/catches - one for each tier: DAL, BLL,UI.
You should only catch when you are going to do something about it.
From what I understand, you simply retrow from DAL so there's no need for it.
From BLL you log the exeption and that is a good practice since you'll be able to collect data about exceptions to eventually improve the application.
Then you catch at the UI tier to translate the exception into something user friendly. That's OK.
So I would only get rid of the try/catch from the DAL layer - if you really don't do anything more than retrowning the exception.
In some scenarios, it can be usefull to add an identifier at the BLL that is passed to the UI exception and shown to the end users so that if they call support, support personel can correlate the given Id with an exception on the server's log.
That can be done, for instance, adding a Guid or something else meaningfull and unique to Exception.Data collection.

A: Unlike the other answers, I am going to advise removing the try/catch from your UI as well.  Your BLL should catch the exception, log it and then provide some mechanism for the UI to query what errors occurred.
This results in much cleaner UI code, as you do not have to enumerate all the possible exceptions that the business layer may throw.  You can simplify your UI code to:
if (businessObject.doSomeOperation == true) {
   // Do whatever you need to here.
} else {
   // output error message from businessobject
   // something like businessObject.LastErrorMessage();
}

A: you need to throw the exception and catch in UI, Like... In BLL
try
        {
            //your code
        }
        catch (System.Data.SqlClient.SqlException ex)
        {
            if (ex.Number == 547)
            {
                throw new Exception("ActiveRecord");
            }
        }
        finally
        {
            MasterConnection.Close();
        }

Catech the execption in UI and show user friendly message.
 if (e.Exception != null)
    {
        if (e.Exception.InnerException.Message == "ActiveRecord")
        {
            //Show here User freind message
        }
    }


text:
Q: I can not edit a field in my database I have a problem I can not edit  the field birthdate in my database .I need help please.
this is the code.employees.php
    $Nom = mysql_real_escape_string($_POST["nom"]);
    $Id = mysql_real_escape_string($_POST["id"]);
    $Prenom = mysql_real_escape_string($_POST["prenom"]);
    $BirthDate = mysql_real_escape_string($_POST["birthdate"]);
    $rs = mysql_query(" UPDATE users SET nom = '" .$Nom ."', prenom = '" .$Prenom ."', birtdate = '" .$BirthDate."' WHERE id = " .$Id) or die(mysql_error());
    echo json_encode($rs);

A: Your query is referencing a field named birtdate, which according to your question and the spelling in the rest of your code should be birthdate
$rs = mysql_query("UPDATE users SET nom = '" .$Nom ."', prenom = '" .$Prenom ."', birthdate = '" .$BirthDate."' WHERE id = " .$Id) or die(mysql_error());


text:
Q: OnClick Image (Push down Effect) Looking for some help a simple onclick effect, sadly my memory is the same as a Gold fish so i cannot remember what to search to get some help on this.
Here's an example http://www.iconfinder.com/search/?q=
If you click the Logo it kinda moves down like a Push.
Just something like that
Would really appreciate some help thanks.

A: In most cases you should do this in CSS with the :active selector. (https://developer.mozilla.org/en-US/docs/Web/CSS/:active)
If you really do want to use javascript you will have to bind on mousedown (to set the margin/position/class) and on mouseup (to set it back to original) and probably on mouseleave for good measure.


text:
Q: Selenium JavaScript with Mocha beforeEach to create new browser instance for every test I am using Selenium with JavaScript and Mocha as the test framework.
I am trying to create a new webdriver instance before each test case (and also quit driver instance after each test case) using beforeEach() and afterEach() methods in Mocha. This is currently what my tests look like right now:
test = require('selenium-webdriver/testing'),
webdriver = require('selenium-webdriver');

test.describe('User A Actions', function(){
  this.timeout(10000);

  test.describe('User A page 1', function(){
    test.it('should see X on page', function(){
      var driver = new webdriver.Builder().withCapabilities(
        webdriver.Capabilities.chrome()).build();
      driver.get('http://mywebsite.org');

      loginUserA(driver);
      goToPage1(driver);
      // assert some element is there
      driver.quit()
  });

  test.describe('User A page 2', function(){
    test.it('should see Y on page', function(){
      var driver = new webdriver.Builder().withCapabilities(
        webdriver.Capabilities.chrome()).build();
      driver.get('http://mywebsite.org');

      loginUserA(driver);
      goToPage2(driver);
      // assert some other element is there
      driver.quit()
  });
});

As you can see, it is creating a new webdriver instance at the beginning of each test, and also quitting it. I feel it is extremely repetitive to have these at the top of each test. Also, if the test fails, it won't reach driver.quit() which leaves the browser hanging.
I was hoping to put a beforeEach() method and afterEach() method inside the top level describe, so it would resemble something like this:
test.describe('User A Actions', function(){
  this.timeout(10000);

  beforeEach(function(){
    var driver = new webdriver.Builder().withCapabilities(
      webdriver.Capabilities.chrome()).build();
    driver.get('http://mywebsite.org');
  });

  afterEach(function(){
    driver.quit();
  });

  test.describe('User A page 1', function(){
    loginUserA(driver);
    goToPage1(driver);
    // assert some element is there
  });

  test.describe('User A page 2', function(){
    loginUserA(driver);
    goToPage2(driver);
    // assert some other element is there
  });
});

When I try this, I am getting an error ReferenceError: driver is not defined. How can I fix this?

A: Mocha does not change the normal rules of JavaScript scoping. If you do something that does not respect the general rules of scoping in JavaScript, then Mocha won't make it work.
You need to declare driver in your test.describe block rather than in your beforeEach hook:
test.describe('User A Actions', function(){
  var driver; // Declare it here.
  this.timeout(10000);

  test.beforeEach(function(){
    driver = new webdriver.Builder().withCapabilities(
      webdriver.Capabilities.chrome()).build();
    driver.get('http://mywebsite.org');
  });

  // ... etc ...

Also, make sure you use the API exported by Selenium, so test.beforeEach rather than beforeEach directly (same with all the other hooks, including the afterEach you already have). Otherwise, you are skipping the control flow management that Selenium does for you when you use the exported API.


text:
Q: Was Sirius Black Ever Vindicated? As per the Harry Potter books (1-5) we know that Sirius Black was on the run from the Ministry of Magic for the supposed killings of twelve muggles and one wizard by the name of Peter Pettigrew. Many muggles declared that they have witnessed this, thus the Ministry of Magic have been trying to capture Black. Prior to Harry Potter and the Prisoner of Azkaban, Sirius was already on the run for twelve years. After then, he has either been hiding or at Number Twelve Grimmauld Place. In Harry Potter and the Order of the Phoenix, Black was executed by none other than Bellatrix Lestrange. Up to this point, the Ministry was after him.
Was the Black name ever vindicated before or after this incident?


text:
Q: how to know current internet connection run on device? i want know the current internet connection on device??
in android i found the two property to know network type like..

ConnectivityManager.TYPE_WIFI
ConnectivityManager.TYPE_MOBILE

but how to know 3G network??
pls help me out
Thanks in Advance!

A: now i can know 3 type of network as follow..........

ConnectivityManager connec = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);
android.net.NetworkInfo wifi = connec.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
android.net.NetworkInfo mobile = connec.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
NetworkInfo info = connec.getActiveNetworkInfo();
int netSubType = info.getSubtype();e
            if (wifi.isConnected())
            {

             wifi is connected

            }
            else if (mobile.isConnected())
            {

                if(netSubType == TelephonyManager.NETWORK_TYPE_UMTS)
                {
                       3G is connected

                }
                else
                {
                      GPRS is connected

                }

            }

A: try to get subType() with this snippet:
NetworkInfo info = mConnectivity.getActiveNetworkInfo();
int netSubType = info.getSubtype();

then if netSubType is TelephonyManager.NETWORK_TYPE_UMTS, then its a 3G network
Updated: What's 'info' here

A: As far as I have used 3G is coming under ConnectivityManager.TYPE_MOBILE only.
If you are using emulator then you can press F8 to connect and disconnect 3G.
It also disconnects GPRS. for both ConnectivityManager.TYPE_MOBILE is used.


text:
Q: What planets or moons in the Solar system are Class M? A friend of mine has listed as her twitter location that she lives on a Class M planet.
Not everyone tweets from Earth, but I assume she tweets from within the Solar System.
Which planets or moons in the real-life Solar system would match Star Trek's "Class M" designation?
Wikipedia and Memory Alpha have descriptions of what the class M criteria are, but doesn't try to analyze bodies in our Solar system (apart from the Earth) against those criteria.

A: Only Earth is a Class M planet capable of sustaining human life.

A: The original definition of a "Class M planet" referred to "Earth-Mars" conditions.
This web page (which is not necessarily definitive) quotes the original Star Trek pitch from 1964:

IV. Nature and duration of command:
  Galaxy exploration and Class M investigation: 5 years
  [...]
  VII. Consistent with the equipment and limitations of your cruiser class vessel, you will confine your landings and contacts to planets approximating earth-Mars conditions, life, and social orders.

It's quite possible that the 'M' originally stood for "Mars". ("Class E" might have been too easily confused with the word "classy", but that's sheer speculation on my part.) The Wikipedia Class M planet article suggests that the "M" is from the Vulcan "Minshara", but that's a much later invention, from the "Star Trek: Enterprise" episode Strange New World.
Remember that this was written in early 1964, when much less was known about the actual conditions on the surface of Mars. Quoting the Wikipedia article:

Until the first successful Mars flyby in 1965 by Mariner 4, many
  speculated about the presence of liquid water on the planet's surface.
  This was based on observed periodic variations in light and dark
  patches, particularly in the polar latitudes, which appeared to be
  seas and continents; long, dark striations were interpreted by some as
  irrigation channels for liquid water.

A "class M Planet" is one whose surface conditions are suitable for human life without a spacesuit or equivalent. At the time the term was invented, it was thought that both Earth and Mars were class M planets. With closer examination of Mars starting about a year later in 1965, we now know that Earth is the only class M planet in our Solar System.

A: According to Wikipedia, Earth is the only M Class-planet, because only it harbors and sustains natural life.
That said, Mars could be considered Class L - easily terraformable into a habitable planet, assuming that Star Trek terraforming projects mentioned in canon exist.
To wit, our solar system would be classified as follows:

*

*Mercury: Class D (Planetoids that could support life underground)

*Venus:  Class N or Y (Potentially habitable, given atmospheric domes, but the toxic atmosphere would lend credence to it being a 'demon world.'  In the case of Venus, there would be a high pressure to contend with)

*Earth: Class M

*Mars: Class L

*Ceres: Class D (See Mercury)

*Jupiter, Saturn, Uranus, Neptune (Class J or T - Gas Giants)

*Europa, Titan, Io, and some of the other moons could range from Class D to K to L, depending on their suitability to sustain life.

*Enceladus, being a water planet, would be Class O or P

*Pluto, Eris, Xena, and the others (Class D)
And yes, I'm old enough to think that Pluto is a planet :)


text:
Q: find and sort array by lowest value in multidimensional array I have an array that contains a number of arrays. Like this:
array{
    array{
        id => 1
        name => place_1
        lat => 56.1705
        lon => 10.2010
        distance => 1.545
    }
    array{
        id => 14
        name => place_14
        lat => 56.1715
        lon => 10.2049
        distance => 1.765
    }
    //etc etc
}

I need to sort the arrays within the array by distance, from low to high - or at least get the position of the lowest distance in the array (like $array[1][4] == 1.765).
I have done something similar before. Then I did it with a function like this:
function sort_by_dist($a, $b){
    return $a['distance'] - $b['distance'];
}
usort($array, 'sort_by_dist');

However, this will in this case only return bool(true)
I have no idea why it acts this way.
I know this question has probably been asked (and answered) before, but as a non-native speaker of English I am a bit at a loss as to what I should search for.
Thank you for your help!

A: My answer just reformats your function a little to make it more explicit what is going on:
$a = array(
    array(
        'id' => 14,
        'name' => 'place_14',
        'lat' => 56.1715,
        'lon' => 10.2049,
        'distance' => 1.765,
    ),
    array(
        'id' => 1,
        'name' => 'place_1',
        'lat' => 56.1705,
        'lon' => 10.2010,
        'distance' => 1.545,
    ),
);

usort($a, function($a, $b) {
    $d1 = $a['distance'];
    $d2 = $b['distance'];

    if ($d1 == $d2) {
        return 0;
    }
    return ($d1 < $d2) ? -1 : 1;
});

// the array $a is sorted.
print_r($a);

The input array to usort is sorted, usort will return false if the sorting failed and true otherwise.

A: You can use array_multisort by iterating thought the array like so:
function sort_by(&$array, $subkey ) {
    foreach ($array as $subarray) {
        $keys[] = $subarray[$subkey];
    }
    array_multisort($keys, SORT_ASC, $array);
}
sort_by($coords, 'distance');// $coords is now sorted by distance

$coords is your multidimensional array.


text: Q: pulley friction assumptions I have a dispute with this lecturer I have been given over the equation $T_2/T_1=e^{μθ}$. My opinion is that since it is derived from $T_2=T_1+\text{Friction}$, so the first equation is valid ONLY in situations where the speed rotates with constant speed, ie. When there is no acceleration in the wheel of the pulley. He finds my opinion strange, can you advise me please?


text:
Q: Has anyone ever read the Java Language Specification(JLS)? I recently had a question about String and String interning - pretty simple question which I got a quick answer to. But lo and behold I got a detailed answer to that same question on pg. 29 of the JLS 3rd Edition. It's really interesting that a lot of the questions we asked are answered in the JLS but its such a boring 600 page read (the 4th Edition is even bigger). How bout you guys how many of you have picked up the JLS lately for a leisurely read?

A: I've referenced it a couple of times, but for light reading I enjoy the VM spec a bit more.

A: I have read all three editions, but not recently. Some of it is really dull (Chapter 16 on Definite Assignment, for example). But I rarely find I need to look something up, and I'm not about to for a question on this site. Really a lot of questions should simply be answered with a reference to docs or a bugs database.

A: I read a good chunk of it five or six years back for a compilers class.  We were tasked with implementing random bits of the Java compiler and my intention was to go way past what the assignments actually entailed.  It was one of the most fun and interesting projects I ever did, especially seeing it work.  I never did complete it, though - didn't even really get as far as generating bytecode.

A: I sometimes read things from here and there, when there is something specific that I need to find out (for example details of how Java's memory model is defined). I have never read the full JLS. I suppose that only language implementors will need to read it all.


text:
Q: getting list of installed programs and installing them again on another drive I will be switching hard drives and upgrading to an ssd drive.
The questions I have are:
1) How can I get a list of programs currently installed on my Ubuntu 13.04 machine.
2) how can install those programs again on the new 13.10 drive without reinstalling each program one by one.
Thanks

A: Alternatively you can use Aptik to do this task using a GUI instead a CLI (personally I prefer the CLI method described above, but here you have another possible solution). Aptik allows you to Backup & Restore your favourite App's, PPA's and many more!
You can get Aptik from official PPA using this simple line:
sudo apt-add-repository -y ppa:teejee2008/ppa && sudo apt-get update && sudo apt-get install aptik

Or:
sudo apt-add-repository -y ppa:teejee2008/ppa
sudo apt-get update
sudo apt-get install aptik

Here you have more info about Aptik:
I used several times in university computers (I'm the SysAdmin) after a fresh Ubuntu installation and this tool help me to save a lot of time.
Also I recommend you Timeshift to make an OS image backup from same author (Clonezilla randomly failed when restoring an HDD image disk into a SSD and really), but also I recommend you Ubuntu AfterInstall wich you can to install a lot of useful software (restricted extras, VLC, etc...) using only a few mouse clicks.

A: The following will get a list of all installed packages and store that list into a file in your user directory:
dpkg --get-selections | grep -v deinstall > ~/packages.list

Then to use that to install the packages on another PC:
sudo dpkg --set-selections < ~/packages.list; sudo apt-get -u dselect-upgrade


text:
Q: org.apache.tiles.util.TilesIOException: JSPException including path '/login.jsp' I m new to tiles and strut2.
I am not able to understand that when I use the HTML tag in login.jsp page then it works fine but at the same time if I code in struts tag in login.jsp then it gives an error. why this is happening I am not able to understand. The following code and error are given below ..kindly help me

HTTP Status 500 - Internal Server Error
type Exception report
messageInternal Server Error
descriptionThe server encountered an internal error that prevented it
from fulfilling this request.
exception
javax.servlet.ServletException: Error executing tag: JSPException
including path '/baseLayout.jsp'.
root cause
org.apache.tiles.TilesException: JSPException including path
'/baseLayout.jsp'.
root cause
org.apache.tiles.util.TilesIOException: JSPException including path
'/baseLayout.jsp'.
root cause
org.apache.tiles.util.TilesIOException: JSPException including path
'/login.jsp'.
root cause
The Struts dispatcher cannot be found.  This is usually caused by
using Struts tags without the associated filter. Struts tags are only
usable when the request has passed through its servlet filter, which
initializes the Struts dispatcher needed for this tag. - [unknown
location]
note The full stack traces of the exception and its root causes are
available in the GlassFish Server Open Source Edition 4.1 logs.

web.xml
  <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns="http://java.sun.com/xml/ns/javaee"
   xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
   http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
   id="WebApp_ID" version="2.5">
   <display-name>Struts2Example15</display-name>

   <context-param>
   <param-name>
      org.apache.tiles.impl.BasicTilesContainer.DEFINITIONS_CONFIG
   </param-name>
   <param-value>
      /WEB-INF/tiles.xml
   </param-value>
   </context-param>

   <listener>
   <listener-class>
      org.apache.struts2.tiles.StrutsTilesListener
   </listener-class>
   </listener>

    <welcome-file-list>
      <welcome-file>index.jsp</welcome-file>
   </welcome-file-list>

   <filter>
   <filter-name>struts2</filter-name>
   <filter-class>
   org.apache.struts2.dispatcher.FilterDispatcher
   </filter-class>
   </filter>

   <filter-mapping>
      <filter-name>struts2</filter-name>
      <url-pattern>/*</url-pattern>
   </filter-mapping>

</web-app>

struts.xml
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>

    <package name="default" extends="struts-default">
        <result-types>
            <result-type name="tiles" class="org.apache.struts2.view.tiles.TilesResult"/>
            </result-types>
        <action name="loginAction" class="package_entry.loginAction" method="execute">
            <result name="getin">welcome.jsp</result>
             <result name="user_login">user_login.jsp</result>

        </action>

    </package>
</struts>

index.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
        <%@page language="java"%>
    <%@taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles" %>
    <tiles:insertTemplate template="/baseLayout.jsp">
        <tiles:putAttribute name="tiles" value="this is tes framework" type="string"/>
            <tiles:putAttribute name="header" value="/header.jsp" />
            <tiles:putAttribute name="menu" value="/menu.jsp" />
            <tiles:putAttribute name="body" value="/body.jsp" />
            <tiles:putAttribute name="footer" value="/footer.jsp" />
    </tiles:insertTemplate>

menu.jsp
<%@taglib uri="/struts-tags" prefix="s"%>
Login

Register

Contact

loging.jsp
<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles" %>
<tiles:insertDefinition name="login.def"/>

tiles.xml
<tiles-definitions>

<definition name="baseLayout" template="/baseLayout.jsp">
<put-attribute name="title"  value="Template"/>
<put-attribute name="header" value="/header.jsp"/>
<put-attribute name="menu"   value="/menu.jsp"/>
<put-attribute name="body"   value="/body.jsp"/>
<put-attribute name="footer"   value="/footer.jsp"/>
</definition>

<definition name="login.def" extends="baseLayout">
<put-attribute name="title"  value="Login form"/>
<put-attribute name="body"   value="/login.jsp"/>
</definition>

<definition name="register.def" extends="baseLayout">
<put-attribute name="title"  value="Register"/>
<put-attribute name="body"   value="/register.jsp"/>
</definition>

<definition name="contact.def" extends="baseLayout">
<put-attribute name="title"  value="contact"/>
<put-attribute name="body"   value="/contact.jsp"/>
</definition>

</tiles-definitions>

login.jsp
<%@taglib uri="/struts-tags" prefix="s"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>

        <s:form>
            <s:textfield name="email_id" label="Email"/>
            <s:password name="password" label="Password"/>
            <s:submit value="login"/>
        </s:form>

A: Most probably you have to add the relative path to each definition
For instance change
value="/login.jsp"/>

in
value="/WEB-INF/path/to/your/login.jsp"/>

Therefore:
<definition name="login.def" extends="baseLayout">
   <put-attribute name="title"  value="Login form"/>
   <put-attribute name="body"   value="/WEB-INF/path/to/your/login.jsp"/>
</definition>

In addition I do not see anywhere your tile render and configurer. Have you added tiles into your pom?


text:
Q: Rails 4 client side validation Since upgrading my site to Rails 4, the client-side-validations gem has stopped working for me. I have had a look at the various alternatives such as jquery-validation-rails and judge, which involve writing quite a bit of javascript, especially for a site so large. And in the case of jquery-validation-rails, re-doing all the validation rules client side. Considering Rails is such a popular framework, it surprises me that there is no 'easy' option. Is there any gem which anyone else is aware of, which does validation as well as the client-side-validation gem?
Or is the best alternative to use the ModelName.validators method mixed with some ajax, and do the validation through the jquery-validation-rails gem?

A: I was able to use a fork of the original client_side_vlaidations that is very active at the moment. I am using the latest version of simple_form, rails 4.1.8, and this client_side_validations. Simple setup with basic config.

A: From the Google.
http://rubygems.org/gems/rails4_client_side_validations
https://github.com/amatsuda/html5_validators
Also this guy seemed to have gotten the same gem you are using to work by using the 4-0-beta branch.
Client Side Validations and Rails4
If the 4-0-beta branch works for you, consider helping to maintain the gem to keep it alive.
To use a certain git repo version in your Gemfile:
gem 'client-side-validations', :git => 'https://github.com/bcardarella/client_side_validations/tree/4-0-beta'

A: While the client side validations will work for the simple cases, they'll require an enormous amount of workarounds to work with more complicated scenarios (for instance - conditional validations).
I would recommend using Judge instead, which give you more control.

A: I know the question is old, but how about good old require: "require"?
For example in view:
<%= f.text_area :body, placeholder: "Write your review here...", class: "form-control", rows: "5", required: "required" %>

A: If you are using Bootstrap Form for Rails, you can give bootstrap_validator_rails a try.
https://github.com/huynhquancam/bootstrap_validator_rails


text:
Q: Parsing a list using java streams My usecase is I have list of Restaurants objects with attributes as city, type, rating and I want to print the list by highest rating for given combination of (city, type). As I created this example to mess with java stream, please reply how it can be achieved using streams:
import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;
import java.util.Map;
import java.util.Optional;
import static java.util.stream.Collectors.maxBy;
import static java.util.stream.Collectors.groupingBy;
import static java.util.Comparator.comparingLong;

class Restaurant {
  public String city; // Any city
  public String type; // Tier1, Tier2, etc.
  public Long rating; // for simplicity sake, assume its a number from 1 to 5
  public Restaurant(String city, String type, Long rating) {
    this.city = city;
    this.type = type;
    this.rating = rating;
  }
  public String getCity() { return city; }
  public String getType() { return type; }
  public Long getRating() { return rating; }
}

public class HelloWorld
{
  public static void main(String[] args)
  {
    List<Restaurant> mylist = new ArrayList<Restaurant>();
    mylist.add(new Restaurant("City1", "Tier1", 1L));
    mylist.add(new Restaurant("City1", "Tier1", 2L));
    mylist.add(new Restaurant("City1", "Tier2", 1L));
    mylist.add(new Restaurant("City2", "Tier1", 1L));
    mylist.add(new Restaurant("City2", "Tier1", 3L));
    mylist.add(new Restaurant("City2", "Tier3", 1L));
    // expected outcome: (City1, Tier1, 2), (City1, Tier2, 1), (City2, Tier1, 3), (City2, Tier3, 1)

    Map<String, Map<String, Optional<Restaurant>>> mymap =
   mylist.stream().collect(groupingBy(Restaurant::getCity, groupingBy(Restaurant::getType, maxBy(comparingLong(Restaurant::getRating)))));
   /* Upto here everything is fine, but I want to have everything stored back into a list. Tried flatMap(Map::values).collect(Collectors.toList()); but it fails*/
  /*My output list should have 4 objects of Restaurant*/
  /*(City1, Tier1, 2), (City1, Tier2, 1), (City2, Tier1, 3), (City2, Tier3, 1)*/
  }
}

A: First, you can create composite key to get rid of nested maps. The Arrays.asList(r.getCity(), r.getType()) is what you need. Next, groupingBy is not well suitable in your case, as you should handle those nasty optionals. Instead use toMap collector with custom merging function:
Map<List<String>, Restaurant> mymap = mylist.stream().collect(
        toMap(r -> Arrays.asList(r.getCity(), r.getType()), r -> r,
                BinaryOperator.maxBy(comparingLong(Restaurant::getRating))));

Now mymap.values() is the flat collection of restaurants as you want. If you really want the List, you can dump it into one:
List<Restaurant> list = new ArrayList<>(mymap.values());

A: The code snippet below should produce the result you are after:
    List<Optional<Restaurant>> resultList = mymap.values()
                                                 .stream()
                                                 .flatMap(map -> map.values().stream())
                                                 .collect(Collectors.toList());

mymap.values().stream() produces a Stream<Map<String, Optional<Restaurant>>>. flatMap() then maps that stream to a Stream<Optional<Restaurant>>, and collect(Collectors.toList()) collects that stream into a List<Optional<Restaurant>>.

A: using Java 8 stream API:
List<Restaurant> sortedList = mylist.stream()
.sorted((restaurant1, restaurant2) -> Long.compare(restaurant1.getRating(), restaurant2.getRating()))
.collect(Collectors.toList());

A: I haven't worked with Java 8 yet but my guess is
mylist.stream().sorted(new Comparator<Restaurant>() {
     public int compare(Restaurant r1, Restaurant r2) {
        // impl here how your restaurant should be compared
        // (by rating or smth. else)
     }
}).collect(groupingBy( .../ al the rest stuff here/ ...));


text:
Q: c++: why open files using .open("a: I'm going through the book "Object-Oriented Programming in C++" by Robert Lafore. In the chapter called "Streams and Files", sometimes files are opened using for instance ifstream is("edata.dat", ios::binary); and sometimes the syntax file.open("a:test.dat"); (after the object file has been created). The syntax ifstream is("edata.dat", ios::binary); is well explained and I understand it, but he doesn't explain what a: means or why one case is preferable over the other one. I tried to google it, but I'm not sure what to search for. Any help would be appreciated.

A: a:test.dat is a valid path on DOS and Windows systems. It means "the file named 'test.dat' on the current directory of drive 'a'".
Drives "a" and "b" on DOS and Windows are reserved for floppy disk drives. Modern computers usually don't come with floppy drives anymore, and those drives are thus not accessible. They're still reserved though even by modern Windows, which is why the first storage filesystem starts with "c".
If you replace a:test.dat with c:test.dat, this will refer to the
"test.dat" file on the current directory of the "c" drive.
The current directory on Windows can be changed using the _chdir() function. By default, it's the root directory of the drive.


text:
Q: Can't register/login with new FB account In order to test the user registration in CocoaLibSpotify, I created a new Facebook account.
After creating the account (and validating the email address), I tried to log in to my app (using CocoaLibSpotify) but got the following error: "General Permanent Error" (error code 10 from CLS).
What could be wrong?
Notes:

*

*I've triple-checked the login credentials and have logged in to the account on Facebook.

*Trying to log in to another account with invalid credentials gives me another error.

*Also, logging in to an account with valid credentials works just fine.

*I haven't logged in to the account using any other Spotify client (desktop, regular Spotify client etc)

EDIT:
In order to move forward, I logged in to the account on desktop and accepted the Facebook stuff and played a track. After that, I tried logging in through CLS again but got the error: "Needs a premium account". Aren't users supposed to get a 48-hour free trial upon first mobile login?

A:
Aren't users supposed to get a 48-hour free trial upon first mobile login?

From Spotify's own client, yes. libSpotify applications aren't eligible to create new users and trials at the moment.


text:
Q: where can I find the documentation for the apple's Darwin API where can I find the documentation for the apple's Darwin API?
such as mach_task_basic_info mach_msg_type_number_tand so on.
I find many documentations of apple's Darwin API is empty on the developer.apple.com


text:
Q: website popup notification I would like make a popup appear on my site like ones that come up when you facebook friend request someone.  im do not want the javascript alert();.  if possible can this popup notification be triggered from a boolean value from a database? thanks

A: Perhaps something like this will meet your needs? A search on Google for "lightbox" will get you thousands of useful links.


text:
Q: Get location in background AND when app is terminated Is there a way to get
1.
Location notification when the app is in the background
2.
Location notification After the app is terminated
3.
When terminated - get the location notification for movement of less than 500 meters
ALL IN SAME APP?
(i've seen articles that says you should use
[myLocationManager startMonitoringSignificantLocationChanges];

INSTEAD of -
[myLocationManager startUpdatingLocation];

can i use both?)
thanks


text:
Q: Fetching lat lng values in a faster way using a php script I have a script shown below which I am using to get lat and lng values of an address stored in a $address variable.
if(my condition here){
    $prepAddr = urlencode($address);
    $geocode = file_get_contents('https://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&sensor=false&key=myapikey');
    $output= json_decode($geocode);

    $address_lat = $output->results[0]->geometry->location->lat;
    $address_lng = $output->results[0]->geometry->location->lng;
}

The script works totally fine. But the problem is I have more than a 1000 addresses that I have to loop through and create a csv result based on the data. When I do this it takes a really long time and always fails after generating results for 200 approx. items.
So how do I get the lat lng values in a php script in a faster way?
I did test to see if the delay was because of csv generation but no, if I replace the lat lng generation code above with static values for lat and lng then the csv is generated quicker(in < 10 sec or so). But with the file_get_contents it takes like 6 to 10 minutes.
So for sure the problem is with the way I am getting lat and lng values. I guess may be some one can let me know of a quicker way to get lat lng values using full address inside of a PHP script.
May be there is a way to include the javascript code inside the PHP script? I don't know how to do that though? And if that is going to be fast?

A: The best way to achieve this is to create a function that fetch one address at a time and retrieve its lat, lng from google API and store it in the address table (add two additional column in address table for lat, lng and one more column to maintain the status of the address whose lat, lng are fetched)
Put this function on CRON on every seconds or what ever time is suitable for you. Now when you required the CSV, fetch the records from the table and make csv from it.
NOTE: There is a per second and day hit limit of google API, in case of your for loop the limit will reach for seconds after certain loops.

A: I'm not sure your need for accuracy, but you could use MaxMind's "Free World Cities Database".
And on that page there is another link to a "GeoNames" database that could also be useful.
Pending these databases will fill your needs you could then import the file data into a database and run queries through them to get your lat/lng much quicker (with some setup of course)..
Not saying this is the best option, just another option..


text:
Q: Jmeter JSON Extractor to get a token value inside a response So Here is the response that I am getting, I am unable to extract "webToken", what should be JSON path expression... I have tried $..webToken and $.webToken.
I am trying to use this in JMeter so I can pass the value
        }
</script>

A: You response is not JSON so your expression will not work.
You can use this regexp:

"webToken":"([^"]+?)"

Configuring Regular_Expression_Extractor this way.


text:
Q: Ember.JS : 'serializer.get is not a function' So i'm learning EMBER JS from codeschool and i sometime like to save my current progress into my computer. Everything went nice and smoothly until we started to see Array Controller ( and by nice and smoothly i mean everything was working fine, as it does on codeschool ). Since then i got this error :
Error while processing route: index serializer.get is not a function TypeError: serializer.get is not a function
at ember$data$lib$system$store$serializer$response$$normalizeResponseHelper (http://localhost:63342/Cours/EmberJS/Flint/js/vendors/ember-data.js:5696:24)
at http://localhost:63342/Cours/EmberJS/Flint/js/vendors/ember-data.js:7450:31
at Object.Backburner.run (http://localhost:63342/Cours/EmberJS/Flint/js/vendors/ember.js:222:25)
at ember$data$lib$system$store$$Service.extend._adapterRun (http://localhost:63342/Cours/EmberJS/Flint/js/vendors/ember-data.js:13030:37)
at http://localhost:63342/Cours/EmberJS/Flint/js/vendors/ember-data.js:7449:19
at tryCatch (http://localhost:63342/Cours/EmberJS/Flint/js/vendors/ember.js:54770:14)
at invokeCallback (http://localhost:63342/Cours/EmberJS/Flint/js/vendors/ember.js:54785:15)
at publish (http://localhost:63342/Cours/EmberJS/Flint/js/vendors/ember.js:54753:9)
at http://localhost:63342/Cours/EmberJS/Flint/js/vendors/ember.js:31568:7
at Queue.invoke (http://localhost:63342/Cours/EmberJS/Flint/js/vendors/ember.js:901:16)

So i thought, somehow, my ember.js or ember-data.js was the culprit but nay, it's not ( im up-to-date ). I think the bug is somewhere located in the way i initialize my Route ( eventho i copy/pasted the content of my local files from those on codeschool who works perfectly ) and according to the error message, i think the index route is responsible so here is my router map :
App.Router.map(function() {
this.route('credits', { path: '/thanks' });
this.resource('products', function() {
    this.resource('product', { path: '/:product_id' });
});
this.resource('contacts', function() {
    this.resource('contact', { path: '/:contact_id' });
});

});
And here's my route ( they're all made like this one, except that i sometime search in 'contact' rather than 'product' )
App.IndexRoute = Ember.Route.extend({
model: function(){
    return this.store.findAll('product');
}

});
We also use the fixture adapter so it might come from this too :
App.ApplicationAdapter = DS.FixtureAdapter.extend({});

Does anybody ever got this bug about the serializer ? Thank you'all in advance !

A: I believe this is due to the removal of the Fixture Adapter in a recent ember-data release.  I'm just learning ember myself, but I was finally able to get rid of this error using a combination of reverting to a slightly older ember-data version and installing the replacement Fixture Adapter addon.
In your application dir, update the ember-data line in both bower.json and package.json to:
   "ember-data": "1.0.0-beta.19.2",

and in package.json add this line after the ember-data one:
   "ember-data-fixture-adapter": "^1.0.0",

Delete the bower_components and node_modules dirs in your application, and then run npm install and bower install from your application's home dir.


text:
Q: How to use PanelColorSettings in custom Gutenberg block? I'm working on a custom Gutenberg block. I have used <PanelBody> <BaseControl> and <ColorPalette> to create some custom color pickers, however, it seems like it would be more efficient to use the built-in <PanelColorSettings> component.
Has anyone used <PanelColorSettings> component in a custom block? The only discussion of this technique I could find was here: https://stackoverflow.com/questions/50480454/add-the-inbuilt-colour-palette-for-gutenberg-custom-block

A: First you need to import the component -
const {
    PanelColorSettings,
} = wp.editor;

then inside the InspectorControls you call the component
<PanelColorSettings
                    title={ __( 'Color Settings' ) }
                    colorSettings={ [
                        {
                            value: color,
                            onChange: ( colorValue ) => setAttributes( { color: colorValue } ),
                            label: __( 'Background Color' ),
                        },
                        {
                            value: textColor,
                            onChange: ( colorValue ) => setAttributes( { textColor: colorValue } ),
                            label: __( 'Text Color' ),
                        },
                    ] }
                >

</PanelColorSettings>

A: <PanelColorSettings
  title={__('Color Settings')}
  colorSettings={[
    {
      value: props.attributes.backgroundColor,
      onChange: (color) => props.setAttributes({ backgroundColor: color }),
      label: __('Background Color')
    },
    {
      value: props.attributes.textColor,
      onChange: (color) => props.setAttributes({ textColor: color }),
      label: __('Text Color'),
      colors: [
        {
          name: 'white',
          color: '#fff'
        },
        {
          name: 'black',
          color: '#222'
        }
      ]
    }
  ]}
/>


text:
Q: Passing File Data using Ajax and jQuery I have a form with both file and text inputs. I want to pass file to a different php file and text data to a different file. I am having trouble passing file data to the other php file using jQuery and Ajax

A: We can achieve the same using the following code. The code will post the uploaded file to the server using AJAX
HTML File
<html>
<body>
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-1.9.0.min.js"></script>

<input id="default_file" type="file" name="music"/>

<script>
    $('#default_file').change(function(){
//on change event
alert("hi");
formdata = new FormData();
if($(this).prop('files').length > 0)
{
    file =$(this).prop('files')[0];
    formdata.append("music", file);
}
alert("hi2");

$.ajax({
url: "php_file_path.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (result) {
     alert(result);
     // if all is well
     // play the audio file
}
   });
   });
  </script>
  </body>
  </html>

PHP File
<?php
if ($_FILES["music"]["error"] == UPLOAD_ERR_OK)
{
    $file = $_FILES["music"]["tmp_name"];
 echo $file;
    // now you have access to the file being uploaded
    //perform the upload operation.
    //move_uploaded_file( $file, "uploads/" . $file);
}
echo "ji";
?>


text:
Q: Using Apache proxy to foward traffic to tinyproxy I need to find a way to proxy some traffic on port 80 to tinyproxy running on a separate port. We have a client working behind a very strict firewall with only port 80 open (and cannot get to sites like meebo.com, etc). I was hoping I could create a CNAME to our domain and a virtual host on apache, catch the request for that new CNAME and forward the traffic right to tinyproxy running on the same box.
I know tinyproxy is setup and working correctly, however, when I try to pass in my traffic through Apache, I don't even see any traffic.
Does anyone have a proposed solution? Here is my VirtualHost entry:
<VirtualHost *:80>
    ServerName sub.domain.com
    ProxyPass / http://127.0.0.1:50001/
    ProxyPassReverse / http://127.0.0.1:50001/
</VirtualHost>

where Tinyproxy is running on port 50001.

A: I don't think it's going to be possible.
ProxyPass is for opaque proxying of web-servers - not redirecting to a proxy. But it might have worked except that AFAIK VirtualHost can only be identified by the Host: header in the http request - so only works for the real request.
In other words - the clients will set a Host: header for the site they want to reach, so your virtualHost is never used.

A: To clarify, the host-name of your domain is http://sub.domain.com/..., and you've verified that Tinyproxy serves your site when requested through tinyproxyhost:50001?
I would consider using iptables on your gateway to selectively NAT requests destined for sub.domain.com on port 80 to tinyproxyhost on port 50001.  Assuming sub.domain.com is at address 12.34.56.78, and that tinyproxy is running on 10.11.12.13:

iptables -t nat -A PREROUTING -p tcp -d 12.34.56.78 --dport 80 -j DNAT \
    --to 10.11.12.13:50001

If you really want to continue using Apache for this, are you sure you've enabled mod_proxy completely?  Ensure you have the following in your config too:

ProxyRequests Off

Order deny,allow
Allow from all

What happens when you try to access http://sub.domain.com in this configuration?  What output do you get in your Apache access_log and error_log?


text:
Q: Detecting Missing Modules Dynamically (Python) When working on bigger projects, I'm very keen on error detection and handling. I'm using some modules that the user may or may not have installed, so I need to account for this possibility.
I'd like to know of a way to detect what modules are missing while attempting to import them. Currently, I have a set of try/except blocks watching for ImportErrors and appending the names of the error-producing modules to a list.
Current Code:
errors = []
try:
    import socket
except ImportError:
    errors.append('socket')
    pass
try:
    import shutil
except ImportError:
    errors.append('shutil')
try:
    import urllib
except ImportError:
    errors.append('urllib')
    pass
if len(errors) > 0:
    print colors.red + '[!] ' + colors.end + 'Error: The Following Module(s) Encountered Error(s): \n'
    for i in range(len(errors)):
        print '\t' + errors[i]
    print colors.blue + '\n[*] ' + colors.end + 'Please Install/Reinstall the Listed Modules'
    quit()

This method seems to work just fine, but I'd like a way that will take up less overall room. The main reason for using this multi-try/except block method is that I need to detect which module had trouble importing.

A: import importlib

moduleNames = ['socket', 'shutil', 'urllib']

missingModuleNames = []

for moduleName in moduleNames:
    try:
        importlib.import_module (moduleName)
    except:
        missingModuleNames.append (moduleName)

print (missingModuleNames)


text:
Q: Add MongoDB Sink Connector on docker? I have a Ubuntu machine, where I followed this steps in order to run Confluent Platform with docker.
https://docs.confluent.io/platform/current/quickstart/ce-docker-quickstart.html
I can produce and subscribe to messages just fine.
I'm trying to add a MongoDB Sink Connector, in order to sync data with a mongo database.

*

*I've downloaded this zip file https://www.confluent.io/hub/hpgrahsl/kafka-connect-mongodb

*I've edited the etc/MongoDbSinkConnector.properties file with the correct mongo endpoint

*I've uploaded the zip to my Ubuntu machine

*I've created a file Dockerfile with the following content
FROM confluentinc/cp-kafka-connect-base

COPY hpgrahsl-kafka-connect-mongodb-1.4.0.zip /tmp/hpgrahsl-kafka-connect-mongodb-1.4.0.zip

RUN confluent-hub install --no-prompt /tmp/hpgrahsl-kafka-connect-mongodb-1.4.0.zip

*I've executed the following command docker build . -t my-custom-image:1.0.0
Sending build context to Docker daemon  15.03MB
Step 1/3 : FROM confluentinc/cp-kafka-connect-base
 ---> 8fe065fffe44
Step 2/3 : COPY hpgrahsl-kafka-connect-mongodb-1.4.0.zip /tmp/hpgrahsl-kafka-connect-mongodb-
1.4.0.zip
 ---> Using cache
 ---> ed2e4ec7ff97
Step 3/3 : RUN confluent-hub install --no-prompt /tmp/hpgrahsl-kafka-connect-mongodb-1.4.0.zip
 ---> Using cache
 ---> 034f82e2e136
Successfully built 034f82e2e136
Successfully tagged my-custom-image:1.0.0

Am I missing something? My mongo does not get updated
Do I have to edit docker-compose.yml also?
How do I debug this connector, does it have logs?

A: When you run Kafka Connect under Docker (including with the cp-kafka-connect-base) image it is usually in distributed mode. To create a connector configuration in this mode you use a REST call; it won't load the configuration from a flat file (per standalone mode).
You can either launch the container that you've created and then manually create the connector with a REST call, or you can automate that REST call - here's an example of doing it within a Docker Compose:
  kafka-connect-01:
    image: confluentinc/cp-kafka-connect-base:6.2.0
    depends_on:
      - kafka
    ports:
      - 8083:8083
    environment:
      CONNECT_BOOTSTRAP_SERVERS: "kafka:29092"
[…]
    command:
      - bash
      - -c
      - |
        #
        echo "Installing connector plugins"
        confluent-hub install --no-prompt hpgrahsl/kafka-connect-mongodb:1.4.0

        #
        echo "Launching Kafka Connect worker"
        /etc/confluent/docker/run &

        #
        echo "Waiting for Kafka Connect to start listening on localhost ⏳"
        while : ; do
          curl_status=$$(curl -s -o /dev/null -w %{http_code} http://localhost:8083/connectors)
          echo -e $$(date) " Kafka Connect listener HTTP state: " $$curl_status " (waiting for 200)"
          if [ $$curl_status -eq 200 ] ; then
            break
          fi
          sleep 5
        done
        echo -e "\n--\n+> Creating connector"
        curl -s -X PUT -H  "Content-Type:application/json" http://localhost:8083/connectors/mongo-connector/config \
            -d '{
              [… connector JSON config goes here …]
        }'
        sleep infinity

References:

*

*https://rmoff.net/2018/12/15/docker-tips-and-tricks-with-kafka-connect-ksqldb-and-kafka/

*https://developer.confluent.io/learn-kafka/kafka-connect/docker/


text:
Q: How do I know if a file has been fully written when using AWS EFS So I decided to use EFS as a shared filesystem for my EC2 instances. Our microservices, which are deployed on different instances, need to read and write to a shared space. One service basically puts the file to the known location, and the second service accesses it.
Now after reading the documentation and doing some tests myself I realized how latencies work and that files may already exist on disk but not be fully written yet.
Are there any mechanisms to check when files are done replicating? My second service would need to know when the file isn't corrupt anymore.

A: I think you may want to call EFS API in order to retrieve creation status of the file.

The CreateFileSystem call returns while the file system's lifecycle state is still creating. You can check the file system creation status by calling the DescribeFileSystems operation, which among other things returns the file system state.

Be noted that calling API is throttled so you should handle it skillfully.

when files are done replicating

Also you only create a new file at a shared network storage and this should not understand as a replication.


text:
Q: How do I set up Mercurial and hgweb on IIS? I've been looking all over for decent instructions on how to get hgweb working on IIS but I haven't found much of worth.
There's this "step by step" on the Mercurial wiki, but it's not very good.
There's also this and this, but again, I can't find good steps to lead up to where those get started.

A: I just had to install a fresh Mercurial instance yesterday, here's updated instructions for 1.7:

*

*Install Mercurial (these instructions were tested with 1.7)

*Install Python (for Mercurial 1.7, you must use the x86 version of Python 2.6.6)

*You will need to download the hgweb.cgi file from the Mercurial source.  You can download the source by running: hg clone https://www.mercurial-scm.org/repo/hg/

*Create a folder that will be your web application folder.  You will need to copy three things into this folder:

*

*The hgweb.cgi file

*The contents of the Library.zip from your "C:\Program Files\Mercurial" folder

*The Templates folder from your "C:\Program Files\Mercurial"

*You will need to make sure you have Python set up in IIS.

*

*Enable CGI via the following: Control Panel -> Turn Windows Features On or Off -> Roles -> Web Server (IIS) -> Add Role Services -> Check CGI

*Create a new Web Site in IIS and make sure the physical path is the folder you created above

*In the Handler Mappings for the new website, select "Add Script Map".  Enter *.cgi for the request path, c:\Python26\python.exe -u "%s" for the Executable, and Python for the Name.

*You will also need to create a file named "hgweb.config" with contents similar to below.  The path within the file needs to be the location on your drive where you want to store the Mercurial repositories:
[collections]
c:\Mercurial\repos = c:\Mercurial\repos

*Edit the hgweb.cgi file and change the line where it sets the path to your hgweb.config to something like the following (wherever the hgweb.config file is):
config = "C:\Mercurial\hgweb.config"

*Now, open a browser and navigate to http://localhost/mercurial/hgweb.cgi (or whatever is the appropriate URL path you set up in IIS) and you should see the Mercurial Repositories page.

Also, check out Jeremy Skinners blog post .  It's a little outdated, but has some extra nice steps like setting up URL re-writing for cleaner URL's.

A: It seems since Mercurial 1.5.2 was released, these tutorials don't work exactly right.  For one thing, hgwebdir.cgi has been removed, and is now replaced with hgweb.cgi.
The instructions that worked best for me is at eworldui.net:
http://www.eworldui.net/blog/post/2010/04/08/Setting-up-Mercurial-server-in-IIS7-using-a-ISAPI-module.aspx
Those instructions are meant for IIS 7 or greater.  If you're setting this up on IIS 6, I wrote up similar instructions geared toward Win2k3 and IIS 6.0:
http://partialclass.blogspot.com/2010/05/setting-up-mercurial-server-on-win2k3.html
UPDATE:  Shortly after getting this working I learned that BitBucket changed their pricing scheme to offer free, unlimited, private hosting: https://bitbucket.org/.  I would've opted for that in a heartbeat when I was originally working on this project.

A: Use mercurial to clone the mercurial repository:
hg clone https://www.mercurial-scm.org/repo/hg/

you will find hgwebdir.cgi at the top level.  It should install
like any other cgi script.

A: I've been fighting with this setup for mercurial 1.7.2 for the past week or so, I had to do things slightly differently than the above articles do in order to get it working.
Posting here because google kept bringing me back here....
Full instructions posted here
I followed a combination of these instructions and these (in the source)
The main differences are that I had to do the "pure python" install of mercurial otherwise it would complain about missing dlls, and I found it was important to use the "python installers" for pywin and isapi-wsgi.  (maybe this is obvious to experienced python developers, but I'm a python newbie so it was news to me)
Hope this helps somebody and I'm not just making stuff up (I might be, like i said, python newbie)

A: Below are what I did after doing a fair amount of research for geting hgwebdir.cgi setup on IIS6 .  It is based on the following sites:

*

*http://python.markrowsoft.com/iiswse.asp

*http://www.jeremyskinner.co.uk/mercurial-on-iis7/
You'll need to install the following on the server:

*

*Mercurial (I used version 1.5)

*Python 2.6. The version of Python depends on the version of Mercurial installed.
Mercurial 1.5 uses Python 2.6.  Install x86 even if you are running x64.

The steps for me were:

*

*Create a directory for the website.  I used c:\inetpub\wwwroot\hg.

*In IIS, right click on the folder for hg, select properties, select the Home Directory tab.

*Click on the Create application button.  Set the execute permissions to "scripts".

*Still in the Home Directory tab, click on the Configuration button.  In the "Application Configuration" popup, click the Add button to add an application extension. The Executable is c:\Python26\python.exe -u "%s" "%s".  The extension is .cgi. Set the "verbs" to "limit to: GET,HEAD,POST".  Check both Script engine and Verify that file exists.

*In the Directory Security tab, click on the Edit button in the Authentication and access control section.  Uncheck all authentication methods, and check the "Basic authenication" method. Set the Default domain if you like to your Active Directory domain.

*In IIS, click on the Web Service Extensions folder on the left panel. Click on "Add a new Web service extension" link.  Extension name should be Python, the required file is c:\Python26\python.exe -u "%s" "%s".  Make sure the new extension is "Allowed".

Now is a good time to test that Python is working.  Create a file in your new Hg folder called test.cgi.  Paste the following python code:
print 'Status: 200 OK'
print 'Content-type: text/html'
print

print ''
print ''
print '
It works!
'
print ''
print ''

Open the browser to your site, for instance, http://localhost/hg/test.cgi
You should see "It works!" in the browser.
Next let's get the hgwebdir working.

*

*Delete test.cgi

*clone the hg repo to a new directory: https://www.mercurial-scm.org/repo/hg/

*copy hgwebdir.cgi to your web directory: c:\inetpub\wwwroot\hg\ from the cloned hg repo

*Edit the file and change

application = hgwebdir('hgweb.config')
wsgicgi.launch(application)

to

application = hgwebdir('c:\inetpub\wwwroot\hg\hgweb.config')
wsgicgi.launch(application)

*

*Unzip the Library.zip file in the Mercurial directory, c:\Program Files\Mercurial\, to your web directory, c:\inetpub\wwwroot\hg\

*Copy the templates directory from  c:\Program Files\Mercurial\templates\ to c:\inetpub\wwwroot\hg\templates\

*Create a file called hgweb.config in your web directory.

Now is a good time to test it out.  Go to the following URL in the browser, http://localhost/hg/hgwebdir.cgi

*

*Edit hgweb.config, and paste the following:

[collections]
\\server\share$\Hg\ = \\server\share$\Hg\
[web]
allow_push = *
push_ssl = false

These are all my preferences, for instance we have our repos in subdirectories at \\server\share$\Hg.  The web app will run under the permissions of the logged in user via the browser, so they'll need read/write permissions to the share.
The last step is to allow for long connections which can happen when you first clone a repo.  Run the following command to increase the timeout to 50 minutes:
cd \inetpub\AdminScripts\
cscript adsutil.vbs GET /W3SVC/CGITimeout
cscript adsutil.vbs SET /W3SVC/CGITimeout 3000

A: The hg red book contains some much better general instructions than I've seen in other places.  They are not IIS specific, but they are quite good:
http://hgbook.red-bean.com/read/collaborating-with-other-people.html#sec:collab:cgi

A: I was running into a "...can not load module..." type error and after some reading, the key for me was to ignore the Library.zip file in the Mercurial folder, and instead use the one from C:\Program Files (x86)\TortoiseHg folder.
That tip I found as #6 in this guide:
http://www.endswithsaurus.com/2010/05/setting-up-and-configuring-mercurial-in.html
Hope this helps someone...

A: I know this is an old question, but I really struggled getting Hg installed on Server 2019 and IIS 10.
Here is what I did to get it working:

*

*Install Python 2.7 which in my case was python-2.7.18.amd64.msi. I will assume it's installed in C:\Python27. Make sure python is added to your path and that pip is installed.

*Install Mercurial as a module using pip at the command line:
pip install mercurial

*Under Default Web Site add a new application called hg and point it to the directory you want to use to use.

*Configure Python as CGI handler in IIS 10.0 for this new website (or the entire web server if you wish). You can do this manually or create/add the follwing to your web.config file:
<system.webServer>
    <handlers accessPolicy="Read, Script">
        <add name="Python 2.7" path="*.cgi" verb="*" modules="CgiModule" scriptProcessor="C:\Python27\python.exe -u "%s"" resourceType="File" />
    </handlers>
</system.webServer>

*In the 'hg' application folder create a hgweb.cgi that looks similar to the following:
#!/usr/bin/env python3
#
# An example hgweb CGI script, edit as necessary
# See also https://mercurial-scm.org/wiki/PublishingRepositories

# Path to repo or hgweb config to serve (see 'hg help hgweb')
config = "hgweb.config"

# Uncomment and adjust if Mercurial is not installed system-wide
# (consult "installed modules" path from 'hg debuginstall'):
# import sys; sys.path.insert(0, "/path/to/python/lib")

# Uncomment to send python tracebacks to the browser if an error occurs:
#import cgitb; cgitb.enable()

from mercurial import demandimport

demandimport.enable()
from mercurial.hgweb import hgweb, wsgicgi

application = hgweb(config)
wsgicgi.launch(application)

*In the 'hg' application folder create the hgweb.config file and point it at your repos like the following:
[collections]
C:\Web\www\hg\repos\ = C:\Web\www\hg\repos\

*Navigate to http://localhost/hg/hgweb.cgi and enjoy!

A: You can try HgLab. This isn't exactly hgwebdir; rather it is a purely managed Mercurial implementation with push and pull server and repository browser.


text:
Q: Example of SemaphorSlim where maxCount is actually useful I'm having trouble coming-up with a semi-realistic scenario/use-case for where SemaphorSlim's maxCount parameter is a needed feature.  It seems to me that the typical use case for SemaphorSlim is to limit concurrent access to some resources, expressed as "I only want X threads to be able to execute method Xyz() concurrently".  The way I think about this capability is that threads are allowed to enter Xyz() until all "slots" are allocated, and then all other threads wait.  When one "slot" opens up, one of the waiting threads is allowed to occupy or check-out that slot and go ahead executing Xyz().  Someone is responsible for calling Wait and Release.  The most straight-forward way to do this is to have the threads themself call Wait before calling Xyz() and then call Release after they are finished calling Xyz().
So is maxCount simply a feature to guard against bad code?  If you've coded your try/finally properly and you can guarantee that any thread that Waits will Release, then it's impossible CurrentCount to exceed the initial count.
The documentation for maxCount implies that somehow you would call Release more times than Wait and that you want the system to throw if that happens too much.  I can't think of a good use-case for this.


text:
Q: Dark Sky JSON to CSV conversion I'm attempting to convert a dark sky JSON to CSV.
I have managed to get the JSON to load, and give me values for the first time period of the first day, using the following:
##%% Load libraries
import sys
import os
import json
import csv

#%% Get file
# Move to correct directory
os.chdir('C:/GitWorkspace/apidumps\darksky')

# Load data from file
with open('Fraser Ave - Inverkeithing KY11 1EJ.json') as f:
    data = json.load(f)

# Get fields from JSON data
date = data["2020-01-01"]

# Get daily data from JSON data
daily_data = data["2020-01-01"]["hourly"]["data"][0]

# Get fields from daily data
time = daily_data['time']
summary = daily_data['summary']
icon = daily_data['icon']
precipIntensity = daily_data['precipIntensity']
precipProbability = daily_data['precipProbability']
temperature = daily_data['temperature']
apparentTemperature = daily_data['apparentTemperature']
dewPoint = daily_data['dewPoint']
humidity = daily_data["humidity"]
pressure = daily_data['pressure']
windSpeed = daily_data['windSpeed']
windGust = daily_data['windGust']
windBearing = daily_data['windBearing']
cloudCover = daily_data['cloudCover']
uvIndex = daily_data['uvIndex']
visibility = daily_data["visibility"]
ozone = daily_data["ozone"]

I've attached a picture of the JSON file format here:

My question is:

*

*How do I get to get all data for all times in that day?

*How do I get it to then loop back with day+1?

*How do I then get all of this into the same CSV file?

Sorry if this is super easy - I'm still learning

A: #!/bin/python3
from functools import reduce
import operator
import csv

# Load data from file
with open('Fraser Ave - Inverkeithing KY11 1EJ.json') as f:
    data = json.load(f)

# Get all dates hourly data from JSON data
toCSV = [date_data['hourly']['data'] for date, date_data in data.items()]

# convert to single list of dict
toCSV = reduce(operator.add, toCSV)

# get header names from first dict
keys = toCSV[0].keys()

# optionaly save as csv file
with open('sample.csv', 'w', newline='')  as output_file:
    dict_writer = csv.DictWriter(output_file, keys)
    dict_writer.writeheader()
    dict_writer.writerows(toCSV)


text:
Q: How fast does XM regenerate? XM (eXotic Matter) can be found everywhere in the Ingress game. Once this XM is captured/eaten by a player, how much time will it take to regenerate and can be captured by the same player (or another player) ?

A: If two players simultaneously gather the same XM (i.e. gathered before the cache updates), they both get it. So it helps to go around in groups!

A:
There are 2 types of XM found:

*

*Portal XM - XM thrown out of portals

*Human XM - XM thrown out of humans.
~BanditoBunny

Portal XM

*

*Portal generates XM cca 21 minutes after consumption. The amount is up to 10% of its current energy.

*The XM accumulated by a portal is capped at a certain amount. (probably 10%)

*Portal will produce new XM within 2 minutes when its level was increased or decreased.
This was especially important when there were no Power Cubes.
Additionaly:

*

*XM can be consumed by more people if it is done quite quickly (within 5-20 sec).

*You can collect XM even when your location is inaccurate.

*You can collect XM wihtout internet connection. This will NOT remove the XM on the map for other players until you connect again.

Human XM

*

*Generated in areas where people walk with Ingress on.
Quite simple explanation: Niantic tracks your movements. Yep. You also send data of discovered wifi networks. + from several other possible sources.

note:
XM generates regardless of player presence or the daytime.

A: There are 2 types of XM found:

*

*Portal XM - XM thrown out of portals

*Human XM - XM thrown out of humans.*

Now my observations on XM generation, no hard info sources:

*

*portal XM is generated pretty fast, after I cleared the portal of XM, it has new XM in about 10-15 minutes

*XM is being constantly produced by portals and humans*

*XM is being accumulated and after certain level no more XM is produced

*XM regenerates the best when no player is around (it's almost like "watched pot never boils")

*I believe several times XM was generated near the portal and consumed by me directly

*I believe XM is user independent and can/will be consumed by any player, probably on first in first gets basis

* Conspiracy theory:
I noticed that Human XM is being almost randomly distributed over the map, but when you compare it with human traffic in the same area it almost perfectly simulates it. It is not clear to me where the niantic lab takes this info, maybe they get some info from other google services, like mobile maps, gmail etc and place XM there where the most people go.


text:
Q: Can anyone suggest me at which case do we need to use Any * Any size class mode?
*

*Can anyone suggest me at which case do we need to use Any * Any  size class mode?

*At which size class mode to be set when the app is build for compatible with both iPhone and iPad?

A: The two questions you're asking are very generic and exposes an important lack of understanding of how size classes work. Answering your questions would go somewhat like this:

*

*In almost all cases

*All size classes are important

I suggest starting here.
Take a look at this image:

If you use Any Width / Any Height it simply means that the constraints/views you are using will be 'installed' for all devices. If you use Compact Width / Regular Height, it means the constraints/views you are using will be installed for all iPhones when they are in portrait mode. If you use Regular / Regular, it means the constraints/views you are using will be installed only for iPads.
Note that when you add constraints and views in your storyboard / xib files, you will be able to toggle back and forth between different size classes to 'install' them for the correct size classes.
Hope this help and sends you in the right direction.

A: First of all you should know what is size class ?
 Size classes are Apple's solution to the question "How can I easily work with so many different screen sizes and device orientations?"
Size classes are the marquee feature of adaptive design. Using them allows you to eliminate code and logic that addressed multiple screen sizes, orientations, or specific devices.
Any * Any size used when your layout doesn't change in any screen size.It also makes it easy to have just one interface for all of the devices available.When u want to make application for multiple device in that case we use Any * Any size.To know more refer apple documentation:https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/MobileHIG/LayoutandAppearance.html
To understand it completely make a demo using size classes.Refer:http://swiftiostutorials.com/using-size-classes-xcode-6/


text:
Q: This function is giving SIGSEGV error. Can anybody correct and tell em the problem? C++ vector<int> cutTheSticks(vector<int> arr) {

    vector<int> a;
    int i,min;
    int n = arr.size();
    a.push_back(n);

    while(arr.size() > 0){

        min = *min_element(arr.begin(),arr.end());

        for(auto j=arr.begin();j!=arr.end();j++){
            if(*j == min){
                arr.erase(j);
                //Problem lies here
            }
            else{
                *j = *j-min;
            }
        }
        a.push_back(arr.size());
    }
    return a;
}

This function is giving SIGSEGV error. Can anybody correct and tell me the problem?

A: The problem is in the chosen loop.
for (auto j = arr.begin(); j != arr.end(); j++) {
  if(*j == min){
    arr.erase(j);
  } else {
    *j = *j - min;
  }
}

Suppose j points the last element in the array, i.e. it is arr.end() - 1. After arr.erase(j); the iterator j is invalid and j++ on next iteration is undefined behavior, probably it advances j behind arr.end().
Correct the loop like below
auto j = arr.begin();
while (j != arr.end()) {
  if(*j == min){
    j = arr.erase(j);
  } else {
    *j = *j - min;
    ++j;
  }
}


text:
Q: One or more layouts are missing the layout_width or layout_height attributes or automatically add all missing attributes In Android Studio i'm getting a message One or more layouts are missing the layout_width or layout_height attributes. These are required in most layouts.  Or: Automatically add all missing attributes.And also suggestion is not showing while typing in xml layout.
<RelativeLayout
    xmlns:android="schemas.android.com/apk/res/android"
    xmlns:app="schemas.android.com/apk/res-auto"
    xmlns:tools="schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />
</RelativeLayout>

A: Please add this library in your build.gradle file
implementation 'com.android.support:design:26.1.0'

Then try to create new layout, and add this in layout file
android:layout_width="match_parent"
android:layout_height="match_parent"

according to your requirement..

A: I have Android studio 3.2 with built on September, 2018 and having same above issue. To fix this error, I have deleted cache files.
These are the followings steps you need to do:

*

*Close Android Studio

*Locate the path and Go to -> C:\Users\yourUserName.AndroidStudio3.2\system\caches

*Delete all the files inside the caches folder.

*Open Android Studio.

*You are done here!!.

A: *

*Close Android Studio

*Locate the path and go to C:\Users\yourUserName.AndroidStudio3.2\system\caches

*Delete all the files inside the caches folder

*Open Android Studio


text:
Q: CSS apply style except on :after From the following CSS code:
p {text-decoration: line-through;}
p:after {text-decoration: none;
content:" text";}

with HTML:

abcd

I woud expect the following:
abcd text
However I get this:
abcd text
Why is this and how can I get what I wanted to achieve?

A: Simply add display: inline-block;

p {
  text-decoration: line-through;
}

p:after {
  content: " text";
  text-decoration: none;
  display: inline-block;
}

abcd

A: You need to select the after then apply text-decoration: none. I.e:
p:after p { text-decoration: none;  }


text:
Q: Salesforce change the format of created data in apex class I have the following apex code that displays the created date of records:
for(let i=0; i<emailMessages.length; i++){
replyBody += 'On '+ emailMessages[i].CreatedDate + ' ' + emailMessages[i].From_Name__c +' ' +'responded: ';
}

This above code displays the message like this:

On 2022-06-30T15:27:36.000Z Sarah Kat responded:

I want to change the date format so it can be displayed as below:

On Thu, Jun 30, 2022 at 4:26 PM Sarah Kat responded:

As there anyway where we can change the date format directly in apex?

A: Using these docs as my reference:

*

*https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_methods_system_datetime.htm#apex_System_Datetime_format

*https://www.salesforcecodecrack.com/2020/04/format-dates-and-time-using-apex-in.html

The "format()" function will do what you want. The code would be:
Datetime createdDate = Datetime.now();
String converted = createdDate.format('E, MMM d, yyyy K:mm a');
System.debug(converted);
// Sat, Jul 2, 2022 5:21 AM

Just change out the Datetime.now() for the CreatedDate of the record you're using.
If you really want that specific format, you'll have to do some extra logic to put in the "at" piece. There are probably more elegant ways to do this but this was quick and easy for me to read.
Datetime createdDate = Datetime.now();
String converted = createdDate.format('E, MMM d, yyyy K:mm a');
String[] splitup = converted.split(' ');
String final_string = '';
for(Integer i = 0; i < splitup.size(); i++)
{
    // right between year and hour
    if(i == 4)
    {
        final_string = final_string + ' at';
    }

    final_string = final_string + ' ' + splitup[i];
}
System.debug(final_string);
// Sat, Jul 2, 2022 at 5:27 AM

UPDATE
Yeah, you needed to make the code a function and return the result into what you need. This will work.
for(let i=0; i<emailMessages.length; i++){
    replyBody += 'On '+ datetime_formatting_email(emailMessages[i].CreatedDate) + ' ' + emailMessages[i].From_Name__c +' ' +'responded: ';
}

public String datetime_formatting_email(Datetime createdDate)
{
    String converted = createdDate.format('E, MMM d, yyyy K:mm a');
    String[] splitup = converted.split(' ');
    String final_string = '';
        for (Integer i = 0; i < splitup.size(); i++)
        {
            // right between year and hour
            if (i == 4) {
                final_string = final_string + ' at';
            }

            final_string = final_string + ' ' + splitup[i];
        }
    return final_string;
}


text:
Q: python programming-reading from multiple files Hi I'm having trouble with a university assignment asking us to create a python program which

*

*asks the user to input three filenames containing words, in the format file1 file2 file3 where each filename is separated by a space. This input is assigned to variable FList.

*The program splits FList into three filenames file1, file2 and file3.

*For each file in FList, the program reads in the words from the file and stores these strings into their respective lists: wordList1, wordList2 and wordList3. For example, words from file1 would be assigned to wordList1.

*The program asks the user to input a search word and assigns it to searchWord.

*The program searches wordList1, wordList2, and wordList3 for searchWord, and counts the number of matches in each file and assigns the result to their respective variables: file1Results, file2Results and file3Results.

Flist=raw_input("Please enter the three filenames seperated by spaces")
Flist=Flist.split()
file1=open(Flist[0],"r")
wordList1=file1.read().split()
file1.close()
file2=open(Flist[1],"r")
wordList2=file2.read().split()
file2.close()
file3=open(Flist[2],"r")
wordList3=file3.read().split()
file3.close()

searchWord=raw_input("Which word would you like to search ")
file1Results=wordList1.count(searchWord)
file2Results=wordList2.count(searchWord)
file3Results=wordList3.count(searchWord)
print "file1Results=",file1Results
print "file2Results=",file2Results
print "file3Results=",file3Results

I've made three .txt files on my desktop named output.txt, output2.txt, output3.txt but for some reason when i test run the program, it says that output2.txt does not exist.

A: I can't tell what your input is, but it sounds like you are looking for the file in the wrong directory.
f1 = open('output1.txt')

would search for the output in the folder the python script is being run.
What you probably need is something like this:
desktop_path = 'C:/Users/YOURNAME/Desktop/'
f1 = open(desktop_path + 'output1.txt') # open(desktop_path + Flist[0])

Also, what maybe a problem is
Flist.split()

which works as follows:

For example, ' 1  2   3  '.split() returns ['1', '2', '3'], and '  1  2   3  '.split(None, 1) returns ['1', '2   3  '].

You can find more on this here.

A: I suggest you add
import os

print(os.getcwd())

to the start of your script and run it; it will tell you what directory you are currently working in.
If I save a script on my desktop and run it by double-clicking, it runs with c:\windows\system32 as the current directory. I suspect yours is doing the same and you happen to have a file called output.txt in that directory.
If that is the case, you can use os.path.join(r"path\to\desktop\", filename) to make it look in the right location.


text:
Q: Use the official binaries of a library without losing the option to load the source on demand Within a Visual Studio (2005/2008) Project I'd like to use an open source library. I'd like to link to the binaries so that I'm not responsible for a proper build and can check those binaries into the source control server (SVN).
So far so good, but if I'd like to debug into the open source library or want to take a look at a class implementation I would be forced to add the the source of the project into my solution and than link my project to the source instead of the binaries.
Is it possible to tell Visual Studio a location of the source of a linked binary library so that things like "go to definition" and debug is working?

A: Absolutely, if you have the pdb symbols its all done for you - look at MFC for example, you get the binaries yet can debug through the source.
If you don't have the symbols, then its a lot more complicated, when you debug through the code it may ask you to show it the source lines, and you'll just have to find them for it (usually the path is the same so its easy).

A: There are multiple ways you can achieve this.

*

*Like gbjbaanb suggested you can use pdb symbols.  It's going to work for both managed an unmanaged code.

*If you're using .NET you can debug with Reflector. Oran Dennison wrote how to debug with Reflector and Visual Studio.  One of my favorite tools is TestDriven.NET. Author of this tool, Jamie Cansale, also blogged about how to debug with Reflector when you have TestDriven.NET.  In his article, Jamie has a link to screencast where he demonstrates how to do it step by step.

*Last, if you use for your SVN client like TortoiseSVN, you can add files/directories from check in. More details how to Ignore Files and Directories with TortoiseSVN.


text:
Q: Editing data in EXCEL sheet using python I have a excel with multiple columns which contains address fields. I want that address line to be in proper case. When I am able to get them in proper case, some words like 1st,2nd,SW(South West),10th etc., are transforming into 1St, 2Nd, Sw, 10Th. I need python code to resolve this.
addr_df['ADDRESS1'] = addr_df.apply(set_propercase_fn,args=("Address1",), axis=1)

with the above code I am able to get the data in proper case. I tried using below code to make possible changes, It did work but not appropriate.
def replacestring(val):
    reps = {'Parker':'Borker', '1St':'st', 'Sw':'SW', 'S W':'SW'}
    for i,j in reps.items():
        if i in val: val = val.replace(i,j)
return val
print(addr_df['ADDRESS1'].apply(replacestring))

A: You can try openpyxl it is a great tool, been using it for a long time. With this tool you can modify each and every cell of an excel file.


text:
Q: MethodAccessException on Task.CompletedTask property I am working on a small wpf application and one of the users is getting the following exception:
System.MethodAccessException:
Attempt by method "xxx.HttpConfirmation.Invoke()" to access method "System.Threading.Tasks.Task.get_CompletedTask()" failed.
at xxx.HttpConfirmation.Invoke()
at xxx.RequestPipeline.<ProcessQueuedRequests>d__11.MoveNext()

According to MSDN documentation, such exception is thrown in the following situations:

*

*A private, protected, or internal method that would not be accessible from normal compiled code is accessed from partially trusted code by using reflection.

*A security-critical method is accessed from transparent code.

*The access level of a method in a class library has changed, and one or more assemblies that reference the library have not been recompiled.

Task.get_CompletedTask() is public since its introduction and I am also not using reflection to access the property.
I also don't think that there is a problem with code security/transparency since only one user is having this issue.
The exception is thrown at the Task.CompletedTask line:
public class HttpConfirmation
{
    public static Task Invoke()
    {
        using (var client = new WebClient())
        {
            try
            {
                // Send the request and don't wait for the response.
                client.UploadStringTaskAsync("http://sampleUrl.com", string.Empty);
            }
            catch
            {
                // ignore
            }
        }

        return Task.CompletedTask;
    }
}

Any ideas on what may cause the exception?

A: The problem was that the customer had .NET 4.5.2 installed and the program targeted .NET 4.6.
Though I still have no clue as to why exactly System.MethodAccessException was thrown as none of the 3 documented situations for throwing this exception did happen.


text:
Q: Javascript createObjectURL.URL fails for MediaStream I'm trying to create an Electron app that takes a screenshot of the screen according to the following guide:
https://ourcodeworld.com/articles/read/280/creating-screenshots-of-your-app-or-the-screen-in-electron-framework
I'm getting an error while executing inside the developer tools console of Electron:
Uncaught TypeError: Failed to execute 'createObjectURL' on 'URL': No function was found that matched the signature provided.

When I console.log the stream object that is passed in video.src = URL.createObjectURL(stream); I see that it's of type MediaStream.
According to https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL the createObjectURL can accept "A File, Blob or MediaSource object to create an object URL for.". How can I convert the MediaStream that I'm getting into the MediaSource?

A: Attach your stream directly to srcObject property instead of using URL.createObjectURL function.
Do this:
video.srcObject = stream; // new implementation

Instead of this:
video.src = URL.createObjectURL(stream); // old implementation

You can read the recommendation in the doc page you've referenced to, in the section: Using object URLs for media streams.


text:
Q: Problems between fftw-2.1.5 libraries and OpenMPI I am trying to install the MPI FFTW2 libraries (fftw2.1.5) as I need them for a program that only works with that version. The specific library I need is "drfftw_mpi.h" so I try the followed:
  ./configure --enable-mpi --enable-type-prefix

But it always gives me the following error:
configure: error: couldn't find mpi library for --enable-mpi

In a previous question they solve it by running sudo ldconfig before, but for me it does not work giving the same error. For other mpi software they solve it in this post by passing mpicc as the right compiler to ./configure, with the CC flag CC=mpicc, something that does not work for me.
I have installed Open MPI version 4.0.3 on a Ubuntu 20.04 LTS, and when --enable-mpi  is not used I was able to install "dfftw.h"  "drfftw.h"  "fftw.h" and "rfftw.h", do you have an idea of what I am doing wrong or what should I do to install "drfftw_mpi.h"?