text:
Q: Can Bootstrap 4 Cards Have Tiled Background Images I am trying to get a card to have a tiled background image. To get a single image background I use:

xxxDescriptionxxx

        xxxSomeTextHerexxx

My problem is that I use cards of different sizes and right now my image size is governing the size of my card; I guess I want it the other way round (the card to govern the size of the displayed background). So I wondered if it was possible to tile a background image so it just fills the background and then it shouldn't matter what size the card or image is.
For all I know, this may not even be possible and if not, that's fine, I'll look for another way to do something like :)
Anyway, thanks for any advice :)
James

A: If the only purpose of using img element is as a background - use background-image CSS property which sets background image on an element.
Edit per comments:
Obviously the float part cause some "problems" on the given markup, BUT there is something more out there... Can't figure myself why this not working - so i remove BS4 (added 2 examples):

.card.img-fluid {
  background: url(http://www.rocksquad.co.uk/images/backcard-brushedmetal.jpg) no-repeat;
  background-position: center;
  background-size: cover;
}

xxxDescriptionxxx

        xxxSomeTextHerexxx
xxxSomeTextHerexxx

xxxDescriptionxxx

        xxxSomeTextHerexxx
xxxSomeTextHerexxx
        xxxSomeTextHerexxx
xxxSomeTextHerexxx
        xxxSomeTextHerexxx
xxxSomeTextHerexxx
        xxxSomeTextHerexxx

This question need some "bootstrap 4 expert" to answer on - clearly this is not me (:

Old (not working) answer:
In your case, since you want the image would cover the element, you can do something like that:

xxxDescriptionxxx

        xxxSomeTextHerexxx


text:
Q: C++: static initialize an array member, member at a time I now I can do this in global scope and everything works fine:
const char* Foo::bars[3] = {"a", "b", "c"};

But I want to do this because this is much more clearer and self documenting (especially if you use Enums as the index):
const char* Foo::bars[3];
bars[0] = "a";
bars[1] = "b";
bars[2] = "c";

Is it anyway possible?
I know I can do this inside a function (for example, the class's constructor) but what if the constructor is not called in the start of the program and I want to use the static array? That leads to problems.

A: How about this?
const char* Foo::bars[3] = {
/* Index    Value */
/* 0 */     "a",
/* 1 */     "b",
/* 2 */     "c"
};

I often use this "technique" to make the initialization of arrays of structs look like a self-documenting spreadsheet.

A: In C++ there is no equivalent of the static Java block.
If you really want to initialize the array automatically, you can create a simple class to do the job:
// in .cpp
class FooInitializer {
public:
    FooInitializer() {
        Foo:bars[0] = "a";
        Foo:bars[1] = "b";
        Foo:bars[2] = "c";
    }
};

static FooInitializer fooInitializer;

A: You can use an accessor-function:
const char* GetArray()
{
    static char* result[3];
    static isInitialized = false;
    if (!isInitialized)
    {
        result[0] = "a";
        result[1] = "b";
        result[3] = "c";
        initialized=true;
    }
    return result;
}

A: Here's another solution that uses the Singleton pattern. Note that the array is initialized once in the singleton's constructor. Also note that this is not thread-safe. Also beware of the evilness of singletons (search this site for "singleton" to find some interesting debate on this matter).
#include <iostream>

class StringTable
{
public:
    enum StringId
    {
        hello,
        bye,
        goodDay,
        stringCount
    };

    static const char* lookup(StringId id) {return instance().table_[id];}

private:
    StringTable()
    {
        table_[hello] = "Hello World!\n";
        table_[bye] = "Goobye, cruel world!\n";
        table_[goodDay] = "I said good day!\n";
    }

    static StringTable& instance()
    {
        static StringTable theInstance;
        return theInstance;
    }

    const char* table_[stringCount];
};

int main()
{
    std::cout << StringTable::lookup(StringTable::hello)
              << StringTable::lookup(StringTable::bye)
              << StringTable::lookup(StringTable::goodDay);
}

A: You probably want an extra const in bars
const char* const Foo::bars[3] =
{
   "a",
   "b",
   "c"
};

The way you declared it, you can actually do what you wanted in setting the members one at a time, although you'd use an "init" function to do it.
If you do want it const, which is probably preferable, it will subsequently become illegal to assign them a line at a time, even in some kind of "init" method and you should simply use a code layout to make it clearer what you are doing.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Accessing API to download data without admin rights on Machine I want to trial accessing an API without admin rights for my work machine - due to corporate setting.
I can't use Python as there is restricted access to the web.
It is possible to build a macro in excel, however this is not a preferred method.
Can you recommend any path forward.
An example API Endpoint URL: https://www.gov.uk/bank-holidays.json
Documentation of API: https://github.com/alphagov/calendars/blob/master/README.md

A: You can use powershell using the Invoke-Restmethod command, for example:
$data = Invoke-RestMethod https://www.gov.uk/bank-holidays.json
$data.'england-and-wales'.events

This returns a long list of the events in the "England and Wales" region

title
date
notes
bunting

New Year's Day
2016-01-01

True

Good Friday
2016-03-25

False

Easter Monday
2016-03-28

True

...
...
...
...

After that you can manipulate the data however you want, its quite simple once you get the hang of it :)


text:
Q: Paypal recurring payment for german payers I am trying to integrate a recurring payment from PayPal with the express checkout, but it seems that it doesn't work with payers from germany.
If I test with a sanbox user which is set to the united states, everything works fine, but if I try to do that with my sanbox user which is set to germany I get an error that "We cannot procceed the request. Please got back to the store an chose another option".
Have anyone a solution for this problem?

A: Recurring payments cannot be created for buyers in Germany or China. In this case, you can use reference transactions as an alternate solution.
https://developer.paypal.com/docs/classic/express-checkout/integration-guide/ECRecurringPayments/?mark=IPN%20notification


text:
Q: Where to store\update tnsnames.ora file when installed oracle client only? I installed the oracle client only but was told to update my tnsnames.ora file with the info my dba sent me.  But I don't have a tnsnames.ora file.
On another machine with a full oracle admin install it is at:

*

*C:\Oracle\product\10.1.0\Db_1\NETWORK\ADMIN\tnsnames.ora

So do I need the tnsnames.ora file?
How do I let oracle know where it is?
fk

A: I have Oracle Client installed on my machine. Last week my DBA updated my "tnsnames.ora" file because of server change. The file is in:

*

*C:\oracle\ora81\network\ADMIN

I guess you should consult your DBA if copying the file to that directory doesn't work.

A: When you say oracle client only, are you using the Oracle Instant Client? If so you should set the TNS_ADMIN environment variable to point to where ever you store your tnsnames.ora file

A: Its in %ORACLE_HOME%\network\admin folder where  %ORACLE_HOME% is the parth to which the client is installed, and an entry is done to the PATH variable. If the file does not exist, create one, using the file on the other machine as a template

A: On Yosemite (10.10.3) with Oracle SQL Developer 4.1.1.19 the default place where the client looks for the file is /etc.
In theory you can override that by setting the TNS_ADMIN environment variable to the folder containing your tnsnames.ora file, but I had trouble doing that.

A: If the .\network\admin folder exists on your machine, simply copy the tnsnames.ora in this directory.


text:
Q: Acra not work in Release Version for reporting my Application Crashes use Acra library via  Android Studio Gradle Dependencies in this form :
 dependencies {
      compile 'ch.acra:acra:4.6.2'
  }

Now in Bebug version it work and return crash report goodly but after export Release version of application not work and return this error in logcat :
Not adding buildConfig to log. Class Not found : " + className + ". Please configure 'buildConfigClass' in your ACRA config

Then i use acra-4-6-2.jar file instead dependencies but not work still!
Too before saw this link but was not helpful fore me.
With thanks for your attention

A: It sounds like you are Proguardng your app on release but have not added the relevant ACRA classes to your Proguard config.
See https://github.com/ACRA/acra/wiki/ProGuard

A: None of the other answers actually provided the fix.
To fix this issue, assign your BuildConfig.class to the buildConfigClass field on your ReportsCrashes annotation declaration.
@ReportsCrashes(
    buildConfigClass = BuildConfig.class )
public class YourApplication extends Application { ... }

A: If you are using so called "dynamic" configuration you are probably having "empty" annotation like @ReportsCrashes().
In that case it turns out that ACRA does not create proper default config. The solution is simple: just add some fake property there like:
@ReportsCrashes(formUri = "placeholder")

which you will later override in the dynamic config...


text:
Q: Serialize / Deserialize XML Derived From Treenode I have two classes, "company" derived from Treenode, and "document".
[Serializable]
[XmlRoot("Company")]
public class Company : TreeNode, IXmlSerializable
{
    private string _x;
    private string _y;

    public Company() { }

    [XmlElement("X")]
    public string X { get; set; }
    [XmlElement("Y")]
    public string Y { get; set; }

    public System.Xml.Schema.XmlSchema GetSchema()
    {
        return null;
    }
    public void ReadXml(XmlReader reader)
    {
        if (reader.MoveToContent() == XmlNodeType.Element && reader.LocalName == "Company")
        {
            x = reader["X"].ToString;
            y = reader["Y"].ToString;
        }
    }
    public void WriteXml(XmlWriter writer)
    {
        writer.WriteElementString("X", this.X.ToString());
        writer.WriteElementString("Y", this.Y.ToString());
    }
}

public class Document
{
    private int _id;
    private string _name;
    private Company _company;

    public Document() { }

    [XmlElement("ID")]
    public int ID { get; set; }
    [XmlElement("Name")]
    public string Name { get; set; }
    [XmlElement("Company")]
    public Company Comp { get; set; }
}

When I try to serialize document, then save to file, its work. But when I deserialize, reader parameter always null. Any solutions ?
This is my code for deserialize. "sr" is variable that hold xml text.
var sr = new StreamReader(ms);
var myStr = sr.ReadToEnd();

XmlSerializer serializer = new XmlSerializer(typeof(List<Document>));
using (TextReader tr = new StringReader(myStr))
{
    List<Document> docu = (List<Document>)serializer.Deserialize(tr);
}

I try to implement ISerialization and debug but never fired, and try to overide serialize and deserialize method, and no luck.
I am using .NET Framework 3.5

A: As explained in this article, implementing IXmlSerializable correctly is in fact quite tricky.  Your implementation of ReadXml() appears to violate the requirement that it consume the wrapper element itself as well as all the contents, like so:
public void ReadXml(System.Xml.XmlReader reader)
{
    reader.MoveToContent();
    // Read attributes
    Boolean isEmptyElement = reader.IsEmptyElement; // (1)
    reader.ReadStartElement();
    if (!isEmptyElement) // (1)
    {
        // Read Child elements X and Y

        // Consume the end of the wrapper element
        reader.ReadEndElement();
    }
}

Furthermore, reader["X"] returns the value of the XML attribute named "X", as explained in the docs.  In your WriteXml() you wrote the values of X and Y as nested XML elements.  This explains the NullReferenceException.  You need to fix your read and write methods to be consistent.
However, I'd suggest an alternative to implementing IXmlSerializable, which is to introduce a surrogate type for your Company.  First, extract all the non-TreeNode properties of Company into an interface:
public interface ICompany
{
    string X { get; set; }
    string Y { get; set; }
}

public class Company : TreeNode, ICompany
{
    public Company() { }

    public string X { get; set; }
    public string Y { get; set; }
}

This is optional but makes the code clearer.  Next, introduce a surrogate POCO that implements the same interface but does not inherit from TreeNode:
public class CompanySurrogate : ICompany
{
    public string X { get; set; }
    public string Y { get; set; }

    public static implicit operator CompanySurrogate(Company company)
    {
        if (company == null)
            return null;
        // For more complex types, use AutoMapper
        return new CompanySurrogate { X = company.X, Y = company.Y };
    }

    public static implicit operator Company(CompanySurrogate surrogate)
    {
        if (surrogate == null)
            return null;
        // For more complex types, use AutoMapper
        return new Company { X = surrogate.X, Y = surrogate.Y };
    }
}

Notice that the surrogate can be implicitly converted to your original Company type?  Now you can use the surrogate in XML serialization by setting the XmlElementAttribute.Type attribute property to be that of the surrogate:
public class Document
{
    public Document() { }

    [XmlElement("ID")]
    public int ID { get; set; }
    [XmlElement("Name")]
    public string Name { get; set; }

    [XmlElement("Company", Type = typeof(CompanySurrogate))]
    public Company Comp { get; set; }
}

This avoids all possibilities of error in implementing IXmlSerializable.  Given the following input list:
var list = new List<Document>
{
    new Document { Name = "my name", ID = 101, Comp = new Company { X = "foo", Y = "bar", NodeFont = new System.Drawing.Font("Arial", 10) } },
    new Document { Name = "2nd name", ID = 222, Comp = new Company { X = "tlon", Y = "ukbar" } },
};

The following XML can will be generated, and can be deserialized successfully:
<ArrayOfDocument xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <Document>
        <ID>101</ID>
        <Name>my name</Name>
        <Company>
            <X>foo</X>
            <Y>bar</Y>
        </Company>
    </Document>
    <Document>
        <ID>222</ID>
        <Name>2nd name</Name>
        <Company>
            <X>tlon</X>
            <Y>ukbar</Y>
        </Company>
    </Document>
</ArrayOfDocument>

That being said, I don't really recommend this design.  Your UI should present your data model, it should not be your data model.  See for instance How does one implement UI independent applications?.  Replacing Company with ICompany whenever possible could be a first step to changing your design; you may find it becomes easier to replace your existing architecture with a TreeNode that looks like this:
public class CompanyNode : TreeNode
{
    public ICompany Company { get; set; }
}


text:
Q: Txt file adding line breaks in html file I have a txt file with fixtures of upcoming football games in the format
Northampton vs Bury

Rochdale vs Southend

Peterborough vs Oxford  <br

I'm then inserting it into my html file with the following jQuery code
$('#GamesTable').load("Fixtures/League1.txt");

however when I open the page the games appear to be 2 line breaks down as though the file has started with

which it hasn't.
Some of my other txt files with other fixtures however appear to only add 1 line break and some don't add any. Any ideas why this would be?


text:
Q: select with case statement give me error in as i write a store procedure with case
SELECT TOP(10000) ORDER,ORDERID,CLIENTNUM,

CASE WHEN ExpArrvDate IS NOT NULL AND ActArrvDate IS NULL THEN 'In Transit'
ELSE
  CASE WHEN ActArrvDate IS NULL   THEN 'NOT COME'
ELSE
 CASE WHEN DRV1NUM IS NOT NULL THEN 'WILL Come'
ELSE
  CASE WHEN PICKEDUP IS NOT NULL THEN 'Picked By JOHN '
ELSE
  CASE WHEN DROPTIME IS NOT NULL THEN 'Dropped Off'
AS OrderDeatils

FROM CTRTABle

what i am doing wrong in this statement in can you please help me

A: You need to END each CASE as
SELECT TOP(10000) ORDER,ORDERID,CLIENTNUM,

    CASE WHEN ExpArrvDate IS NOT NULL AND ActArrvDate IS NULL THEN 'In Transit'
    ELSE
      CASE WHEN ActArrvDate IS NULL   THEN 'NOT COME'
    ELSE
     CASE WHEN DRV1NUM IS NOT NULL THEN 'WILL Come'
    ELSE
      CASE WHEN PICKEDUP IS NOT NULL THEN 'Picked By JOHN '
    ELSE
      CASE WHEN DROPTIME IS NOT NULL THEN 'Dropped Off'
    END END END END END -- Added line. Added END for each CASE
    AS OrderDeatils

    FROM CTRTABle


text:
Q: OpenLayers 3 support for WMS 1.3.0 CRS:1 I am trying to get a TileWMS layer working with the CS as CRS:1 defined in WMS 1.3.0. By defining the right projection stated in CRS:1, axisorientation as 'es', I could get it working for ImageWMS. However, when using TileWMS, I found all the tileGrids defined in OpenLayers 3 are always aligned with 'en' direction. tileindex x increments as x goes right, tileindex y increments as y goes up. So it is different from the CRS:1 definition. This causes the tiles are put into wrong direction in y axis.
My question is that is there any way that I can change tiling direction to follow the axixorientation defined in my projection, in this case, is 'es'? Or are there any advice or examples for 'es' projection like CRS:1 in tiled API of OpenLayers 3?


text:
Q: Stacking my conditions in a CASE statement it's not returning all cases for each member SELECT DISTINCT
    Member_ID,
    CASE
        WHEN a.ASTHMA_MBR = 1 THEN 'ASTHMA'
        WHEN a.COPD_MBR = 1 THEN 'COPD'
        WHEN a.HYPERTENSION_MBR = 1 THEN 'HYPERTENSION'
    END AS DX_FLAG

So a member may have more than one, but my statement is only returning one of them.
I'm using Teradata and trying to convert multiple columns of boolean data into one column. The statement is only returning one condition when members may have 2 or more. I tried using Select instead of Select Distinct and it made no difference.

A: This is a kind of UNPIVOT:
with base_data as
 ( -- select the columns you want to unpivot
   select
      member_id
     ,date_col

      -- the aliases will be the final column value
     ,ASTHMA_MBR AS ASTHMA
     ,COPD_MBR AS COPD
     ,HYPERTENSION_MBR AS HYPERTENSION
   from your_table
 )
,unpvt as
 (
   select member_id, date_col, x, DX_FLAG
   from base_data
   -- now unpivot those columns into rows
   UNPIVOT(x FOR DX_FLAG IN (ASTHMA, COPD, HYPERTENSION)
          ) dt
 )
select member_id, DX_FLAG, date_col
from unpvt
-- only show rows where the condition is true
where x = 1


text:
Q: Sending email to a remote user which has the same domain name My smtp servers domain(origin) is xxx.com.
When I try to email user51@xxx.com from smtp server, it does not deliver that mail since this user51 is not hosted on this smtp server.
user51 has an google apps account with domain xxx.com
So I want smtp server to deliver mail remotely if that user is not hosted locally.
How is that possible with postfix?
partial main.cf
# mydomain
relayhost = $mydomain
# relay_domains

A: If the "real" xxx.com is pointed at Google Apps for email (ie, its MX records as the internet understands them are pointing at Googles email servers), then your local SMTP should not claim that it is a relay for that domain.  It is incorrectly configured.
All you need to do is remove xxx.com as a domain from your smtp server.
If on the other hand, the real email server for xxx.com is your server, then it should correctly attempt to deliver locally and fail if the account doesn't exist.
You cannot have an email domain in two different places like this.  You can have two different email servers that are valid recipients for a domains email, but once they take possession of the email it is up to them to ensure they cooperate and get it to the emailbox of the user.

A: Try removing xxx.com or $myorigin from mydestination in main.cf

A: You can using transport.

main.cf
  transport_maps = hash:/etc/postfix/transport
/etc/postfix/transport
  user51@xxx.com smtpserver.google.com:25

Don't forget to postmap /etc/postfix/transport


text:
Q: Porblema al subir imagen al servidor con Spring java ya llevo 2 dias sin poder solucionar esto y no veo de otra que recurrir aqui, el problema es qeu intento subir la imagen a servidor con el framework spring de java y colocar la ruta de su ubicacion en la base de datos, pero al mandarla me arroja un error y realmente no se que pueda ser aqui les dejo el metodo que hace lo subida
public static final String TEACHER_UPLOADED_FOLDER = "images/teachers/";

//CREATE{img}
@RequestMapping(value = "/teachers/images", method = RequestMethod.POST, headers = ("content-type=multipart/form-data"))
public ResponseEntity<byte[]> uploadTeacherImage(@RequestParam("idTeacher") Long idTeacher, @RequestParam("file")MultipartFile multipartFile, UriComponentsBuilder uriComponentsBuilder) {
    if (idTeacher == null) {
        return new ResponseEntity(new CustomErrorType("Please set id_teacher"), HttpStatus.NO_CONTENT);
    }

    if (multipartFile.isEmpty()) {
        return new ResponseEntity(new CustomErrorType("Please select a file to upload"), HttpStatus.NO_CONTENT);
    }

    Teacher teacher = _teacherService.findById(idTeacher);
    if (teacher == null) {
        return new ResponseEntity(new CustomErrorType("Teacher with id_teacher: " + idTeacher + " not found"), HttpStatus.NOT_FOUND);
    }

    if (!teacher.getAvatar().isEmpty() || teacher.getAvatar() != null) {
        String fileName = teacher.getAvatar();
        Path path = Paths.get(fileName);
        File f = path.toFile();
        if (f.exists()) {
            f.delete();
        }
    }

    try {
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String dateName = dateFormat.format(date);

        String fileName = String.valueOf(idTeacher)
                + "-pictureTaecher-" + dateName + "."
                + multipartFile.getContentType().split("/")[1];
        teacher.setAvatar(TEACHER_UPLOADED_FOLDER + fileName);

        byte[] image = multipartFile.getBytes();
        Path path = Paths.get(TEACHER_UPLOADED_FOLDER + fileName);
        Files.write(path, image);//****AQUI ME ARROJA EL ERROR****

        _teacherService.update(teacher);
        return ResponseEntity.ok().contentType(MediaType.IMAGE_JPEG).body(image);
    } catch (Exception e) {
        e.printStackTrace();
        return new ResponseEntity(
                new CustomErrorType("Error during upload: " + multipartFile.getOriginalFilename()),
                HttpStatus.CONFLICT
        );
    }
}

Me arroja el error en esta parte del codigo:

byte[] image = multipartFile.getBytes();
        Path path = Paths.get(TEACHER_UPLOADED_FOLDER + fileName);
        Files.write(path, image);//****AQUI ME ARROJA EL ERROR****

Aqui esta el objeto teacher:

@Entity
@Table(name = "teacher")
public class Teacher implements Serializable {

@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long idTeacher;

@Column(name = "name")
private String name;

@Column(name = "avatar")
private String avatar;

@OneToMany(mappedBy = "teacher")
@JsonIgnore
private Set<Course> courses;

@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "id_teacher")
@JsonIgnore
private Set<TeacherSocialMedia> teacherSocialMedia;

public Teacher () { }

public Teacher (String name, String avatar) {
    this.name = name;
    this.avatar = avatar;
}

public Long getIdTeacher () {
    return idTeacher;
}

public void setIdTeacher (Long idTeacher) {
    this.idTeacher = idTeacher;
}

public String getName () {
    return name;
}

public void setName (String name) {
    this.name = name;
}

public String getAvatar () {
    return avatar;
}

public void setAvatar (String avatar) {
    this.avatar = avatar;
}

public Set<Course> getCourses () {
    return courses;
}

public void setCourses (Set<Course> courses) {
    this.courses = courses;
}

public Set<TeacherSocialMedia> getTeacherSocialMedia () {
    return teacherSocialMedia;
}

public void setTeacherSocialMedia (Set<TeacherSocialMedia> teacherSocialMedia) {
    this.teacherSocialMedia = teacherSocialMedia;
}

}

El error que me arroja es el siguiente:
  La linea 197 de TeacherController esta dentro del metodo que esta
  arriba

java.nio.file.NoSuchFileException: images/teachers/2-pictureTaecher-2018-09-27.png
at java.base/sun.nio.fs.UnixException.translateToIOException(UnixException.java:92)
at java.base/sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:111)
at java.base/sun.nio.fs.UnixException.rethrowAsIOException(UnixException.java:116)
at java.base/sun.nio.fs.UnixFileSystemProvider.newByteChannel(UnixFileSystemProvider.java:215)
at java.base/java.nio.file.spi.FileSystemProvider.newOutputStream(FileSystemProvider.java:434)
at java.base/java.nio.file.Files.newOutputStream(Files.java:218)
at java.base/java.nio.file.Files.write(Files.java:3355)
at com.platzi.profesoresplatzi.controller.TeacherController.uploadTeacherImage(TeacherController.java:197)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)


text:
Q: Is there a way, in html, to refer to the domain of a website without actually knowing it? For example, I want a link to take the viewer to a folder on the website
 Click here to go to this folder
But now I want to make it so that other developers can use my code on their website without having to personally edit it. Is there a way for me to reference the "http://www.Example.com" without actually knowing what the domain is?

A: If you simply want to make a relative link, i.e. a link relative to the current URL or domain, simply leave out the domain:
always goes to foo.html in the same folder as this document
always goes to /foo.html in the same domain

The same way you can also make a protocol relative URL:
goes to https://.. if current page is https, otherwise http


text:
Q: Could not save .mp4 video file to iphone camera roll? I received the video file contents in the format of NSData and I am playing that file in MPMoviePlayerController successfully with following code
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *FileExtension=[[NSString alloc]init];

if([contentType hasPrefix:@"video"] || [contentType isEqualToString:@"application/video"]) {
    FileExtension=@"mov";
   //FileExtension=@"mp4";
}
else
{
  FileExtension=[contentType lastPathComponent];
}

 //appFile is type of NSString.
 appFile = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"MyFile.%@",FileExtension]];

//videoData is type of NSData
[videoData writeToFile:appFile atomically:YES];

NSURL *fileURL = [NSURL fileURLWithPath:appFile isDirectory:NO];

moviePlayerController = [[MPMoviePlayerController alloc] initWithContentURL:fileURL];
moviePlayerController.view.frame = self.view.bounds;
moviePlayerController.movieSourceType = MPMovieSourceTypeFile;
moviePlayerController.fullscreen = YES;
moviePlayerController.shouldAutoplay=NO;

[self.view addSubview:moviePlayerController.view];
[moviePlayerController prepareToPlay];

but I am unable to write/save this video file to camera roll,this is my code for writing code to the camera roll.
  ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
  NSURL *filePathURL = [NSURL fileURLWithPath:appFile isDirectory:NO];
  if ([library videoAtPathIsCompatibleWithSavedPhotosAlbum:filePathURL]) {
    [library writeVideoAtPathToSavedPhotosAlbum:filePathURL completionBlock:^(NSURL *assetURL, NSError *error){
        if (error) {
            NSLog(@"Not success");
        } else {
            NSLog(@"success");
        }
    }];

}

this code is work fine when I set mimeType/file_format as .mov & .3Gp but I have problem related to save video to the camera roll when mimeType/file_format as .mp4 file.

A: You can convert your .mp4 to .mov if you change your appFile this way:
Your code:
 appFile = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"MyFile.%@",FileExtension]];

New code:
 appFile = [documentsDirectory stringByAppendingPathComponent:@"MyFile.mov"];

The SO automatically converts .mp4 to .mov


text:
Q: How to extract only the name from an email in lambda node js Hi am using node js in the lambda function. I need to extract only the name from an email to query the dynamo db. I need only name because for eg: if I give pavi@gamil.com. I should get all the duplicate emails like
pavi1@gmail.com
pavi2@gmail.com

Please help me to do that
 Below is my code:
const AWS = require('aws-sdk');
var docClient = new AWS.DynamoDB.DocumentClient();

var tableName = "Testing";

exports.handler = (event, context, callback) => {
    console.log(event.PersonName)

docClient.scan(params, function(err, data){
    if(err){
        callback(err, data);
    }else{
        callback(err, data);
   }

In the above code I gave directly the name. When it comes dynamically it should be able to extract the name from an email and should get assign to val

A: You can use regular expression.
Here is a one line code to get username from email.
   var emailId = event.emailId; // or any other var which is having emaiID
   var username = emailId.replace(/@.*$/,"");

For more use case Regular expression for email
For your case
exports.handler = (event, context, callback) => {
    console.log(event.PersonName)

var emailId = event.emailId; // or any other var which is having emaiID
var val = emailId.replace(/@.*$/,"");

// use console.log to see if you're getting correct username

var params=  {
    TableName:'Testing',
    KeyConditionExpression : 'EmailID = :EmailID',
    FilterExpression : 'begins_with (EmailID, :val) ',
    ExpressionAttributeValues : {
       ':val' :  val
   }
};


text:
Q: How to join two diffrent tables in php PDO I have two tables with this content:
Table users:

id                       1
username                 demoUser
pwd                      123
uid                      ghuyd3t2fgaggascxucxtu767fjc1g1e

Table all_product:

id                       1
p_name                   demoNmae
price                    demo
product_id               ghuyd3t2fgaggascxucxtu767fjc1g1e

I want to join them and fetch data, this is the code I'm using:
$uid = $_GET['pid'];

$query = "SELECT users.*, all_product.* FROM users tableUsers JOIN all_product tableProduct ON tableUsers.uid = tableProduct.product_id WHERE tableProduct.product_id = tableUsers.$uid";

$statement = $con->prepare($query);
$statement->execute();
$result = $statement->fetchAll();

foreach($result as $row){
  echo $row['id'];
  echo $row['username'];
  echo $row['p_name'];
}

But I got this error:

Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[42S02]: Base table or view not found: 1051 Unknown table 'users'' in /Applications/AMPPS/www/AppenceMedia/fetch_user.php:22 Stack trace: #0 /Applications/AMPPS/www/AppenceMedia/fetch_user.php(22): PDOStatement->execute() #1 {main} thrown in /Applications/AMPPS/www/AppenceMedia/fetch_user.php on line 22

A: You're using the alias of table but in select you're using the name of table.. that gives you the error.
Also in where condition bind the parameter
Try this code:
    $uid = $_GET['pid'];

    $query = "SELECT tableUsers.*, tableProduct.* FROM users tableUsers JOIN all_product tableProduct ON tableUsers.uid = tableProduct.product_id WHERE tableProduct.product_id = :product_id";

    $statement = $con->prepare($query);
    $statement->bindParam(':product_id', $uid, PDO::PARAM_STR);
    $statement->execute();
    $result = $statement->fetchAll();

    foreach($result as $row){
      echo $row['id'];
      echo $row['username'];
      echo $row['p_name'];
    }

A: Be sure that you have really a table named  users and If you are using  table alias the try use these in everywhere
$query = "SELECT tableUsers.*, tableProduct.*
FROM users tableUsers
JOIN all_product tableProduct ON tableUsers.uid = tableProduct.product_id
WHERE tableProduct.product_id = tableUsers.$uid";

anyway  you should not use php var in sql  .. you are at risk for sqlijection  .. try take a look at prepared  statement and binding param

A: I think your query is a bit wrong. You should do it like:
table_name as table_alias

So in your case:
$query = "SELECT users.*, tableProduct.* FROM tableUsers  as users JOIN all_product as tableProduct ON tableUsers.uid = tableProduct.product_id WHERE tableProduct.product_id = tableUsers.$uid";

br


text:
Q: How can I do this with list comprehension? Or how can I extract every even position element from list and store it in a list? p = [i.text.strip() for i in soup.select('p.card-text')]
j = []
for i in p:
     if p.index(i)%2 == 0:
          j.append(i)

*

*I am doing this because I only want to extract even position element from my list p.

*Is there any other way to do this (to get only even position element from list)?

*If not, how can I write the code above using list comprehension? I have extracted even position element using this code. I want to know of any other method I can apply or how to write list comprehension for the above code?

A: You can try the following by using list comprehension along with enumerate in python
p = [i.text.strip() for index,i in enumerate(soup.select('p.card-text')) if index%2==0]

A: Um... simply slice:
j = p[::2]

Or if select returns a list (looks like it does), do it earlier to save work:
soup.select('p.card-text')[::2]


text:
Q: Write at specified location (Console) I am trying to create points inside a console window based on a 80x49 grid. But I am getting stuck on the basic idea.
My thought was to first of all print out spaces on the entire page so that later, when my method Draw() is called, it replaces a space with a character of choosing.
Keep in mind that the application should be able to print out new points on the same "canvas" again and again. Say that we first print a * at 4,5 and then a * at 4,7 . I am guessing SetCursorPos wouldn't work?

A: Yes, Console.SetCursorPosition is what you should use.

A: see advanced console io in .net


text:
Q: Android ADB shell commands: Mount host PC folder? Hope this isn't too much of an amateur/moron question: I'm trying to replace most ringtones and alarms (Dell Streak 5 (2.2.2 rooted)) with a few of my own pet sounds.
For reasons I won't bother you with, I can't use an SD card, so my .ogg replacements need be transferred straight from my PC to their respective default folders under /system/media/audio/ .
ADB push and pull commands don't seem to accept widlcards (which is a pain) but anyway, despite setting the system folder to rw, I get 'permission denied' when I tediously attempt to pull or push files one by one.
But I should be able to rm and cp interactively from ADB's shell # prompt, with simple Unix commands to transfer groups of files between the /system/media/audio folders and my Windows PC. But to do this I presumably need to mount my PC source folder, and I have no idea how to do this.
I'd be grateful for any info or ideas...

A: You need to have root access on the phone.  My advice as a programmer would be to
1) Write a program to do this...
or just do it the easy way haha.  Try this (your device must be rooted):

*

*adb shell into your device using $> adb shell

*move to the local folder using $> cd /data/local

*Now create a directory for your tones with $> mkdir my_tones - this shouldn't require su

*Next you must push your .ogg files from your computer to the /data/local/my_tones folder

*Now you can become su user with $> su

*Now you should be able to copy the files from the /data/local/my_tones directory to where ever it is you would like them.

Hope this helps.


text:
Q: Capistrano 3: undefined method 'colorize' for :location:Symbol on first deploy attempt I'm trying to set up deployment via ssh using capistrano 3.2.1 from a Windows machine to remote host. But on first run I get the following error:
cap production deploy --trace --verbose
SSHKit::Runner::ExecuteError: Exception while executing on host #<Capistrano::Configuration::Server:0x29b1460>: undefined method `colorize' for :location:Symbol
(eval):4:in `blue'
C:/tools/Ruby193/lib/ruby/gems/1.9.1/gems/sshkit-1.5.1/lib/sshkit/formatters/pretty.rb:22:in `write_command'
C:/tools/Ruby193/lib/ruby/gems/1.9.1/gems/sshkit-1.5.1/lib/sshkit/formatters/pretty.rb:10:in `write'
C:/tools/Ruby193/lib/ruby/gems/1.9.1/gems/sshkit-1.5.1/lib/sshkit/backends/netssh.rb:129:in `block in _execute'
C:/tools/Ruby193/lib/ruby/gems/1.9.1/gems/sshkit-1.5.1/lib/sshkit/backends/netssh.rb:128:in `tap'
C:/tools/Ruby193/lib/ruby/gems/1.9.1/gems/sshkit-1.5.1/lib/sshkit/backends/netssh.rb:128:in `_execute'
C:/tools/Ruby193/lib/ruby/gems/1.9.1/gems/sshkit-1.5.1/lib/sshkit/backends/netssh.rb:66:in `execute'
C:/tools/Ruby193/lib/ruby/gems/1.9.1/gems/capistrano-3.2.1/lib/capistrano/tasks/git.rake:17:in `block (3 levels) in <top (required)>'
C:/tools/Ruby193/lib/ruby/gems/1.9.1/gems/sshkit-1.5.1/lib/sshkit/backends/netssh.rb:54:in `instance_exec'
C:/tools/Ruby193/lib/ruby/gems/1.9.1/gems/sshkit-1.5.1/lib/sshkit/backends/netssh.rb:54:in `run'
C:/tools/Ruby193/lib/ruby/gems/1.9.1/gems/sshkit-1.5.1/lib/sshkit/runners/parallel.rb:13:in `block (2 levels) in execute'
NoMethodError: undefined method `colorize' for :location:Symbol
(eval):4:in `blue'

I've set up my release like this:
deploy.rb
lock '3.2.1'

set :application, 'myapp.com'
set :user, "deploy"
set :repo_url, 'git@bitbucket.org:me/myapp.com.git'
set :use_sudo, false
set :deploy_to, '/var/www/#{application}'
set :ssh_options, { :forward_agent => true }
set :deploy_via, :remote_cache
set :pty, true

Capfile
require 'capistrano/setup'
require 'capistrano/deploy'

Production.rb
set :location, "myapp.com"
role :app, :location
role :web, :location
role :db,  :location, :primary => true

server 'myapp.com', :roles => [:app, :web, :db], :primary => true

Installed gems and versions:
*** LOCAL GEMS ***

bigdecimal (1.1.0)
capistrano (3.2.1)
chunky_png (1.2.9)
colorize (0.7.3)
compass (0.12.2)
foundation (1.0.4)
fssm (0.2.10)
i18n (0.6.11)
io-console (0.3)
json (1.5.5)
minitest (2.5.1)
net-scp (1.2.1)
net-ssh (2.9.1)
rake (10.3.2, 0.9.2.2)
rdoc (3.9.5)
rubygems-update (2.1.11)
sass (3.2.12)
sshkit (1.5.1)
thor (0.18.1)

Does anyone know what to do or how to debug this? I can't find anything from googling... I saw something about colorize gem having to be 0.6+, but as seen above, I have latest (0.7.3 atm).

A: Alright, found out: this seems to has to do with version compatibility stuff in the Ruby gems. Found out, it worked on another laptop of mine and then compared configs - working machine was running

sshkit (1.3.0)

I downgraded sshkit from v. 1.5.1 to 1.3.0, which solved it.


text:
Q: Checking containment using integer programming For this question, a region is a subset of Zd defined by finitely many linear inequalities with integer coefficients, where Zd is the set of d-tuples of integers. For example, the set of pairs (x, y) of non-negative integers with 2x+3y >= 10 constitutes a region with d=2 (non-negativity just imposes the additional inequalities x>=0 and y>=0).

Question: is there a good way, using integer programming (or something else?), to check if one region is contained in a union of finitely many other regions?

I know one way to check containment, which I describe below, but I'm hoping someone may be able to offer some improvements, as it's not too efficient.

Here's the way I know to check containment. First, integer programming libraries can directly check if a region is empty: in integer programming terminology (as I understand it), emptiness of a region corresponds to infeasibility of a model. I have coded up something using the gurobi library to check emptiness, and it seems to work well in practice for the kind of regions I care about.
Suppose now that we want to check if a region X is contained in another region Y (a special case of the question). Let Z be the intersection of X with the complement of Y. Then X is contained in Y if and only if Z is empty. Now, Z itself is not a region in my sense of the word, but it is a union of regions Z_1, ..., Z_n, where n is the number of inequalities used to define Y. We can check if Z is empty by checking that each of Z_1, ..., Z_n is empty, and we can do this as described above.
The general case can be handled in exactly the same way: if Y is a finite union of regions Y_1, ..., Y_k then Z is still a finite union of regions Z_1, ..., Z_n, and so we just check that each Z_i is empty. If Y_i is defined by m_i inequalities then n = m_1 * m_2 * ... * m_k.
So to summarize, we can reduce the containment problem to the emptiness problem, which the library can solve directly. The issue is that we may have to solve a very large number of emptiness problems to solve containment (e.g., if each Y_i is defined by only two inequalities then n = 2^k grows exponentially with k), and so this may take a lot of time.

A: You can't really expect a simple answer. Suppose that A is defined by all constraints of the form  0 <= x_i <= 1. A can be thought of as the collection of all possible rows of a truth table. Given any logical expression of the form e.g. x or (not y) or z, you can express it as a linear inequality
such as x + (1-y) + z >= 1 (along with the 0-1 constraints). Using this approach, any Boolean formula in conjunctive normal form (CNF) can be expressed as a region in Z^n. If A is defined as above and B_1, B_2, ...., B_k is a list of regions corresponding to CNFs then A is contained in the union of the B_i if and only if the disjunction of those CNFs is a tautology. But tautology-checking is a canonical example of an NP-complete problem.
None of this is to say that it can't be usefully reduced to ILP (which itself is NP-complete). I don't see of any direct way to do so, though I suspect that some of the techniques used to identify redundant constraints would be relevant.


text:
Q: Remove focus when starting activity with scroll view I have the following layout for an activity:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/colorPrimary"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="10dp" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dp"
        android:layout_marginBottom="50dp"
        android:orientation="vertical"
        android:paddingLeft="20dp"
        android:descendantFocusability="beforeDescendants"
        android:focusableInTouchMode="true"
        android:focusable="true"
        android:paddingRight="20dp" >

        <EditText
            android:id="@+id/txtSignUpName"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:background="@android:color/white"
            android:hint="@string/signup_hint_name"
            android:inputType="textPersonName"
            android:padding="10dp"
            android:singleLine="true"
            android:textColor="@color/input_color"
            android:textColorHint="@color/input_hint_color" />

        <EditText
            android:id="@+id/txtSignUpEmail"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:background="@android:color/white"
            android:hint="@string/signup_hint_email"
            android:inputType="textEmailAddress"
            android:padding="10dp"
            android:singleLine="true"
            android:textColor="@color/input_color"
            android:textColorHint="@color/input_hint_color" />

        <EditText
            android:id="@+id/txtSignUpPassword"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:background="@android:color/white"
            android:hint="@string/signup_hint_password"
            android:inputType="textPassword"
            android:padding="10dp"
            android:singleLine="true"
            android:textColor="@color/input_color"
            android:textColorHint="@color/input_hint_color" />

        <Button
            android:id="@+id/btnSignUpGender"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/white"
            android:textColor="@color/input_hint_color"
            android:textAlignment="textStart"
            android:layout_marginBottom="10dp"
            android:paddingLeft="10dp"
            android:text="@string/signup_hint_gender" />

        <Button
            android:id="@+id/btnBirthdayDatePicker"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/white"
            android:textColor="@color/input_hint_color"
            android:textAlignment="textStart"
            android:paddingLeft="10dp"
            android:text="@string/signup_hint_birthday" />

        <!-- Login Button -->

        <Button
            android:id="@+id/btnSignUp"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dip"
            android:background="@color/colorAccent"
            android:text="@string/btn_signup"
            android:textColor="@android:color/white" />

        <!-- Link to Login Screen -->

        <Button
            android:id="@+id/btnLinkToLogin"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="40dip"
            android:background="@null"
            android:text="@string/btn_link_to_login"
            android:textAllCaps="false"
            android:textColor="@android:color/white"
            android:textSize="15dp" />
    </LinearLayout>
</ScrollView>

And when the activity starts it automatically starts the keyboard and the edit text get focused. How can I avoid this and start the activity without focus?
I have tried the following in the linear layout and in the scroll view without success.
android:descendantFocusability="beforeDescendants"
android:focusable="true"
android:focusableInTouchMode="true"

This seems weird because I have other activity with almost the same structure but less edit text's and works perfectly
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/colorPrimary"
    android:gravity="center"
    android:orientation="vertical"
    android:padding="10dp" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:orientation="vertical"
        android:paddingLeft="20dp"
        android:descendantFocusability="beforeDescendants"
        android:focusableInTouchMode="true"
        android:paddingRight="20dp" >

        <EditText
            android:id="@+id/txtLoginEmail"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:background="@android:color/white"
            android:hint="@string/login_hint_email"
            android:inputType="textEmailAddress"
            android:padding="10dp"
            android:singleLine="true"
            android:textColor="@color/input_color"
            android:textColorHint="@color/input_hint_color" />

        <EditText
            android:id="@+id/txtLoginPassword"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginBottom="10dp"
            android:background="@android:color/white"
            android:hint="@string/login_hint_password"
            android:inputType="textPassword"
            android:padding="10dp"
            android:singleLine="true"
            android:textColor="@color/input_color"
            android:textColorHint="@color/input_hint_color" />

        <!-- Login Button -->

        <Button
            android:id="@+id/btnLogin"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dip"
            android:background="@color/colorAccent"
            android:text="@string/btn_login"
            android:textColor="@android:color/white" />

        <!-- Link to Login Screen -->

        <Button
            android:id="@+id/btnLinkToRegister"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="40dip"
            android:background="@null"
            android:text="@string/btn_link_to_register"
            android:textAllCaps="false"
            android:textColor="@android:color/white"
            android:textSize="15dp" />
    </LinearLayout>
</ScrollView>

How can I make the first one work?

A: set android:windowSoftInputMode="stateAlwaysHidden" from manifest file
<activity
            android:name=".activitiyName"
            android:label="@string/label"
            android:windowSoftInputMode="stateAlwaysHidden" />


text:
Q: C#: Http Get behavior varies in different LAN I started an HTTP server in a local area network from C# as:
HttpListener listener = new HttpListener();
listener.Prefixes.Add(url);
listener.Start();

In another thread, it sends response as:
HttpListenerContext context = listener.GetContext();
context.Response.StatusCode = 200;
using (StreamWriter writer = new StreamWriter(context.Response.OutputStream)) {
    writer.WriteLine(responseJson);
}

And in my client code, Http request is sent and processed as:
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();
string result = await response.Content.ReadAsStringAsync();

This server-client application works well in one LAN. But after I copied the application to another machine in another LAN, the last line of client code (await response result) got error " The input was not in a correct format". I really have no idea what it is about. I visited the server url from web browser, the correct response could be retrieved. So this is more likely to be a client-side issue, I guess.
Any help is appreciate.


text:
Q: Yesod Persistent functions inaccessible from Handler. What should I include? I'm having trouble with a slightly altered Yesod scaffold. I've got my Entity described like so in /config/models:
Artist
    ident Int
    value Text

and here is my handler at /Handler/Artist.hs
{-# LANGUAGE QuasiQuotes, TypeFamilies, GeneralizedNewtypeDeriving, TemplateHaskell,
             OverloadedStrings, GADTs, FlexibleContexts #-}
module Handler.Artist where

import Import
import qualified Control.Monad.IO.Class as M
import Text.Hamlet (shamlet)
import Text.Blaze.Html.Renderer.String (renderHtml)
import Database.Persist
import Database.Persist.Sqlite
import Database.Persist.TH
import Control.Monad.IO.Class (liftIO)

getArtistR = concatMap (renderListElement . value) $ artists
  where artists = selectList ([] :: [Filter Artist]) []
        renderListElement name = renderHtml [shamlet|<li>#{name}|]

(I included with redundancy :) )
And lastly, my errors:
Rebuilding application... (using cabal)

Handler/Artist.hs:14:45: Not in scope: `value'
Build failure, pausing...

I'm not sure what I should do! Do I need to throw in something like $(widgetFile "artist") in the handler? Where is the patching going wrong? Any help would be so awesome. Thank you in advance!!!

A: You should prefix functions with model name, so value becomes artistValue.
Documentation contains example of generated code.


text:
Q: Why does call to jQuery's appendChild fail with undefined error? Here is my simple HTML:

        Hello World!

Here is the accompanying JavaScript:
$(document).ready(function() {
    var myDOMElement = document.getElementById("myParentDivElement");

    var newDivID = "div_1";
    var newDiv = $('
');
    $( newDiv ).css('marginLeft', '50px');

    var newSpanID = "span_1";
    var newSpan = $('');
    newSpan.text('myLabel');
    newDiv.appendChild(newSpan);
    $( myDOMElement ).appendChild(newDiv);
});

But when I run this code the line newDiv.appendChild(newSpan); gives the following error:
Uncaught TypeError: undefined is not a function

Can someone explain why?
Here is the JSFiddle showing that it doesn't work: http://jsfiddle.net/TsTMx/2/

A: Use .append()
newDiv.append(newSpan);

.appendChild() works with DOM element. newDiv is jQuery Object not a plain JavaScript DOM element.
Working Fiddle

A: newDiv is a jQuery object, not a DOM object.
jQuery objects do not have an appendChild method, they have an append method.

A: .appendChild() is a plain JavaScript method, not jQuery. The jQuery method is .append().
newDiv.append(newSpan);
$( myDOMElement ).append(newDiv);


text:
Q: Flutter test on provider with mockito I am creating test for my login procedures.
in first case if I expect only ProcessState.loading my test get success, but to confirm the full process I need to add second approach ProcessState.error but it is giving me the error that I defined below.
C:\src\flutter\bin\flutter.bat --no-color test --machine --start-paused --plain-name "Login provider" test\provider_test\login_provider_state.dart

package:test_api                                    expectLater
package:flutter_test/src/widget_tester.dart 468:10  expectLater
test\provider_test\login_provider_state.dart 27:7   main.<fn>.<fn>
loginCall:: ProcessState.error

Expected: ProcessState:<ProcessState.error>
  Actual: ProcessState:<ProcessState.loading>

As you can see it's printing ProcessState.error, but not working.
attaching my full code below.
Test section
class MockLoginRepository extends Mock implements LoginRepository {}

void main(){
  group('Login provider', (){
    LoginProvider loginProvider;
    MockLoginRepository repository;

setUp((){
  repository = MockLoginRepository();
  loginProvider = LoginProvider(repository);
});

test('login screen state test', () {
  loginProvider.emailController.text = 'mail@mailinator.com';
  loginProvider.passwordController.text = '12345678';

  loginProvider.loginCall();

  expect(loginProvider.state, ProcessState.loading);
  expectLater(loginProvider.state, ProcessState.error);
});

  });
}

Repository section
abstract class LoginRepository {
  Future<LoginResponse> loginCall(String email, String password);
}

Provider section
enum ProcessState {ideal, loading, loaded, error}

class LoginProvider extends ProviderState {
  final LoginRepository loginRepository;

  TextEditingController emailController = TextEditingController();
  TextEditingController passwordController = TextEditingController();

  LoginProvider(this.loginRepository);

  void loginCall() async {
    state = ProcessState.loading;

    LoginResponse response = await loginRepository.loginCall(
      emailController.text,
      passwordController.text,
    );

    if(response != null) {
      state = ProcessState.loaded;
      print('loginCall:: $state');
    } else {
      state = ProcessState.error;
      print('loginCall:: $state');
    }
  }
}

class ProviderState extends ChangeNotifier {
  ProcessState _state;

  ProcessState get state => _state;

  set state(ProcessState value) {
    _state = value;
    notifyListeners();
  }
}


text:
Q: XSLT - Nested For-each with core-if I want to remove the Resource nodes from the XML if they are not present in TaskLabor node using the resourceID attribute. I don't know how to access the variables inside for-each. can anyone please fix this?
I have provided the XSL transformation below. Instead of for-each, Can it be done using apply-templates?
Input XML:
<Project projectID="project1" name="My Project">
    <Resources>
        <Resource resourceID="abc@mycompany.com"/>
        <Resource resourceID="def@mycompany.com"/> <!-- Need to Remove this -->
        <Resource resourceID="xyz@mycompany.com"/>
        <Resource resourceID="test@mycompany.com"/> <!-- Need to Remove this -->
    </Resources>
    <Tasks>
        <Task name="Task1"
        taskID="100-150221">
            <Assignments>
                <TaskLabor finish="2020-12-31"
                   resourceID="abc@mycompany.com"
                   start="2020-01-01">
                </TaskLabor>
                <TaskLabor finish="2020-12-31"
                   resourceID="xyz@mycompany.com"
                   start="2020-01-01">
                </TaskLabor>
            </Assignments>
        </Task>
        <Task name="Task2"
        taskID="100-12313">
            <Assignments>
                <TaskLabor finish="2020-12-31"
                   resourceID="abc@mycompany.com"
                   start="2020-01-01">
                </TaskLabor>
            </Assignments>
        </Task>
    </Tasks>
</Project>

XSL Transformation:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

    <xsl:template match="/">
        <xsl:variable name="resources" select="Project/Resources/Resource"/>
        <xsl:variable name="tasks" select="Project/Tasks/Task"/>
        <xsl:for-each select="$resources">
            <xsl:variable name="resID" select="./@resourceID"/>
            <xsl:for-each select="$tasks">
                <xsl:for-each select="./Assignments/TaskLabor">
                     <xsl:if test="$resID = ./@resourceID">
                        <xsl:value-of select="Project/Resources/Resource"/>

                     </xsl:if>
                </xsl:for-each>
            </xsl:for-each>
        </xsl:for-each>
     </xsl:template>
</xsl:stylesheet>

Expected Output
<Project projectID="project1" name="My Project">
    <Resources>
        <Resource resourceID="abc@mycompany.com"/>
        <Resource resourceID="xyz@mycompany.com"/>
    </Resources>
    <Tasks>
        <Task name="Task1"
        taskID="100-150221">
            <Assignments>
                <TaskLabor finish="2020-12-31"
                   resourceID="abc@mycompany.com"
                   start="2020-01-01">
                </TaskLabor>
                <TaskLabor finish="2020-12-31"
                   resourceID="xyz@mycompany.com"
                   start="2020-01-01">
                </TaskLabor>
            </Assignments>
        </Task>
        <Task name="Task2"
        taskID="100-12313">
            <Assignments>
                <TaskLabor finish="2020-12-31"
                   resourceID="abc@mycompany.com"
                   start="2020-01-01">
                </TaskLabor>
            </Assignments>
        </Task>
    </Tasks>
</Project>

A: Declare a key <xsl:key name="task-ref" match="TaskLabor" use="@resourceID"/>  and then you simply need to block elements which don't reference a TaskLabor from being copied by the identity transformation by using an empty template for them:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    version="1.0">

  <xsl:key name="task-ref" match="TaskLabor" use="@resourceID"/>

  <xsl:template match="@* | node()">
    <xsl:copy>
      <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="Resource[not(key('task-ref', @resourceID))]"/>

</xsl:stylesheet>

https://xsltfiddle.liberty-development.net/3NSTbfg


text:
Q: Under what conditions does an Integer Programming problem run in polynomial time? Given $AX\leq B$ where $A\in\Bbb Z^{m\times n}$,$B\in\Bbb Z^m$ finding $X\in\Bbb Z^n$ where $m\geq n$ is the integer programming problem. If $A$ is totally unimodular then the problem is solvable in polynomial time ($(mn)^c$ arithmetic operations on $(mn)^c$ sized words suffices).
Supposing we have the promise that the number of feasible solutions is polynomial then under what conditions can the problem be solved in polynomial time using Kannan's and Barnivok's algorithm (other than total unimodularity)?

*

*It may be possible that naturally defining IP with poly # solutions is in P unless somehow defined by Unique-SAT.

*Is it possible that if perfect basis reduction for given problem is in P then Kannan's algorithm is in P?

*Is there necessary and sufficient conditions on categories of inputs on which the algorithms run in poly time?
It is unlikely that Kannan's algorithm or Barnivok's algorithm runs uniformly in $n^{O(n)}$ time for all inputs.
There is no evidence whatsoever that Kannan's or Barnivok's algorithm ever runs in poly time for any non-trivial class of inputs which is why the query. It seems unbelievable that there cannot be input families for which these terminate in poly time.
By non-trivial class of inputs I mean an exponential set of inputs.
https://cstheory.stackexchange.com/questions/37777/under-what-conditions-does-an-integer-programming-problem-run-in-polynomial-time

A: The way I think about Kannan's algorithm (or, for that matter, any of the several "Lenstra-type" algorithms which present similar bounds as the original Lenstra algo from 1983) is that it's designed with the extreme worst-case instances of integer programming (IP) in mind. The goal here is to get a small (i.e., polynomial) bound on the complexity of the general problem instance without any assumptions about any special structure of the input (matrix $A$, or even $B$).
Notice that IP with totally unimodular (TU) $A$ matrix is solvable in polynomial time not by Kannan's algorithm (or by any of the Lenstra-type algorithms), but by simply solving the IP as a linear program, which could be done in polynomial time, and we get integrality "for free" in that process. Other generalizations of TU matrices such as balanced matrices or total dual integrality (TDI) also guarantee integrality "for free" in a similar fashion as instances where $A$ is TU (some times with additional assumptions on $B$ also). Recently (STOC '17), Artmann, Weismantel, and Zenklusen gave a strongly polynomial algo for bimodular IPs, where $|\det(S)| \leq 2$ for all submatrices $S$ of $A$ (preprint might be available on ResearchGate). People have also considered the natural generalization of this problem where $|\det(S)| \leq \Delta$ for higher (but fixed) values of $\Delta$. The latest preprint by Gribanov provides an FTP algo for instances of IP where $A$ is "near square" (see the preprint for details). But again, all these families of algorithms somehow use the special problem structure, e.g., $|\det(S)| \leq \Delta$ (on a related note, we have studied (arXiv) a class of IP instances where $A$ is not TU, no fixed bound on $|\det(S)|$ is assumed, but still the LP relaxation of the IPs are guaranteed to have integer optimal solutions; but even here, the problems have a different kind of special structure).
In other words, the Lenstra-type algos (including Kannan's) are not designed to work better (or faster) on any specific subclass of IPs with special structure. As such, it's not surprising no such obvious instances have been identified as yet.


text:
Q: Pitivi blank box Where the layer settings (I think) box should be in Pitivi 0.93 in Ubuntu 14.10, there's only a white box.

Terminal output when starting Pitivi:

(pitivi:8218): Clutter-WARNING **: clutter_x11_set_use_argb_visual() can only be used before calling clutter_init()

(pitivi:8218): Clutter-WARNING **: clutter_x11_set_display() can only be used before calling clutter_init()

(pitivi:8218): Clutter-WARNING **: clutter_x11_disable_event_retrieval() can only be used before calling clutter_init()

(pitivi:8218): Clutter-WARNING **: clutter_disable_accessibility() can only be called before initializing Clutter.
Missing soft dependency:
- pycanberra not found on the system
    -> enables sound notifications when rendering is complete
Missing soft dependency:
- GnomeDesktop not found on the system
    -> file thumbnails provided by GNOME's thumbnailers

(pitivi:8218): Gdk-WARNING **: gdk_window_set_icon_list: icons too large
/usr/lib/x86_64-linux-gnu/pitivi/python/pitivi/project.py:559: TypeError: Passing arguments to gi.types.Boxed.__init__() is deprecated. All arguments passed will be ignored.
  Gst.Caps("application/ogg"),
/usr/lib/x86_64-linux-gnu/pitivi/python/pitivi/project.py:563: TypeError: Passing arguments to gi.types.Boxed.__init__() is deprecated. All arguments passed will be ignored.
  video_profile = GstPbutils.EncodingVideoProfile.new(Gst.Caps("video/x-theora"),
/usr/lib/x86_64-linux-gnu/pitivi/python/pitivi/project.py:565: TypeError: Passing arguments to gi.types.Boxed.__init__() is deprecated. All arguments passed will be ignored.
  Gst.Caps("video/x-raw"),
/usr/lib/x86_64-linux-gnu/pitivi/python/pitivi/project.py:569: TypeError: Passing arguments to gi.types.Boxed.__init__() is deprecated. All arguments passed will be ignored.
  audio_profile = GstPbutils.EncodingAudioProfile.new(Gst.Caps("audio/x-vorbis"),
/usr/lib/x86_64-linux-gnu/pitivi/python/pitivi/project.py:571: TypeError: Passing arguments to gi.types.Boxed.__init__() is deprecated. All arguments passed will be ignored.
  Gst.Caps("audio/x-raw"),
/usr/lib/x86_64-linux-gnu/pitivi/python/pitivi/project.py:792: TypeError: Passing arguments to gi.types.Boxed.__init__() is deprecated. All arguments passed will be ignored.
  self.container_profile.set_format(Gst.Caps(muxertype))
/usr/lib/x86_64-linux-gnu/pitivi/python/pitivi/project.py:771: TypeError: Passing arguments to gi.types.Boxed.__init__() is deprecated. All arguments passed will be ignored.
  self.video_profile.set_format(Gst.Caps(videotype))
/usr/lib/x86_64-linux-gnu/pitivi/python/pitivi/project.py:751: TypeError: Passing arguments to gi.types.Boxed.__init__() is deprecated. All arguments passed will be ignored.
  self.audio_profile.set_format(Gst.Caps(audiotype))
/usr/lib/python2.7/dist-packages/gi/overrides/GLib.py:548: Warning: Source ID 38 was not found when attempting to remove it
  super(MainLoop, self).run()

And when I import video and drag it to the layer area (when the white box appears):

(pitivi:8362): Gdk-WARNING **: gdk_window_set_icon_list: icons too large

(pitivi:8362): Clutter-WARNING **: Unable to query pixmap: 44019c2

(pitivi:8362): Clutter-WARNING **: Unable to query pixmap: 44019c4

(pitivi:8362): Clutter-WARNING **: Unable to query pixmap: 44019c6

(pitivi:8362): Clutter-WARNING **: Unable to query pixmap: 44019c8

(pitivi:8362): Clutter-WARNING **: Unable to query pixmap: 44019ca

(pitivi:8362): Clutter-WARNING **: Unable to query pixmap: 44019cc

(pitivi:8362): Clutter-WARNING **: Unable to query pixmap: 44019ce

(pitivi:8362): Clutter-WARNING **: Unable to query pixmap: 44019ff

(pitivi:8362): GStreamer-CRITICAL **: _gst_util_uint64_scale: assertion 'denom != 0' failed

(pitivi:8362): Clutter-WARNING **: Unable to query pixmap: 4401af2

(pitivi:8362): Clutter-WARNING **: Unable to query pixmap: 4401b19

(pitivi:8362): Clutter-WARNING **: Unable to query pixmap: 4401b40

(pitivi:8362): Clutter-WARNING **: Unable to query pixmap: 4401b67

(pitivi:8362): Clutter-WARNING **: Unable to query pixmap: 4401b8e

(pitivi:8362): Clutter-WARNING **: Unable to query pixmap: 4401bb5

More (pitivi:8362): Clutter-WARNING **: Unable to query pixmap: <blahblah> is dumped when trying to interact with the white box (It can be drug down and strings back).
Changing gnome theme and restart the app changes nothing.
There are two horizontal areas within the white box that respond right click events and show a context menu about moving or deleting a layer.


text:
Q: MVC Not Parsing the Correct Value from Model Can anyone tell me why, if my model clearly shows my values to be "true" or "false" MVC still thinks it says, "true,false."  I assume this is because it is confusing the Request with my Model; however, I am explicitly telling it to use the Model.

As you can see in the image above, the model value is "true."  However, in the image below, it thinks the value is "true,false."  How can I make it just use "true?"

Model
public class TagCategorySearchViewModel
{
    public long Id { get; set; }

    public string Name { get; set; }

    public List<TagSearchViewModel> Tags { get; set; }
}

public class TagSearchViewModel
{
    public long Id { get; set; }

    public string Name { get; set; }

    public bool IsSelected { get; set; }
}

Controller
    [Authorize]
    public ActionResult FilterPrereqGrid(EditStudentPrerequisitesViewModel model, int page = 1)
    {
        model.Prerequisites = new List<PrerequisiteListViewModel>();
        var businessPartner = _bpManager.GetBusinessPartnerByMapGuid(model.BusinessPartnerMapGuid);

        model.Prerequisites.AddRange(_epManager.GetFullPrerequisitesLeftJoinedWithExperience(model.ExperienceId, businessPartner?.Id));

        // fix for how MVC binds checkboxes... it send "true,false" instead of just true, so we need to just get the true
        for (int i = 0; i < model.TagCategories?.Count(); i++)
        {
            for (int j = 0; j < model.TagCategories[i].Tags?.Count(); j++)
            {
                model.TagCategories[i].Tags[j].IsSelected = bool.Parse((Request.QueryString[$"TagCategories[{i}].Tags[{j}].IsSelected"] ?? "false").Split(',')[0]);
            }
        }

        var selectedTagIds = model.TagCategories?.SelectMany(x => x.Tags).Where(x => x.IsSelected == true).Select(x => x.Id).ToArray();

        // filter by selected tags
        if (selectedTagIds.Any())
        {
            model.Prerequisites = (from p in model.Prerequisites
                                   let prereqTagIds = p.Prerequisite.PrerequisiteTags.Select(et => et.TagId)
                                   where selectedTagIds.All(x => prereqTagIds.Contains(x))
                                   select p).ToList();
        }

        model.Prerequisites = (from m in model.Prerequisites
                               let ownerDocs = _deManager.GetDocumentsByOwnerAndSourceId(model.BusinessPartnerMapGuid, m.Prerequisite.Id).OrderByDescending(e => e.CreatedDate)
                               select new PrerequisiteListViewModel
                               {
                                   Prerequisite = m.Prerequisite,
                                   Selected = m.Selected,
                                   Mandatory = m.Mandatory,
                                   HasExpiration = m.Prerequisite.HasExpiration,
                                   BusinessExpirationPeriod = m.Prerequisite.ExpirationPeriod == 0 ? "None" : m.Prerequisite.ExpirationPeriod.ToString(),
                                   DocOwnerGuid = (ownerDocs.Any() ? model.BusinessPartnerMapGuid : Guid.Empty),
                                   DocRowGuid = (ownerDocs.Any() ? ownerDocs.First().DocRowguid : Guid.Empty),
                                   HasDocuments = ownerDocs.Any()
                               }).ToList();

        int rowsPerPage = 1;

        model.TotalRecords = model.Prerequisites.Count();
        model.Prerequisites = model.Prerequisites.Skip(page * rowsPerPage - rowsPerPage).Take(rowsPerPage).ToList();

        return PartialView("~/Views/BusinessExperience/_EditPrerequisites.cshtml", model);
    }

A: That is by design.  The Html.CheckBoxFor extension actually renders something like the following:
<input type="checkbox" .. />
<input type="hidden" />

So both of these have the same name as the property you are rendering out.  When checked, the checkbox returns "True", but when unchecked, the checkbox returns nothing.  That is the way checkboxes work with form posts.  In order to determine that nothing was checked, the MVC framework included a hidden field so that it would return "False" when not checked, but "True,False" when checked (since multiple items with the same name return this way from the form post).  And then MVC model binding converts "True,False" to true.
You could just render your own <input type="checkbox" /> with a value of true, and that would just return true, but when unchecked, nothing gets rendered.  Be aware of that...

A: This actually works, it's a shame I can't just do the obvious way and have to write this all out though!
@model List<Prep2PracticeWeb.Models.ViewModels.TagCategorySearchViewModel>

@if (Model != null)
{

        @for (int i = 0; i < Model.Count(); i++)
        {
            @Html.HiddenFor(x => Model[i].Id)
            @Html.HiddenFor(x => Model[i].Name)

                @Model[i].Name

                                @if (Model[i].Tags != null)
                                {
                                    for (int j = 0; j < Model[i].Tags.Count(); j++)
                                    {
                                        @Html.HiddenFor(x => Model[i].Tags[j].Id)
                                        @Html.HiddenFor(x => Model[i].Tags[j].Name)
                                        @* the following commented out line won't work because MVC is funny *@
                                        @*@Html.CheckBoxFor(x => Model[i].Tags[j].IsSelected) @Model[i].Tags[j].Name*@

                                            <input @(Model[i].Tags[j].IsSelected ? @"checked=""checked""" : string.Empty) data-val="true" data-val-required="The IsSelected field is required." id="TagCategories_@(i)__Tags_@(j)__IsSelected" name="TagCategories[@i].Tags[@j].IsSelected" type="checkbox" value="true"> @Model[i].Tags[j].Name
                                            <input name="TagCategories[@i].Tags[@j].IsSelected" type="hidden" value="false">

                                    }
                                }

        }

}

Update: I realized GET was not an appropriate strategy in this scenario given the fact that the querystring can only be so long before the server returns a 500 error.  I switched to POST which alleviated the issue.


text:
Q: Organizing unit tests in angular app Testing modules dependent on other modules, and providers and services in them - possible. Let's say we need to test module 'A' that depends on module 'B':
totally not coffeescript, rather pseudo code for brevity :)
 beforeEach ->
    angular.module('B',[])
    module ($provide)->
       $provide.provider 'foo', ->
           this.$get = ->  # ...etc...etc.

 it 'testing module A', ->
    module('A')
    inject ->  # ...etc...etc.

Now, imagine we have quite a few modules that need to be mocked, and many services and providers. So how would you move faking 'B' part into a separate file?
and how they'd be used after? It's quite possible to use module loaders (webpack, browserify) but how would one do without? Using angular capabilities and what Karma offers out of the box?
Is it possible to wrap entire mock into an angular module and load it in beforeEach?

A: Yes, actually, making services their own modules can easily be tested in Angular using Karma.
As long as you have your testing framework set up properly—Angular mocks, and all of the required modules are loaded into Karma (check the Karma config)—then this is fairly straight-forward.
The below example assumes FirstService is the service you are testing, and SecondService is another service that FirstService depends on and interacts with.
describe('FirstService', function () {
  var SecondService;

  beforeEach(module('FirstService'));

  beforeEach(inject(function (_SecondService_) {
    SecondService = _SecondService_;
    spyOn(SecondService, 'doSomethingElse');
  }));

  it('calls SecondService.doSomethingElse', function () {
    FirstService.doSomething();

    expect(SecondService.doSomethingElse).toHaveBeenCalled();
  });
});

You include the module in a beforeEach as specified on the first line—do not use square brackets [] when including it as that redefines the module and you want to include the existing module as-is.
Although you should omit the square brackets when importing modules, you should be sure that when you are initially creating your FirstService module (e.g., in your app.js file, if that's how your project is set up) that you are indeed including SecondService as a dependency:
angular.module('FirstService', ['SecondService'])

The second beforeEach is injecting the SecondService module. It is already globally available to be injected and can be accessed by its module name with a leading and trailing underscore, i.e. _SecondService_. I've assigned it to a variable so that it is available to be used in the it statements, otherwise I would need to inject it in each it statement instead of a beforeEach.
I am creating a spy using Jasmine's spyOn to spy on the method doSomethingElse to ensure it has been called. The second parameter of spyOn (the method name) should have quotes but the first should not—it should be the variable you just defined for your SecondService.
The example unit test tests that calling FirstService.doSomething() calls SecondService.doSomethingElse().


text:
Q: Is it correct to say "expanded job opportunities"? The sentence in question:

Comparatively, they refused to shrink back into the domestic sphere; 80 percent who worked outside the home wished to continue doing so by the war's end. Women continued to push for expanded job opportunities, entry into professional roles, and greater access to higher education.

The dictionary says, expanded:

a) being or having been enlarged or extended (related to shape)

surely doesn't apply in this sentence

b) become or make larger or more extensive.

with subparts based on: become less reserved in character or behaviour OR give a fuller version or account of.
Surely, none of the above definitions correspond to the correct intended meaning of the word, as said by KA, that women sought more opportunities in the workforce.
Hence, My question:

Why is "expanded" the correct word to use in this sentence, when none of its dictionary meanings correspond to what it's actually supposed to mean?

for reference - courtesy KA; correct answer for editing the word "expanded" is - no change
Passage: "A "Rosie" Turn on American Labor"
[four initial paragraphs omitted]
As a result of their entry into careers from which they were previously excluded, women exercised a newfound social and economic independence. They enjoyed having an income of their own and living on their own for the first time. Comparatively, they refused to shrink back into the domestic sphere; 80 percent who worked outside the home wished to continue doing so by the war's end. Women continued to push for expanded job opportunities, entry into professional roles, and greater access to higher education. As the graph suggests, Rosie's influence persisted even after the war. To this day, Rosie continues to influence women as a symbol of feminism in popular culture.
All options:
A. NO CHANGE
This choice is the best answer because "expanded" is the most contextually appropriate way to say that women sought more opportunities in the workforce.
B. inflated
"Inflated" is not the most contextually appropriate way to suggest that women sought further opportunities and advancements in the workforce. While "inflated" does offer some sense of growth, it also carries the negative connotation of something gaining more power than its actual value merits.
C. amplified
"Amplified" is not the most contextually appropriate way to suggest that women sought further opportunities and advancements in the workforce. While "amplified" does offer some sense of growth, it also carries a connotation of sound and intensity that is not appropriate in this context.
D. prolonged
"Prolonged" is not the most contextually appropriate way to suggest that women sought further opportunities and advancements in the workforce. While "prolonged" does offer some sense of growth, it also implies a temporal factor associated with the jobs, which is not relevant in this context.


text:
Q: How to match two lists of tuples? It's easy enough when the elements are primitive values, and a match is for identity.  Unfortunately, I've got lists of distance and direction, and I want to see if anything in one list "obscures" (is in the same direction and closer than) anything in the other and just retain the ones in the first list that are not obscured by anything in the second.  I'm happy to sort the lists, but the matching and list management is getting complicated.  Direction is a pair of integers (dx and dy) and only exact matches are interesting.
The tuples in both lists are of the form (dx, dy, distance)

A: I hope I understood your problem correctly, but wouldn't this help:

*

*Put the list items into buckets by their direction.

*Sort each bucket by distance, so that the least distant item is always the first one.

*Take only the first item from each bucket.


text:
Q: using() and dispose with multiple wrapped streams Am I right that you'd only need a using() for the outermost stream if you're doing e.g
MemoryStream mstr = new MemoryStream();

using(StreamWriter w = new StreamWriter(mstr)) {
    ....
}

As disposing the StreamWriter should also dispose/close the underlying stream, there's no need to do this ?:
using(MemoryStream mstr = new MemoryStream())
using(StreamWriter w = new StreamWriter(mstr)) {
    ....
}

(Note these are just examples, for how to dispose wrapped streams, not looking for alternatives like just use a StringWriter etc.)

A: My rule of thumb: If it implements IDisposable, dispose of it.
While currently (and probably forever), calling StreamWriter.Dispose() closes the underlying stream, other stream-derived classes you may use in the future may not.  Also, it seems not to actually call Dispose() either, so non-MemoryStreams may not get properly disposed (although I can't think of any that would suffer from that right now).
So, while you can safely dispose only of the StreamWriter, I find it a much better practice to always use using blocks for disposables whenever possible.

A: From looking at the StreamWriter.Dispose method in Reflector, it looks like the underlying streams get closed, but not disposed.  I would put each stream in a "using" block in order to explicity dispose of them all.

A: To answer your actual question. TextWriter's Dispose method
public void Dispose()
{
    this.Dispose(true);
    GC.SuppressFinalize(this);
}

It calls a protected Dispose and passes true to it. From TextWriter.Dispose Method (Boolean)

When the disposing parameter is true,
  this method releases all resources
  held by any managed objects that this
  TextWriter references. This method
  invokes the Dispose method of each
  referenced object.

However it is best practice to wrap everything that implements IDisposable in a using block, because we cannot guarantee that that the protected Dipose method will always be called with the true parameter.

A: It's a good idea to put all dependent resources in their own using blocks from a readability and maintainability point of view as much as anything. e.g. in the below code, after the final brace, it's impossible to attempt to access mstr because it is scoped to within the block where it is valid:
using (MemoryStream mstr = new MemoryStream())
using (StreamWriter w = new StreamWriter(mstr) {
    ....
}

// cannot attempt to access mstr here

If you don't scope it like this, then it's still possible to access mstr outside the scope of where it is valid
MemoryStream mstr = new MemoryStream();
using (StreamWriter w = new StreamWriter(mstr) {
    ....
}

mstr.Write(...); // KABOOM! ObjectDisposedException occurs here!

So while it may not always be necessary (and in this case it isn't) it's a good idea as it both clarifies and enforces your intention as to its scope.

A: It's really a better practice to just always use a using block.
"Always", except for the one well-known case of WCF proxy classes, where a design flaw can sometimes cause their Dispose methods to throw an exception, losing your original exception.


text:
Q: How to use Assert method and Selenium with TestNg framework to compare two integers I am practicing Selenium using the TestNG framework and assertion and there are 3 things that I can't solve.
note: there is no page for XPath.. integers are static.

*

*selenium script to Compare 3 and 5.

*selenium script to get boolean result of 3>5.

*Selenium script for a string to check palindrom.

A: https://www.javadoc.io/doc/org.testng/testng/latest/org/testng/Assert.html
see the full list of support assertion , so there is no specific method for checking greater than, use equals and true.
import org.testng.Assert;

Assert.assertEquals(2, 2);
Assert.assertFalse( 2 > 30 , "comparing 2 greater than 30");
Assert.assertEquals("teet", new StringBuilder("teet").reverse().toString());

Assert.assertTrue("teet".contentEquals(new StringBuilder("teet").reverse().toString())


text:
Q: Wordpress comments security The comments section of the wordpress accepts anything that the user write without filtering the content of it for any malicious entry. I checked this by adding a javascript comment as a comment to my site. Please see the below two points regarding this issue.
1) I have setup my Wordpress site to show comments when the admin approves them. Therefore at the moment any user from the outside will not see any spam comments which I haven't been approved. However, these spam comments are appears when I login as an admin and view the site. Can I block unapproved comments on my posts when I login and view the site as an admin?
2) Are there any technical solutions for this issue? I am using "All-in-one-security&firewall" plugin and "Wordfence" plugin in my blog. It looks like these plugins are not protecting my site from commnts. Are there any free plugin that I can use to stop this thing happening again?

A: You can always mark comments as spam in the comments section of your wordpress backend.
Also, like some suggested, it's possible to install a plugin that takes care of comments right away, so they will be put in the spam section automatically. Here are two plugins that worked fine for me and are free to use, that you could try:
https://wordpress.org/plugins/invisible-captcha/
https://wordpress.org/plugins/antispam-bee/


text:
Q: Parse current cell contents into URL based on the content of the same cell in Google Sheets I would like to parse the content of a cell into a URL based on the entered content of the same cell in Google Sheets.  I need the entire column to be processed.
Right now I can only accomplish this with two columns like this...
Column A has an ID number.  Column B uses an array to parse a URL based on the ID number in Column A.  The array formula I'm using in B2 is...
=ARRAYFORMULA(HYPERLINK("http://www.website.com/content/"&B3:B, ""&B3:B))

So A3 might have the ID number entry: 216856
And this creates the URL in B3: http://www.website.com/content/216856
But what I would really love, is a way to do this with one column.  Perhaps through a script?  Can anyone help me with this, please?  Thank you!

A: If you highlight the column you want to transform then go to edit and choose the find and replace functionality or press command shift and H it will also pop up - then in the find field enter: ^ and in the replace field enter http://www.website.com/content/ and check the search using regular expressions checkbox.
Once you click replace all, it will add that part of the url to the beginning of all the cells thus turning it into a URL for you. Super easy and generally pretty quick depending on how many rows you have - I have done this with tens of thousands of rows and more.


text:
Q: How to show and update total price with javascript? So I want to add a product and at the same time update the totalprice in the shopping cart.
$(".articel input[type='button']").click(function() {
    var price = $(this).siblings("input[name='price']").attr("value");
    var quantity = $(this).siblings("input[type='number']").attr("value");

    if (quantity % 1 != 0) {
        alert("You must add a whole number");
    }
    else if (quantity <= 0) {
        alert("You can not add a negative number or nothing");
    }
    else {
        var name = $(this).siblings("input[name='prodname']").attr("value");
        var ul = document.getElementById("buylist");
        var totalprice = quantity * price;
        var prod = name + " x " + quantity + "= " + totalprice + "$";
        var el = document.createElement("li");
        el.innerHTML = prod;
        ul.appendChild(el);
    }
});
});

Here is where the products and totalprice adds:

Shopping Cart

Total price:

Checkout

And here one of the forms where I add products to the cart
<form class="articel">
    Quantity: <input type="number" style="width:30px;">

    Add to cart: <input type="button" class="btn">
    <input type="hidden" value="30" name="price">
    <input type="hidden" value="The walking dead" name="prodname">
</form>

A: Maybe I don't really understand. But when the products or their quantity change, you have to calculate the price. I suggest, that you already have an event for both of those actions. Then I'd run a function who calculates the price.
Now it depends if you already have a fix price or also have to multiply that with the quantity. Loop through the products and calculate the price.
NOTE: To select the price & quantity I used selectors which you actually don't have in your code.
function calculatePrice() {
    var quantity, price, sum = 0;
    //loop through product "blocks"
    $('.articel').each(function() {
        price = $(this).children('.price').val();
        quantity = $(this).children('.quantity').val();
        //Add price to sum if number
        if (!isNaN(price) && !isNaN(quantity)) {
            sum += price * quantity;
        }
    });
    //Update Price
    $('#totalprice').html('
Total price:' + sum + '</h4');
}

A: If you add the price and quantity to the UL you can process easily:

...

Add this function to the javascript file.
function calcTotal (ul) {
  var newTotal = 0;
  ul.find('li').each( function(i,e) {
    var li = $(e);
    newTotal += li.data('quantity') * li.data('price');
  });
}

Then in your code, where there is the last else:
itemPrice = quantity * price;
var prodDesc = name + " x " + quantity + "= " + itemPrice + "$";//same as it was.
var newLi = $("
");
newLi.text(prodDesc).data('quantity', quantity).data('price', price);
ul.append(newLi);
var totalPrice = calcTotal(ul);
$('#totalprice h4').text('Total Price: ' + totalPrice);

More or less that's it.


text:
Q: Convergence of Newton Raphson when derivative at root is 0 How would one show that the newton raphson method converges linearly in these 2 cases?
$i) f'(\alpha)=0, f''(\alpha)\ne0$
$ii)f'(\alpha)=0, f''(\alpha)=0, f'''(\alpha)\ne0$
where $\alpha$ is the root of the function. The hint I have been given is to use L'Hopitals rule, but cant quite figure it out.

A: Write $f(x)=(x-α)^m·g(x)$ with $g(α)\ne 0$ and use $x\approx α$ to find
$$
x-\frac{f(x)}{f'(x)}\approx α+\frac{m-1}m(x-α)
$$


text:
Q: Central limit theorem: Poisson equals Normal? Tell me where I'm wrong We just covered the Central Limit theorem in class, and I stumbled upon the following reasoning that makes me think I am missing some key part of... well, something. So, here goes:
Let $X_1$ and $X_2$ be independent Poisson random variables with parameters $\lambda _1$ and $\lambda _2$ respectively. Then, $X_1 + X_2 \sim P(\lambda_1 + \lambda_2)$. By induction, for any finite $n$, if $X_i \sim P(\frac1n)$ iid, $\sum ^n X_i= X \sim P(1)$, and this holds (I think) for $n \to \infty$.
But, by the CLT,
$$ \frac{\sum ^n X_i - n\cdot\frac1n}{\sqrt{n\cdot \frac1n}}\to \tilde Y \sim N(0, 1) $$
And rearranging I get $X \to Y \sim N(1, 1)$.
But $X$ was a Poisson random variable, therefore discrete, and thus its CDF is constant everywhere except over the integers; while $Y$ is a Normal, and therefore its CDF is never constant. How is one supposed to converge to the other?
This result is clearly wrong, but I can't understand why. Can anyone please explain where in my argument I made a mistake?

A: The central limit theorem does not apply here because the distribution of the random variable you're considering depends on $n$. If you wanted to apply CLT you'd do it to $X_i \sim P(\lambda)$ and keep $\lambda$ fixed.
The relevant theorem in this situation is closer to the Poisson limit theorem.

A: Suppose $X_1,X_2,X_3,\ldots\sim \operatorname{i.i.d.~Poisson(1)}.$ Then
$$
\frac{(X_1+\cdots+X_n)-n}{\sqrt n} \overset{\text{distribution}} \longrightarrow N(0,1) \text{ as } n\to\infty. \tag 1
$$
More generally, if $X\sim\operatorname{Poisson}(\lambda)$ then
$$
\frac{X-\lambda}{\sqrt\lambda} \overset{\text{distribution}}\longrightarrow N(0,1) \text{ as } \lambda\to\infty \\  \text{(where $\lambda$ is not constrained to take integer values).}
$$
But notice that in $(1),$ the distribution of each random variable $X_1,X_2,X_3,\ldots$ remains the same as $n\to\infty.$ You need that in order to apply the central limit theorem.


text:
Q: Git merge. Behavior different on explicit merge than on pull I have a problem with my git configuration. I like to use the --no-ff option when I merge two branch. So I put on my configuration file ~/.gitconfig under the section [merge] the option ff = no. Which set the no fast forward behavior by default.
But now my problem is that when I do a git pull, it create a new commit (and merge) even if there's no modification. So i'm obliged to specify --ff on the pull command... Which is the same than specify --no-ff on the merge.
Is there a way to configure separately each of there two command ?
Thanks for your answers.


text:
Q: How to burn a burn folder from Applescript I've written an AppleScript script which creates a burn folder and copies aliases for the files I want to burn to the CD/DVD in that folder.  It works well.  What I'd like the script to do next is actually start the burn process.  It's OK if I get prompted to insert a disk.
How do you get AppleScript to start the burn process?  Is it possible?

A: May be the with Automator.app included action "Burn a Disc" could help you. It's under "Utilities".
ADDITION
I just did a man -k burn in Terminal and it showed a console utility named drutil -- interact with CD/DVD burners. That looks like it would do the trick*
(it's easy to call any console utility with the do shell script command)


text:
Q: Zero line for primary and secondary axis - matplotlib I am trying to display 2 data on a plot, each of them is assigned on primary and secondary axis respectively.
Here are the codes
ax2 = ax1.twinx()
ax1.plot(df['year'], df['present_value']/1000000, 'g-')
ax2.plot(df['year'], df['cum_pv']/1000000, 'b-')

ax1.set_xlabel('X data')
ax1.set_ylabel('Y1 data', color='g')
ax2.set_ylabel('Y2 data', color='b')

plt.show()

But it displays a chart with not equal zero levels, (notice how 0 on primary is on a different level from 0 on secondary axis) `
How can I make the zero scale on the same level from my codes above?

A: You can use the set_ylim()-method of each axis to adjust them manually.
import matplotlib.pyplot as plt

y1 = [-1,2,3]
y2 = [-10,-5,10]
x = [1,2,3]

fig, ax1 = plt.subplots() # opens a figure with a single axis
ax2 = ax1.twinx() # instantiate a second axes that shares the same x-axis
ax1.plot(x,y1, 'g-')
ax2.plot(x,y2, 'b-')

plt.show()

Here is a way, which assumes that there actually is a zero in both y-axes
# range
ax1_range = ax1.get_ylim()[1] - ax1.get_ylim()[0]
fct = (0 - ax1.get_ylim()[0])/ax1_range

ax2_ylim = ax2.get_ylim()
# calculate new values for the second axis
ax2_ylim_new = (ax2_ylim[0],(0 - ax2_ylim[0]) / fct + ax2_ylim[0])
# set new limits
ax2.set_ylim( ax2_ylim_new )

plt.show()

I scaled the second y-axis ax2 so that it exhibits the 0 at the same height of the axis as the first y-axis ax1. This becomes more tricky if one of the axes does not contain zero (so the limits do not have a change of the sign). You could write a little function, which handles the different cases if you like to have a generic solution.


text:
Q: represent identifier hierarchy - java I have a need to have XYZIdentifier object which will be used in composition in other class to identify the object.
However, Depending on the use-case (a variable in the client object), the identifier can be either a String, long, or even a Class.
Something like IntegerIdentifier, StringIdentifier, FooIdentifier and some interface defined which can be generic.
How can I create this design?

A: Not sure what your full context is, but part of the solution may involve generics to fetch the kind of result you need, like:
public <T extends IdentifierBase> T getIdentifier(Class<T> kindYouWant) { ... }

The idea being you tell it which flavor you need, and it could either convert with best-effort, or return Null if that kind isn's available.
Like I said, not sure of your whole question...


text:
Q: Pixel Art Game in Cocos2D: Changeable Colors We are working on a pixel-art based game for iPhone using Cocos2D. We have a peculiar requirement - we would like users to be able to change the color scheme for some objects. So, for example, we might have a red car with blue wheels; the user can use a selector to change among different color schemes, like yellow body and green wheels; black body and white wheels; and so on.
The simple approach, of course, would be to pre-render the art; but this will increase the build of the game enormously, since we have 40 color combinations and dozens of objects.
What is the best way to approach this in your opinion? We are complete newbies to Cocos2D, having worked only on non-gaming apps, so even pointing us to the right direction in the Cocos2D docs would be more than enough!
Thanks all!

A: Have you looked at actions? Specifically  CCTintBy or CCTintTo. Make an image, say a grey wheel then tint it to the color you want with an action:
CCSprite *wheel = //make a sprite
[wheel runAction:[CCTintTo actionWithDuration:0.5 red: r green: g:blue: b]];